.classpath | 4 etc/eclipse-tools/maven/RHQ | 13 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 | 101 modules/common/jboss-as/src/main/java/org/jboss/on/common/jbossas/JmxConnectionHelper.java | 262 ++ modules/core/client-api/pom.xml | 86 modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/measurement/MeasurementAgentService.java | 4 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-build.xml | 2 modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml | 2 modules/core/dbutils/src/main/scripts/dbsetup/auth-schema.xml | 19 modules/core/dbutils/src/main/scripts/dbsetup/authz-schema.xml | 19 modules/core/dbutils/src/main/scripts/dbsetup/config-schema.xml | 1 modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml | 12 modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml | 3 modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml | 46 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/AlertCondition.java | 20 modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertConditionLog.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/alert/notification/AlertNotification.java | 19 modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java | 91 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 | 16 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/AbstractGroupConfigurationUpdate.java | 3 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/Advisory.java | 6 modules/core/domain/src/main/java/org/rhq/core/domain/content/Architecture.java | 12 modules/core/domain/src/main/java/org/rhq/core/domain/content/CVE.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestStatus.java | 56 modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestType.java | 54 modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentServiceRequest.java | 16 modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSource.java | 10 modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSourceType.java | 14 modules/core/domain/src/main/java/org/rhq/core/domain/content/Distribution.java | 14 modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionFile.java | 5 modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionType.java | 13 modules/core/domain/src/main/java/org/rhq/core/domain/content/DownloadMode.java | 48 modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackage.java | 10 modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackageHistory.java | 9 modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/AdvisoryDetailsComposite.java | 1 modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/PackageListItemComposite.java | 51 modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ContentResponseResult.java | 52 modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployIndividualPackageResponse.java | 74 modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackageStep.java | 58 modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackagesResponse.java | 59 modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/RemovePackagesResponse.java | 53 modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java | 7 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertCriteria.java | 4 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertDefinitionCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDeploymentCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDestinationCriteria.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleFileCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleResourceDeploymentCriteria.java | 17 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleVersionCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/CallTimeDataCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/Criteria.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/EventCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GroupOperationHistoryCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/InstalledPackageCriteria.java | 4 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDataTraitCriteria.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDefinitionCriteria.java | 4 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementScheduleCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationDefinitionCriteria.java | 4 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationHistoryCriteria.java | 23 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/PackageVersionCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RepoCriteria.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java | 10 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java | 13 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupCriteria.java | 43 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupDefinitionCriteria.java | 12 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceOperationHistoryCriteria.java | 6 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java | 13 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RoleCriteria.java | 95 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SavedSearchCriteria.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java | 23 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TagCriteria.java | 7 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java | 31 modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/Dashboard.java | 18 modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/DashboardPortlet.java | 2 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/MeasurementDataRequest.java | 61 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/operation/composite/GroupOperationLastCompletedComposite.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationScheduleComposite.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationLastCompletedComposite.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationScheduleComposite.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/resource/CreateResourceHistory.java | 21 modules/core/domain/src/main/java/org/rhq/core/domain/resource/DeleteResourceHistory.java | 6 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/InventorySummary.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java | 177 - 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 | 107 - 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/ResourceAvailabilitySummary.java | 2 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/ResourceIdFlyWeight.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceInstallCount.java | 6 modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java | 73 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ClusterKey.java | 21 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/GroupDefinition.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ResourceGroup.java | 50 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterFlyweight.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterKeyFlyweight.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ResourceGroupComposite.java | 15 modules/core/domain/src/main/java/org/rhq/core/domain/tagging/compsite/TagReportComposite.java | 20 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/CriteriaUtils.java | 58 modules/core/domain/src/main/java/org/rhq/core/domain/util/PageList.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java | 75 modules/core/domain/src/main/java/org/rhq/core/domain/util/UnlimitedPageControl.java | 7 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/domain/src/test/java/org/rhq/core/domain/util/StringUtilsTest.java | 47 modules/core/native-system/pom.xml | 92 modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java | 11 modules/core/plugin-api/pom.xml | 90 modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java | 48 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 | 11 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 | 479 +++- 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/measurement/MeasurementManager.java | 13 modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/ClassLoaderManager.java | 15 modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java | 22 modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginManager.java | 7 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 | 45 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 | 61 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java | 325 --- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java | 122 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java | 39 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java | 107 - 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/SearchGUI.java | 119 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java | 277 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/AdministrationView.java | 191 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/agent/install/RemoteAgentInstallView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java | 29 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesView.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java | 234 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java | 167 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java | 34 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java | 114 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java | 503 ++++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GeneralPropertiesAlertDefinitionForm.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsDataSource.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java | 309 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java | 245 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NotificationsAlertDefinitionForm.java | 221 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java | 185 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsDataSource.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java | 161 + 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 | 641 ++++++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.java | 86 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SingleAlertDefinitionView.java | 3 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/alert/definitions/TemplateAlertDefinitionsDataSource.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java | 27 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java | 4 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/BundleView.java | 6 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/AboutModalWindow.java | 60 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java | 3 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 | 1046 +++++++--- 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/configuration/PropertyValueChangeEvent.java | 59 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeListener.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/EnhancedDynamicForm.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/selector/AbstractSelector.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java | 259 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/PropertyGrid.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java | 60 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java | 57 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java | 54 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleDistributionFileUploadForm.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleFileUploadForm.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/TextFileRetrieverForm.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/AbstractWizard.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortalLayout.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java | 73 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformPortletView.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java | 596 +++++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationsPortlet.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/footer/FavoritesButton.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java | 49 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertGWTService.java | 10 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 | 41 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 | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RoleGWTService.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java | 2 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 | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleListView.java | 26 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java | 96 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeDetailsView.java | 29 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java | 46 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/ResourceGroupDataSourceField.java | 71 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java | 38 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java | 29 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java | 132 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java | 149 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java | 365 +++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/AutoGroupTopView.java | 106 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java | 306 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java | 267 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTitleBar.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java | 27 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java | 313 -- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeDatasource.java | 368 --- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java | 336 ++- 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/inventory/ResourceGroupMembershipView.java | 133 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java | 52 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/schedules/SchedulesDataSource.java | 50 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java | 98 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateStep.java | 54 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java | 34 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java | 212 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDataSourceField.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java | 89 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/CustomResourceTreeGrid.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java | 201 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTitleBar.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java | 40 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java | 449 ++-- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java | 483 +++- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryDataSource.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java | 93 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java | 91 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupSelector.java | 50 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupsView.java | 125 + 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/operation/OperationHistoryView.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/create/OperationCreateWizard.java | 2 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 | 339 --- 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/discovery/AutodiscoveryQueueDataSource.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/ResourceAutodiscoveryView.java | 20 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/ResourceSelector.java | 78 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/inventory/resource/type/ResourceTypeRepository.java | 160 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java | 94 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/FavoritesMenu.java | 43 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java | 135 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java | 190 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/operation/RecentOperationsDataSource.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ReportTopView.java | 155 - 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/report/measurement/MeasurementOOBView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/favorites/SavedSearchManager.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java | 311 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java | 130 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/BrowserUtility.java | 58 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java | 43 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/FormUtility.java | 46 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java | 88 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java | 45 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TableUtility.java | 44 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TreeUtility.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetUtility.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetsField.java | 63 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java | 103 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java | 147 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java | 113 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java | 29 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java | 33 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/RPCManager.java | 2 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/client/util/selenium/SeleniumUtility.java | 23 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java | 34 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java | 137 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AuthorizationGWTServiceImpl.java | 44 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ClusterGWTServiceImpl.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java | 211 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ContentGWTServiceImpl.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java | 28 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java | 54 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java | 142 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java | 65 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java | 165 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java | 125 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java | 64 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java | 52 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java | 49 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java | 47 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/TagGWTServiceImpl.java | 66 modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css | 34 modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html | 5 modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml | 27 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/authentication/SessionAccessServlet.java | 25 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/common/tag/FunctionTagLibrary.java | 6 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/inventory/resource/DisambiguatedResourceLineageRenderer.java | 28 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/ResourceLineageRenderer.java | 4 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/common/events/EventDetailsAction.java | 58 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/java/org/rhq/enterprise/gui/legacy/taglib/InventoryHierarchyTag.java | 14 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/display/DisambiguatedResourceNameTag.java | 13 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/navigation/group/ResourceGroupTreeContextMenuUIBean.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/WEB-INF/web.xml | 2 modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp | 104 modules/enterprise/gui/portal-war/src/main/webapp/rhq/admin/report/resourceInstallReport-body.xhtml | 9 modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/events/data-plain.xhtml | 180 + modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/graphs-plain.xhtml | 123 + modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/measurement/data-plain.xhtml | 197 + modules/enterprise/gui/portal-war/src/main/webapp/rhq/group/monitor/graphs-plain.xhtml | 2 modules/enterprise/gui/portal-war/src/main/webapp/rhq/resource/monitor/graphs-plain.xhtml | 19 modules/enterprise/pom.xml | 11 modules/enterprise/remoting/cli/pom.xml | 88 modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/proxy/ResourceClientProxy.java | 4 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 | 118 + 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/alert/AlertDefinitionManagerBean.java | 37 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerLocal.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerRemote.java | 6 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/AuthSession.java | 4 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java | 26 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java | 36 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationDefinitionUpdateReport.java | 17 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java | 12 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/measurement/MeasurementDataManagerBean.java | 17 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/ResourceFactoryManagerBean.java | 21 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerLocal.java | 10 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerRemote.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java | 196 + modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java | 39 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 | 31 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerLocal.java | 5 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java | 45 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/Disambiguator.java | 15 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/MutableDisambiguationReport.java | 28 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java | 157 + modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerLocal.java | 65 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/definition/GroupDefinitionManagerBean.java | 14 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java | 19 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/ServerVersion.java | 6 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 | 34 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 | 253 +- modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/PluginDescriptorUtil.java | 70 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java | 2 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/test/UpdateSubsytemTestBase.java | 8 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/AbstractEJB3Test.java | 3 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java | 7 modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml | 70 modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml | 92 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 | 356 --- modules/enterprise/server/plugins/alert-operations/src/main/resources/META-INF/rhq-serverplugin.xml | 17 modules/enterprise/server/plugins/alert-operations/src/main/resources/operations.xhtml | 79 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/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java | 2 modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java | 47 modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl | 12 modules/helpers/pom.xml | 12 modules/jopr/etc/jbas5-jnp-client/client.sh | 38 modules/jopr/etc/jbas5-jnp-client/src/main/java/test/RmiClient.java | 7 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/java/org/rhq/plugins/jbossas5/ApplicationServerComponent.java | 2 modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java | 103 modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerPluginConfigurationProperties.java | 3 modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossProperties.java | 4 modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JmxConnectionHelper.java | 264 -- modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml | 31 modules/plugins/jboss-as-5/testsuite/src/main/java/org/rhq/plugins/jbossas5/JBossServerTest.java | 13 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/java/org/rhq/plugins/jbossas/JBossASServerComponent.java | 8 modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossProperties.java | 2 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 | 33 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/mysql/src/main/java/org/rhq/plugins/mysql/MySqlComponent.java | 21 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/java/org/rhq/plugins/platform/FileSystemDiscoveryComponent.java | 36 modules/plugins/platform/src/main/resources/META-INF/rhq-plugin.xml | 10 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 629 files changed, 28889 insertions(+), 9677 deletions(-)
New commits: commit f7aa5f57e02fb94389c33ac5b22bcef222488bc7 Merge: 077dd3d... 08566cc... Author: Lukas Krejci lkrejci@redhat.com Date: Wed Oct 13 11:16:45 2010 +0200
Merge branch 'master' into code-smell
diff --cc modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java index 4034184,bc1fc64..484d591 --- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java +++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java @@@ -87,10 -87,12 +87,12 @@@ public class Props
private Set<Template> templates = new HashSet<Template>();
- private Set<MetricProps> metrics = new LinkedHashSet<MetricProps>();; + private Set<MetricProps> metrics = new LinkedHashSet<MetricProps>();
- private Set<OperationProps> operations = new LinkedHashSet<OperationProps>();; + private Set<OperationProps> operations = new LinkedHashSet<OperationProps>();
+ private Set<TypeKey> runsInsides = new LinkedHashSet<TypeKey>();; + private String pluginName; private String pluginDescription;
commit 08566cc2f400a51b1c81f7a8be6b7e405d47eb26 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Oct 12 17:40:26 2010 -0400
Fix issues with sticky tab navigation between different resources or resources and autogroups.
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 cf9e470..3544941 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 @@ -40,6 +40,7 @@ import org.rhq.enterprise.gui.coregui.client.admin.AdministrationView; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.bundle.BundleTopView; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardsView; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupDetailView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupTopView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.InventoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTopView; @@ -60,6 +61,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { private static final String DEFAULT_VIEW_PATH = DashboardsView.VIEW_ID;
+ // just to avoid constructing this over and over + private static final String TREE_NAV_VIEW_PATTERN = "(" + ResourceTopView.VIEW_ID + "|" + + ResourceGroupTopView.VIEW_ID + "|" + ResourceGroupDetailView.AUTO_GROUP_VIEW_PATH + ")/[^/]*"; + public static final String CONTENT_CANVAS_ID = "BaseContent";
private static ErrorHandler errorHandler = new ErrorHandler(); @@ -255,8 +260,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // We're already there - just refresh the view. refresh(); } else { - if (viewPath.matches("(" + ResourceTopView.VIEW_ID + "|" + ResourceGroupTopView.VIEW_ID + ")/[^/]*")) { - // e.g. "Resource/10001" + if (viewPath.matches(TREE_NAV_VIEW_PATTERN)) { + // e.g. "Resource/10001" or "Resource/AutoGroup/10003" if (!currentViewPath.startsWith(viewPath)) { // 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 @@ -265,6 +270,10 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // 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*[^/]*", ""); + // make sure we're not *too* sticky, stop no deeper than the subtab level. This prevents + // trying to render non-applicable detail views. We'll do this by chopping at the start + // of any other numeric in the path + suffix = suffix.replaceFirst("\d.*", ""); viewPath += suffix; } } 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 f63e185..79606f6 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 @@ -208,7 +208,7 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo // Do *not* select the tab and trigger the tab selected event until the subtab has been selected first.
SubTab subtab = (subtabTitle != null) ? tab.getSubTabByTitle(subtabTitle) : tab.getDefaultSubTab(); - if (subtab == null || tab.getLayout().isDisabled()) { + if (subtab == null || tab.getLayout().isSubTabDisabled(subtab)) { CoreGUI.getErrorHandler().handleError("Invalid subtab name: " + subtabTitle); // TODO: Should we fire a history event here to redirect to a valid bookmark? subtab = tab.getLayout().getDefaultSubTab();
commit bc08fd4b21cdde7b5bde37a5cdd73ce47647e035 Author: John Mazzitelli mazz@redhat.com Date: Tue Oct 12 17:00:19 2010 -0400
no longer need the DELETEME jsf tab - gwt ui should now be able to do everything the jsf alert def ui was able to do
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 159a679..0e22ac2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -100,7 +100,6 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo private SubTab opSched; private SubTab alertHistory; private SubTab alertDef; - private SubTab alertDelete; private SubTab configCurrent; private SubTab configHistory; private SubTab eventHistory; @@ -157,8 +156,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo alertsTab = new TwoLevelTab(getTabSet().extendLocatorId("Alerts"), "Alerts", "/images/icons/Alert_grey_16.png"); this.alertHistory = new SubTab(alertsTab.extendLocatorId("History"), "History", null); this.alertDef = new SubTab(alertsTab.extendLocatorId("Definitions"), "Definitions", null); - this.alertDelete = new SubTab(alertsTab.extendLocatorId("DELETEME"), "DELETEME", null); - alertsTab.registerSubTabs(alertHistory, alertDef, alertDelete); + alertsTab.registerSubTabs(alertHistory, alertDef); tabs.add(alertsTab);
configurationTab = new TwoLevelTab(getTabSet().extendLocatorId("Configuration"), "Configuration", @@ -269,8 +267,6 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo "/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" + resource.getId()), true, true); updateSubTab(this.alertsTab, this.alertDef, new ResourceAlertDefinitionsView(alertsTab .extendLocatorId("AlertDefView"), this.resourceComposite), true, true); - updateSubTab(this.alertsTab, this.alertDelete, new FullHTMLPane( - "/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()), true, true);
if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), resourcePermissions .isConfigureRead())) {
commit c8cd1d264fb1f59d19e2016e35ac2d271c2022f8 Author: John Mazzitelli mazz@redhat.com Date: Tue Oct 12 16:49:35 2010 -0400
monumental commit. I think this finishes the initial coding of the entire resource alert definition UI. this commit completes the relative resource operation notification. lots-o-testing and lots-o-bug-fixing is still required.
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 1b7b233..b2e9c05 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 @@ -24,8 +24,10 @@ package org.rhq.enterprise.gui.coregui.client.alert.definitions;
import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.Map; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; @@ -167,6 +169,12 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio 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)); + ancestorTypeSelectItem.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + populateRelativeDescendantsDropDownMenu(null); + } + });
descendantTypeSelectItem = new SelectItem("descendantTypeSelectItem", "Then Filter By"); descendantTypeSelectItem.setStartRow(true); @@ -221,8 +229,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio descendantTypeSelectItem.clearValue(); descendantNameTextItem.clearValue(); hideOperationDropDownMenu(); - populateRelativeAncestorDropDownMenu(null); - // TODO + populateRelativeDropDownMenus(null, null); break; } } @@ -253,9 +260,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio break; } case RELATIVE: { - populateRelativeAncestorDropDownMenu(notifInfo.getAncestorTypeId()); - // TODO - descendantTypeSelectItem.setValue(notifInfo.getDescendantTypeId()); + populateRelativeDropDownMenus(notifInfo.getAncestorTypeId(), notifInfo.getDescendantTypeId()); if (notifInfo.getDescendantName() != null) { descendantNameTextItem.setValue(notifInfo.getDescendantName()); } @@ -268,7 +273,9 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio } }
- private void populateRelativeAncestorDropDownMenu(final Integer selectedResourceTypeId) { + private void populateRelativeDropDownMenus(final Integer selectedResourceTypeId, + final Integer descendantResourceTypeId) { + if (ancestorTypeSelectItem.getValue() == null) { AsyncCallback<ArrayList<ResourceType>> callback = new AsyncCallback<ArrayList<ResourceType>>() { @Override @@ -283,6 +290,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio } else { ancestorTypeSelectItem.setValue(String.valueOf(results.get(0).getId())); } + populateRelativeDescendantsDropDownMenu(descendantResourceTypeId); }
@Override @@ -301,6 +309,40 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio } }
+ private void populateRelativeDescendantsDropDownMenu(final Integer selectedDescendantResourceTypeId) { + Object rootResourceTypeIdObj = ancestorTypeSelectItem.getValue(); + final int rootResourceTypeId; + + if (rootResourceTypeIdObj == null) { + rootResourceTypeId = this.resourceType.getId(); + } else { + rootResourceTypeId = Integer.parseInt(rootResourceTypeIdObj.toString()); + } + GWTServiceLookup.getResourceTypeGWTService().getResourceTypeDescendantsWithOperations(rootResourceTypeId, + new AsyncCallback<HashMap<Integer, String>>() { + + @Override + public void onSuccess(HashMap<Integer, String> results) { + LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(results.size() + 1); + map.put(String.valueOf(rootResourceTypeId), "Root Ancestor Type"); + for (Map.Entry<Integer, String> entry : results.entrySet()) { + map.put(entry.getKey().toString(), entry.getValue()); + } + descendantTypeSelectItem.setValueMap(map); + if (selectedDescendantResourceTypeId != null) { + descendantTypeSelectItem.setValue(selectedDescendantResourceTypeId.toString()); + } else { + descendantTypeSelectItem.setValue(String.valueOf(rootResourceTypeId)); + } + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Cannot get type descendants", caught); + } + }); + } + /** * 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. 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 2b2bd45..e2eeb96 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,6 +1,7 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
import java.util.ArrayList; +import java.util.HashMap;
import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @@ -18,5 +19,5 @@ public interface ResourceTypeGWTService extends RemoteService {
ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId);
- ArrayList<ResourceType> getResourceTypeDescendantsWithOperations(int resourceTypeId); + HashMap<Integer, String> 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 e99d65d..be25a0b 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,6 +1,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import java.util.ArrayList; +import java.util.HashMap; import java.util.List;
import org.rhq.core.domain.criteria.ResourceTypeCriteria; @@ -61,13 +62,12 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement }
@Override - public ArrayList<ResourceType> getResourceTypeDescendantsWithOperations(int resourceTypeId) { + public HashMap<Integer, String> getResourceTypeDescendantsWithOperations(int resourceTypeId) { try { ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); - List<ResourceType> list = typeManager.getResourceTypeDescendantsWithOperations(getSessionSubject(), + HashMap<Integer, String> map = typeManager.getResourceTypeDescendantsWithOperations(getSessionSubject(), resourceTypeId); - return SerialUtility.prepare(new ArrayList<ResourceType>(list), - "ResourceTypes.getResourceTypeDescendantsWithOperations"); + return SerialUtility.prepare(map, "ResourceTypes.getResourceTypeDescendantsWithOperations"); } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } 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 9dc348c..1837023 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 @@ -23,6 +23,7 @@ import java.util.Arrays; 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; @@ -44,6 +45,7 @@ import org.jboss.annotation.IgnoreDependency;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.ResourceTypeCriteria; +import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; @@ -426,20 +428,25 @@ public class ResourceTypeManagerBean implements ResourceTypeManagerLocal, Resour return results; }
- public List<ResourceType> getResourceTypeDescendantsWithOperations(Subject subject, int resourceTypeId) { + public HashMap<Integer, String> getResourceTypeDescendantsWithOperations(Subject subject, int resourceTypeId) { List<ResourceType> types = getAllResourceTypeDescendants(subject, resourceTypeId); - List<ResourceType> results = excludeThoseWithoutOperations(types); + excludeThoseWithoutOperations(types); + HashMap<Integer, String> results = new HashMap<Integer, String>(types.size()); + for (ResourceType type : types) { + results.put(type.getId(), type.getName()); + } return results; }
- private List<ResourceType> excludeThoseWithoutOperations(List<ResourceType> types) { - List<ResourceType> results = new ArrayList<ResourceType>(); - for (ResourceType next : types) { - if (next.getOperationDefinitions() != null && next.getOperationDefinitions().size() != 0) { - results.add(next); + private void excludeThoseWithoutOperations(List<ResourceType> types) { + Iterator<ResourceType> iterator = types.iterator(); + while (iterator.hasNext()) { + ResourceType next = iterator.next(); + Set<OperationDefinition> operations = next.getOperationDefinitions(); + if (operations == null || operations.isEmpty()) { + iterator.remove(); } } - return results; }
public List<ResourceType> getAllResourceTypeAncestors(Subject subject, int resourceTypeId) { 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 6cd3639..6886944 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.server.resource;
+import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; @@ -133,7 +134,7 @@ public interface ResourceTypeManagerLocal {
ResourceType getResourceTypeByNameAndPlugin(Subject subject, String name, String plugin);
- List<ResourceType> getResourceTypeDescendantsWithOperations(Subject subject, int resourceTypeId); + HashMap<Integer, String> 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 deleted file mode 100644 index 2d85548..0000000 --- a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsBackingBean.java +++ /dev/null @@ -1,358 +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.server.plugins.alertOperations; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.rhq.core.domain.alert.AlertDefinition; -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.Property; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; -import org.rhq.core.domain.operation.OperationDefinition; -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceType; -import org.rhq.enterprise.server.plugin.pc.alert.CustomAlertSenderBackingBean; -import org.rhq.enterprise.server.plugins.alertOperations.OperationInfo.ResourceSelectionMode; -import org.rhq.enterprise.server.resource.ResourceTypeNotFoundException; -import org.rhq.enterprise.server.util.LookupUtil; - -/** - * Backing bean for the operations alert sender - * @author Joseph Marques - */ -public class OperationsBackingBean extends CustomAlertSenderBackingBean { - - private Map<String, String> selectionModeOptions = new LinkedHashMap<String, String>(); - private Map<String, String> ancestorTypeOptions = new LinkedHashMap<String, String>(); - private Map<String, String> descendantTypeOptions = new LinkedHashMap<String, String>(); - private Map<String, String> operationNameOptions = new LinkedHashMap<String, String>(); - - private String selectionMode = ""; - private String resourceId; - private String ancestorTypeId; - private String descendantName; - private String descendantTypeId; - private String operationDefinitionId; - - private String effectiveResourceTypeName; - private String effectiveResourceTypeId; - - private ConfigurationDefinition argumentsConfigurationDefinition; - private Configuration argumentsConfiguration; - - private Subject overlord; - - private Subject getOverlord() { - if (overlord == null) { - overlord = LookupUtil.getSubjectManager().getOverlord(); - } - return overlord; - } - - @Override - public void loadView() { - selectionMode = get(OperationInfo.Constants.SELECTION_MODE, "none"); - - // always load first list - for (ResourceSelectionMode mode : ResourceSelectionMode.values()) { - selectionModeOptions.put(mode.displayString, mode.name()); - } - - Configuration previousArguments = extraParameters; - - // load secondList if currentType is selected - if (selectionMode.equals("none")) { - return; - } - - if (selectionMode.equals(ResourceSelectionMode.SPECIFIC.name())) { - resourceId = get(OperationInfo.Constants.SPECIFIC_RESOURCE_ID, ""); - } else if (selectionMode.equals(ResourceSelectionMode.RELATIVE.name())) { - ancestorTypeId = get(OperationInfo.Constants.RELATIVE_ANCESTOR_TYPE_ID, "none"); - descendantName = get(OperationInfo.Constants.RELATIVE_DESCENDANT_NAME, "Name (optional)"); - descendantTypeId = get(OperationInfo.Constants.RELATIVE_DESCENDANT_TYPE_ID, "none"); - - ResourceType contextType = computeResourceTypeFromContext(); // should not be null - List<ResourceType> ancestors = null; - if (context.equals("resource")) { - try { - List<Resource> ancestry = LookupUtil.getResourceManager().getResourceLineage( - Integer.parseInt(contextSubId)); - ancestors = new ArrayList<ResourceType>(); - for (Resource next : ancestry) { - ancestors.add(next.getResourceType()); - } - } catch (Throwable t) { - // ignore, we'll default to a different loading style below - } - } - - if (ancestors == null) { // if not in the resource content or fallback if resource ancestry loading bombs - // 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); - - if (ancestorTypeId.equals("none") == false) { - List<ResourceType> descendants = LookupUtil.getResourceTypeManager() - .getResourceTypeDescendantsWithOperations(getOverlord(), Integer.parseInt(ancestorTypeId)); - load(descendantTypeOptions, descendants); - } else { - List<ResourceType> descendants = LookupUtil.getResourceTypeManager() - .getResourceTypeDescendantsWithOperations(getOverlord(), contextType.getId()); - load(descendantTypeOptions, descendants); - } - } - - // compute effectiveResourceTypeId from given info - ResourceType type = null; - if (selectionMode.equals(ResourceSelectionMode.SELF.name())) { - type = computeResourceTypeFromContext(); - - } else if (selectionMode.equals(ResourceSelectionMode.SPECIFIC.name())) { - if (resourceId.equals("") == false) { - Resource resource = LookupUtil.getResourceManager().getResource(getOverlord(), - Integer.parseInt(resourceId)); - type = resource.getResourceType(); - } - - } else if (selectionMode.equals(ResourceSelectionMode.RELATIVE.name())) { - try { - if (descendantTypeId.equals("none") == false) { - type = LookupUtil.getResourceTypeManager().getResourceTypeById(getOverlord(), - Integer.parseInt(descendantTypeId)); - } else if (ancestorTypeId.equals("none") == false) { - type = LookupUtil.getResourceTypeManager().getResourceTypeById(getOverlord(), - Integer.parseInt(ancestorTypeId)); - } - } catch (ResourceTypeNotFoundException rtnfe) { - // debugging message - } - } - - if (type == null) { - return; - } - - effectiveResourceTypeId = String.valueOf(type.getId()); - effectiveResourceTypeName = type.getName(); - - operationDefinitionId = get(OperationInfo.Constants.OPERATION_ID, "none"); - List<OperationDefinition> definitions = LookupUtil.getOperationManager().findSupportedResourceTypeOperations( - getOverlord(), Integer.valueOf(effectiveResourceTypeId), false); - for (OperationDefinition nextDefinition : definitions) { - operationNameOptions.put(nextDefinition.getDisplayName(), String.valueOf(nextDefinition.getId())); - } - - if (operationDefinitionId.equals("none")) { - return; - } - - try { - OperationDefinition operation = LookupUtil.getOperationManager().getOperationDefinition(getOverlord(), - Integer.parseInt(operationDefinitionId)); - argumentsConfigurationDefinition = operation.getParametersConfigurationDefinition(); - - if (argumentsConfigurationDefinition == null) { - return; - } - - if (previousArguments == null) { - // create it for the first time or if this was previous removed due to switching form options - Configuration emptyConfiguration = LookupUtil.getConfigurationManager() - .getConfigurationFromDefaultTemplate(argumentsConfigurationDefinition); - argumentsConfiguration = emptyConfiguration.deepCopy(false); - } else { - argumentsConfiguration = previousArguments; - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void load(Map<String, String> resourceTypeOptions, List<ResourceType> types) { - for (ResourceType nextType : types) { - resourceTypeOptions.put(nextType.getName(), String.valueOf(nextType.getId())); - } - } - - private ResourceType computeResourceTypeFromContext() { - AlertDefinition definition = LookupUtil.getAlertDefinitionManager().getAlertDefinitionById(getOverlord(), - Integer.parseInt(contextId)); - - ResourceType type = null; - if (definition.getResource() != null) { - type = definition.getResource().getResourceType(); - } else if (definition.getResourceGroup() != null) { - type = definition.getResourceGroup().getResourceType(); - } else { - type = definition.getResourceType(); - } - return type; - } - - private String get(OperationInfo.Constants operationInfoConstant, String defaultValue) { - return alertParameters.getSimpleValue(operationInfoConstant.propertyName, defaultValue); - } - - @Override - public void saveView() { - set(selectionMode, OperationInfo.Constants.SELECTION_MODE); - set(resourceId, OperationInfo.Constants.SPECIFIC_RESOURCE_ID); - set(ancestorTypeId, OperationInfo.Constants.RELATIVE_ANCESTOR_TYPE_ID); - set("Name (optional)".equals(descendantName) ? null : descendantName, - OperationInfo.Constants.RELATIVE_DESCENDANT_NAME); - set(descendantTypeId, OperationInfo.Constants.RELATIVE_DESCENDANT_TYPE_ID); - set(operationDefinitionId, OperationInfo.Constants.OPERATION_ID); - - // persist the updates to the argumentsConfiguration - if (operationDefinitionId != null && !operationDefinitionId.equals("none") && argumentsConfiguration != null) { - extraParameters = persistConfiguration(argumentsConfiguration); - } else { - extraParameters = null; - //deleteExtraParameters(); - } - - alertParameters = persistConfiguration(alertParameters); - } - - private boolean set(String value, OperationInfo.Constants operationInfoConstant) { - String propertyName = operationInfoConstant.propertyName; - if (value == null) { - Property previous = alertParameters.remove(propertyName); - if (previous == null) { - return false; // removing a non-existence property, no change - } - return ((PropertySimple) previous).getStringValue() != null; - } - PropertySimple property = alertParameters.getSimple(propertyName); - if (property == null) { - property = new PropertySimple(propertyName, value); - alertParameters.put(property); - return true; // adding a property that previously didn't exist - } else { - String oldStringValue = property.getStringValue(); - property.setStringValue(value); - return !value.equals(oldStringValue); - } - } - - public Map<String, String> getSelectionModeOptions() { - return selectionModeOptions; - } - - public Map<String, String> getAncestorTypeOptions() { - return ancestorTypeOptions; - } - - public Map<String, String> getDescendantTypeOptions() { - return descendantTypeOptions; - } - - public Map<String, String> getOperationNameOptions() { - return operationNameOptions; - } - - public String getSelectionMode() { - return selectionMode; - } - - public void setSelectionMode(String selectionMode) { - this.selectionMode = selectionMode; - } - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public String getAncestorTypeId() { - return ancestorTypeId; - } - - public void setAncestorTypeId(String ancestorTypeId) { - this.ancestorTypeId = ancestorTypeId; - } - - public String getDescendantName() { - return descendantName; - } - - public void setDescendantName(String descendantName) { - this.descendantName = descendantName; - } - - public String getDescendantTypeId() { - return descendantTypeId; - } - - public void setDescendantTypeId(String descendantTypeId) { - this.descendantTypeId = descendantTypeId; - } - - public String getOperationDefinitionId() { - return operationDefinitionId; - } - - public void setOperationDefinitionId(String operationDefinitionId) { - this.operationDefinitionId = operationDefinitionId; - } - - public String getEffectiveResourceTypeId() { - return effectiveResourceTypeId; - } - - public String getEffectiveResourceTypeName() { - return effectiveResourceTypeName; - } - - public ConfigurationDefinition getArgumentsConfigurationDefinition() { - return argumentsConfigurationDefinition; - } - - public void setArgumentsConfigurationDefinition(ConfigurationDefinition argumentsConfigurationDefinition) { - this.argumentsConfigurationDefinition = argumentsConfigurationDefinition; - } - - public Configuration getArgumentsConfiguration() { - return argumentsConfiguration; - } - - public void setArgumentsConfiguration(Configuration argumentsConfiguration) { - this.argumentsConfiguration = argumentsConfiguration; - } - - public String getNoParametersMessage() { - return "This operation does not take any parameters."; - } - - public String getNotInitializedMessage() { - return "This operation parameters definition has not been initialized."; - } -} diff --git a/modules/enterprise/server/plugins/alert-operations/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/alert-operations/src/main/resources/META-INF/rhq-serverplugin.xml index 752f5b3..9c5debe 100644 --- a/modules/enterprise/server/plugins/alert-operations/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/alert-operations/src/main/resources/META-INF/rhq-serverplugin.xml @@ -14,19 +14,18 @@ Used to execute known operations on resources currently in inventory. </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>Resource Operations</short-name>
<!-- Class that does the actual sending --> <plugin-class>OperationsSender</plugin-class>
- <custom-ui> - <ui-snippet-name>operations.xhtml</ui-snippet-name> - <backing-bean-class>OperationsBackingBean</backing-bean-class> - <backing-bean-name>operationsBean</backing-bean-name> - </custom-ui> + <alert-configuration> + <c:simple-property name="selection-mode" type="string" required="true" description="How the resource is to be identified: SELF, SPECIFIC or RELATIVE"/> + <c:simple-property name="selection-specific-resource-id" type="integer" required="true" description="If SPECIFIC mode, identifies the resource"/> + <c:simple-property name="selection-relative-ancestor-type-id" type="integer" required="true" description="If RELATIVE, the type at the top of the hierarchy"/> + <c:simple-property name="selection-relative-descendant-type-id" type="integer" required="true" description="If RELATIVE, the type at the bottom of the hierarchy to identify the resource by its type"/> + <c:simple-property name="selection-relative-descendant-name" type="integer" required="false" description="If RELATIVE and not-null, this further helps identify the resource by its name"/> + <c:simple-property name="operation-definition-id" type="integer" required="true" description="Identifies the operation to be invoked"/> + </alert-configuration> </alert-plugin> \ No newline at end of file diff --git a/modules/enterprise/server/plugins/alert-operations/src/main/resources/operations.xhtml b/modules/enterprise/server/plugins/alert-operations/src/main/resources/operations.xhtml deleted file mode 100644 index 0502e73..0000000 --- a/modules/enterprise/server/plugins/alert-operations/src/main/resources/operations.xhtml +++ /dev/null @@ -1,79 +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" - xmlns:onc="http://jboss.org/on/component" > - -<body> - - <h:panelGrid columns="2"> - <h:outputText value="Resource Selection Mode:" style="width: 150px;" /> - <h:selectOneMenu value="#{operationsBean.selectionMode}" > - <f:selectItem itemValue="none" itemLabel="Select..." /> - <f:selectItems value="#{operationsBean.selectionModeOptions}" /> - </h:selectOneMenu> - - <h:outputText value="Resource ID:" rendered="#{operationsBean.selectionMode eq 'SPECIFIC'}" /> - <h:panelGroup rendered="#{operationsBean.selectionMode eq 'SPECIFIC'}"> - <h:inputText value="#{operationsBean.resourceId}" id="resourceId" /> - <a href="#" - onclick="window.open('/rhq/inventory/resourcePicker.xhtml?nomenu=true&fieldId=customContentForm:resourceId', 'ResourcePicker','width=1000,height=700,scrollbars=yes,toolbar=no,resizable=yes,location=no,status=no,left=100,top=100'); return false;" - class="buttonmed">Pick</a> - </h:panelGroup> - - <h:outputText value="Start Search From:" style="width: 200px;" rendered="#{operationsBean.selectionMode eq 'RELATIVE'}" /> - <h:selectOneMenu value="#{operationsBean.ancestorTypeId}" rendered="#{operationsBean.selectionMode eq 'RELATIVE'}"> - <f:selectItem itemValue="none" itemLabel="Select..." /> - <f:selectItems value="#{operationsBean.ancestorTypeOptions}" /> - </h:selectOneMenu> - - <h:outputText value="Then Filter By:" style="width: 200px;" rendered="#{operationsBean.selectionMode eq 'RELATIVE'}"/> - <h:panelGroup rendered="#{operationsBean.selectionMode eq 'RELATIVE'}"> - <h:selectOneMenu value="#{operationsBean.descendantTypeId}"> - <f:selectItem itemValue="none" itemLabel="Select..." /> - <f:selectItems value="#{operationsBean.descendantTypeOptions}" /> - </h:selectOneMenu> - <h:inputText value="#{operationsBean.descendantName}" id="nameFilter" - onfocus="if (this.value == 'Name (optional)') { this.value = ''; this.style.color = 'black'; } " - onblur="if (this.value == '') { this.value = 'Name (optional)'; this.style.color = 'gray'; } "/> - </h:panelGroup> - - <h:outputText value="Operation Name:" rendered="#{!empty operationsBean.effectiveResourceTypeId}"/> - <h:selectOneMenu value="#{operationsBean.operationDefinitionId}" - rendered="#{!empty operationsBean.effectiveResourceTypeId}" > - <f:selectItem itemValue="none" itemLabel="Select..." /> - <f:selectItems value="#{operationsBean.operationNameOptions}"/> - </h:selectOneMenu> - </h:panelGrid> - - <h:panelGroup rendered="#{!empty operationsBean.operationDefinitionId and operationsBean.operationDefinitionId ne 'none'}"> - <onc:config configurationDefinition="#{operationsBean.argumentsConfigurationDefinition}" - configuration="#{operationsBean.argumentsConfiguration}" - nullConfigurationDefinitionMessage="#{operationsBean.noParametersMessage}" - nullConfigurationMessage="#{operationsBean.notInitializedMessage}" - nullConfigurationStyle="InfoBlock" - readOnly="false" /> - </h:panelGroup> - - <script> - addWindowOnLoadEvent(function() { - var nameFilterElement = getElementCrossBrowser('customContentForm:nameFilter') - if (nameFilterElement.value == 'Name (optional)') { - nameFilterElement.style.color = 'gray'; - } - }); - </script> - -<rich:modalPanel id="ResourcePicker"> - <h:outputLink>Hello World</h:outputLink> - <p/> - <a onclick="Richfaces.hideModalPanel('ResourcePicker');" href="#">Hide</a> -</rich:modalPanel> - - -</body> -</html>
commit 63f55447f31e96dfdf6bc0459069634b248f0549 Author: John Mazzitelli mazz@redhat.com Date: Tue Oct 12 16:45:54 2010 -0400
we can't assume our server will be able to respond within 10s for every request. increase to 60s just to be safe (a slow UI is better than a broken UI)
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 d0760d2..ebd0ab5 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,7 +139,7 @@ public class GWTServiceLookup {
public static class SessionRpcRequestBuilder extends RpcRequestBuilder {
- private static int RPC_TIMEOUT = 10000; + private static int RPC_TIMEOUT = 60000;
@Override protected RequestBuilder doCreate(String serviceEntryPoint) {
commit a59dda22140b5b001fdc1d91cfaec59d44827e21 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Oct 12 14:17:25 2010 -0400
Fix issue with empty condition and notif alert def tabs
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java index bdaff67..bea63ba 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java @@ -136,6 +136,8 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { final AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); criteria.addFilterId(id); criteria.fetchGroupAlertDefinition(true); + criteria.fetchConditions(true); + criteria.fetchAlertNotifications(true); GWTServiceLookup.getAlertDefinitionService().findAlertDefinitionsByCriteria(criteria, new AsyncCallback<PageList<AlertDefinition>>() { public void onFailure(Throwable caught) {
commit df34ecb6adae45dfcc15c60b216d3454eca4d6c5 Author: John Mazzitelli mazz@redhat.com Date: Tue Oct 12 12:26:30 2010 -0400
build form in constructor - for some reason, onInit was also getting called during destroy which in turn caused "global exception" to occur
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 2519e6e..1b7b233 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 @@ -94,11 +94,11 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio super(locatorId, notif, sender); this.resourceType = resourceType; this.theResource = res; + + buildUI(); }
- @Override - protected void onInit() { - super.onInit(); + private void buildUI() {
dynamicForm = new LocatableDynamicForm(extendLocatorId("resOpForm")); dynamicForm.setNumCols(3);
commit d12d99072c8fba68ddc2cbffc93df618c7733e91 Author: John Sanda jsanda@redhat.com Date: Tue Oct 12 11:11:48 2010 -0400
[BZ 614251] Forgot to include updated interface in previous commit
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/measurement/MeasurementAgentService.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/measurement/MeasurementAgentService.java index 66a5524..786e60f 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/measurement/MeasurementAgentService.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/measurement/MeasurementAgentService.java @@ -22,11 +22,13 @@ */ package org.rhq.core.clientapi.agent.measurement;
+import java.util.List; import java.util.Map; import java.util.Set;
import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementData; +import org.rhq.core.domain.measurement.MeasurementDataRequest; import org.rhq.core.domain.measurement.ResourceMeasurementScheduleRequest;
/** @@ -74,7 +76,7 @@ public interface MeasurementAgentService { * @param measurementNames the names of the numeric metrics or traits to be collected * @return the set of collected measurements with their data values collected */ - Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, DataType dataType, String... measurementNames); + Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, List<MeasurementDataRequest> requests);
Map<String, Object> getMeasurementScheduleInfoForResource(int resourceId); } \ No newline at end of file
commit e4530b09fd5e37ebca580153107090e4a10e06a8 Merge: ca28918... 04f6d32... Author: John Sanda jsanda@redhat.com Date: Tue Oct 12 11:03:19 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit ca289182efed696e10cbda5c8ad2b53ff2bc5acb Author: John Sanda jsanda@redhat.com Date: Tue Oct 12 10:55:23 2010 -0400
[BZ 614251] Making multiple changes so that live metric data can be fetched and displayed
There are two changes with this commit. First, in the CLI the ResourceProxy class was using a criteria query that is too broad, at least when the jboss-as and jboss-as-5 plugins are involved.
Secondly, the server/agent API used to get the metric data is inadequate. It accepts a variable number of measurement names but only a single data type for those measurements. This is problematic because there is nothing to guarantee that all of the metrics are of the same type. On the server side, we were using a hard-coded value of METRIC for the data type argument. The method(s) MeasurementManagerLocal.findLiveData and MeasurementManagerRemote.findLiveData will fail any time one of the measurement definitions has a data type other than METRIC. MeasurementManager.getRealTimeMeasurementValue has been refactored to take a list of MeasurementDataRequest objects. Each request specifies the metric name along with its corresponding data type.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataRequest.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataRequest.java new file mode 100644 index 0000000..3417777 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataRequest.java @@ -0,0 +1,61 @@ +package org.rhq.core.domain.measurement; + +import java.io.Serializable; + +public class MeasurementDataRequest implements Serializable { + private static final long serialVersionUID = 1L; + + /** The meausurement name */ + private String name; + + /** The meausurement's data type */ + private DataType type; + + public MeasurementDataRequest(MeasurementDefinition definition) { + name = definition.getName(); + type = definition.getDataType(); + } + + public MeasurementDataRequest(String metricName, DataType type) { + name = metricName; + this.type = type; + } + + /** + * @return The requested measurement's name + */ + public String getName() { + return name; + } + + /** + * @return The requested measurement's data type + */ + public DataType getType() { + return type; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (obj == this) { + return true; + } + + if (obj instanceof MeasurementDataRequest) { + MeasurementDataRequest that = (MeasurementDataRequest) obj; + return this.name.equals(that.name) && this.type.equals(that.name); + } + + return false; + } + + @Override + public int hashCode() { + return 41 * (name.hashCode() + type.hashCode()); + } + +} 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 e8c1c05..c777284 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 @@ -43,6 +43,7 @@ import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.measurement.Availability; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementData; +import org.rhq.core.domain.measurement.MeasurementDataRequest; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.pc.inventory.InventoryManager; @@ -613,8 +614,13 @@ public class StandaloneContainer { String[] metricNames = new String[tokens.length - 2]; System.arraycopy(tokens, 2, metricNames, 0, tokens.length - 2);
+ List<MeasurementDataRequest> requests = new ArrayList<MeasurementDataRequest>(); + for (String metric : metricNames) { + requests.add(new MeasurementDataRequest(metric, dataType)); + } + MeasurementManager mm = pc.getMeasurementManager(); - Set<MeasurementData> dataset = mm.getRealTimeMeasurementValue(resourceId, dataType, metricNames); + Set<MeasurementData> dataset = mm.getRealTimeMeasurementValue(resourceId, requests); if (dataset == null) { System.err.println("No data returned"); return; diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/measurement/MeasurementManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/measurement/MeasurementManager.java index b58f607..2cf62d1 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/measurement/MeasurementManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/measurement/MeasurementManager.java @@ -27,6 +27,7 @@ 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.PriorityQueue; import java.util.Set; @@ -46,6 +47,7 @@ import org.rhq.core.clientapi.agent.measurement.MeasurementAgentService; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementData; import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementDataRequest; import org.rhq.core.domain.measurement.MeasurementReport; import org.rhq.core.domain.measurement.MeasurementSchedule; import org.rhq.core.domain.measurement.MeasurementScheduleRequest; @@ -398,9 +400,8 @@ public class MeasurementManager extends AgentService implements MeasurementAgent // corresponding metric defs - one for the raw value and one for the derived per-minute value. There's no // way to tell which value the caller wants. For now, it assumes the caller wants the raw value. // (ips, 09/05/08) - public Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, DataType dataType, - String... measurementName) { - if (measurementName.length == 0) { + public Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, List<MeasurementDataRequest> requests) { + if (requests.size() == 0) { // There's no need to even call getValues() on the ResourceComponent if the list of metric names is empty. return Collections.emptySet(); } @@ -426,9 +427,9 @@ public class MeasurementManager extends AgentService implements MeasurementAgent
MeasurementReport report = new MeasurementReport(); Set<MeasurementScheduleRequest> allMeasurements = new HashSet<MeasurementScheduleRequest>(); - for (String name : measurementName) { - MeasurementScheduleRequest request = new MeasurementScheduleRequest(1, name, 0, true, dataType); - allMeasurements.add(request); + for (MeasurementDataRequest dataRequest : requests) { + allMeasurements.add(new MeasurementScheduleRequest(1, dataRequest.getName(), 0, true, + dataRequest.getType())); }
try { diff --git a/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/proxy/ResourceClientProxy.java b/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/proxy/ResourceClientProxy.java index d1ff605..a76a0ad 100644 --- a/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/proxy/ResourceClientProxy.java +++ b/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/proxy/ResourceClientProxy.java @@ -222,7 +222,9 @@ public class ResourceClientProxy {
private void initMeasurements() { MeasurementDefinitionCriteria criteria = new MeasurementDefinitionCriteria(); - criteria.addFilterResourceTypeName(resource.getResourceType().getName()); + criteria.addFilterResourceTypeId(resource.getResourceType().getId()); +// criteria.addFilterResourceTypeName(resource.getResourceType().getName()); +// criteria.setStrict(true);
this.measurementDefinitions = remoteClient.getMeasurementDefinitionManagerRemote() .findMeasurementDefinitionsByCriteria(remoteClient.getSubject(), criteria); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBean.java index c65cc8c..df006e8 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBean.java @@ -61,6 +61,7 @@ import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.DisplayType; import org.rhq.core.domain.measurement.MeasurementData; import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementDataRequest; import org.rhq.core.domain.measurement.MeasurementDataTrait; import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.measurement.MeasurementReport; @@ -783,19 +784,21 @@ public class MeasurementDataManagerBean implements MeasurementDataManagerLocal, q.setParameter("ids", ArrayUtils.wrapInList(definitionIds)); List<MeasurementDefinition> definitions = q.getResultList();
- String[] names = new String[definitions.size()]; - int i = 0; - for (MeasurementDefinition def : definitions) { - names[i++] = def.getName(); - } - AgentClient ac = agentClientManager.getAgentClient(agent); Set<MeasurementData> values = ac.getMeasurementAgentService().getRealTimeMeasurementValue(resourceId, - DataType.MEASUREMENT, names); + createRequests(definitions));
return values; }
+ private List<MeasurementDataRequest> createRequests(List<MeasurementDefinition> definitions) { + List<MeasurementDataRequest> requests = new ArrayList<MeasurementDataRequest>(); + for (MeasurementDefinition definition : definitions) { + requests.add(new MeasurementDataRequest(definition)); + } + return requests; + } + /** * Return all known trait data for the passed schedule, defined by resourceId and definitionId * diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/test/UpdateSubsytemTestBase.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/test/UpdateSubsytemTestBase.java index b279a5a..d8effb3 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/test/UpdateSubsytemTestBase.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/test/UpdateSubsytemTestBase.java @@ -50,6 +50,7 @@ import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementData; +import org.rhq.core.domain.measurement.MeasurementDataRequest; import org.rhq.core.domain.measurement.ResourceMeasurementScheduleRequest; import org.rhq.core.domain.plugin.Plugin; import org.rhq.core.domain.resource.Agent; @@ -266,10 +267,9 @@ public class UpdateSubsytemTestBase extends AbstractEJB3Test { */ public class MockAgentService implements MeasurementAgentService {
- public Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, DataType dataType, - String... measurementNames) { - // TODO Auto-generated method stub - return null; + @Override + public Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, List<MeasurementDataRequest> requests) { + return null; //To change body of implemented methods use File | Settings | File Templates. }
public void scheduleCollection(Set<ResourceMeasurementScheduleRequest> resourceSchedules) { diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java index a02e6cf..2c08880 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java @@ -57,6 +57,7 @@ import org.rhq.core.domain.discovery.ResourceSyncInfo; import org.rhq.core.domain.measurement.Availability; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementData; +import org.rhq.core.domain.measurement.MeasurementDataRequest; import org.rhq.core.domain.measurement.ResourceMeasurementScheduleRequest; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.Resource; @@ -124,9 +125,9 @@ public class TestAgentClient implements AgentClient, BundleAgentService, Content
// provide no-ops for all agent services
- public Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, DataType dataType, - String... measurementNames) { - return null; + + public Set<MeasurementData> getRealTimeMeasurementValue(int resourceId, List<MeasurementDataRequest> requests) { + return null; //To change body of implemented methods use File | Settings | File Templates. }
public void scheduleCollection(Set<ResourceMeasurementScheduleRequest> resourceSchedules) { diff --git a/modules/plugins/jboss-as-5/testsuite/src/main/java/org/rhq/plugins/jbossas5/JBossServerTest.java b/modules/plugins/jboss-as-5/testsuite/src/main/java/org/rhq/plugins/jbossas5/JBossServerTest.java index 0a09f56..6192478 100644 --- a/modules/plugins/jboss-as-5/testsuite/src/main/java/org/rhq/plugins/jbossas5/JBossServerTest.java +++ b/modules/plugins/jboss-as-5/testsuite/src/main/java/org/rhq/plugins/jbossas5/JBossServerTest.java @@ -460,16 +460,13 @@ public class JBossServerTest extends ServletTestCase PluginContainer pc = PluginContainer.getInstance(); Set<MeasurementDefinition> definitions = defaultDS.getResourceType().getMetricDefinitions();
- List<String> defNames = new ArrayList<String>(); - for (MeasurementDefinition definition : definitions) - { - defNames.add(definition.getName()); + List<MeasurementDataRequest> requests = new ArrayList<MeasurementDataRequest>(); + for (MeasurementDefinition definition : definitions) { + requests.add(new MeasurementDataRequest(definition)); } - String[] stringArray = new String[definitions.size()]; - defNames.toArray(stringArray); - Set<MeasurementData> data = pc.getMeasurementAgentService().getRealTimeMeasurementValue(defaultDS.getId(), null, stringArray); + Set<MeasurementData> data = pc.getMeasurementAgentService().getRealTimeMeasurementValue(defaultDS.getId(), + requests); assert data.size() > 0 : "We should be getting some kind of measurement data back"; - }
commit 04f6d32e9f68614cb913085211d8393d6cf63d83 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Oct 12 10:02:15 2010 -0400
Fixed some Selenium Locator issues
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 84ccc47..f63e185 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 @@ -126,15 +126,13 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo if (getSelectedItemId() == null) { CoreGUI.goToView(History.getToken()); } else { - - // selectSubTabByTitle(tabSelectedEvent.getId(), tabSelectedEvent.getSubTabId()); String tabPath = "/" + tabSelectedEvent.getId() + "/" + tabSelectedEvent.getSubTabId(); String path = this.baseViewPath + "/" + getSelectedItemId() + tabPath;
// If the tab that was selected is not already the current history item, the user clicked on the tab, rather // than going directly to the tab's URL. In this case, fire a history event to go to the tab and make it the // current history item. - if (!History.getToken().equals(path)) { + if (!History.getToken().equals(path) && !History.getToken().startsWith(path)) { CoreGUI.goToView(path); } } @@ -223,10 +221,10 @@ 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(); + ((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/common/event/EventCompositeHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java index 28e91f6..4bdfdd4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java @@ -56,22 +56,22 @@ public class EventCompositeHistoryView extends TableSection { private EntityContext context; private boolean hasWriteAccess;
- public static EventCompositeHistoryView get(ResourceGroupComposite composite) { + public static EventCompositeHistoryView get(String locatorId, ResourceGroupComposite composite) { String tableTitle = "Group Event History"; EntityContext context = EntityContext.forGroup(composite.getResourceGroup().getId()); boolean hasWriteAccess = composite.getResourcePermission().isEvent(); - return new EventCompositeHistoryView(tableTitle, context, hasWriteAccess); + return new EventCompositeHistoryView(locatorId, tableTitle, context, hasWriteAccess); }
- public static EventCompositeHistoryView get(ResourceComposite composite) { + public static EventCompositeHistoryView get(String locatorId, ResourceComposite composite) { String tableTitle = "Resource Event History"; EntityContext context = EntityContext.forResource(composite.getResource().getId()); boolean hasWriteAccess = composite.getResourcePermission().isEvent(); - return new EventCompositeHistoryView(tableTitle, context, hasWriteAccess); + return new EventCompositeHistoryView(locatorId, tableTitle, context, hasWriteAccess); }
- private EventCompositeHistoryView(String tableTitle, EntityContext context, boolean hasWriteAccess) { - super("EventCompositeHistoryTable", tableTitle, new SortSpecifier[] { DEFAULT_SORT_SPECIFIER }); + private EventCompositeHistoryView(String locatorId, String tableTitle, EntityContext context, boolean hasWriteAccess) { + super(locatorId, tableTitle, new SortSpecifier[] { DEFAULT_SORT_SPECIFIER }); this.context = context; this.hasWriteAccess = hasWriteAccess;
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 b41d7f0..4f71441 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 @@ -253,16 +253,16 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource 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 GroupResourceConfigurationEditView(this.configCurrent.extendLocatorId("View"), - this.groupComposite), 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); }
if (updateTab(this.eventsTab, groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.EVENT), true)) { - updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(groupComposite), true, true); + updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(this.eventsTab + .extendLocatorId("CompositeHistView"), groupComposite), true, true); }
this.show(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 05c37b6..159a679 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -276,13 +276,13 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo .isConfigureRead())) { updateSubTab(this.configurationTab, this.configCurrent, new ResourceConfigurationEditView(this .extendLocatorId("ResourceConfigView"), resourceComposite), true, true); - updateSubTab(this.configurationTab, this.configHistory, ConfigurationHistoryView.getHistoryOf( - resource.getId()), true, true); + updateSubTab(this.configurationTab, this.configHistory, ConfigurationHistoryView.getHistoryOf(this + .extendLocatorId("ConfigHistView"), resource.getId()), true, true); }
if (updateTab(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT), true)) { - updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(resourceComposite), true, - true); + updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(this.eventsTab + .extendLocatorId("CompositeHistoryView"), resourceComposite), true, true); }
if (updateTab(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT), true)) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java index aa11b05..8b84889 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java @@ -40,7 +40,6 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; */ public class ConfigurationHistoryView extends TableSection { public static final String VIEW_ID = "RecentConfigurationChanges"; - private static final String LOCATOR_ID = "ConfigurationHistory"; private static final String TITLE = "Configuration History";
private Integer resourceId; @@ -48,8 +47,8 @@ public class ConfigurationHistoryView extends TableSection { /** * Use this constructor to view config histories for all viewable Resources. */ - public ConfigurationHistoryView() { - super(LOCATOR_ID, TITLE); + public ConfigurationHistoryView(String locatorId) { + super(locatorId, TITLE); final ConfigurationHistoryDataSource datasource = new ConfigurationHistoryDataSource(); setDataSource(datasource); } @@ -59,8 +58,8 @@ public class ConfigurationHistoryView extends TableSection { * * @param resourceId a Resource ID */ - public ConfigurationHistoryView(int resourceId) { - super(LOCATOR_ID, TITLE, createCriteria(resourceId)); + public ConfigurationHistoryView(String locatorId, int resourceId) { + super(locatorId, TITLE, createCriteria(resourceId)); this.resourceId = resourceId; ConfigurationHistoryDataSource datasource = new ConfigurationHistoryDataSource(); setDataSource(datasource); @@ -157,11 +156,10 @@ public class ConfigurationHistoryView extends TableSection {
}
- // -------- Static Utility loaders ------------
- public static ConfigurationHistoryView getHistoryOf(int resourceId) { - return new ConfigurationHistoryView(resourceId); + public static ConfigurationHistoryView getHistoryOf(String locatorId, int resourceId) { + return new ConfigurationHistoryView(locatorId, resourceId); }
} 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 0a9359e..4970242 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 @@ -216,7 +216,7 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView } else if (MeasurementOOBView.VIEW_ID.equals(pageName)) { content = new MeasurementOOBView(this.extendLocatorId("SuspectMetrics")); } else if (ConfigurationHistoryView.VIEW_ID.equals(pageName)) { - content = new ConfigurationHistoryView(); + content = new ConfigurationHistoryView(this.extendLocatorId("ConfigHistory")); } else if (OperationHistoryView.VIEW_ID.equals(pageName)) { content = new OperationHistoryView(this.extendLocatorId("RecentOps")); } else if (AlertsView.VIEW_ID.equals(pageName)) {
commit f1000879c9f75dfa1153919ca5ca335ef6bf0286 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Oct 12 10:01:52 2010 -0400
Fix an issue where an F5 refresh while viewing a details page messed up the history and rendering. The problem seemed due to an assumption in the master-details impl that the master (list view) would always be rendered prior to a details page.
Also, fix an issue with null protection for RefreshableViews. Removed a showDetails() override in AbstractAlertDefinitionsView as the default behavior seems adequate.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java index 89a6c8b..bdaff67 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java @@ -18,7 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.alert.definitions;
-import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.widgets.Canvas; @@ -102,17 +101,6 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { }
@Override - public void showDetails(ListGridRecord record) { - Canvas canvas = getDetailsView(record); - setDetailsView(canvas); - - Integer id = record.getAttributeAsInt("id"); - History.newItem(getBasePath() + "/" + id.intValue(), false); - - switchToDetailsView(); - } - - @Override public Canvas getDetailsView(ListGridRecord record) { if (record == null) { return getDetailsView(0); 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 fe69ec7..b4aff2b 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 @@ -437,14 +437,18 @@ public class Table extends LocatableHLayout implements RefreshableView { private ArrayList<Integer> fieldSizes = new ArrayList<Integer>();
public void refresh(Criteria criteria) { - this.listGrid.invalidateCache(); - this.listGrid.setCriteria(criteria); - this.listGrid.markForRedraw(); + if (null != this.listGrid) { + this.listGrid.invalidateCache(); + this.listGrid.setCriteria(criteria); + this.listGrid.markForRedraw(); + } }
public void refresh() { - this.listGrid.invalidateCache(); - this.listGrid.markForRedraw(); + if (null != this.listGrid) { + this.listGrid.invalidateCache(); + this.listGrid.markForRedraw(); + } }
public void setTableTitle(String titleString) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java index c8ab12b..f5118f7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java @@ -85,6 +85,12 @@ public abstract class TableSection extends Table implements BookmarkableView { detailsHolder.hide();
addMember(detailsHolder); + + // if the detailsView is already defined it means we want the details view to be rendered prior to + // the master view, probably due to a direct navigation or refresh (like F5 when sitting on the details page) + if (null != detailsView) { + switchToDetailsView(); + } }
@Override @@ -222,6 +228,8 @@ public abstract class TableSection extends Table implements BookmarkableView { */ protected void switchToDetailsView() { Canvas contents = getTableContents(); + + // If the Table has not yet been initialized then ignore if (contents != null) { if (contents.isVisible()) { contents.animateHide(AnimationEffect.WIPE, new AnimationCallback() {
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 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 ebd4ec6f3c0ec9232970ee6c58ebdecf16b5b4a2 Author: John Mazzitelli mazz@redhat.com Date: Sat Oct 2 21:59:28 2010 -0400
be able to resize the new notif dialog
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 f707dc1..117fcb0 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
commit f0b0a15a1804d4606a03af3fb89ccfc0fb5bff91 Author: John Mazzitelli mazz@redhat.com Date: Sat Oct 2 21:32:53 2010 -0400
add gwt-log to eclipse classpath
diff --git a/.classpath b/.classpath index 0a567d7..1a1236c 100644 --- a/.classpath +++ b/.classpath @@ -252,6 +252,7 @@ <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/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"/>
commit 9325dbcc42782c4a89be13acb7243dc08b618ec2 Author: Ian Springer ian.springer@redhat.com Date: Fri Oct 1 21:15:08 2010 -0400
work on completing impl of map-of-simples in ConfigurationEditor
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 343a709..fdc2d9c 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 @@ -39,6 +39,7 @@ import com.smartgwt.client.types.TreeModelType; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.util.BooleanCallback; import com.smartgwt.client.util.SC; +import com.smartgwt.client.util.ValueCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Label; @@ -73,6 +74,8 @@ import com.smartgwt.client.widgets.form.validator.Validator; 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.CellSavedEvent; +import com.smartgwt.client.widgets.grid.events.CellSavedHandler; import com.smartgwt.client.widgets.grid.events.RecordClickEvent; import com.smartgwt.client.widgets.grid.events.RecordClickHandler; import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler; @@ -115,11 +118,13 @@ import org.rhq.core.domain.configuration.definition.constraint.FloatRangeConstra import org.rhq.core.domain.configuration.definition.constraint.IntegerRangeConstraint; 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.components.table.PropertyGrid; 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.util.CanvasUtility; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; @@ -561,12 +566,12 @@ public class ConfigurationEditor extends LocatableVLayout { }
private void buildMapsField(ArrayList<FormItem> fields, PropertyDefinitionMap propertyDefinitionMap, - PropertyMap propertyMap) { + final PropertyMap propertyMap) { // create the property grid - PropertyGrid propertyGrid = new PropertyGrid(); + 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(); @@ -575,29 +580,123 @@ public class ConfigurationEditor extends LocatableVLayout { // set the editors and attribute name where to find the record type propertyGrid.setEditorsMap("fieldType", editorsMap);
- if (propertyMap != null) { - ListGridRecord[] records = new ListGridRecord[propertyMap.getMap().size()]; + if (propertyDefinitionMap != null) { + ListGridRecord[] records = new ListGridRecord[propertyDefinitionMap.getPropertyDefinitions().size()]; int i = 0; - for (Property property : propertyMap.getMap().values()) { + // 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(); - record.setAttribute("Name", property.getName()); - record.setAttribute("Value", ((PropertySimple) property).getStringValue()); + 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; } propertyGrid.setData(records); }
- propertyGrid.draw(); + VLayout canvas = new VLayout(); + + canvas.addMember(propertyGrid); + + // Footer + 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 "open" maps. + if (propertyDefinitionMap.getPropertyDefinitions().isEmpty() && !propertyDefinitionMap.isReadOnly()) { + final IButton deleteButton = new LocatableIButton(extendLocatorId(propertyMap.getName()), "Delete"); + deleteButton.setDisabled(true); + deleteButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + final ListGridRecord[] selectedRecords = propertyGrid.getSelection(); + String noun = (selectedRecords.length == 1) ? "property" : "properties"; + String message = "Are you sure you want to delete the selected" + noun + "?"; + SC.ask(message, new BooleanCallback() { + public void execute(Boolean confirmed) { + if (confirmed) { + for (ListGridRecord selectedRecord : selectedRecords) { + propertyGrid.removeData(selectedRecord); + String propertyName = selectedRecord.getAttribute("Name"); + propertyMap.getMap().remove(propertyName); + } + } + } + }); + } + }); + footer.addMember(deleteButton);
- CanvasItem item = new CanvasItem(); - item.setCanvas(propertyGrid); - // item.setHeight(500); - item.setColSpan(3); - item.setEndRow(true); - item.setShowTitle(false); - fields.add(item); + propertyGrid.addSelectionChangedHandler(new SelectionChangedHandler() { + public void onSelectionChanged(SelectionEvent selectionEvent) { + int count = propertyGrid.getSelection().length; + deleteButton.setDisabled(count < 1); + } + }); + + final IButton newButton = new LocatableIButton(extendLocatorId(propertyMap.getName()), "New"); + newButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + SC.askforValue("Enter the name of the property to be added.", new ValueCallback() { + @Override + public void execute(String propertyName) { + if (propertyMap.get(propertyName) != null) { + CoreGUI.getMessageCenter().notify( + new Message("Cannot add property named '" + propertyName + + "', because the set already contains a property with that name.", + Message.Severity.Error, EnumSet.of(Message.Option.Transient))); + } else { + propertyMap.put(new PropertySimple(propertyName, null)); + + ListGridRecord record = new ListGridRecord(); + record.setAttribute("Name", propertyName); + record.setAttribute("Value", ""); + record.setAttribute("fieldType", "simpleText"); + + propertyGrid.addData(record); + propertyGrid.focus(); + propertyGrid.enableSpecificEditor(record); + + CoreGUI.getMessageCenter().notify(new Message("Added property to the set.", EnumSet.of( + Message.Option.Transient))); + } + } + }); + } + }); + footer.addMember(newButton); + }
+ propertyGrid.addCellSavedHandler(new CellSavedHandler() { + @Override + public void onCellSaved(CellSavedEvent cellSavedEvent) { + Record record = cellSavedEvent.getRecord(); + String propertyName = record.getAttribute("Name"); + PropertySimple prop = propertyMap.getSimple(propertyName); + if (prop == null) { + prop = new PropertySimple(propertyName, null); + } + String value = record.getAttribute("Value"); + prop.setStringValue(value); + } + }); + + propertyGrid.draw(); + + CanvasItem canvasItem = new CanvasItem(); + canvasItem.setCanvas(canvas); + // item.setHeight(500); + canvasItem.setColSpan(3); + canvasItem.setEndRow(true); + canvasItem.setShowTitle(false); + fields.add(canvasItem); }
private void buildListOfMapsField(final String locatorId, ArrayList<FormItem> fields, diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/PropertyGrid.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/PropertyGrid.java index ee6b7d7..73340fa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/PropertyGrid.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/PropertyGrid.java @@ -38,7 +38,6 @@ import com.smartgwt.client.widgets.grid.events.RecordClickHandler; * @author Dan Mihai Ile */ public class PropertyGrid extends ListGrid { - /** * Map to hold the editors */ @@ -56,7 +55,7 @@ public class PropertyGrid extends ListGrid { */ public PropertyGrid() {
- // create the 2 fields, one for names, other for values + // Create the 2 fields - one for names, other for values. ListGridField nameField = new ListGridField(); nameField.setCanEdit(false); ListGridField valueField = new ListGridField(); @@ -100,7 +99,7 @@ public class PropertyGrid extends ListGrid {
/** * Set the name of the attribute from where the row will get the editor name - * to be used on the {@link Map} from where the rows will get it's editors + * to be used on the {@link Map} from where the rows will get its editors * <p/> * When an edit starts the {@link PropertyGrid} will retrieve the key of the * editor form the row's attributes and use that key on the map to get the @@ -120,8 +119,9 @@ public class PropertyGrid extends ListGrid { * * @param record the record */ - private void enableSpecificEditor(Record record) { - if (editorsMap != null) { + public void enableSpecificEditor(Record record) { + boolean readOnly = record.getAttributeAsBoolean("readOnly"); + if (editorsMap != null && !readOnly) { String attribute = record.getAttribute(valueFieldAttribute); if (editorsMap.containsKey(attribute)) { FormItem formItem = editorsMap.get(attribute); @@ -129,5 +129,4 @@ public class PropertyGrid extends ListGrid { } } } - } \ No newline at end of file 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 429ef36..3a0b464 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 @@ -39,6 +39,10 @@ public class Message { public enum Severity { Info, Warning, Error, Fatal }; public enum Option { Transient, Sticky, BackgroundJobResult };
+ public Message(String conciseMessage) { + this(conciseMessage, (Severity)null); + } + public Message(String conciseMessage, Severity severity) { this(conciseMessage, null, severity); } @@ -46,7 +50,11 @@ public class Message { public Message(String conciseMessage, String detailedMessage) { this(conciseMessage, detailedMessage, null); } - + + public Message(String conciseMessage, EnumSet<Option> options) { + this(conciseMessage, null, options); + } + public Message(String conciseMessage, String detailedMessage, Severity severity) { this(conciseMessage, detailedMessage, severity, null); }
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 614e969e489795a4408f23e474507f174c95fdf2 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 e9b7788..cf9e470 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 @@ -304,12 +304,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 53a86e032a7df9e9c35bb50c9bde6fca72c722aa 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/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 c06c636..d6cfdba 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 @@ -628,6 +628,7 @@ public class ResourceTreeView extends LocatableVLayout { }
if (!root.equals(ResourceTreeView.this.rootResource)) { + if (treeGrid != null) { treeGrid.destroy(); }
commit 4d9fbbc3af633a1e59f5148edcb6bab040d618c0 Author: John Mazzitelli mazz@redhat.com Date: Fri Oct 1 18:59:21 2010 -0400
create the catch-all simple notif sender config editor
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 357943f..5b8b0b4 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 @@ -37,9 +37,41 @@ public abstract class AbstractNotificationSenderForm extends LocatableVLayout {
private Configuration configuration; private Configuration extraConfiguration; + private final String sender;
- public AbstractNotificationSenderForm(String locatorId) { + public AbstractNotificationSenderForm(String locatorId, AlertNotification notif, String sender) { super(locatorId); + + this.sender = sender; + + if (notif != null) { + // make our own deep copies of the configs so we can throw them away without + // affecting the actual notif in case the user clicks cancel + Configuration notifConfig = notif.getConfiguration(); + Configuration notifExtraConfig = notif.getExtraConfiguration(); + + if (notifConfig != null) { + configuration = notifConfig.deepCopy(true); + } else { + configuration = new Configuration(); // must not be null + } + if (notifExtraConfig != null) { + extraConfiguration = notifExtraConfig.deepCopy(true); + } else { + extraConfiguration = null; // allowed to be null + } + } else { + configuration = new Configuration(); + extraConfiguration = null; + } + } + + /** + * The name of the alert sender that is to be configured. + * @return the sender name + */ + public String getSender() { + return sender; }
/** 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 92d8f75..390357c 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 @@ -197,11 +197,33 @@ public class NewNotificationEditor extends LocatableDynamicForm { if (oldCanvas != null) { oldCanvas.markForDestroy(); } - - // TODO: need to create different forms for different types of senders - SimpleNotificationSenderForm newCanvas = new SimpleNotificationSenderForm(extendLocatorId(newAlertSender)); + AbstractNotificationSenderForm newCanvas = createNotificationSenderForm(newAlertSender); senderCanvasItem.setCanvas(newCanvas); - markForRedraw(); } + + private AbstractNotificationSenderForm createNotificationSenderForm(String sender) { + String newLocatorId = extendLocatorId(sender); + AbstractNotificationSenderForm newCanvas; + + // NOTE: today there is no way for an alert server plugin developer + // to be able to provide us with a custom UI component to render (like we used to be able + // to do when the ui was implemented in JSF and the server plugin can give us a JSF snippet). + // We have to hard code the names of the "special" plugins that require special UIs which + // are necessary to build the sender configuration for these special alert senders. + // 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 + } else if ("System Roles".equals(sender)) { + newCanvas = null; // TODO + } else if ("Resource Operations".equals(sender)) { + newCanvas = null; // TODO + } 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. + newCanvas = new SimpleNotificationSenderForm(newLocatorId, notificationToEdit, sender); + } + return newCanvas; + } } 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 a70bd82..4a16380 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 @@ -23,8 +23,15 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Label;
+import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +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.gwt.GWTServiceLookup; + /** * This notification form will be used for most alert senders since most alert senders * only need to be given a simple set of configuration properties where the user @@ -34,14 +41,35 @@ import com.smartgwt.client.widgets.Label; */ public class SimpleNotificationSenderForm extends AbstractNotificationSenderForm {
- public SimpleNotificationSenderForm(String locatorId) { - super(locatorId); + public SimpleNotificationSenderForm(String locatorId, AlertNotification notif, String sender) { + super(locatorId, notif, sender); }
@Override - protected void onInit() { - super.onInit(); - // TODO add config editor - addMember(new Label("simple form : " + getLocatorId())); + protected void onDraw() { + super.onDraw(); + + GWTServiceLookup.getAlertDefinitionService().getConfigurationDefinitionForSender(getSender(), + new AsyncCallback<ConfigurationDefinition>() { + @Override + public void onSuccess(ConfigurationDefinition configDef) { + ConfigurationEditor configEditor = new ConfigurationEditor(extendLocatorId("configEditor"), + configDef, getConfiguration()); + configEditor.setHeight(500); + configEditor.setWidth(500); + addMember(configEditor); + markForRedraw(); + } + + @Override + public void onFailure(Throwable caught) { + String errMsg = "Cannot get alert sender configuration definition"; + CoreGUI.getErrorHandler().handleError(errMsg, caught); + Label label = new Label(errMsg); + label.setIcon("[SKIN]/Dialog/error.png"); + addMember(label); + markForRedraw(); + } + }); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java index ee93aed..ceb427e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java @@ -22,6 +22,7 @@ import com.google.gwt.user.client.rpc.RemoteService;
import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.util.PageList;
@@ -43,4 +44,6 @@ public interface AlertDefinitionGWTService extends RemoteService { String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws Exception;
String[] getAllAlertSenders() throws Exception; + + ConfigurationDefinition getConfigurationDefinitionForSender(String sender) throws Exception; } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java index b906473..ada48ab 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java @@ -22,6 +22,7 @@ import java.util.List;
import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.exception.ThrowableUtil; @@ -122,4 +123,15 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } } + + @Override + public ConfigurationDefinition getConfigurationDefinitionForSender(String sender) throws Exception { + try { + ConfigurationDefinition results = alertNotifManager.getConfigurationDefinitionForSender(sender); + return SerialUtility.prepare(results, "getConfigurationDefinitionForSender"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + } \ No newline at end of file
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 3c5a00e40f93589f3fd333502d3b0d4ffde0c743 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 30 22:19:06 2010 -0400
cosmetic - reformatting
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 242aa4b..8da5ef0 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 @@ -82,6 +82,7 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag clearMessage();
this.label = createLabel(message); + addMember(this.label); markForRedraw();
commit 4288e5e7ec99e01767be54eb91a2698b2e515036 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 30 22:18:48 2010 -0400
tweak display of top/center message
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 02d3e33..242aa4b 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 @@ -40,8 +40,7 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag private static final String LOCATOR_ID = "MessageBar"; private static final int AUTO_HIDE_DELAY_MILLIS = 30000; // 30 seconds
- private static final Map<Message.Severity, String> SEVERITY_TO_STYLE_NAME_MAP = - new HashMap<Message.Severity, String>(); + private static final Map<Message.Severity, String> SEVERITY_TO_STYLE_NAME_MAP = new HashMap<Message.Severity, String>(); static { SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Info, "InfoBlock"); SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Warning, "WarnBlock"); @@ -49,8 +48,7 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Fatal, "FatalBlock"); }
- private static final Map<Message.Severity, String> SEVERITY_TO_ICON_MAP = - new HashMap<Message.Severity, String>(); + private static final Map<Message.Severity, String> SEVERITY_TO_ICON_MAP = new HashMap<Message.Severity, String>(); static { SEVERITY_TO_ICON_MAP.put(Message.Severity.Info, "info/icn_info_blue.png"); SEVERITY_TO_ICON_MAP.put(Message.Severity.Warning, "info/icn_info_orange.png"); @@ -70,7 +68,6 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag super.onDraw();
setWidth100(); - setAutoHeight(); setHeight(35);
setAlign(Alignment.CENTER); @@ -112,17 +109,15 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag private Label createLabel(Message message) { Label label = new Label();
- String contents = (message.getConciseMessage() != null) ? - message.getConciseMessage() : message.getDetailedMessage(); + String contents = (message.getConciseMessage() != null) ? message.getConciseMessage() : message + .getDetailedMessage(); label.setContents(contents); + label.setAlign(Alignment.CENTER);
String styleName = (contents != null) ? SEVERITY_TO_STYLE_NAME_MAP.get(message.getSeverity()) : null; label.setStyleName(styleName);
- label.setAutoHeight(); - label.setHeight(30); - label.setAutoWidth(); - label.setWidth("75%"); + label.setWidth(400);
String icon = (contents != null) ? SEVERITY_TO_ICON_MAP.get(message.getSeverity()) : null; label.setIcon(icon);
commit be9e31c733dcb1e75299025ed32caa3af28584a1 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 30 19:14:57 2010 -0400
minor fixes to SearchBarPanel for maintainability
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java index 0d920ef..657c4d3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java @@ -29,7 +29,6 @@ import com.smartgwt.client.widgets.form.fields.ComboBoxItem; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.SpacerItem; -import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.grid.ListGridField; @@ -44,6 +43,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** * @author Greg Hinkle + * @author Joseph Marques */ public class SearchBarPane extends LocatableHLayout {
@@ -54,6 +54,31 @@ public class SearchBarPane extends LocatableHLayout { setHeight(28); }
+ public enum SearchType { + RESOURCE("Resources"), // + GROUP("Resource Groups"); + + private String displayName; + + private SearchType(String displayName) { + this.displayName = displayName; + } + + public String getDisplayName() { + return displayName; + } + + public static String[] getValueMap() { + SearchType[] searchTypes = SearchType.values(); + String[] results = new String[searchTypes.length]; + int i = 0; + for (SearchType nextType : searchTypes) { + results[i++] = nextType.getDisplayName(); + } + return results; + } + } + @Override protected void onDraw() { super.onDraw(); @@ -63,9 +88,10 @@ public class SearchBarPane extends LocatableHLayout { form.setColWidths("120", "140", "400");
final SelectItem searchType = new SelectItem("searchType", "Search"); + String[] valueMap = SearchType.getValueMap(); + searchType.setValueMap(valueMap); + searchType.setValue(valueMap[0]); searchType.setWidth(120); - searchType.setValueMap("Resources", "Resource Groups"/*, "Bundles", "Packages", "Users", "Roles"*/); - searchType.setValue("Resources"); searchType.addChangedHandler(new ChangedHandler() { @Override public void onChanged(ChangedEvent event) { @@ -74,21 +100,7 @@ public class SearchBarPane extends LocatableHLayout { });
ComboBoxItem resourceSearch = getResourceComboBox(); - resourceSearch.setShowIfCondition(new FormItemIfFunction() { - public boolean execute(FormItem formItem, Object o, DynamicForm dynamicForm) { - return form.getValueAsString("searchType").equals("Resources"); - } - }); - ComboBoxItem groupSearch = getGroupComboBox(); - groupSearch.setShowIfCondition(new FormItemIfFunction() { - public boolean execute(FormItem formItem, Object o, DynamicForm dynamicForm) { - return form.getValueAsString("searchType").equals("Resource Groups"); - } - }); - - TextItem query = new TextItem("query"); - query.setShowTitle(false);
ButtonItem search = new ButtonItem("Search", "Search"); search.setStartRow(false); @@ -102,14 +114,7 @@ public class SearchBarPane extends LocatableHLayout { }
private ComboBoxItem getResourceComboBox() { - - final ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); - comboBox.setWidth(400); - comboBox.setShowTitle(false); - comboBox.setHint("resource search"); - comboBox.setShowHintInField(true); - - comboBox.setOptionDataSource(new ResourceDatasource()); + final ComboBoxItem comboBox = getBaseComboBox(SearchType.RESOURCE);
ListGridField nameField = ResourceDataSourceField.NAME.getListGridField(250); ListGridField descriptionField = ResourceDataSourceField.DESCRIPTION.getListGridField(); @@ -124,38 +129,13 @@ public class SearchBarPane extends LocatableHLayout {
comboBox.setValueField("id"); comboBox.setDisplayField(ResourceDataSourceField.NAME.propertyName()); - comboBox.setPickListWidth(800); - comboBox.setTextMatchStyle(TextMatchStyle.SUBSTRING); - comboBox.setCompleteOnTab(true); - - comboBox.addChangedHandler(new ChangedHandler() { - public void onChanged(ChangedEvent changedEvent) { - try { - Integer resourceId = (Integer) changedEvent.getValue(); - comboBox.setValue(""); - - String link = LinkManager.getResourceLink(resourceId); - if (!link.contains("#")) { - com.google.gwt.user.client.Window.Location.assign(link); - } else { - History.newItem(link.substring(1)); - } - } catch (Exception e) { - } - } - }); + comboBox.setOptionDataSource(new ResourceDatasource());
return comboBox; }
private ComboBoxItem getGroupComboBox() { - final ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); - comboBox.setWidth(400); - comboBox.setShowTitle(false); - comboBox.setHint("group search"); - comboBox.setShowHintInField(true); - - comboBox.setOptionDataSource(new ResourceGroupsDataSource()); + final ComboBoxItem comboBox = getBaseComboBox(SearchType.GROUP);
ListGridField nameField = ResourceGroupDataSourceField.NAME.getListGridField(250); ListGridField descriptionField = ResourceGroupDataSourceField.DESCRIPTION.getListGridField(); @@ -167,27 +147,57 @@ public class SearchBarPane extends LocatableHLayout {
comboBox.setValueField("id"); comboBox.setDisplayField(ResourceGroupDataSourceField.NAME.propertyName()); + comboBox.setOptionDataSource(new ResourceGroupsDataSource()); + + return comboBox; + } + + private ComboBoxItem getBaseComboBox(final SearchType searchType) { + final ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); + comboBox.setWidth(400); + comboBox.setShowTitle(false); + comboBox.setHint("search"); + comboBox.setShowHintInField(true); + comboBox.setPickListWidth(800); comboBox.setTextMatchStyle(TextMatchStyle.SUBSTRING); comboBox.setCompleteOnTab(true);
comboBox.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { - try { - Integer groupId = (Integer) changedEvent.getValue(); - comboBox.setValue(""); - - String link = LinkManager.getResourceGroupLink(groupId); - if (!link.contains("#")) { - com.google.gwt.user.client.Window.Location.assign(link); - } else { - History.newItem(link.substring(1)); - } - } catch (Exception e) { + //System.out.println("ChangedEvent: " + changedEvent.getValue()); + + Object intermediate = changedEvent.getValue(); + if (!(intermediate instanceof Integer)) { + return; + } + + Integer id = (Integer) changedEvent.getValue(); + comboBox.setValue(""); + + String link = null; + if (searchType == SearchType.RESOURCE) { + link = LinkManager.getResourceLink(id); + } else if (searchType == SearchType.GROUP) { + link = LinkManager.getResourceGroupLink(id); + } else { + throw new IllegalArgumentException("There is no global search type for " + searchType); + } + + if (!link.contains("#")) { + com.google.gwt.user.client.Window.Location.assign(link); + } else { + History.newItem(link.substring(1)); } } });
+ comboBox.setShowIfCondition(new FormItemIfFunction() { + public boolean execute(FormItem formItem, Object o, DynamicForm dynamicForm) { + return dynamicForm.getValueAsString("searchType").equals(searchType.getDisplayName()); + } + }); + return comboBox; }
commit acf0d09358c36e094bb041ebf5106a921009a51a Author: Joseph Marques joseph@redhat.com Date: Thu Sep 30 17:30:43 2010 -0400
prevent exceptions when using integer-based filters that might pass empty string instead of null
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 1184697..a717108 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 @@ -286,7 +286,7 @@ public abstract class RPCDataSource<T> extends DataSource { S result = null;
Object value = criteriaMap.get(paramName); - if (value == null) { + if (value == null || value.toString().equals("")) { // nothing to do, result is already null } else { String strValue = value.toString();
commit 3f5cc3fd0018b723b4082e9f31b20d94bed328c8 Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 30 21:55:29 2010 -0400
implement v2 of the new MessageCenter API; fix a few bugs in resource and plugin config relating to authz checking and to Save button
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java index 5e66764..9aaa0e9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java @@ -39,7 +39,7 @@ import org.rhq.enterprise.gui.coregui.client.CoreGUI; 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.inventory.resource.type.ResourceTypeRepository.MetadataType; -import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** @@ -129,13 +129,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new TransientMessage("[" + result + "] alert definitions enabled", Severity.Info)); + new Message("[" + result + "] alert definitions enabled.", Severity.Info)); ResourceAlertDefinitionsView.this.refresh(); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleTransientError("Failed to enable alert definitions", caught); + CoreGUI.getErrorHandler().handleError("Failed to enable alert definitions", caught); } }); } @@ -156,13 +156,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new TransientMessage("[" + result + "] alert definitions disabled", Severity.Info)); + new Message("[" + result + "] alert definitions disabled.", Severity.Info)); ResourceAlertDefinitionsView.this.refresh(); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleTransientError("Failed to disable alert definitions", caught); + CoreGUI.getErrorHandler().handleError("Failed to disable alert definitions.", caught); } }); } @@ -183,13 +183,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new TransientMessage("[" + result + "] alert definitions deleted", Severity.Info)); + new Message("[" + result + "] alert definitions deleted.", Severity.Info)); ResourceAlertDefinitionsView.this.refresh(); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleTransientError("Failed to delete alert definitions", caught); + CoreGUI.getErrorHandler().handleError("Failed to delete alert definitions.", caught); } }); } @@ -202,13 +202,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new TransientMessage("Alert definition is created", Severity.Info)); + new Message("Alert definition is created", Severity.Info)); alertDefinition.setId(result.intValue()); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleTransientError("Failed to create alert definition", caught); + CoreGUI.getErrorHandler().handleError("Failed to create alert definition.", caught); } }); } else { @@ -217,12 +217,12 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(AlertDefinition result) { CoreGUI.getMessageCenter().notify( - new TransientMessage("Alert definition is updated", Severity.Info)); + new Message("Alert definition is updated.", Severity.Info)); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleTransientError("Failed to update alert definition", caught); + CoreGUI.getErrorHandler().handleError("Failed to update alert definition.", caught); } }); } 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 544ded9..eb1e2d2 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 @@ -159,8 +159,8 @@ public class ConfigurationEditor extends LocatableVLayout {
private boolean readOnly = false; private Set<String> invalidPropertyNames = new HashSet<String>(); - private Set<ValidationStateChangeListener> validationStateChangeListeners = - new HashSet<ValidationStateChangeListener>(); + private Set<PropertyValueChangeListener> validationStateChangeListeners = + new HashSet<PropertyValueChangeListener>();
public static enum ConfigType { plugin, resource @@ -218,7 +218,7 @@ public class ConfigurationEditor extends LocatableVLayout { return this.valuesManager.hasErrors(); }
- public void addValidationStateChangeListener(ValidationStateChangeListener validationStateChangeListener) { + public void addValidationStateChangeListener(PropertyValueChangeListener validationStateChangeListener) { this.validationStateChangeListeners.add(validationStateChangeListener); }
@@ -250,11 +250,11 @@ public class ConfigurationEditor extends LocatableVLayout { EnumSet.of(ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); + //System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); definition = types.get(resourceTypeId).getResourceConfigurationDefinition(); if (definition == null) { loadingLabel.hide(); - showError("No configuration supported for this resource"); + showError("Configuration is not supported by this Resource."); } reload(); } @@ -276,10 +276,10 @@ public class ConfigurationEditor extends LocatableVLayout { EnumSet.of(ResourceTypeRepository.MetadataType.pluginConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); + //System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); definition = types.get(resourceTypeId).getPluginConfigurationDefinition(); if (definition == null) { - showError("No configuration supported for this resource"); + showError("Connection settings are not supported by this Resource."); } reload(); } @@ -556,6 +556,10 @@ public class ConfigurationEditor extends LocatableVLayout { } }
+ public Set<String> getInvalidPropertyNames() { + return this.invalidPropertyNames; + } + private void buildMapsField(ArrayList<FormItem> fields, PropertyDefinitionMap propertyDefinitionMap, PropertyMap propertyMap) { // create the property grid @@ -564,7 +568,7 @@ public class ConfigurationEditor extends LocatableVLayout { propertyGrid.getValuesField().setName("Value");
// create the editors - HashMap<String, FormItem> editorsMap = new HashMap<String, FormItem>(); + Map<String, FormItem> editorsMap = new HashMap<String, FormItem>(); TextItem textEditor = new TextItem(); editorsMap.put("simpleText", textEditor);
@@ -768,8 +772,8 @@ public class ConfigurationEditor extends LocatableVLayout { return record; }
- private FormItem buildSimpleField(ArrayList<FormItem> fields, PropertyDefinitionSimple propertyDefinition, - boolean oddRow, Property property) { + private FormItem buildSimpleField(ArrayList<FormItem> fields, final PropertyDefinitionSimple propertyDefinition, + boolean oddRow, final Property property) { final PropertySimple propertySimple = (PropertySimple) property;
FormItem valueItem = null; @@ -887,10 +891,11 @@ public class ConfigurationEditor extends LocatableVLayout { ConfigurationEditor.this.invalidPropertyNames.add(propertySimple.getName()); } boolean isValidNow = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); - if (isValidNow != wasValidBefore) { - for (ValidationStateChangeListener validationStateChangeListener : ConfigurationEditor.this.validationStateChangeListeners) { - validationStateChangeListener.validationStateChanged(isValidNow); - } + boolean validationStateChanged = (isValidNow != wasValidBefore); + for (PropertyValueChangeListener validationStateChangeListener : ConfigurationEditor.this.validationStateChangeListeners) { + PropertyValueChangeEvent event = new PropertyValueChangeEvent(property, propertyDefinition, + validationStateChanged, ConfigurationEditor.this.invalidPropertyNames); + validationStateChangeListener.propertyValueChanged(event); } } }); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeEvent.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeEvent.java new file mode 100644 index 0000000..2ba852d --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeEvent.java @@ -0,0 +1,59 @@ +/* + * 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.Set; + +import org.rhq.core.domain.configuration.Property; +import org.rhq.core.domain.configuration.definition.PropertyDefinition; + +/** + * @author Ian Springer + */ +public class PropertyValueChangeEvent { + private Property property; + private PropertyDefinition propertyDefinition; + private boolean validationStateChanged; + private Set<String> invalidPropertyNames; + + public PropertyValueChangeEvent(Property property, PropertyDefinition propertyDefinition, boolean validationStatechanged, + Set<String> invalidPropertyNames) { + this.property = property; + this.propertyDefinition = propertyDefinition; + this.validationStateChanged = validationStatechanged; + this.invalidPropertyNames = invalidPropertyNames; + } + + public Property getProperty() { + return property; + } + + public PropertyDefinition getPropertyDefinition() { + return propertyDefinition; + } + + public boolean isValidationStateChanged() { + return validationStateChanged; + } + + public Set<String> getInvalidPropertyNames() { + return invalidPropertyNames; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeListener.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeListener.java new file mode 100644 index 0000000..0ed46f4 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyValueChangeListener.java @@ -0,0 +1,30 @@ +/* + * 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; + +/** + * A listener that can register to be notified by a {@link ConfigurationEditor} when a configuration property's value + * changes. + * + * @author Ian Springer + */ +public interface PropertyValueChangeListener { + void propertyValueChanged(PropertyValueChangeEvent event); +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java deleted file mode 100644 index 154c731..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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; - -/** - * @author Ian Springer - */ -public interface ValidationStateChangeListener { - void validationStateChanged(boolean isValid); -} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java index 1008b83..4e66027 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java @@ -37,7 +37,6 @@ 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.inventory.groups.ResourceGroupListView; import org.rhq.enterprise.gui.coregui.client.util.message.Message; -import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage;
/** * A wizard for creating a new Resource group. @@ -92,13 +91,11 @@ public class GroupCreateWizard extends AbstractWizard {
public void onSuccess(ResourceGroup result) { String groupUrl = LinkManager.getResourceGroupLink(result.getId()); - CoreGUI.getMessageCenter().notify( - new TransientMessage("Resource group created. [<a href='" + groupUrl + "'>View Group</a>]", - Message.Severity.Info)); - CoreGUI.getMessageCenter().notify( - new Message("Created new " + result.getGroupCategory().name().toLowerCase() + " Resource group '" - + result.getName() + "' with " + memberStep.getSelectedResourceIds().length + " members.", - Message.Severity.Info)); + String conciseMessage = "Resource group created. [<a href='" + groupUrl + "'>View Group</a>]"; + String detailedMessage = + "Created new " + result.getGroupCategory().name().toLowerCase() + " Resource group '" + + result.getName() + "' with " + memberStep.getSelectedResourceIds().length + " members."; + CoreGUI.getMessageCenter().notify(new Message(conciseMessage, detailedMessage)); resourceGroupListView.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 b002f0b..f5afb2c 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 @@ -18,6 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration;
+import java.util.EnumSet; + import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.IButton; @@ -33,19 +35,21 @@ 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.components.configuration.ConfigurationEditor; -import org.rhq.enterprise.gui.coregui.client.components.configuration.ValidationStateChangeListener; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; -import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** + * A view for editing a Resource's configuration. + * * @author Greg Hinkle * @author Ian Springer */ -public class ResourceConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { +public class ResourceConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { private Resource resource; private ResourcePermission resourcePermission; private ConfigurationEditor editor; @@ -76,20 +80,30 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements V save(); } }); - this.saveButton.disable(); toolStrip.addMember(saveButton); + + addMember(toolStrip); + reloadConfiguration();
- editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId()); + if (!this.resourcePermission.isConfigureWrite()) { + Message message = new Message("You do not have permission to edit this Resource'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); + } + editor = new ConfigurationEditor(this.extendLocatorId("Editor"), resource.getId(), + resource.getResourceType().getId()); editor.setOverflow(Overflow.AUTO); editor.addValidationStateChangeListener(this); editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); - - addMember(toolStrip); addMember(editor); - - Message message = new TransientMessage("You do not have permission to edit this Resource's configuration.", - Message.Severity.Info, true); - CoreGUI.getMessageCenter().notify(message); }
private void save() { @@ -103,24 +117,31 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements V
public void onSuccess(ResourceConfigurationUpdate result) { CoreGUI.getMessageCenter().notify( - new Message("Configuration updated for Resource [" + resource.getName() + "].", + new Message("Configuration updated.", + "Configuration updated for Resource [" + resource.getName() + "].", Message.Severity.Info)); - + reloadConfiguration(); } }); }
@Override - public void validationStateChanged(boolean isValid) { + public void propertyValueChanged(PropertyValueChangeEvent event) { MessageCenter messageCenter = CoreGUI.getMessageCenter(); Message message; - if (isValid) { - this.saveButton.enable(); - message = new TransientMessage("All configuration properties now have valid values, so the configuration can now be saved.", Message.Severity.Info); + 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)); + } 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.Severity.Error, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); + } + messageCenter.notify(message); } else { - this.saveButton.disable(); - message = new TransientMessage("One or more configuration properties have invalid values. The values must be corrected before the configuration can be saved.", Message.Severity.Error, true); + this.saveButton.enable(); } - 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 1483cfa..4556da0 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 @@ -18,6 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory;
+import java.util.EnumSet; + import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.events.ClickEvent; @@ -32,19 +34,21 @@ 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.components.configuration.ConfigurationEditor; -import org.rhq.enterprise.gui.coregui.client.components.configuration.ValidationStateChangeListener; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; -import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** + * A view for editing a Resource's plugin configuration (aka connection settings). + * * @author Greg Hinkle * @author Ian Springer */ -public class PluginConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { +public class PluginConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { private Resource resource; private ResourcePermission resourcePermission; private ConfigurationEditor editor; @@ -76,20 +80,30 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Val } }); this.saveButton.disable(); - toolStrip.addMember(saveButton); + toolStrip.addMember(this.saveButton); + + addMember(toolStrip); + reloadConfiguration(); + + if (!this.resourcePermission.isInventory()) { + Message message = new Message("You do not have permission to edit this Resource's connection settings.", + Message.Severity.Info, EnumSet.of(Message.Option.Transient)); + CoreGUI.getMessageCenter().notify(message); + } + }
- editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId(), - ConfigurationEditor.ConfigType.plugin); + private void reloadConfiguration() { + this.saveButton.disable(); + if (editor != null) { + editor.destroy(); + removeMember(editor); + } + editor = new ConfigurationEditor(extendLocatorId("Editor"), resource.getId(), + resource.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin); editor.setOverflow(Overflow.AUTO); editor.addValidationStateChangeListener(this); editor.setReadOnly(!this.resourcePermission.isInventory()); - - addMember(toolStrip); addMember(editor); - - Message message = new TransientMessage("You do not have permission to edit this Resource's connection properties.", - Message.Severity.Info, true); - CoreGUI.getMessageCenter().notify(message); }
private void save() { @@ -103,24 +117,31 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Val
public void onSuccess(PluginConfigurationUpdate result) { CoreGUI.getMessageCenter().notify( - new Message("Connection settings updated for Resource [" + resource.getName() + "].", + new Message("Connection settings updated.", + "Connection settings updated for Resource [" + resource.getName() + "].", Message.Severity.Info)); - + reloadConfiguration(); } }); }
@Override - public void validationStateChanged(boolean isValid) { + public void propertyValueChanged(PropertyValueChangeEvent event) { MessageCenter messageCenter = CoreGUI.getMessageCenter(); Message message; - if (isValid) { - this.saveButton.enable(); - message = new TransientMessage("All connection properties now have valid values, so the configuration can now be saved.", Message.Severity.Info); + if (event.isValidationStateChanged()) { + if (event.getInvalidPropertyNames().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)); + } 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.Severity.Error, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); + } + messageCenter.notify(message); } else { - this.saveButton.disable(); - message = new TransientMessage("One or more connection properties have invalid values. The values must be corrected before the configuration can be saved.", Message.Severity.Error, true); + this.saveButton.enable(); } - messageCenter.notify(message); } } \ No newline at end of file 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 6e5f80b..49bb67e 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 @@ -20,31 +20,21 @@ package org.rhq.enterprise.gui.coregui.client.util;
import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.util.message.Message; -import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage;
/** * @author Greg Hinkle */ public class ErrorHandler { - public void handleError(String message) { handleError(message, null); }
public void handleError(String message, Throwable t) { - Message errorMessage = new Message(message, (t == null) ? null : t.toString(), Message.Severity.Error); - CoreGUI.getMessageCenter().notify(errorMessage); - - if (t != null) { - t.printStackTrace(); - } - } - - public void handleTransientError(String message, Throwable t) { - Message errorMessage = new TransientMessage(message, (t == null) ? null : t.toString(), Message.Severity.Error); + Message errorMessage = new Message(message, (t == null) ? null : t.toString(), Message.Severity.Fatal); CoreGUI.getMessageCenter().notify(errorMessage);
if (t != null) { + System.err.println(message); t.printStackTrace(); } } 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 97cc7ab..429ef36 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 @@ -19,36 +19,55 @@ package org.rhq.enterprise.gui.coregui.client.util.message;
import java.util.Date; +import java.util.EnumSet;
/** + * 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 title; - protected String detail; + protected String conciseMessage; + protected String detailedMessage; protected Date fired = new Date(); protected Severity severity; + protected EnumSet<Option> options;
// TODO: Add Debug severity? - public enum Severity { Info, Warning, Error }; + public enum Severity { Info, Warning, Error, Fatal }; + public enum Option { Transient, Sticky, BackgroundJobResult }; + + public Message(String conciseMessage, Severity severity) { + this(conciseMessage, null, severity); + } + + public Message(String conciseMessage, String detailedMessage) { + this(conciseMessage, detailedMessage, null); + } + + public Message(String conciseMessage, String detailedMessage, Severity severity) { + this(conciseMessage, detailedMessage, severity, null); + }
- public Message(String title, Severity severity) { - this(title, null, severity); + public Message(String conciseMessage, Severity severity, EnumSet<Option> options) { + this(conciseMessage, null, severity, options); }
- public Message(String title, String detail, Severity severity) { - this.title = title; - this.detail = detail; + public Message(String conciseMessage, String detailedMessage, Severity severity, EnumSet<Option> options) { + this.conciseMessage = conciseMessage; + this.detailedMessage = detailedMessage; this.severity = (severity != null) ? severity : Severity.Info; + this.options = (options != null) ? options : EnumSet.noneOf(Option.class); }
- public String getTitle() { - return title; + public String getConciseMessage() { + return conciseMessage; }
- public String getDetail() { - return detail; + public String getDetailedMessage() { + return detailedMessage; }
public Date getFired() { @@ -59,13 +78,26 @@ public class Message { return severity; }
+ public boolean isTransient() { + return options.contains(Option.Transient); + } + + public boolean isSticky() { + return options.contains(Option.Sticky); + } + + public boolean isBackgroundJobResult() { + return options.contains(Option.BackgroundJobResult); + } + @Override public String toString() { return "Message{" + - "title='" + title + ''' + - ", detail='" + detail + ''' + - ", fired=" + fired + - ", severity=" + severity + + "conciseMessage='" + this.conciseMessage + ''' + + ", detailedMessage='" + this.detailedMessage + ''' + + ", fired=" + this.fired + + ", severity=" + this.severity + + ", options=" + this.options + '}'; } } 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 b03499f..02d3e33 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 @@ -46,6 +46,7 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Info, "InfoBlock"); SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Warning, "WarnBlock"); SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Error, "ErrorBlock"); + SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Fatal, "FatalBlock"); }
private static final Map<Message.Severity, String> SEVERITY_TO_ICON_MAP = @@ -70,7 +71,7 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag
setWidth100(); setAutoHeight(); - setHeight(40); + setHeight(35);
setAlign(Alignment.CENTER);
@@ -79,18 +80,16 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag
@Override public void onMessage(Message message) { - if (message instanceof TransientMessage) { - TransientMessage transientMessage = (TransientMessage)message; - + if (!message.isBackgroundJobResult()) { // First clear any previous message. clearMessage();
- this.label = createLabel(transientMessage); - addMember(this.label); + this.label = createLabel(message); + addMember(this.label); markForRedraw();
// Auto-clear the message after 30 seconds unless it's been designated as sticky. - if (!transientMessage.isSticky()) { + if (!message.isSticky()) { Timer hideTimer = new Timer() { @Override public void run() { @@ -113,17 +112,15 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag private Label createLabel(Message message) { Label label = new Label();
- String contents = message.getTitle(); - if (message.getDetail() != null) { - contents += ": " + message.getDetail(); - } + String contents = (message.getConciseMessage() != null) ? + message.getConciseMessage() : message.getDetailedMessage(); label.setContents(contents);
String styleName = (contents != null) ? SEVERITY_TO_STYLE_NAME_MAP.get(message.getSeverity()) : null; label.setStyleName(styleName);
label.setAutoHeight(); - label.setHeight(35); + label.setHeight(30); label.setAutoWidth(); label.setWidth("75%");
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java index a3c29dd..a9070b1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java @@ -29,12 +29,14 @@ public class MessageCenter { private LinkedList<Message> messages = new LinkedList<Message>(); private List<MessageListener> listeners = new ArrayList<MessageListener>();
- private static final int MAX_MESSAGES = 100; + private static final int MAX_MESSAGES = 50;
public void notify(Message message) { - this.messages.add(message); - if (messages.size() > MAX_MESSAGES) { - messages.removeFirst(); + if (!message.isTransient()) { + this.messages.add(message); + if (messages.size() > MAX_MESSAGES) { + messages.removeFirst(); + } } for (MessageListener listener : listeners) { listener.onMessage(message); @@ -45,6 +47,11 @@ public class MessageCenter { this.listeners.add(listener); }
+ /** + * Returns a list of recently published non-transient messages. + * + * @return a list of recently published non-transient messages + */ public List<Message> getMessages() { return messages; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java index 5d81646..d51bc47 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java @@ -86,7 +86,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter MenuItem[] items = new MenuItem[messages.size()]; for (int i = 0, messagesSize = messages.size(); i < messagesSize; i++) { final Message message = messages.get(i); - MenuItem messageItem = new MenuItem(message.title, getSeverityIcon(message.severity)); + MenuItem messageItem = new MenuItem(message.conciseMessage, getSeverityIcon(message.severity));
items[i] = messageItem;
@@ -116,7 +116,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter form.setWrapItemTitles(false);
StaticTextItem title = new StaticTextItem("title", "Title"); - title.setValue(message.title); + title.setValue(message.conciseMessage);
StaticTextItem severity = new StaticTextItem("severity", "Severity"); FormItemIcon severityIcon = new FormItemIcon(); @@ -129,7 +129,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter
StaticTextItem detail = new StaticTextItem("detail", "Detail"); detail.setTitleOrientation(TitleOrientation.TOP); - detail.setValue(message.detail); + detail.setValue(message.detailedMessage); detail.setColSpan(2);
ButtonItem okButton = new ButtonItem("Ok", "Ok"); @@ -139,7 +139,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter form.setItems(title, severity, date, detail, okButton);
final Window window = new LocatableWindow(this.extendLocatorId("Message")); - window.setTitle(message.title); + window.setTitle(message.conciseMessage); window.setWidth(600); window.setHeight(400); window.setIsModal(true); @@ -157,8 +157,8 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter }
public void onMessage(final Message message) { - if (!(message instanceof TransientMessage)) { - final Label label = new Label(message.title); + if (!message.isTransient()) { + final Label label = new Label(message.conciseMessage); label.setMargin(5); label.setAutoFit(true); label.setHeight(25); @@ -168,7 +168,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter
label.setIcon(iconSrc);
- label.setTooltip(message.detail); + label.setTooltip(message.detailedMessage);
label.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { @@ -196,13 +196,14 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter private String getSeverityIcon(Message.Severity severity) { String iconSrc = null; switch (severity) { - case Info: + case Info: iconSrc = "info/icn_info_blue.png"; break; - case Warning: + case Warning: iconSrc = "info/icn_info_orange.png"; break; - case Error: + case Error: + case Fatal: iconSrc = "info/icn_info_red.png"; break; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/TransientMessage.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/TransientMessage.java deleted file mode 100644 index 318c4a5..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/TransientMessage.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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.util.message; - -/** - * @author Ian Springer - */ -public class TransientMessage extends Message { - private boolean sticky; - - public TransientMessage(String title, Severity severity) { - super(title, severity); - } - - public TransientMessage(String title, String detail, Severity severity) { - super(title, detail, severity); - } - - public TransientMessage(String title, Severity severity, boolean sticky) { - this(title, null, severity, sticky); - } - - public TransientMessage(String title, String detail, Severity severity, boolean sticky) { - super(title, detail, severity); - this.sticky = sticky; - } - - public boolean isSticky() { - return this.sticky; - } -}
commit dd8fc9bcd360542eb8933be9c34995d06e638fcb Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 30 17:28:16 2010 -0400
write transient messages when enabling/disabling/creating alert defs
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java index cbf368d..5e66764 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java @@ -39,7 +39,7 @@ import org.rhq.enterprise.gui.coregui.client.CoreGUI; 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.inventory.resource.type.ResourceTypeRepository.MetadataType; -import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** @@ -129,13 +129,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new Message("[" + result + "] alert definitions enabled", Severity.Info)); + new TransientMessage("[" + result + "] alert definitions enabled", Severity.Info)); ResourceAlertDefinitionsView.this.refresh(); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to enable alert definitions", caught); + CoreGUI.getErrorHandler().handleTransientError("Failed to enable alert definitions", caught); } }); } @@ -156,13 +156,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new Message("[" + result + "] alert definitions disabled", Severity.Info)); + new TransientMessage("[" + result + "] alert definitions disabled", Severity.Info)); ResourceAlertDefinitionsView.this.refresh(); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to disable alert definitions", caught); + CoreGUI.getErrorHandler().handleTransientError("Failed to disable alert definitions", caught); } }); } @@ -183,13 +183,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { @Override public void onSuccess(Integer result) { CoreGUI.getMessageCenter().notify( - new Message("[" + result + "] alert definitions deleted", Severity.Info)); + new TransientMessage("[" + result + "] alert definitions deleted", Severity.Info)); ResourceAlertDefinitionsView.this.refresh(); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to delete alert definitions", caught); + CoreGUI.getErrorHandler().handleTransientError("Failed to delete alert definitions", caught); } }); } @@ -201,13 +201,14 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { Integer.valueOf(resource.getId()), new AsyncCallback<Integer>() { @Override public void onSuccess(Integer result) { - CoreGUI.getMessageCenter().notify(new Message("Alert definition is created", Severity.Info)); + CoreGUI.getMessageCenter().notify( + new TransientMessage("Alert definition is created", Severity.Info)); alertDefinition.setId(result.intValue()); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create alert definition", caught); + CoreGUI.getErrorHandler().handleTransientError("Failed to create alert definition", caught); } }); } else { @@ -215,12 +216,13 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { alertDefinition, true, new AsyncCallback<AlertDefinition>() { @Override public void onSuccess(AlertDefinition result) { - CoreGUI.getMessageCenter().notify(new Message("Alert definition is updated", Severity.Info)); + CoreGUI.getMessageCenter().notify( + new TransientMessage("Alert definition is updated", Severity.Info)); }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to update alert definition", caught); + CoreGUI.getErrorHandler().handleTransientError("Failed to update alert definition", caught); } }); }
commit b3cf656d35e05a0c0b1130f994747900596a8f0e Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 30 17:27:56 2010 -0400
provide a convienence method to write out a transient error message
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 d410c54..6e5f80b 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 @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client.util;
import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage;
/** * @author Greg Hinkle @@ -38,4 +39,13 @@ public class ErrorHandler { t.printStackTrace(); } } + + public void handleTransientError(String message, Throwable t) { + Message errorMessage = new TransientMessage(message, (t == null) ? null : t.toString(), Message.Severity.Error); + CoreGUI.getMessageCenter().notify(errorMessage); + + if (t != null) { + t.printStackTrace(); + } + } }
commit 54400ac63137b081d50b7bdac7419b44e9ab2dbc Merge: 9cfec33... cd224c2... Author: John Sanda jsanda@redhat.com Date: Thu Sep 30 16:48:03 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit cd224c2d8b3c2a2ed53d5b66ec4bbdb66b404a41 Author: John Mazzitelli mazz@redhat.com Date: Fri Oct 1 14:33:01 2010 -0400
start building framework for the different forms needed for the different senders
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 new file mode 100644 index 0000000..357943f --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.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, 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 org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * Superclass to all alert senders' forms. Instances of this class + * are displayed when switching the drop-down option menu selecting + * a specific sender. + * + * @author John Mazzitelli + */ +public abstract class AbstractNotificationSenderForm extends LocatableVLayout { + + private Configuration configuration; + private Configuration extraConfiguration; + + public AbstractNotificationSenderForm(String locatorId) { + super(locatorId); + } + + /** + * The {@link AlertNotification#getConfiguration()} for the new alert definition notification. + * + * @return the configuration + */ + public Configuration getConfiguration() { + return configuration; + } + + public void setConfiguration(Configuration configuration) { + this.configuration = configuration; + } + + /** + * The {@link AlertNotification#getExtraConfiguration()} for the new alert definition notification. + * + * @return the extra configuration + */ + public Configuration getExtraConfiguration() { + return extraConfiguration; + } + + public void setExtraConfiguration(Configuration extraConfiguration) { + this.extraConfiguration = extraConfiguration; + } +} 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 5da3c43..92d8f75 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 @@ -28,12 +28,14 @@ import java.util.LinkedHashMap;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; -import com.smartgwt.client.widgets.form.DynamicForm; -import com.smartgwt.client.widgets.form.FormItemIfFunction; +import com.smartgwt.client.widgets.Canvas; 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.SpacerItem; +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;
@@ -54,6 +56,7 @@ public class NewNotificationEditor extends LocatableDynamicForm { private final Runnable closeFunction; // this is called after a button is pressed and the editor should close
private SelectItem notificationSenderSelectItem; + private CanvasItem senderCanvasItem;
public NewNotificationEditor(String locatorId, AlertDefinition alertDefinition, ArrayList<AlertNotification> notifs, AlertNotification notifToEdit, Runnable closeFunc) { @@ -71,17 +74,30 @@ public class NewNotificationEditor extends LocatableDynamicForm {
setMargin(20);
+ // this is the container that will house the sender-specific form components + senderCanvasItem = new CanvasItem(); + senderCanvasItem.setShowTitle(false); + senderCanvasItem.setColSpan(2); + notificationSenderSelectItem = new SelectItem("notificationSender", "Notification Sender"); + notificationSenderSelectItem.setDefaultToFirstOption(true); + notificationSenderSelectItem.setWrapTitle(false); + notificationSenderSelectItem.setRedrawOnChange(true); + notificationSenderSelectItem.setWidth("*");
if (notificationToEdit != null) { // we were given a notification to edit, you can't change the sender type, its the only option notificationSenderSelectItem.setDisabled(true); + String senderName = notificationToEdit.getSenderName(); LinkedHashMap<String, String> senders = new LinkedHashMap<String, String>(1); - senders.put(notificationToEdit.getSenderName(), notificationToEdit.getSenderName()); + senders.put(senderName, senderName); notificationSenderSelectItem.setValueMap(senders); + switchToAlertSender(senderName); + senderCanvasItem.setVisible(true); } else { notificationSenderSelectItem.setValueMap("Loading..."); notificationSenderSelectItem.setDisabled(true); + senderCanvasItem.setVisible(false); // don't show it yet, until we determine what senders exist // we are creating a new notification, need to provide all senders as options GWTServiceLookup.getAlertDefinitionService().getAllAlertSenders(new AsyncCallback<String[]>() { @Override @@ -94,6 +110,8 @@ public class NewNotificationEditor extends LocatableDynamicForm { notificationSenderSelectItem.setValueMap(senders); notificationSenderSelectItem.setDisabled(false); notificationSenderSelectItem.redraw(); + switchToAlertSender(result[0]); + senderCanvasItem.show(); } else { CoreGUI.getErrorHandler().handleError("No alert senders available"); } @@ -106,10 +124,13 @@ public class NewNotificationEditor extends LocatableDynamicForm { }); }
- notificationSenderSelectItem.setDefaultToFirstOption(true); - notificationSenderSelectItem.setWrapTitle(false); - notificationSenderSelectItem.setRedrawOnChange(true); - notificationSenderSelectItem.setWidth("*"); + notificationSenderSelectItem.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + String newAlertSender = event.getValue().toString(); + switchToAlertSender(newAlertSender); + } + });
SpacerItem spacer1 = new SpacerItem(); spacer1.setColSpan(2); @@ -145,7 +166,7 @@ public class NewNotificationEditor extends LocatableDynamicForm { ArrayList<FormItem> formItems = new ArrayList<FormItem>(); formItems.add(notificationSenderSelectItem); formItems.add(spacer1); - // TODO put config editor here + formItems.add(senderCanvasItem); formItems.add(spacer2); formItems.add(ok); formItems.add(cancel); @@ -166,20 +187,21 @@ public class NewNotificationEditor extends LocatableDynamicForm { notif = notificationToEdit; }
- // notif.setConfiguration(configuration); - // notif.setExtraConfiguration(extraConfiguration); + AbstractNotificationSenderForm senderForm = (AbstractNotificationSenderForm) senderCanvasItem.getCanvas(); + notif.setConfiguration(senderForm.getConfiguration()); + notif.setExtraConfiguration(senderForm.getExtraConfiguration()); }
- private class ShowIfSenderFunction implements FormItemIfFunction { - private final String senderName; - - public ShowIfSenderFunction(String senderName) { - this.senderName = senderName; + private void switchToAlertSender(String newAlertSender) { + Canvas oldCanvas = senderCanvasItem.getCanvas(); + if (oldCanvas != null) { + oldCanvas.markForDestroy(); }
- public boolean execute(FormItem item, Object value, DynamicForm form) { - String selectedSenderString = form.getValue("notificationSender").toString(); - return senderName.equals(selectedSenderString); - } + // TODO: need to create different forms for different types of senders + SimpleNotificationSenderForm newCanvas = new SimpleNotificationSenderForm(extendLocatorId(newAlertSender)); + senderCanvasItem.setCanvas(newCanvas); + + markForRedraw(); } } 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 bc585ac..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 @@ -237,7 +237,7 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement configField.setWidth("75%"); getListGrid().setFields(senderField, configField);
- getListGrid().addDoubleClickHandler(new DoubleClickHandler() { + setListGridDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { ListGrid listGrid = (ListGrid) event.getSource(); 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 new file mode 100644 index 0000000..a70bd82 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.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, 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 com.smartgwt.client.widgets.Label; + +/** + * This notification form will be used for most alert senders since most alert senders + * only need to be given a simple set of configuration properties where the user + * provides values via the normal configuration editor. + * + * @author John Mazzitelli + */ +public class SimpleNotificationSenderForm extends AbstractNotificationSenderForm { + + public SimpleNotificationSenderForm(String locatorId) { + super(locatorId); + } + + @Override + protected void onInit() { + super.onInit(); + // TODO add config editor + addMember(new Label("simple form : " + getLocatorId())); + } +}
commit 7101d3d1535d107523615a2a7f7d4d56ec1f537e Author: John Mazzitelli mazz@redhat.com Date: Fri Oct 1 14:32:00 2010 -0400
provide a way to add a double-click handler to the Table API
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 c933047..f5c9a40 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 @@ -35,6 +35,8 @@ import com.smartgwt.client.widgets.Img; import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.events.DoubleClickEvent; +import com.smartgwt.client.widgets.events.DoubleClickHandler; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.SelectItem; @@ -122,6 +124,7 @@ public class Table extends LocatableHLayout {
;
+ private DoubleClickHandler doubleClickHandler; private List<TableActionInfo> tableActions = new ArrayList<TableActionInfo>(); private boolean tableActionDisableOverride = false; protected List<Canvas> extraWidgets = new ArrayList<Canvas>(); @@ -259,6 +262,15 @@ public class Table extends LocatableHLayout { // Now give subclasses a chance to configure the table configureTable();
+ listGrid.addDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + if (doubleClickHandler != null && !getTableActionDisableOverride()) { + doubleClickHandler.onDoubleClick(event); + } + } + }); + setTableInfo(new Label("Total: " + listGrid.getTotalRows()));
// NOTE: It is essential that we wait to hide any excluded fields until after super.onDraw() is called, since @@ -480,6 +492,10 @@ public class Table extends LocatableHLayout { tableActions.add(info); }
+ public void setListGridDoubleClickHandler(DoubleClickHandler handler) { + doubleClickHandler = handler; + } + public void addExtraWidget(Canvas canvas) { this.extraWidgets.add(canvas); } @@ -502,6 +518,9 @@ public class Table extends LocatableHLayout { * buttons regardless of which rows are selected. This method let's * you set this override-disable flag. * + * Note: this also effects the double-click handler - if this disable override + * is on, the double-click handler is not called. + * * @param disabled if true, all table action buttons will be disabled * if false, table action buttons will be enabled based on their predefined * selection enablement rule.
commit ef62478885fcdd851184b31e9d5a94ebad5f7d29 Author: Ian Springer ian.springer@redhat.com Date: Fri Oct 1 14:51:33 2010 -0400
integrate gwt-log and convert over all System.out.println's to logging; add test config view (#TestConfig) for testing config editor
diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index c8dce21..21dd681 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -107,6 +107,12 @@ <version>1.0.0</version> </dependency>
+ <dependency> + <groupId>com.google.code.gwt-log</groupId> + <artifactId>gwt-log</artifactId> + <version>3.0.3</version> + </dependency> + <!-- for file uploads --> <dependency> <groupId>commons-fileupload</groupId> 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 8db747c..ed2ce42 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 @@ -1,5 +1,5 @@ -<!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"> +<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.0//EN" + "http://google-web-toolkit.googlecode.com/svn/releases/2.0/distro-source/core/src/gwt-module.dtd">
<module>
@@ -11,20 +11,45 @@ <inherits name="com.smartgwt.tools.SmartGwtTools"/>
<inherits name='com.google.gwt.user.theme.standard.Standard'/> -<!-- - <inherits name="com.smartclient.theme.graphite.Graphite"/> ---> + <!-- + <inherits name="com.smartclient.theme.graphite.Graphite"/> + -->
<inherits name='ca.nanometrics.gflot.GFlot'/>
<!-- - <inherits name='com.google.gwt.widgetideas.WidgetIdeas'/> + <inherits name='com.google.gwt.widgetideas.WidgetIdeas'/> -->
-<!-- <generate-with class="org.rhq.core.rebind.RecordBuilderGenerator"> + <!-- ============================ gwt-log ============================= --> + + <!-- For development, a default of 'DEBUG' is recommended. --> + <inherits name="com.allen_sauer.gwt.log.gwt-log-DEBUG" /> + + <!-- For production, most teams prefer to set the default log level to 'OFF'. --> + <!--<inherits name="com.allen_sauer.gwt.log.gwt-log-OFF" />--> + + <!-- + Enable experimental WindowLogger, which logs messages to a separate + popup window. There are currently a couple of restrictions: + + 1. When Firefox is configured to open new Windows as new tabs, + WindowLogger does not work + 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: + --> + <set-property name="log_DivLogger" value="DISABLED" /> + + <!-- + <generate-with class="org.rhq.core.rebind.RecordBuilderGenerator"> <when-type-assignable class="org.rhq.core.domain.util.Recordizable"/> - </generate-with>--> - + </generate-with> + -->
<replace-with class="org.rhq.enterprise.gui.coregui.client.components.upload.DynamicCallbackFormImpl"> <when-type-is class="org.rhq.enterprise.gui.coregui.client.components.upload.DynamicCallbackFormImpl"/> @@ -47,6 +72,7 @@ <entry-point class='org.rhq.enterprise.gui.coregui.client.CoreGUI'/> <entry-point class='org.rhq.enterprise.gui.coregui.client.SearchGUI'/>
+ <servlet path="/AlertGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AlertGWTServiceImpl"/> <servlet path="/AlertDefinitionGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AlertDefinitionGWTServiceImpl"/> <servlet path="/AuthorizationGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AuthorizationGWTServiceImpl"/> 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..e9b7788 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client;
+import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; @@ -45,6 +46,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceT import org.rhq.enterprise.gui.coregui.client.menu.MenuBarView; import org.rhq.enterprise.gui.coregui.client.report.ReportTopView; import org.rhq.enterprise.gui.coregui.client.report.tag.TaggedView; +import org.rhq.enterprise.gui.coregui.client.test.TestConfigurationView; import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.WidgetUtility; import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; @@ -84,7 +86,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { public void onModuleLoad() { String hostPageBaseURL = GWT.getHostPageBaseURL(); if (hostPageBaseURL.indexOf("/coregui/") == -1) { - System.out.println("Suppressing load of CoreGUI module"); + Log.info("Suppressing load of CoreGUI module"); return; // suppress loading this module if not using the new GWT app }
@@ -165,7 +167,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
public void onValueChange(ValueChangeEvent<String> stringValueChangeEvent) { String event = URL.decodeComponent(stringValueChangeEvent.getValue()); - //System.out.println("Handling history event: " + event); + com.allen_sauer.gwt.log.client.Log.debug("Handling history event: " + event); currentPath = event;
currentViewPath = new ViewPath(event); @@ -208,6 +210,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { canvas = new AlertsView("Alert"); } else if (breadcrumbName.equals(ReportTopView.VIEW_ID)) { canvas = new ReportTopView("Report"); + } else if (breadcrumbName.equals(TestConfigurationView.VIEW_ID)) { + canvas = new TestConfigurationView("TestConfig"); } else { canvas = null; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java index bd0aabe..d252fb8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java @@ -89,7 +89,7 @@ public class DemoCanvas extends Canvas { configSelectMenu.addItemClickHandler(new ItemClickHandler() { public void onItemClick(ItemClickEvent itemClickEvent) { int x = configSelectMenu.getItemNum(itemClickEvent.getItem()); - System.out.println("Loading: " + x); + com.allen_sauer.gwt.log.client.Log.info("Loading: " + x); topTabSet.removeTab(configTab); switch (x) { case 0: diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index 24ef812..3d79afd 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -178,7 +178,7 @@ public class LoginView extends Canvas { ResourceTypeRepository.Cache.getInstance().getResourceTypes((Integer[]) null, EnumSet.allOf(ResourceTypeRepository.MetadataType.class), new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - System.out.println("Preloaded [" + types.size() + "] resource types"); + com.allen_sauer.gwt.log.client.Log.info("Preloaded [" + types.size() + "] resource types"); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java index 2266993..55588e9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java @@ -41,7 +41,7 @@ public class SearchGUI implements EntryPoint {
public void onModuleLoad() { if (SearchBar.existsOnPage() == false) { - System.out.println("Suppressing load of SearchGUI module"); + com.allen_sauer.gwt.log.client.Log.info("Suppressing load of SearchGUI module"); return; }
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 5219213..ecbd719 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 @@ -22,6 +22,7 @@ */ package org.rhq.enterprise.gui.coregui.client;
+import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; @@ -30,7 +31,6 @@ import com.google.gwt.http.client.Response; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.util.SC;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.SubjectCriteria; @@ -66,7 +66,7 @@ public class UserSessionManager { private static Timer sessionTimer = new Timer() { @Override public void run() { - System.out.println("Session Timer Expired"); + Log.info("Session timer expired."); new LoginView().showLoginDialog(); // log user out, show login dialog } }; @@ -88,7 +88,7 @@ public class UserSessionManager { try { b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { - System.out.println("response text = " + response.getText()); + com.allen_sauer.gwt.log.client.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]); - System.out.println("sessionAccess-subjectId: " + subjectId); - System.out.println("sessionAccess-sessionId: " + sessionId); - System.out.println("sessionAccess-lastAccess: " + lastAccess); + 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);
String previousSessionId = getPreviousSessionId(); // may be null - System.out.println("sessionAccess-previousSessionId: " + previousSessionId); + com.allen_sauer.gwt.log.client.Log.info("sessionAccess-previousSessionId: " + previousSessionId); if (previousSessionId == null || previousSessionId.equals(sessionId) == false) {
// persist sessionId if different from previously saved sessionId - System.out.println("sessionAccess-savingSessionId: " + sessionId); + com.allen_sauer.gwt.log.client.Log.info("sessionAccess-savingSessionId: " + sessionId); saveSessionId(sessionId);
// new sessions get the full 29 minutes to expire - System.out.println("sessionAccess-schedulingSessionTimeout: " + SESSION_TIMEOUT); + com.allen_sauer.gwt.log.client.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 }
- System.out.println("sessionAccess-reschedulingSessionTimeout: " + expiryMillis); + com.allen_sauer.gwt.log.client.Log.info("sessionAccess-reschedulingSessionTimeout: " + expiryMillis); sessionTimer.schedule((int) expiryMillis); }
@@ -143,13 +143,13 @@ public class UserSessionManager { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "UserSessionManager: Failed to load user's subject", caught); - System.out.println("Failed to load user's subject"); + com.allen_sauer.gwt.log.client.Log.info("Failed to load user's subject"); new LoginView().showLoginDialog(); }
public void onSuccess(PageList<Subject> result) { - System.out.println("Found subject"); Subject subject = result.get(0); + Log.debug("Found subject [" + subject + "]."); subject.setSessionId(Integer.valueOf(sessionId));
// reset the session subject to the latest, for wrapping in user preferences @@ -187,7 +187,7 @@ public class UserSessionManager {
@Override public void onFailure(Throwable caught) { - SC.say("Unable to determine login status, check server status"); + Log.error("Unable to determine login status - check Server status."); } }); } @@ -213,7 +213,7 @@ public class UserSessionManager {
// now continue with the rest of the login logic loggedIn = true; - System.out.println("Refreshing Session Timer"); + Log.info("Refreshing session timer..."); sessionTimer.schedule(millis); }
@@ -223,7 +223,7 @@ public class UserSessionManager { }
loggedIn = false; - System.out.println("Destroying Session Timer"); + Log.info("Destroying session timer..."); sessionTimer.cancel();
// log out the web session on the server-side in a delayed fashion, @@ -250,7 +250,7 @@ public class UserSessionManager { }
public static boolean isLoggedIn() { - //System.out.println("isLoggedIn = " + loggedIn); + Log.trace("isLoggedIn = " + loggedIn); return loggedIn; }
@@ -272,5 +272,4 @@ public class UserSessionManager { public static UserPreferences getUserPreferences() { return userPreferences; } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java index 61b58b7..a950c34 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java @@ -153,7 +153,7 @@ public class AlertDataSource extends RPCDataSource<Alert> {
public void onSuccess(PageList<Alert> result) { long fetchTime = System.currentTimeMillis() - start; - System.out.println(result.size() + " alerts fetched in: " + fetchTime + "ms"); + com.allen_sauer.gwt.log.client.Log.info(result.size() + " alerts fetched in: " + fetchTime + "ms"); response.setData(buildRecords(result)); // For paging to work, we have to specify size of full result set. response.setTotalRows(result.getTotalSize()); @@ -284,7 +284,7 @@ public class AlertDataSource extends RPCDataSource<Alert> { CoreGUI.getMessageCenter().notify( new Message("Acknowledged [" + alertIds.length + "] alerts", Message.Severity.Info));
- System.out.println("Acknowledged Alerts with id's: " + Arrays.toString(alertIds) + "."); + com.allen_sauer.gwt.log.client.Log.info("Acknowledged Alerts with id's: " + Arrays.toString(alertIds) + "."); alertsView.refresh(); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java index d21ab76..ad825a9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java @@ -96,7 +96,7 @@ public class AlertPortletDataSource extends AlertDataSource {
public void onSuccess(PageList<Alert> result) { long fetchTime = System.currentTimeMillis() - start; - System.out.println(result.size() + " alerts fetched in: " + fetchTime + "ms"); + com.allen_sauer.gwt.log.client.Log.info(result.size() + " alerts fetched in: " + fetchTime + "ms"); response.setData(buildRecords(result)); response.setTotalRows(result.size()); processResponse(request.getRequestId(), response); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java index 7da68cd..fa823e3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java @@ -106,7 +106,7 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView if (viewPath.isEnd()) { if (currentNextPath == null && bundlesListView != null) { // refresh - System.out.println("Refreshing BundleTopView"); + com.allen_sauer.gwt.log.client.Log.info("Refreshing BundleTopView");
bundlesListView.refresh(); } else { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java index c90ca57..bc296cc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java @@ -33,7 +33,7 @@ public class FullHTMLPane extends HTMLPane {
public FullHTMLPane(String url) { this(); - //System.out.println("Creating IFrame pane with URL [" + url + "]..."); + com.allen_sauer.gwt.log.client.Log.debug("Creating IFrame pane with URL [" + url + "]..."); setContentsURL(url); } } 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 eb1e2d2..343a709 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 @@ -241,7 +241,7 @@ public class ConfigurationEditor extends LocatableVLayout {
public void onSuccess(Configuration result) { configuration = result; - System.out.println("Config retreived in: " + (System.currentTimeMillis() - start)); + com.allen_sauer.gwt.log.client.Log.info("Config retreived in: " + (System.currentTimeMillis() - start)); reload(); } }); @@ -250,7 +250,7 @@ public class ConfigurationEditor extends LocatableVLayout { EnumSet.of(ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - //System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); + com.allen_sauer.gwt.log.client.Log.debug("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); definition = types.get(resourceTypeId).getResourceConfigurationDefinition(); if (definition == null) { loadingLabel.hide(); @@ -276,7 +276,7 @@ public class ConfigurationEditor extends LocatableVLayout { EnumSet.of(ResourceTypeRepository.MetadataType.pluginConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - //System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); + com.allen_sauer.gwt.log.client.Log.debug("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); definition = types.get(resourceTypeId).getPluginConfigurationDefinition(); if (definition == null) { showError("Connection settings are not supported by this Resource."); @@ -302,7 +302,7 @@ public class ConfigurationEditor extends LocatableVLayout {
if (definition.getConfigurationFormat() == ConfigurationFormat.RAW || definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { - System.out.println("Loading files view..."); + com.allen_sauer.gwt.log.client.Log.info("Loading files view..."); Tab tab = new LocatableTab("Files", "Files"); tab.setPane(buildRawPane()); tabSet.addTab(tab); @@ -310,7 +310,7 @@ public class ConfigurationEditor extends LocatableVLayout {
if (definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED || definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { - System.out.println("Loading properties view..."); + com.allen_sauer.gwt.log.client.Log.info("Loading properties view..."); Tab tab = new LocatableTab("Properties", "Properties"); tab.setPane(buildStructuredPane()); tabSet.addTab(tab); @@ -358,10 +358,10 @@ public class ConfigurationEditor extends LocatableVLayout { fileTree.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { String path = selectionEvent.getRecord().getAttribute("name"); - System.out.println("Getting Path: " + path); + com.allen_sauer.gwt.log.client.Log.info("Getting Path: " + path); rawEditor.setValue(filesMap.get(path).getContents()); rawEditor.redraw(); - System.out.println("Data: " + filesMap.get(path).getContents()); + com.allen_sauer.gwt.log.client.Log.info("Data: " + filesMap.get(path).getContents()); } });
@@ -391,7 +391,7 @@ public class ConfigurationEditor extends LocatableVLayout { }
for (PropertyGroupDefinition definition : definitions) { - // System.out.println("building: " + definition.getDisplayName()); + // com.allen_sauer.gwt.log.client.Log.info("building: " + definition.getDisplayName()); sectionStack.addSection(buildGroupSection(layout.extendLocatorId(definition.getName()), definition)); }
@@ -656,7 +656,7 @@ public class ConfigurationEditor extends LocatableVLayout { editField.setCanHide(false); editField.addRecordClickHandler(new RecordClickHandler() { public void onRecordClick(RecordClickEvent recordClickEvent) { - System.out.println("You want to edit: " + recordClickEvent.getRecord()); + 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( "_RHQ_PROPERTY")); @@ -678,7 +678,7 @@ public class ConfigurationEditor extends LocatableVLayout {
removeField.addRecordClickHandler(new RecordClickHandler() { public void onRecordClick(final RecordClickEvent recordClickEvent) { - System.out.println("You want to delete: " + recordClickEvent.getRecordNum()); + com.allen_sauer.gwt.log.client.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) { @@ -865,7 +865,7 @@ public class ConfigurationEditor extends LocatableVLayout { Click handlers seem to be turned off for disabled fields... need an alternative valueItem.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { - System.out.println("Click in value field"); + com.allen_sauer.gwt.log.client.Log.info("Click in value field"); clickEvent.getItem().setDisabled(false); unsetItem.setValue(false);
@@ -1000,10 +1000,10 @@ public class ConfigurationEditor extends LocatableVLayout { list.add(finalMap); ListGridRecord record = buildSummaryRecord(definitions, finalMap);
- System.out.println("here"); + com.allen_sauer.gwt.log.client.Log.info("here"); try { summaryTable.addData(record); - System.out.println("there"); + com.allen_sauer.gwt.log.client.Log.info("there"); } catch (Exception e) { e.printStackTrace(); } 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 index 9e0e480..7136199 100644 --- 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 @@ -73,7 +73,7 @@ public class ListGridConfigurationEditor extends VLayout {
public void onSuccess(Configuration result) { configuration = result; - System.out.println("Got config"); + com.allen_sauer.gwt.log.client.Log.info("Got config"); reload(); } }); @@ -85,7 +85,7 @@ public class ListGridConfigurationEditor extends VLayout {
public void onSuccess(ConfigurationDefinition result) { definition = result; - System.out.println("Got def"); + com.allen_sauer.gwt.log.client.Log.info("Got def"); reload(); }
@@ -108,7 +108,7 @@ public class ListGridConfigurationEditor extends VLayout { sectionStack.setOverflow(Overflow.VISIBLE);
for (PropertyGroupDefinition definition : definitions) { - System.out.println("building: " + definition.getDisplayName()); + com.allen_sauer.gwt.log.client.Log.info("building: " + definition.getDisplayName()); sectionStack.addSection(buildGroupSection(definition)); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java index f4b3cad..ca5a929 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java @@ -198,7 +198,7 @@ public class DashboardView extends LocatableVLayout { picker.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { Object v = changedEvent.getValue(); - System.out.println("color chagned to " + v); + com.allen_sauer.gwt.log.client.Log.info("color chagned to " + v); setBackgroundColor(String.valueOf(v)); storedDashboard.getConfiguration().put(new PropertySimple(Dashboard.CFG_BACKGROUND, String.valueOf(v))); save(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java index 7e0fb8e..422c244 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java @@ -314,7 +314,7 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView } } } else { - System.out.println("WARN: While rendering DashboardsView tabSet is null."); + com.allen_sauer.gwt.log.client.Log.info("WARN: While rendering DashboardsView tabSet is null."); } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortalLayout.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortalLayout.java index 8a3d355..aad543c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortalLayout.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortalLayout.java @@ -81,7 +81,7 @@ public class PortalLayout extends LocatableHLayout { colNum++; } save(); - System.out.println("Rearranged column indexes"); + com.allen_sauer.gwt.log.client.Log.info("Rearranged column indexes"); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java index a21e4f5..b30714f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java @@ -96,7 +96,7 @@ public abstract class AbstractMeasurementDataTraitDataSource extends RPCDataSour
public void onSuccess(PageList<MeasurementDataTrait> result) { long fetchDuration = System.currentTimeMillis() - startTime; - System.out.println(result.size() + " traits fetched in: " + fetchDuration + "ms"); + com.allen_sauer.gwt.log.client.Log.info(result.size() + " traits fetched in: " + fetchDuration + "ms");
response.setData(buildRecords(result)); // For paging to work, we have to specify size of full result set. 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 08f3473..e1181ab 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 @@ -105,7 +105,7 @@ public abstract class AbstractMeasurementScheduleDataSource extends RPCDataSourc
public void onSuccess(PageList<MeasurementSchedule> result) { long fetchDuration = System.currentTimeMillis() - startTime; - System.out.println(result.size() + " measurement schedules fetched in: " + fetchDuration + "ms"); + com.allen_sauer.gwt.log.client.Log.info(result.size() + " measurement schedules fetched in: " + fetchDuration + "ms");
response.setData(buildRecords(result)); // For paging to work, we have to specify size of full result set. 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 6c9127b..9e2442b 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 @@ -110,7 +110,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka public void onSelectionChanged(SelectionEvent selectionEvent) { if (selectionEvent.getState()) { Record selectedNode = selectionEvent.getRecord(); - System.out.println("Node selected in tree: " + selectedNode); + com.allen_sauer.gwt.log.client.Log.info("Node selected in tree: " + selectedNode); ResourceType type = (ResourceType) selectedNode.getAttributeAsObject("resourceType"); if (type != null) { // It's a cluster group node, not a subcategory node or an autoTypeGroup node. @@ -118,14 +118,14 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka if (key == null) { // The root group was selected. String groupId = selectedNode.getAttribute("id"); - //System.out.println("Selecting group [" + groupId + "]..."); + com.allen_sauer.gwt.log.client.Log.debug("Selecting group [" + groupId + "]..."); String viewPath = ResourceGroupTopView.VIEW_ID + "/" + groupId; String currentViewPath = History.getToken(); if (!currentViewPath.startsWith(viewPath)) { CoreGUI.goToView(viewPath); } } else { - //System.out.println("Selecting cluster group [" + key + "]..."); + com.allen_sauer.gwt.log.client.Log.debug("Selecting cluster group [" + key + "]..."); selectClusterGroup(key); } } 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 ccf8ee3..7bf4903 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 @@ -65,19 +65,21 @@ public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource {
@Override protected void enableSchedules(AbstractMeasurementScheduleListView measurementScheduleListView, - int[] measurementDefinitionIds, final List<String> measurementDefinitionDisplayNames) { - this.measurementService.enableSchedulesForCompatibleGroup(this.resourceGroupId, measurementDefinitionIds, + final int[] measurementDefinitionIds, final List<String> measurementDefinitionDisplayNames) { + final String s = (measurementDefinitionIds.length > 1) ? "s" : ""; + this.measurementService.enableSchedulesForCompatibleGroup(this.resourceGroupId, measurementDefinitionIds, new AsyncCallback<Void>() { @Override public void onFailure(Throwable throwable) { - CoreGUI.getErrorHandler().handleError("Failed to enable collection of metrics " + CoreGUI.getErrorHandler().handleError("Failed to enable collection of metric" + s + " " + measurementDefinitionDisplayNames + " for Resource group with id [" + resourceGroupId + "].", throwable); }
@Override public void onSuccess(Void aVoid) { - CoreGUI.getMessageCenter().notify(new Message("Enabled collection of metrics " + CoreGUI.getMessageCenter().notify(new Message("Enabled collection of selected metric" + s + ".", + "Enabled collection of metric" + s + " " + measurementDefinitionDisplayNames + " for Resource group with id [" + resourceGroupId + "].", Message.Severity.Info));
@@ -87,18 +89,20 @@ public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource {
@Override protected void disableSchedules(AbstractMeasurementScheduleListView measurementScheduleListView, int[] measurementDefinitionIds, final List<String> measurementDefinitionDisplayNames) { - this.measurementService.disableSchedulesForCompatibleGroup(this.resourceGroupId, measurementDefinitionIds, + final String s = (measurementDefinitionIds.length > 1) ? "s" : ""; + this.measurementService.disableSchedulesForCompatibleGroup(this.resourceGroupId, measurementDefinitionIds, new AsyncCallback<Void>() { @Override public void onFailure(Throwable throwable) { - CoreGUI.getErrorHandler().handleError("Failed to disable collection of metrics " + CoreGUI.getErrorHandler().handleError("Failed to disable collection of metric" + s + " " + measurementDefinitionDisplayNames + " for Resource group with id [" + resourceGroupId + "].", throwable); }
@Override public void onSuccess(Void aVoid) { - CoreGUI.getMessageCenter().notify(new Message("Disabled collection of metrics " + CoreGUI.getMessageCenter().notify(new Message("Disabled collection of selected metric" + s + ".", + "Disabled collection of metric" + s + " " + measurementDefinitionDisplayNames + " for Resource group with id [" + resourceGroupId + "].", Message.Severity.Info));
@@ -109,19 +113,21 @@ public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource { @Override protected void updateSchedules(AbstractMeasurementScheduleListView measurementScheduleListView, int[] measurementDefinitionIds, final List<String> measurementDefinitionDisplayNames, final long collectionInterval) { + final String s = (measurementDefinitionIds.length > 1) ? "s" : ""; this.measurementService.updateSchedulesForCompatibleGroup(this.resourceGroupId, measurementDefinitionIds, collectionInterval, new AsyncCallback<Void>() { @Override public void onFailure(Throwable throwable) { CoreGUI.getErrorHandler().handleError("Failed to set collection interval to " + (collectionInterval / 1000) - + " seconds for metrics " + measurementDefinitionDisplayNames + " for Resource group with id [" + + " seconds for metric" + s + " " + measurementDefinitionDisplayNames + " for Resource group with id [" + resourceGroupId + "].", throwable); }
@Override public void onSuccess(Void aVoid) { - CoreGUI.getMessageCenter().notify(new Message("Collection interval for metrics " + CoreGUI.getMessageCenter().notify(new Message("Updated collection intervals of selected metric" + s + ".", + "Collection interval for metric" + s + " " + measurementDefinitionDisplayNames + " for Resource group with id [" + resourceGroupId + "] set to " + (collectionInterval / 1000) + " seconds.", Message.Severity.Info));
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 e1bed72..6382fcb 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 @@ -165,7 +165,7 @@ public class ResourceSearchView extends Table {
long start = System.currentTimeMillis(); getListGrid().fetchData(c); - System.out.println("Loaded in: " + (System.currentTimeMillis() - start)); + com.allen_sauer.gwt.log.client.Log.info("Loaded in: " + (System.currentTimeMillis() - start)); } } });*/ 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 bccf8c5..35eb2d6 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 @@ -133,12 +133,12 @@ public class NewResourceTreeDataSource extends DataSource { ResourceCriteria criteria = new ResourceCriteria();
if (p == null) { - System.out.println("DataSourceTree: Loading initial data"); + com.allen_sauer.gwt.log.client.Log.info("DataSourceTree: Loading initial data");
criteria.addFilterId(rootId);
} else { - System.out.println("DataSourceTree: Loading " + p); + com.allen_sauer.gwt.log.client.Log.info("DataSourceTree: Loading " + p);
criteria.addFilterParentResourceId(Integer.parseInt(p)); } @@ -319,7 +319,7 @@ public class NewResourceTreeDataSource extends DataSource { String parentId = resource.getParentResource() == null ? null : (resource.getParentResource().getId() + "_" + resource.getResourceType().getName());
- // System.out.println(id + " / " + parentId); + // com.allen_sauer.gwt.log.client.Log.info(id + " / " + parentId);
setID(id); setParentID(parentId); 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 bad1ada..da08c04 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 @@ -124,7 +124,7 @@ public class NewResourceTreeView extends LocatableVLayout { if (treeGrid.getSelectedRecord() instanceof ResourceTreeDatasource.ResourceTreeNode) { ResourceTreeDatasource.ResourceTreeNode node = (ResourceTreeDatasource.ResourceTreeNode) treeGrid .getSelectedRecord(); - System.out.println("Resource selected in tree: " + node.getResource()); + com.allen_sauer.gwt.log.client.Log.info("Resource selected in tree: " + node.getResource());
String newToken = "Resource/" + node.getResource().getId(); String currentToken = History.getToken(); 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 1c73198..d577c4d 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 @@ -107,7 +107,6 @@ public class ResourceTreeDatasource extends DataSource { case UPDATE: //executeAdd(lstRec, false); break; - default: break; } @@ -119,12 +118,12 @@ public class ResourceTreeDatasource extends DataSource { //final long start = System.currentTimeMillis();
String parentResourceId = request.getCriteria().getAttribute("parentId"); - // System.out.println("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) { - System.out.println("ResourceTreeDatasource: Loading initial data..."); + com.allen_sauer.gwt.log.client.Log.info("ResourceTreeDatasource: Loading initial data...");
// criteria.addFilterId(rootId);
@@ -133,7 +132,7 @@ public class ResourceTreeDatasource extends DataSource { return;
} else { - System.out.println("ResourceTreeDatasource: Loading Resource [" + parentResourceId + "]..."); + com.allen_sauer.gwt.log.client.Log.info("ResourceTreeDatasource: Loading Resource [" + parentResourceId + "]...");
criteria.addFilterParentResourceId(Integer.parseInt(parentResourceId)); } @@ -205,14 +204,14 @@ public class ResourceTreeDatasource extends DataSource { Resource parentResource = resource.getParentResource(); ResourceSubCategory subcategory = type.getSubCategory(); if (subcategory != null) { - //System.out.println("Processing " + subcategory + "..."); + 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); - //System.out.println("Adding " + subcategoryNode + " to tree..."); + com.allen_sauer.gwt.log.client.Log.debug("Adding " + subcategoryNode + " to tree..."); updatedNodes.add(subcategoryNode); } } while ((subcategory = subcategory.getParentSubCategory()) != null); @@ -221,7 +220,7 @@ public class ResourceTreeDatasource extends DataSource { if (!type.isSingleton()) { AutoGroupTreeNode autogroupNode = new AutoGroupTreeNode(resource); autogroupNodes.put(autogroupNodeId, autogroupNode); - //System.out.println("Adding " + autogroupNode + " to tree..."); + com.allen_sauer.gwt.log.client.Log.debug("Adding " + autogroupNode + " to tree..."); updatedNodes.add(autogroupNode); } } 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 4cea21b..c06c636 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 @@ -159,7 +159,7 @@ public class ResourceTreeView extends LocatableVLayout { treeGrid.deselectAllRecords(); } } else if (selectedRecord instanceof AutoGroupTreeNode) { - System.out.println("AutoGroup Node selected in tree: " + selectedRecord); + com.allen_sauer.gwt.log.client.Log.info("AutoGroup Node selected in tree: " + selectedRecord);
AutoGroupTreeNode agNode = (AutoGroupTreeNode) selectedRecord; selectedNodeId = agNode.getID(); @@ -173,7 +173,7 @@ public class ResourceTreeView extends LocatableVLayout { } }); } else { - System.out.println("Unhandled Node selected in tree: " + selectedRecord); + com.allen_sauer.gwt.log.client.Log.info("Unhandled Node selected in tree: " + selectedRecord); } } } @@ -628,7 +628,6 @@ public class ResourceTreeView extends LocatableVLayout { }
if (!root.equals(ResourceTreeView.this.rootResource)) { - if (treeGrid != null) { treeGrid.destroy(); } 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 4556da0..116e1ad 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 @@ -118,8 +118,7 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro public void onSuccess(PluginConfigurationUpdate result) { CoreGUI.getMessageCenter().notify( new Message("Connection settings updated.", - "Connection settings updated for Resource [" + resource.getName() + "].", - Message.Severity.Info)); + "Connection settings updated for Resource [" + resource.getName() + "].")); reloadConfiguration(); } }); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/create/OperationCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/create/OperationCreateWizard.java index 5d0be9d..e76e2ca 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/create/OperationCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/create/OperationCreateWizard.java @@ -113,7 +113,7 @@ public class OperationCreateWizard extends AbstractWizard { }
private void execute() { - System.out.println("TODO Executed operation!!"); + com.allen_sauer.gwt.log.client.Log.info("TODO Executed operation!!");
OperationGWTServiceAsync operationService = GWTServiceLookup.getOperationService();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java index cfa51bf..1c01176 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java @@ -109,7 +109,7 @@ public class ResourceTypeRepository { } });
- // System.out.println("Loaded types from cache in " + (System.currentTimeMillis() - start)); + // com.allen_sauer.gwt.log.client.Log.info("Loaded types from cache in " + (System.currentTimeMillis() - start)); }
public void loadResourceTypes(final PageList<ResourceGroup> groups, final ResourceTypeLoadedInGroupCallback callback) { @@ -142,7 +142,7 @@ public class ResourceTypeRepository { } });
- // System.out.println("Loaded types from cache in " + (System.currentTimeMillis() - start)); + // com.allen_sauer.gwt.log.client.Log.info("Loaded types from cache in " + (System.currentTimeMillis() - start)); }
public void getResourceTypes(Integer[] resourceTypeIds, final TypesLoadedCallback callback) { @@ -234,7 +234,7 @@ public class ResourceTypeRepository {
criteria.setPageControl(PageControl.getUnlimitedInstance());
- System.out.println("Loading " + typesNeeded.size() + com.allen_sauer.gwt.log.client.Log.info("Loading " + typesNeeded.size() + ((metadataTypes != null) ? (" types: " + metadataTypes) : ""));
resourceTypeService.findResourceTypesByCriteria(criteria, new AsyncCallback<PageList<ResourceType>>() { @@ -313,7 +313,7 @@ public class ResourceTypeRepository { public void preloadAll() { getResourceTypes((Integer[]) null, EnumSet.allOf(MetadataType.class), new TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - System.out.println("Preloaded [" + types.size() + "] Resource types."); + com.allen_sauer.gwt.log.client.Log.info("Preloaded [" + types.size() + "] Resource types."); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java index da5b92e..f6e1730 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java @@ -119,7 +119,7 @@ public class DropDownMenuBarView extends LocatableVLayout { resourcesMenu.addItem(favoritesMenu); menu.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { - System.out.println("over here"); + com.allen_sauer.gwt.log.client.Log.info("over here"); favoritesMenu.refresh(); } }); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java index 657c4d3..5e6d943 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java @@ -165,7 +165,7 @@ public class SearchBarPane extends LocatableHLayout {
comboBox.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { - //System.out.println("ChangedEvent: " + changedEvent.getValue()); + com.allen_sauer.gwt.log.client.Log.debug("ChangedEvent: " + changedEvent.getValue());
Object intermediate = changedEvent.getValue(); if (!(intermediate instanceof Integer)) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java index 47dcded..42c830b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java @@ -140,7 +140,7 @@ public class SearchBar extends SimplePanel { }
public SearchBar() { - System.out.println("Loading SearchBar..."); + com.allen_sauer.gwt.log.client.Log.info("Loading SearchBar...");
// in the future, will be instantiated directly from a higher-level widget if (existsOnPage()) { 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 new file mode 100644 index 0000000..bfcb322 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java @@ -0,0 +1,293 @@ +/* + * 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.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +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.PropertyDefinitionEnumeration; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; +import org.rhq.core.domain.configuration.definition.PropertyGroupDefinition; +import org.rhq.core.domain.configuration.definition.PropertySimpleType; + +/** + * A utility class that provides methods for creating a test {@link ConfigurationDefinition} and a + * {@link Configuration} that conforms to that definition. + * + * @author Ian Springer + */ +public abstract class TestConfigurationFactory { + public static ConfigurationDefinition createConfigurationDefinition() { + ConfigurationDefinition configurationDefinition = new ConfigurationDefinition("TestConfig", "a test config"); + Map<String, PropertyDefinition> propertyDefinitions = new HashMap<String, PropertyDefinition>(); + configurationDefinition.setPropertyDefinitions(propertyDefinitions); + + PropertyDefinitionSimple simplePropDef; + + simplePropDef = createStringPropDef1(); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + simplePropDef = createStringPropDef2(); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + simplePropDef = new PropertyDefinitionSimple("LongString", "a Long String simple prop", false, + PropertySimpleType.LONG_STRING); + simplePropDef.setDisplayName(simplePropDef.getName()); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + simplePropDef = new PropertyDefinitionSimple("Password", "a Password simple prop", false, + PropertySimpleType.PASSWORD); + simplePropDef.setDisplayName(simplePropDef.getName()); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + simplePropDef = new PropertyDefinitionSimple("Boolean", "a required Boolean simple prop", true, + PropertySimpleType.BOOLEAN); + simplePropDef.setDisplayName(simplePropDef.getName()); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + simplePropDef.setRequired(true); + + simplePropDef = createIntegerPropDef(); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + simplePropDef = new PropertyDefinitionSimple("Float", "a Float simple prop", false, PropertySimpleType.FLOAT); + simplePropDef.setDisplayName(simplePropDef.getName()); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + simplePropDef = new PropertyDefinitionSimple("StringEnum1", + "a String enum prop with <=5 items - should be rendered as radio buttons", false, + PropertySimpleType.STRING); + simplePropDef.setDisplayName(simplePropDef.getName()); + ArrayList<PropertyDefinitionEnumeration> propDefEnums = new ArrayList<PropertyDefinitionEnumeration>(); + propDefEnums.add(new PropertyDefinitionEnumeration("NY", "NY")); + propDefEnums.add(new PropertyDefinitionEnumeration("NJ", "NJ", true)); + propDefEnums.add(new PropertyDefinitionEnumeration("PA", "PA")); + simplePropDef.setEnumeratedValues(propDefEnums, false); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + 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()); + propDefEnums = new ArrayList<PropertyDefinitionEnumeration>(); + propDefEnums.add(new PropertyDefinitionEnumeration("red", "red")); + propDefEnums.add(new PropertyDefinitionEnumeration("orange", "orange", true)); + propDefEnums.add(new PropertyDefinitionEnumeration("yellow", "yellow")); + propDefEnums.add(new PropertyDefinitionEnumeration("green", "green")); + propDefEnums.add(new PropertyDefinitionEnumeration("blue", "blue")); + propDefEnums.add(new PropertyDefinitionEnumeration("purple", "purple")); + simplePropDef.setEnumeratedValues(propDefEnums, false); + propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + + 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); + + PropertyDefinitionMap openMapPropDef = new PropertyDefinitionMap("OpenMapOfSimples", "an open map of simples", + false); + openMapPropDef.setDisplayName(openMapPropDef.getName()); + propertyDefinitions.put(openMapPropDef.getName(), openMapPropDef); + + 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); + + PropertyDefinitionList listOfSimplesPropDef = new PropertyDefinitionList("ListOfStrings", + "another list of Strings", true, new PropertyDefinitionSimple("note", "a note", false, + PropertySimpleType.STRING)); + listOfSimplesPropDef.setDisplayName(listOfSimplesPropDef.getName()); + propertyDefinitions.put(listOfSimplesPropDef.getName(), listOfSimplesPropDef); + + PropertyDefinitionMap mapInListPropDef = + new PropertyDefinitionMap("MapOfSimplesInList", "a map of simples in a list", false); + mapInListPropDef.put(createStringPropDef1()); + mapInListPropDef.put(createStringPropDef2()); + mapInListPropDef.put(createIntegerPropDef()); + mapInListPropDef.setDisplayName(mapInListPropDef.getName()); + + PropertyDefinitionList listPropDef = new PropertyDefinitionList("ListOfMaps", "a list of maps", true, + mapInListPropDef); + listPropDef.setDisplayName(listPropDef.getName()); + propertyDefinitions.put(listPropDef.getName(), listPropDef); + + PropertyDefinitionMap mapInReadOnlyListPropDef = + new PropertyDefinitionMap("MapOfSimplesInReadOnlyList", "a map of simples in a list", false); + mapInReadOnlyListPropDef.put(createStringPropDef1()); + mapInReadOnlyListPropDef.put(createStringPropDef2()); + mapInReadOnlyListPropDef.put(createIntegerPropDef()); + mapInReadOnlyListPropDef.setDisplayName(mapInReadOnlyListPropDef.getName()); + + PropertyDefinitionList readOnlyListPropDef = new PropertyDefinitionList("ReadOnlyListOfMaps", + "a read-only list of maps", true, mapInReadOnlyListPropDef); + readOnlyListPropDef.setDisplayName(readOnlyListPropDef.getName()); + readOnlyListPropDef.setReadOnly(true); + propertyDefinitions.put(readOnlyListPropDef.getName(), readOnlyListPropDef); + + PropertyGroupDefinition propertyGroupDefinition = new PropertyGroupDefinition("myGroup"); + propertyGroupDefinition.setDisplayName(propertyGroupDefinition.getName()); + propertyGroupDefinition.setDescription("this is an example group"); + + PropertyDefinitionSimple myString = new PropertyDefinitionSimple("myString1", "my little string", true, + PropertySimpleType.STRING); + myString.setDisplayName(myString.getName()); + myString.setSummary(true); + propertyDefinitions.put(myString.getName(), myString); + 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); + myString2.setPropertyGroupDefinition(propertyGroupDefinition); + + PropertyGroupDefinition propertyGroupDefinition2 = new PropertyGroupDefinition("myGroup2"); + propertyGroupDefinition2.setDisplayName(propertyGroupDefinition2.getName()); + propertyGroupDefinition2.setDescription("this is another example group"); + + PropertyDefinitionSimple myString3 = new PropertyDefinitionSimple("myString3", "my third string", true, + PropertySimpleType.STRING); + myString3.setDisplayName((myString3.getName())); + myString3.setSummary(true); + propertyDefinitions.put(myString3.getName(), myString3); + myString3.setPropertyGroupDefinition(propertyGroupDefinition2); + + PropertyDefinitionSimple enumExample = new PropertyDefinitionSimple("myEnum", + "a grouped enum prop with <=5 items", false, PropertySimpleType.STRING); + enumExample.setDisplayName(enumExample.getName()); + ArrayList<PropertyDefinitionEnumeration> myEnums = new ArrayList<PropertyDefinitionEnumeration>(); + myEnums.add(new PropertyDefinitionEnumeration("Burlington", "Burlington")); + myEnums.add(new PropertyDefinitionEnumeration("Camden", "Camden", true)); + myEnums.add(new PropertyDefinitionEnumeration("Gloucester", "Gloucester")); + enumExample.setEnumeratedValues(myEnums, false); + propertyDefinitions.put(enumExample.getName(), enumExample); + enumExample.setPropertyGroupDefinition(propertyGroupDefinition2); + + return configurationDefinition; + } + + public static Configuration createConfiguration() { + Configuration configuration = new Configuration(); + configuration.setNotes("a test config"); + configuration.setVersion(1); + + configuration.put(new PropertySimple("String1", "blah")); + configuration.put(new PropertySimple("String2", + "a really, really, really, really, really long value that won't fit in the text input box")); + configuration.put(new PropertySimple("LongString", "blah blah blah\nblah blah blah")); + configuration.put(new PropertySimple("Password", null)); + configuration.put(new PropertySimple("Boolean", false)); + configuration.put(new PropertySimple("Integer", 666)); + configuration.put(new PropertySimple("Float", Math.PI)); + + configuration.put(new PropertySimple("StringEnum1", "PA")); + configuration.put(new PropertySimple("StringEnum2", "blue")); + + PropertyMap propMap1 = new PropertyMap("MapOfSimples"); + propMap1.put(new PropertySimple("String1", "One")); + propMap1.put(new PropertySimple("String2", "Two")); + propMap1.put(new PropertySimple("Integer", 11)); + configuration.put(propMap1); + + PropertyMap openPropMap1 = new PropertyMap("OpenMapOfSimples"); + openPropMap1.put(new PropertySimple("PROCESSOR_ARCHITECTURE", "x86")); + openPropMap1.put(new PropertySimple("PROCESSOR_IDENTIFIER", "x86 Family 6 Model 15 Stepping 6, GenuineIntel")); + openPropMap1.put(new PropertySimple("PROCESSOR_LEVEL", "6")); + openPropMap1.put(new PropertySimple("PROCESSOR_REVISION", "0f06")); + configuration.put(openPropMap1); + + PropertyMap openPropMap2 = new PropertyMap("ReadOnlyOpenMapOfSimples"); + openPropMap2.put(new PropertySimple("ANT_HOME", "C:\opt\ant-1.6.5")); + 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"))); + + PropertyMap propMap2 = new PropertyMap("MapOfSimples"); + 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"); + propMap3.put(new PropertySimple("String1", "Un")); + propMap3.put(new PropertySimple("String2", "Deux")); + propMap3.put(new PropertySimple("Integer", Integer.MAX_VALUE)); + configuration.put(new PropertyList("ListOfMaps", propMap2, propMap3)); + + PropertyMap propMap4 = new PropertyMap("MapOfSimples"); + propMap4.put(new PropertySimple("String1", "A")); + propMap4.put(new PropertySimple("String2", "B")); + propMap4.put(new PropertySimple("Integer", 999)); + PropertyMap propMap5 = new PropertyMap("MapOfSimples"); + propMap5.put(new PropertySimple("String1", "a")); + propMap5.put(new PropertySimple("String2", "b")); + propMap5.put(new PropertySimple("Integer", 0)); + configuration.put(new PropertyList("ReadOnlyListOfMaps", propMap4, propMap5)); + + configuration.put(new PropertySimple("myString1", "grouped String 1")); + configuration.put(new PropertySimple("myString2", "grouped String 2")); + configuration.put(new PropertySimple("myString3", "strings are cool")); + configuration.put(new PropertySimple("myEnum", "Burlington")); + + return configuration; + } + + private static PropertyDefinitionSimple createStringPropDef1() { + PropertyDefinitionSimple stringPropDef1; + stringPropDef1 = new PropertyDefinitionSimple("String1", + "an optional String simple prop", false, PropertySimpleType.STRING); + stringPropDef1.setDisplayName(stringPropDef1.getName()); + return stringPropDef1; + } + + private static PropertyDefinitionSimple createStringPropDef2() { + PropertyDefinitionSimple stringPropDef2; + stringPropDef2 = new PropertyDefinitionSimple("String2", + "a read-only String simple prop", false, PropertySimpleType.STRING); + stringPropDef2.setDisplayName(stringPropDef2.getName()); + stringPropDef2.setReadOnly(true); + return stringPropDef2; + } + + private static PropertyDefinitionSimple createIntegerPropDef() { + PropertyDefinitionSimple integerPropDef; + integerPropDef = new PropertyDefinitionSimple("Integer", + "a required summary Integer simple prop", true, PropertySimpleType.INTEGER); + integerPropDef.setDisplayName(integerPropDef.getName()); + integerPropDef.setSummary(true); + return integerPropDef; + } + + private TestConfigurationFactory() { + } +} 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 new file mode 100644 index 0000000..0349718 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java @@ -0,0 +1,129 @@ +/* + * 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.test; + +import java.util.EnumSet; + +import com.smartgwt.client.types.Overflow; +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.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; +import org.rhq.enterprise.gui.coregui.client.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; + +/** + * @author Ian Springer + */ +public class TestConfigurationView + extends LocatableVLayout implements PropertyValueChangeListener { + public static final String VIEW_ID = "TestConfig"; + + private ConfigurationEditor editor; + private LocatableIButton saveButton; + private ConfigurationDefinition configurationDefinition; + private Configuration configuration; + + public TestConfigurationView(String locatorId) { + super(locatorId); + } + + @Override + protected void onDraw() { + super.onDraw(); + build(); + } + + public void build() { + setWidth100(); + setHeight100(); + + 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(); + } + }); + this.saveButton.disable(); + toolStrip.addMember(this.saveButton); + + addMember(toolStrip); + + this.configurationDefinition = TestConfigurationFactory.createConfigurationDefinition(); + this.configuration = TestConfigurationFactory.createConfiguration(); + + 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(); + Message message; + if (event.isValidationStateChanged()) { + if (event.getInvalidPropertyNames().isEmpty()) { + this.saveButton.enable(); + message = new Message("All properties now have valid values, so the configuration can now be saved.", + Message.Severity.Info, EnumSet.of(Message.Option.Transient)); + } + else { + this.saveButton.disable(); + message = new Message( + "One or more properties have invalid values. 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(); + } + } +} 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 a717108..2640674 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 @@ -56,7 +56,7 @@ public abstract class RPCDataSource<T> extends DataSource {
public RPCDataSource(String name) { if (name != null) { - System.out.println("Trying to build DS: " + name); + com.allen_sauer.gwt.log.client.Log.info("Trying to build DS: " + name); setID(name); } // TODO until http://code.google.com/p/smartgwt/issues/detail?id=490 is fixed always go to the server for data @@ -245,7 +245,7 @@ public abstract class RPCDataSource<T> extends DataSource {
@SuppressWarnings("unchecked") public static <S> S[] getArrayFilter(DSRequest request, String paramName, Class<S> type) { - //System.out.println("Fetching array " + paramName + " (" + type + ")"); + com.allen_sauer.gwt.log.client.Log.debug("Fetching array " + paramName + " (" + type + ")"); Criteria criteria = request.getCriteria(); Map<String, Object> criteriaMap = criteria.getValues();
@@ -272,14 +272,14 @@ public abstract class RPCDataSource<T> extends DataSource { throw new IllegalArgumentException("No support for passing array filters of type " + type); }
- //System.out.println("Result array = " + resultArray); + com.allen_sauer.gwt.log.client.Log.debug("Result array = " + resultArray);
return resultArray; }
@SuppressWarnings("unchecked") public static <S> S getFilter(DSRequest request, String paramName, Class<S> type) { - //System.out.println("Fetching " + paramName + " (" + type + ")"); + com.allen_sauer.gwt.log.client.Log.debug("Fetching " + paramName + " (" + type + ")"); Criteria criteria = request.getCriteria(); Map<String, Object> criteriaMap = criteria.getValues();
@@ -301,7 +301,7 @@ public abstract class RPCDataSource<T> extends DataSource { } }
- //System.out.println("Result = " + result); + com.allen_sauer.gwt.log.client.Log.debug("Result = " + result);
return result; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TreeUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TreeUtility.java index 360fd86..17049a8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TreeUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TreeUtility.java @@ -38,7 +38,7 @@ public class TreeUtility { for (int i = 0; i < level; i++) { System.out.print(" "); } - System.out.println("* " + toString(node)); + com.allen_sauer.gwt.log.client.Log.info("* " + toString(node)); TreeNode[] childNodes = tree.getChildren(node); for (TreeNode childNode : childNodes) { printTreeNode(tree, childNode); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetUtility.java index 5790c70..5714634 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetUtility.java @@ -165,7 +165,7 @@ public class WidgetUtility { indent.append(" "); }
- System.out.println(indent + simpleClassName + "[id=" + id + ", title=" + title + ", flags=[" + flags + "]]"); + com.allen_sauer.gwt.log.client.Log.info(indent + simpleClassName + "[id=" + id + ", title=" + title + ", flags=[" + flags + "]]"); }
private static List<Widget> getChildren(Widget widget) { 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 8da5ef0..6b356ae 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 @@ -120,6 +120,10 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag
label.setWidth(400);
+ // TODO: Create some custom edge images in greed, yellow, red, etc. so we can add nice rounded corners to the + // label. + //label.setShowEdges(true); + String icon = (contents != null) ? SEVERITY_TO_ICON_MAP.get(message.getSeverity()) : null; label.setIcon(icon);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java index d51bc47..1a6968d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client.util.message;
import java.util.List;
+import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.user.client.Timer; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.AnimationEffect; @@ -158,6 +159,8 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter
public void onMessage(final Message message) { if (!message.isTransient()) { + logMessage(message); + final Label label = new Label(message.conciseMessage); label.setMargin(5); label.setAutoFit(true); @@ -193,6 +196,25 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter } }
+ private void logMessage(Message message) { + // TODO: Format the message better. + String logMessage = message.toString(); + switch (message.getSeverity()) { + case Info: + Log.info(logMessage); + break; + case Warning: + Log.warn(logMessage); + break; + case Error: + Log.error(logMessage); + break; + case Fatal: + Log.fatal(logMessage); + break; + } + } + private String getSeverityIcon(Message.Severity severity) { String iconSrc = null; switch (severity) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java index 2064f63..8ae0364 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java @@ -55,7 +55,7 @@ public class MonitoringRequestCallback implements RequestCallback { if (STATUS_CODE_OK == response.getStatusCode()) { RPCManager.getInstance().succeedCall(this); callback.onResponseReceived(request, response); - //System.out.println("MonitoringRequestCallback: OK"); + com.allen_sauer.gwt.log.client.Log.debug("MonitoringRequestCallback: OK"); } else { RPCManager.getInstance().failCall(this); callback.onResponseReceived(request, response); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/RPCManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/RPCManager.java index 10213f4..3e2e007 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/RPCManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/RPCManager.java @@ -62,7 +62,7 @@ public class RPCManager { }
public void succeedCall(MonitoringRequestCallback callback) { - //System.out.println("RPC [" + callback.getName() + "] succeeded in [" + callback.age() + "] ms."); + com.allen_sauer.gwt.log.client.Log.debug("RPC [" + callback.getName() + "] succeeded in [" + callback.age() + "] ms."); inProgress.remove(callback); refresh(); } 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 63b71a0..08d8046 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 @@ -102,7 +102,7 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen }
public RawConfiguration dummy(RawConfiguration config) { - System.out.println(config.getPath()); + com.allen_sauer.gwt.log.client.Log.info(config.getPath()); return new RawConfiguration(); // Dummy method for gwt compiler } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java index 7c3acfb..e090640 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java @@ -25,6 +25,8 @@ import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Set;
+import com.allen_sauer.gwt.log.client.Log; + import org.rhq.core.domain.resource.Resource;
/** @@ -37,7 +39,7 @@ public class ObjectFilter { for (Object object : collection) { filterFields(object, goodFields); } - System.out.println("Object filtered from size [" + sizeOfBefore + "] to [" + sizeOf(collection) + "]"); + com.allen_sauer.gwt.log.client.Log.info("Object filtered from size [" + sizeOfBefore + "] to [" + sizeOf(collection) + "]");
return collection; } @@ -51,11 +53,11 @@ public class ObjectFilter { // Only clearing objects, no point in clearing primitives as it // doesn't save any space on the stream if (!f.getType().isPrimitive()) { - // System.out.println("clearing " + f.getName()); + Log.debug("Clearing " + f.getName() + "..."); f.setAccessible(true); f.set(object, null); } else { - // System.out.println("Can't do " + f.getType()); + Log.debug("Can't do " + f.getType()); } } } 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 14c6f8d..4e14b75 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 @@ -111,7 +111,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re @Override public void init(ServletConfig config) throws ServletException { super.init(config); - System.out.println("Loading GWT RPC Services"); + com.allen_sauer.gwt.log.client.Log.info("Loading GWT RPC Services"); }
public ResourceGWTServiceImpl() { 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 c74aa3c..4d6706c 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 @@ -26,7 +26,7 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement }
public RawConfiguration dummy(RawConfiguration config) { - System.out.println(config.getPath()); + com.allen_sauer.gwt.log.client.Log.info(config.getPath()); return new RawConfiguration(); } } \ No newline at end of file
commit 198bfdca2ff0c5f150e2f98a20655a5bde66d247 Author: Joseph Marques joseph@redhat.com Date: Fri Oct 1 13:48:22 2010 -0400
add jxpath to eclipse .classpath
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 374f578bc10335cd4cd93a8800b264ee5dcd5ee2 Author: Joseph Marques joseph@redhat.com Date: Fri Oct 1 13:18:06 2010 -0400
fix all current gwt services to wrap exceptions that are gwt-serializable
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java index a1f47c9..dc7497f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import org.rhq.core.domain.alert.Alert; import org.rhq.core.domain.criteria.AlertCriteria; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.AlertGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.alert.AlertManagerLocal; @@ -35,15 +36,27 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert private AlertManagerLocal alertManager = LookupUtil.getAlertManager();
public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) { - return SerialUtility.prepare(this.alertManager.findAlertsByCriteria(getSessionSubject(), criteria), - "AlertService.findAlertsByCriteria"); + try { + return SerialUtility.prepare(this.alertManager.findAlertsByCriteria(getSessionSubject(), criteria), + "AlertService.findAlertsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void deleteResourceAlerts(Integer[] alertIds) { - this.alertManager.deleteResourceAlerts(getSessionSubject(), alertIds); + try { + this.alertManager.deleteResourceAlerts(getSessionSubject(), alertIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void acknowledgeResourceAlerts(Integer[] alertIds) { - this.alertManager.acknowledgeAlerts(getSessionSubject(), alertIds); + try { + this.alertManager.acknowledgeAlerts(getSessionSubject(), alertIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AuthorizationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AuthorizationGWTServiceImpl.java index 7218061..4b8d73f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AuthorizationGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AuthorizationGWTServiceImpl.java @@ -22,6 +22,7 @@ import java.util.HashSet; import java.util.Set;
import org.rhq.core.domain.authz.Permission; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.AuthorizationGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.authz.AuthorizationManagerLocal; @@ -32,30 +33,53 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class AuthorizationGWTServiceImpl extends AbstractGWTServiceImpl implements AuthorizationGWTService {
+ private static final long serialVersionUID = 1L; + private AuthorizationManagerLocal authorizationManager = LookupUtil.getAuthorizationManager();
public Set<Permission> getExplicitResourcePermissions(int resourceId) { - return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getExplicitResourcePermissions( - getSessionSubject(), resourceId)), "AuthorizationManager.getExplicitResourcePermissions"); + try { + return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getExplicitResourcePermissions( + getSessionSubject(), resourceId)), "AuthorizationManager.getExplicitResourcePermissions"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Set<Permission> getImplicitResourcePermissions(int resourceId) { - return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getImplicitResourcePermissions( - getSessionSubject(), resourceId)), "AuthorizationManager.getImplicitResourcePermissions"); + try { + return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getImplicitResourcePermissions( + getSessionSubject(), resourceId)), "AuthorizationManager.getImplicitResourcePermissions"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Set<Permission> getExplicitGroupPermissions(int groupId) { - return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getExplicitGroupPermissions( - getSessionSubject(), groupId)), "AuthorizationManager.getExplicitGroupPermissions"); + try { + return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getExplicitGroupPermissions( + getSessionSubject(), groupId)), "AuthorizationManager.getExplicitGroupPermissions"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Set<Permission> getImplicitGroupPermissions(int groupId) { - return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getImplicitGroupPermissions( - getSessionSubject(), groupId)), "AuthorizationManager.getImplicitGroupPermissions"); + try { + return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getImplicitGroupPermissions( + getSessionSubject(), groupId)), "AuthorizationManager.getImplicitGroupPermissions"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Set<Permission> getExplicitGlobalPermissions() { - return SerialUtility.prepare(new HashSet<Permission>(authorizationManager - .getExplicitGlobalPermissions(getSessionSubject())), "AuthorizationManager.getExplicitGlobalPermissions"); + try { + return SerialUtility.prepare(new HashSet<Permission>(authorizationManager + .getExplicitGlobalPermissions(getSessionSubject())), + "AuthorizationManager.getExplicitGlobalPermissions"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java index cbf72c7..4b636f0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java @@ -18,10 +18,10 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
-import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.measurement.Availability; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.AvailabilityGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.measurement.AvailabilityManagerLocal; @@ -32,15 +32,16 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class AvailabilityGWTServiceImpl extends AbstractGWTServiceImpl implements AvailabilityGWTService {
+ private static final long serialVersionUID = 1L;
private AvailabilityManagerLocal availabilityManager = LookupUtil.getAvailabilityManager();
public PageList<Availability> findAvailabilityForResource(int resourceId, PageControl pc) { - - return SerialUtility.prepare( - availabilityManager.findAvailabilityForResource(getSessionSubject(), resourceId, pc), - "AvailabilityService.findAvailabilityForResource" - ); - + try { + return SerialUtility.prepare(availabilityManager.findAvailabilityForResource(getSessionSubject(), + resourceId, pc), "AvailabilityService.findAvailabilityForResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ClusterGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ClusterGWTServiceImpl.java index f3f8323..211735d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ClusterGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ClusterGWTServiceImpl.java @@ -38,32 +38,28 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class ClusterGWTServiceImpl extends AbstractGWTServiceImpl implements ClusterGWTService {
+ private static final long serialVersionUID = 1L;
private ClusterManagerLocal clusterManager = LookupUtil.getClusterManager();
- public ResourceGroup createAutoClusterBackingGroup(ClusterKey clusterKey, boolean addResources) { - return SerialUtility.prepare( - clusterManager.createAutoClusterBackingGroup(getSessionSubject(), clusterKey, addResources), - "ClusterGWTServiceImpl.createAutoClusterBackingGroup"); + return SerialUtility.prepare(clusterManager.createAutoClusterBackingGroup(getSessionSubject(), clusterKey, + addResources), "ClusterGWTServiceImpl.createAutoClusterBackingGroup"); }
public ResourceGroup getAutoClusterBackingGroup(ClusterKey clusterKey) { - return SerialUtility.prepare( - clusterManager.getAutoClusterBackingGroup(getSessionSubject(), clusterKey), - "ClusterGWTServiceImpl.getAutoClusterBackingGroup"); + return SerialUtility.prepare(clusterManager.getAutoClusterBackingGroup(getSessionSubject(), clusterKey), + "ClusterGWTServiceImpl.getAutoClusterBackingGroup"); }
public List<Resource> getAutoClusterResources(ClusterKey clusterKey) { - return SerialUtility.prepare( - clusterManager.getAutoClusterResources(getSessionSubject(), clusterKey), - "ClusterGWTServiceImpl.getAutoClusterResources"); + return SerialUtility.prepare(clusterManager.getAutoClusterResources(getSessionSubject(), clusterKey), + "ClusterGWTServiceImpl.getAutoClusterResources"); }
public ClusterFlyweight getClusterTree(int groupId) { - return SerialUtility.prepare( - clusterManager.getClusterTree(getSessionSubject(), groupId), - "ClusterGWTServiceImpl.getClusterTree"); + return SerialUtility.prepare(clusterManager.getClusterTree(getSessionSubject(), groupId), + "ClusterGWTServiceImpl.getClusterTree");
} } 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 487b167..63b71a0 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,6 +1,5 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
-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; @@ -9,79 +8,97 @@ import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; -import org.rhq.core.domain.util.PageOrdering; +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.configuration.ConfigurationUpdateStillInProgressException; import org.rhq.enterprise.server.util.LookupUtil;
-import com.google.gwt.user.server.rpc.RemoteServiceServlet; - public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implements ConfigurationGWTService {
+ private static final long serialVersionUID = 1L;
private ConfigurationManagerLocal configurationManager = LookupUtil.getConfigurationManager();
public Configuration getPluginConfiguration(int resourceId) { - - - Configuration configuration = configurationManager.getPluginConfiguration(getSessionSubject(), resourceId); - - return SerialUtility.prepare(configuration, "PluginConfiguration"); + try { + Configuration configuration = configurationManager.getPluginConfiguration(getSessionSubject(), resourceId); + return SerialUtility.prepare(configuration, "PluginConfiguration"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public ConfigurationDefinition getPluginConfigurationDefinition(int resourceTypeId) { - - ConfigurationDefinition definition = configurationManager.getPluginConfigurationDefinitionForResourceType(getSessionSubject(), resourceTypeId); - return SerialUtility.prepare(definition, "PluginDefinition"); + try { + ConfigurationDefinition definition = configurationManager.getPluginConfigurationDefinitionForResourceType( + getSessionSubject(), resourceTypeId); + return SerialUtility.prepare(definition, "PluginDefinition"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- public Configuration getResourceConfiguration(int resourceId) { - - Configuration configuration = configurationManager.getResourceConfiguration(getSessionSubject(), resourceId); - return SerialUtility.prepare(configuration, "ResourceConfiguration"); + try { + Configuration configuration = configurationManager + .getResourceConfiguration(getSessionSubject(), resourceId); + return SerialUtility.prepare(configuration, "ResourceConfiguration"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public ConfigurationDefinition getResourceConfigurationDefinition(int resourceTypeId) { - - ConfigurationDefinition definition = configurationManager.getResourceConfigurationDefinitionWithTemplatesForResourceType(getSessionSubject(), resourceTypeId); - return SerialUtility.prepare(definition, "ResourceDefinition"); + try { + ConfigurationDefinition definition = configurationManager + .getResourceConfigurationDefinitionWithTemplatesForResourceType(getSessionSubject(), resourceTypeId); + return SerialUtility.prepare(definition, "ResourceDefinition"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- public PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdates( - Integer resourceId, Long beginDate, Long endDate, boolean suppressOldest, PageControl pc) { - - PageList<ResourceConfigurationUpdate> result = - configurationManager.findResourceConfigurationUpdates( - getSessionSubject(), resourceId, beginDate, endDate, suppressOldest, pc); - - return SerialUtility.prepare(result, "ConfigurationService.findResourceConfigurationUpdates"); + public PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdates(Integer resourceId, Long beginDate, + Long endDate, boolean suppressOldest, PageControl pc) { + try { + PageList<ResourceConfigurationUpdate> result = configurationManager.findResourceConfigurationUpdates( + getSessionSubject(), resourceId, beginDate, endDate, suppressOldest, pc); + return SerialUtility.prepare(result, "ConfigurationService.findResourceConfigurationUpdates"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- public ResourceConfigurationUpdate updateResourceConfiguration(int resourceId, Configuration configuration) { - ResourceConfigurationUpdate update = - configurationManager.updateResourceConfiguration(getSessionSubject(), resourceId, configuration); - - return SerialUtility.prepare(update, "ConfigurationService.updateResourceConfiguration"); + try { + ResourceConfigurationUpdate update = configurationManager.updateResourceConfiguration(getSessionSubject(), + resourceId, configuration); + return SerialUtility.prepare(update, "ConfigurationService.updateResourceConfiguration"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PluginConfigurationUpdate updatePluginConfiguration(int resourceId, Configuration configuration) { - PluginConfigurationUpdate update = - configurationManager.updatePluginConfiguration(getSessionSubject(), resourceId, configuration); - - return SerialUtility.prepare(update, "ConfigurationService.updatePluginConfiguration"); + try { + PluginConfigurationUpdate update = configurationManager.updatePluginConfiguration(getSessionSubject(), + resourceId, configuration); + return SerialUtility.prepare(update, "ConfigurationService.updatePluginConfiguration"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- public PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdatesByCriteria(ResourceConfigurationUpdateCriteria criteria) { - PageList<ResourceConfigurationUpdate> updates = - configurationManager.findResourceConfigurationUpdatesByCriteria( - getSessionSubject(), criteria - ); - - return SerialUtility.prepare(updates, "ConfigurationService.findResourceConfigurationUpdatesByCriteria"); + public PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdatesByCriteria( + ResourceConfigurationUpdateCriteria criteria) { + try { + PageList<ResourceConfigurationUpdate> updates = configurationManager + .findResourceConfigurationUpdatesByCriteria(getSessionSubject(), criteria); + return SerialUtility.prepare(updates, "ConfigurationService.findResourceConfigurationUpdatesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public RawConfiguration dummy(RawConfiguration config) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ContentGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ContentGWTServiceImpl.java index 91c45f8..2d112fb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ContentGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ContentGWTServiceImpl.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import org.rhq.core.domain.content.PackageVersion; import org.rhq.core.domain.criteria.PackageVersionCriteria; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ContentGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.content.ContentManagerLocal; @@ -35,16 +36,17 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class ContentGWTServiceImpl extends AbstractGWTServiceImpl implements ContentGWTService {
+ private static final long serialVersionUID = 1L;
private ContentManagerLocal contentManager = LookupUtil.getContentManager();
- - public PageList<PackageVersion> findPackageVersionsByCriteria(PackageVersionCriteria criteria) { - return SerialUtility.prepare(contentManager.findPackageVersionsByCriteria(getSessionSubject(), criteria), + try { + return SerialUtility.prepare(contentManager.findPackageVersionsByCriteria(getSessionSubject(), criteria), "ContentService.findPackageVersionsByCriteria"); - + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java index 1d28f7d..742c68e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import java.util.List;
import org.rhq.core.domain.dashboard.Dashboard; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.DashboardGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.dashboard.DashboardManagerLocal; @@ -35,25 +36,42 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class DashboardGWTServiceImpl extends AbstractGWTServiceImpl implements DashboardGWTService {
- private DashboardManagerLocal dashboardManager = LookupUtil.getDashboardManagerLocal(); + private static final long serialVersionUID = 1L;
+ private DashboardManagerLocal dashboardManager = LookupUtil.getDashboardManagerLocal();
public List<Dashboard> findDashboardsForSubject() { - return SerialUtility.prepare(dashboardManager.findDashboardsForSubject(getSessionSubject()), + try { + return SerialUtility.prepare(dashboardManager.findDashboardsForSubject(getSessionSubject()), "DashboardManager.findDashboardsForSubject"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public List<Dashboard> findSharedDashboards() { - return SerialUtility.prepare(dashboardManager.findSharedDashboards(getSessionSubject()), + try { + return SerialUtility.prepare(dashboardManager.findSharedDashboards(getSessionSubject()), "DashboardManager.findSharedDashboards"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Dashboard storeDashboard(Dashboard dashboard) { - return SerialUtility.prepare(dashboardManager.storeDashboard(getSessionSubject(),dashboard), + try { + return SerialUtility.prepare(dashboardManager.storeDashboard(getSessionSubject(), dashboard), "DashboardManager.storeDashboard"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void removeDashboard(int dashboardId) { - dashboardManager.removeDashboard(getSessionSubject(), dashboardId); + try { + dashboardManager.removeDashboard(getSessionSubject(), dashboardId); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java index 665f370..3dbae8e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java @@ -30,6 +30,7 @@ import org.rhq.core.domain.event.Event; import org.rhq.core.domain.event.EventSeverity; import org.rhq.core.domain.event.composite.EventComposite; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.EventGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.event.EventManagerLocal; @@ -46,37 +47,66 @@ public class EventGWTServiceImpl extends AbstractGWTServiceImpl implements Event private EventManagerLocal eventManager = LookupUtil.getEventManager();
public EventSeverity[] getSeverityBuckets(int resourceId, long begin, long end, int numBuckets) { - return SerialUtility.prepare(eventManager.getSeverityBuckets(getSessionSubject(), resourceId, begin, end, - numBuckets), "EventService.getSeverityBuckets"); + try { + return SerialUtility.prepare(eventManager.getSeverityBuckets(getSessionSubject(), resourceId, begin, end, + numBuckets), "EventService.getSeverityBuckets"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public EventSeverity[] getSeverityBucketsForAutoGroup(int parentResourceId, int resourceTypeId, long begin, long end, int numBuckets) { - return SerialUtility.prepare(eventManager.getSeverityBucketsForAutoGroup(getSessionSubject(), parentResourceId, - resourceTypeId, begin, end, numBuckets), "EventService.getSeverityBucketsForAutoGroup"); + try { + return SerialUtility.prepare(eventManager.getSeverityBucketsForAutoGroup(getSessionSubject(), + parentResourceId, resourceTypeId, begin, end, numBuckets), + "EventService.getSeverityBucketsForAutoGroup"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public EventSeverity[] getSeverityBucketsForCompGroup(int resourceGroupId, long begin, long end, int numBuckets) { - return SerialUtility.prepare(eventManager.getSeverityBucketsForCompGroup(getSessionSubject(), resourceGroupId, - begin, end, numBuckets), "EventService.getSeverityBucketsForCompGroup"); + try { + return SerialUtility.prepare(eventManager.getSeverityBucketsForCompGroup(getSessionSubject(), + resourceGroupId, begin, end, numBuckets), "EventService.getSeverityBucketsForCompGroup"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<Event> findEventsByCriteria(EventCriteria criteria) { - return SerialUtility.prepare(eventManager.findEventsByCriteria(getSessionSubject(), criteria), - "EventService.findEventsByCriteria"); + try { + return SerialUtility.prepare(eventManager.findEventsByCriteria(getSessionSubject(), criteria), + "EventService.findEventsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<EventComposite> findEventCompositesByCriteria(EventCriteria criteria) { - return SerialUtility.prepare(eventManager.findEventCompositesByCriteria(getSessionSubject(), criteria), - "EventService.findEventsByCriteria"); + try { + return SerialUtility.prepare(eventManager.findEventCompositesByCriteria(getSessionSubject(), criteria), + "EventService.findEventsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public int deleteEventsForContext(EntityContext context, List<Integer> eventIds) { - return eventManager.deleteEventsForContext(getSessionSubject(), context, eventIds); + try { + return eventManager.deleteEventsForContext(getSessionSubject(), context, eventIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public int purgeEventsForContext(EntityContext context) { - return eventManager.purgeEventsForContext(getSessionSubject(), context); + try { + return eventManager.purgeEventsForContext(getSessionSubject(), context); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
} 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 78232b6..1cc9170 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 @@ -34,6 +34,7 @@ import org.rhq.core.domain.measurement.composite.MeasurementDataNumericHighLowCo import org.rhq.core.domain.measurement.composite.MeasurementOOBComposite; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.MeasurementDataGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.measurement.CallTimeDataManagerLocal; @@ -58,89 +59,140 @@ public class MeasurementDataGWTServiceImpl extends AbstractGWTServiceImpl implem private MeasurementDefinitionManagerLocal definitionManager = LookupUtil.getMeasurementDefinitionManager();
public List<MeasurementDataTrait> findCurrentTraitsForResource(int resourceId, DisplayType displayType) { - return SerialUtility.prepare(dataManager.findCurrentTraitsForResource(getSessionSubject(), resourceId, - displayType), "MeasurementDataService.findCurrentTraitsForResource"); + try { + return SerialUtility.prepare(dataManager.findCurrentTraitsForResource(getSessionSubject(), resourceId, + displayType), "MeasurementDataService.findCurrentTraitsForResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Set<MeasurementData> findLiveData(int resourceId, int[] definitionIds) { - return SerialUtility.prepare(dataManager.findLiveData(getSessionSubject(), resourceId, definitionIds), - "MeasurementDataService.findLiveData"); + try { + return SerialUtility.prepare(dataManager.findLiveData(getSessionSubject(), resourceId, definitionIds), + "MeasurementDataService.findLiveData"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public List<List<MeasurementDataNumericHighLowComposite>> findDataForResource(int resourceId, int[] definitionIds, long beginTime, long endTime, int numPoints) { - return SerialUtility.prepare(dataManager.findDataForResource(getSessionSubject(), resourceId, definitionIds, - beginTime, endTime, numPoints), "MeasurementDataService.findDataForResource"); + try { + return SerialUtility.prepare(dataManager.findDataForResource(getSessionSubject(), resourceId, + definitionIds, beginTime, endTime, numPoints), "MeasurementDataService.findDataForResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<CallTimeDataComposite> findCallTimeDataForResource(int scheduleId, long start, long end, PageControl pageControl) { - return SerialUtility.prepare(callTimeDataManager.findCallTimeDataForResource(getSessionSubject(), scheduleId, - start, end, pageControl), "MeasurementDataService.findCallTimeDataForResource"); + try { + return SerialUtility.prepare(callTimeDataManager.findCallTimeDataForResource(getSessionSubject(), + scheduleId, start, end, pageControl), "MeasurementDataService.findCallTimeDataForResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<MeasurementDefinition> findMeasurementDefinitionsByCriteria(MeasurementDefinitionCriteria criteria) { - return SerialUtility.prepare(definitionManager.findMeasurementDefinitionsByCriteria(getSessionSubject(), - criteria), "MeasurementDataService.findMeasurementDefinintionsByCriteria"); + try { + return SerialUtility.prepare(definitionManager.findMeasurementDefinitionsByCriteria(getSessionSubject(), + criteria), "MeasurementDataService.findMeasurementDefinintionsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<MeasurementSchedule> findMeasurementSchedulesByCriteria(MeasurementScheduleCriteria criteria) { - return SerialUtility.prepare(scheduleManager.findSchedulesByCriteria(getSessionSubject(), criteria), - "MeasurementDataService.findMeasurementSchedulesByCriteria"); + try { + return SerialUtility.prepare(scheduleManager.findSchedulesByCriteria(getSessionSubject(), criteria), + "MeasurementDataService.findMeasurementSchedulesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- - public PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, String resourceNameFilter, String parentNameFilter, PageControl pc) { - return SerialUtility.prepare( - measurementOOBManager.getSchedulesWithOOBs( - getSessionSubject(), - metricNameFilter, - resourceNameFilter, - parentNameFilter, - pc), + public PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, String resourceNameFilter, + String parentNameFilter, PageControl pc) { + try { + return SerialUtility.prepare(measurementOOBManager.getSchedulesWithOOBs(getSessionSubject(), + metricNameFilter, resourceNameFilter, parentNameFilter, pc), "MeasurementDataService.getSchedulesWithOOBs"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<MeasurementOOBComposite> getHighestNOOBsForResource(int resourceId, int n) { - return SerialUtility.prepare( - measurementOOBManager.getHighestNOOBsForResource( - getSessionSubject(), - resourceId, - n), - "MeasurementDataService.getHighestNOOBsForResource"); + try { + return SerialUtility.prepare(measurementOOBManager.getHighestNOOBsForResource(getSessionSubject(), + resourceId, n), "MeasurementDataService.getHighestNOOBsForResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void enableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) { - scheduleManager.enableSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds); + try { + scheduleManager.enableSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void disableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) { - scheduleManager.disableSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds); + try { + scheduleManager.disableSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateSchedulesForResource(int resourceId, int[] measurementDefinitionIds, long collectionInterval) { - scheduleManager.updateSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds, + try { + scheduleManager.updateSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds, collectionInterval); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void enableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) { - scheduleManager.enableSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, measurementDefinitionIds); + try { + scheduleManager.enableSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, + measurementDefinitionIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void disableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) { - scheduleManager.disableSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, measurementDefinitionIds); + try { + scheduleManager.disableSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, + measurementDefinitionIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds, - long collectionInterval) { - scheduleManager.updateSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, measurementDefinitionIds, - collectionInterval); - } + long collectionInterval) { + try { + scheduleManager.updateSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, + measurementDefinitionIds, collectionInterval); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + }
public PageList<MeasurementDataTrait> findTraitsByCriteria(MeasurementDataTraitCriteria criteria) { - return SerialUtility.prepare(dataManager.findTraitsByCriteria(getSessionSubject(), criteria), - "MeasurementDataService.findTraitsByCriteria"); + try { + return SerialUtility.prepare(dataManager.findTraitsByCriteria(getSessionSubject(), criteria), + "MeasurementDataService.findTraitsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } - - diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java index 62dc79b..7c3acfb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ObjectFilter.java @@ -18,22 +18,20 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
-import org.rhq.core.domain.resource.Resource; - import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; -import java.util.List; import java.util.Set;
+import org.rhq.core.domain.resource.Resource; + /** * @author Greg Hinkle */ public class ObjectFilter {
- public static <T extends Collection<?>> T filterFieldsInCollection(T collection, Set<String> goodFields) { long sizeOfBefore = sizeOf(collection); for (Object object : collection) { @@ -45,7 +43,6 @@ public class ObjectFilter { }
public static <T> T filterFields(T object, Set<String> goodFields) { - try { Field[] fields = Resource.class.getDeclaredFields(); for (Field f : fields) { @@ -54,11 +51,11 @@ public class ObjectFilter { // Only clearing objects, no point in clearing primitives as it // doesn't save any space on the stream if (!f.getType().isPrimitive()) { -// System.out.println("clearing " + f.getName()); + // System.out.println("clearing " + f.getName()); f.setAccessible(true); f.set(object, null); } else { -// System.out.println("Can't do " + f.getType()); + // System.out.println("Can't do " + f.getType()); } } } @@ -67,11 +64,9 @@ public class ObjectFilter { e.printStackTrace(); }
- return object; }
- private static int sizeOf(Object object) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(50000); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java index a7f72ed..4519e00 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java @@ -33,6 +33,7 @@ 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.core.util.IntExtractor; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.OperationGWTService; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.create.ExecutionSchedule; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; @@ -52,29 +53,33 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O
public PageList<ResourceOperationHistory> findResourceOperationHistoriesByCriteria( ResourceOperationHistoryCriteria criteria) { - return SerialUtility.prepare(operationManager.findResourceOperationHistoriesByCriteria(getSessionSubject(), - criteria), "OperationService.findResourceOperationHistoriesByCriteria"); - + try { + return SerialUtility.prepare(operationManager.findResourceOperationHistoriesByCriteria(getSessionSubject(), + criteria), "OperationService.findResourceOperationHistoriesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<GroupOperationHistory> findGroupOperationHistoriesByCriteria(GroupOperationHistoryCriteria criteria) { - return SerialUtility.prepare(operationManager.findGroupOperationHistoriesByCriteria(getSessionSubject(), - criteria), "OperationService.findGroupOperationHistoriesByCriteria"); + try { + return SerialUtility.prepare(operationManager.findGroupOperationHistoriesByCriteria(getSessionSubject(), + criteria), "OperationService.findGroupOperationHistoriesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void scheduleResourceOperation(int resourceId, String operationName, Configuration parameters, ExecutionSchedule schedule, String description, int timeout) throws RuntimeException { - ResourceOperationSchedule opSchedule; try { - + ResourceOperationSchedule opSchedule; if (schedule.getStart() == ExecutionSchedule.Start.Immediately) { opSchedule = operationManager.scheduleResourceOperation(getSessionSubject(), resourceId, operationName, 0, 0, 0, 0, parameters, description); } else { - CronTrigger ct = new CronTrigger("resource " + resourceId + "_" + operationName, "group", schedule .getCronString()); - opSchedule = operationManager.scheduleResourceOperation(getSessionSubject(), resourceId, operationName, parameters, ct, description); } @@ -88,34 +93,40 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O */ public List<DisambiguationReport<ResourceOperationLastCompletedComposite>> findRecentCompletedOperations( int pageSize) { + try { + PageControl pageControl = new PageControl(0, pageSize); + PageList<ResourceOperationLastCompletedComposite> lastCompletedResourceOps = operationManager + .findRecentlyCompletedResourceOperations(getSessionSubject(), null, pageControl);
- PageControl pageControl = new PageControl(0, pageSize); - PageList<ResourceOperationLastCompletedComposite> lastCompletedResourceOps = operationManager - .findRecentlyCompletedResourceOperations(getSessionSubject(), null, pageControl); - - //translate the returned problem resources to disambiguated links - List<DisambiguationReport<ResourceOperationLastCompletedComposite>> disambiguatedLastCompletedResourceOps = resourceManager - .disambiguate(lastCompletedResourceOps, RESOURCE_OPERATION_RESOURCE_ID_EXTRACTOR, - DefaultDisambiguationUpdateStrategies.getDefault()); + //translate the returned problem resources to disambiguated links + List<DisambiguationReport<ResourceOperationLastCompletedComposite>> disambiguatedLastCompletedResourceOps = resourceManager + .disambiguate(lastCompletedResourceOps, RESOURCE_OPERATION_RESOURCE_ID_EXTRACTOR, + DefaultDisambiguationUpdateStrategies.getDefault());
- return disambiguatedLastCompletedResourceOps; + return disambiguatedLastCompletedResourceOps; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
/** Find scheduled operations, disambiguate them and return that list. * */ public List<DisambiguationReport<ResourceOperationScheduleComposite>> findScheduledOperations(int pageSize) { + try { + PageControl pageControl = new PageControl(0, pageSize); + PageList<ResourceOperationScheduleComposite> scheduledResourceOps = operationManager + .findCurrentlyScheduledResourceOperations(getSessionSubject(), pageControl);
- PageControl pageControl = new PageControl(0, pageSize); - PageList<ResourceOperationScheduleComposite> scheduledResourceOps = operationManager - .findCurrentlyScheduledResourceOperations(getSessionSubject(), pageControl); - - //translate the returned problem resources to disambiguated links - List<DisambiguationReport<ResourceOperationScheduleComposite>> disambiguatedNextScheduledResourceOps = resourceManager - .disambiguate(scheduledResourceOps, RESOURCE_OPERATION_SCHEDULE_RESOURCE_ID_EXTRACTOR, - DefaultDisambiguationUpdateStrategies.getDefault()); + //translate the returned problem resources to disambiguated links + List<DisambiguationReport<ResourceOperationScheduleComposite>> disambiguatedNextScheduledResourceOps = resourceManager + .disambiguate(scheduledResourceOps, RESOURCE_OPERATION_SCHEDULE_RESOURCE_ID_EXTRACTOR, + DefaultDisambiguationUpdateStrategies.getDefault());
- return disambiguatedNextScheduledResourceOps; + return disambiguatedNextScheduledResourceOps; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
private static final IntExtractor<ResourceOperationLastCompletedComposite> RESOURCE_OPERATION_RESOURCE_ID_EXTRACTOR = new IntExtractor<ResourceOperationLastCompletedComposite>() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java index 45c2c5e..073a6f7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import org.rhq.core.domain.content.Repo; import org.rhq.core.domain.criteria.RepoCriteria; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.RepoGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.content.RepoManagerLocal; @@ -35,13 +36,17 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class RepoGWTServiceImpl extends AbstractGWTServiceImpl implements RepoGWTService {
+ private static final long serialVersionUID = 1L; + private RepoManagerLocal repoManager = LookupUtil.getRepoManagerLocal();
public PageList<Repo> findReposByCriteria(RepoCriteria criteria) { - return SerialUtility.prepare( - repoManager.findReposByCriteria(getSessionSubject(), criteria), + try { + return SerialUtility.prepare(repoManager.findReposByCriteria(getSessionSubject(), criteria), "ContentService.findReposByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
- } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java index 5ac22b5..fb00c3a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.resource.InventorySummary; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceBossGWTService; import org.rhq.enterprise.server.resource.ResourceBossLocal; import org.rhq.enterprise.server.util.LookupUtil; @@ -34,6 +35,8 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class ResourceBossGWTServiceImpl extends AbstractGWTServiceImpl implements ResourceBossGWTService {
+ private static final long serialVersionUID = 1L; + private ResourceBossLocal resourceBoss = LookupUtil.getResourceBoss();
public InventorySummary getInventorySummaryForLoggedInUser() { @@ -42,6 +45,10 @@ public class ResourceBossGWTServiceImpl extends AbstractGWTServiceImpl implement }
public InventorySummary getInventorySummary(Subject user) { - return resourceBoss.getInventorySummary(user); + try { + return resourceBoss.getInventorySummary(user); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } 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 2e2f6d6..14c6f8d 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 @@ -43,6 +43,7 @@ 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; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.discovery.DiscoveryBossLocal; @@ -57,6 +58,8 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements ResourceGWTService {
+ private static final long serialVersionUID = 1L; + private ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); private ResourceFactoryManagerLocal resourceFactoryManager = LookupUtil.getResourceFactoryManager(); private DiscoveryBossLocal discoveryBoss = LookupUtil.getDiscoveryBoss(); @@ -122,8 +125,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re
return SerialUtility.prepare(result, "ResourceService.findResourcesByCriteria"); } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } }
@@ -139,8 +141,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re
return SerialUtility.prepare(result, "ResourceService.findResourceCompositesByCriteria"); } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } }
@@ -148,18 +149,21 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re * Criteria passed in not currently used. */ public List<DisambiguationReport<ProblemResourceComposite>> findProblemResources(long ctime, int maxItems) { + try { + List<ProblemResourceComposite> located = new ArrayList<ProblemResourceComposite>(); + MeasurementProblemManagerLocal problemManager = LookupUtil.getMeasurementProblemManager(); + ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
- List<ProblemResourceComposite> located = new ArrayList<ProblemResourceComposite>(); - MeasurementProblemManagerLocal problemManager = LookupUtil.getMeasurementProblemManager(); - ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); - - //retrieve list of discovered problem resources. Grab all, live scrolling data - located = problemManager.findProblemResources(getSessionSubject(), ctime, new PageControl(0, maxItems)); + //retrieve list of discovered problem resources. Grab all, live scrolling data + located = problemManager.findProblemResources(getSessionSubject(), ctime, new PageControl(0, maxItems));
- //translate the returned problem resources to disambiguated links - List<DisambiguationReport<ProblemResourceComposite>> translated = resourceManager.disambiguate(located, - RESOURCE_ID_EXTRACTOR, DefaultDisambiguationUpdateStrategies.getDefault()); - return translated; + //translate the returned problem resources to disambiguated links + List<DisambiguationReport<ProblemResourceComposite>> translated = resourceManager.disambiguate(located, + RESOURCE_ID_EXTRACTOR, DefaultDisambiguationUpdateStrategies.getDefault()); + return translated; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
private static final IntExtractor<ProblemResourceComposite> RESOURCE_ID_EXTRACTOR = new IntExtractor<ProblemResourceComposite>() { @@ -169,71 +173,112 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re };
public List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId) { - return SerialUtility.prepare(resourceManager.getResourceLineageAndSiblings(getSessionSubject(), resourceId), - "ResourceService.getResourceLineageAndSiblings"); + try { + return SerialUtility.prepare( + resourceManager.getResourceLineageAndSiblings(getSessionSubject(), resourceId), + "ResourceService.getResourceLineageAndSiblings"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Resource getPlatformForResource(int resourceId) { - return SerialUtility.prepare(resourceManager.getRootResourceForResource(resourceId), - "ResourceService.getPlatformForResource"); + try { + return SerialUtility.prepare(resourceManager.getRootResourceForResource(resourceId), + "ResourceService.getPlatformForResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public List<RecentlyAddedResourceComposite> findRecentlyAddedResources(long ctime, int maxItems) { - List<RecentlyAddedResourceComposite> platforms = resourceManager.findRecentlyAddedPlatforms( - getSessionSubject(), ctime, maxItems); + try { + List<RecentlyAddedResourceComposite> platforms = resourceManager.findRecentlyAddedPlatforms( + getSessionSubject(), ctime, maxItems);
- for (RecentlyAddedResourceComposite platform : platforms) { - List<RecentlyAddedResourceComposite> servers = resourceManager.findRecentlyAddedServers( - getSessionSubject(), ctime, platform.getId()); - platform.setChildren(servers); - } + for (RecentlyAddedResourceComposite platform : platforms) { + List<RecentlyAddedResourceComposite> servers = resourceManager.findRecentlyAddedServers( + getSessionSubject(), ctime, platform.getId()); + platform.setChildren(servers); + }
- return platforms; + return platforms; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public List<Integer> uninventoryResources(int[] resourceIds) { - return SerialUtility.prepare(resourceManager.uninventoryResources(getSessionSubject(), resourceIds), - "ResourceService.uninventoryResources"); + try { + return SerialUtility.prepare(resourceManager.uninventoryResources(getSessionSubject(), resourceIds), + "ResourceService.uninventoryResources"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateResource(Resource resource) { - resourceManager.updateResource(getSessionSubject(), resource); + try { + resourceManager.updateResource(getSessionSubject(), resource); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void createResource(int parentResourceId, int newResourceTypeId, String newResourceName, Configuration newResourceConfiguration) { + try {
- ConfigurationDefinition pluginConfigDefinition = LookupUtil.getConfigurationManager() - .getPluginConfigurationDefinitionForResourceType(getSessionSubject(), newResourceTypeId); - Configuration pluginConfig = null; - if (pluginConfigDefinition != null) { - ConfigurationTemplate pluginConfigTemplate = pluginConfigDefinition.getDefaultTemplate(); - pluginConfig = (pluginConfigTemplate != null) ? pluginConfigTemplate.createConfiguration() - : new Configuration(); + ConfigurationDefinition pluginConfigDefinition = LookupUtil.getConfigurationManager() + .getPluginConfigurationDefinitionForResourceType(getSessionSubject(), newResourceTypeId); + Configuration pluginConfig = null; + if (pluginConfigDefinition != null) { + ConfigurationTemplate pluginConfigTemplate = pluginConfigDefinition.getDefaultTemplate(); + pluginConfig = (pluginConfigTemplate != null) ? pluginConfigTemplate.createConfiguration() + : new Configuration();
- // TODO GH: Is this still necessary now that we don't blow up on non-normalized configs - // ConfigurationUtility.normalizeConfiguration(pluginConfig, pluginConfigDefinition); - } + // TODO GH: Is this still necessary now that we don't blow up on non-normalized configs + // ConfigurationUtility.normalizeConfiguration(pluginConfig, pluginConfigDefinition); + }
- resourceFactoryManager.createResource(getSessionSubject(), parentResourceId, newResourceTypeId, - newResourceName, pluginConfig, newResourceConfiguration); + resourceFactoryManager.createResource(getSessionSubject(), parentResourceId, newResourceTypeId, + newResourceName, pluginConfig, newResourceConfiguration); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Map<Resource, List<Resource>> getQueuedPlatformsAndServers(HashSet<InventoryStatus> statuses, PageControl pc) { - return SerialUtility.prepare(discoveryBoss.getQueuedPlatformsAndServers(getSessionSubject(), EnumSet - .copyOf(statuses), pc), "ResourceService.getQueuedPlatformsAndServers"); + try { + return SerialUtility.prepare(discoveryBoss.getQueuedPlatformsAndServers(getSessionSubject(), EnumSet + .copyOf(statuses), pc), "ResourceService.getQueuedPlatformsAndServers"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void importResources(Integer[] resourceIds) { - discoveryBoss.importResources(getSessionSubject(), resourceIds); + try { + discoveryBoss.importResources(getSessionSubject(), resourceIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void ignoreResources(Integer[] resourceIds) { - discoveryBoss.ignoreResources(getSessionSubject(), resourceIds); + try { + discoveryBoss.ignoreResources(getSessionSubject(), resourceIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void unignoreResources(Integer[] resourceIds) { - discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); + try { + discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
} \ No newline at end of file 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 6ff33b3..c74aa3c 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,25 +1,28 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
-import com.google.gwt.user.server.rpc.RemoteServiceServlet; - -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 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.auth.SubjectManagerLocal; import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implements ResourceTypeGWTService {
- public PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria) { + private static final long serialVersionUID = 1L;
- ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); + public PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria) { + try { + ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager();
- return SerialUtility.prepare(typeManager.findResourceTypesByCriteria(getSessionSubject(), criteria), "ResourceTypes.findResourceTypesByCriteria"); + return SerialUtility.prepare(typeManager.findResourceTypesByCriteria(getSessionSubject(), criteria), + "ResourceTypes.findResourceTypesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public RawConfiguration dummy(RawConfiguration config) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java index 7b278e1..ed7e50d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.criteria.RoleCriteria; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.RoleGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.authz.RoleManagerLocal; @@ -31,34 +32,64 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class RoleGWTServiceImpl extends AbstractGWTServiceImpl implements RoleGWTService {
+ private static final long serialVersionUID = 1L; + private RoleManagerLocal roleManager = LookupUtil.getRoleManager();
public PageList<Role> findRolesByCriteria(RoleCriteria criteria) { - return SerialUtility.prepare(roleManager.findRolesByCriteria(getSessionSubject(), criteria), - "RoleService.findRolesByCriteria"); + try { + return SerialUtility.prepare(roleManager.findRolesByCriteria(getSessionSubject(), criteria), + "RoleService.findRolesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Role createRole(Role role) { - return SerialUtility.prepare(roleManager.createRole(getSessionSubject(), role), "RoleService.createRole"); + try { + return SerialUtility.prepare(roleManager.createRole(getSessionSubject(), role), "RoleService.createRole"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Role updateRole(Role role) { - return SerialUtility.prepare(roleManager.updateRole(getSessionSubject(), role), "RoleService.updateRole"); + try { + return SerialUtility.prepare(roleManager.updateRole(getSessionSubject(), role), "RoleService.updateRole"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void removeRoles(Integer[] roleIds) { - roleManager.deleteRoles(getSessionSubject(), roleIds); + try { + roleManager.deleteRoles(getSessionSubject(), roleIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void setAssignedResourceGroups(int roleId, int[] resourceGroupIds) { - roleManager.setAssignedResourceGroups(getSessionSubject(), roleId, resourceGroupIds); + try { + roleManager.setAssignedResourceGroups(getSessionSubject(), roleId, resourceGroupIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void setAssignedSubjects(int roleId, int[] subjectIds) { - roleManager.setAssignedSubjects(getSessionSubject(), roleId, subjectIds); + try { + roleManager.setAssignedSubjects(getSessionSubject(), roleId, subjectIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void setAssignedRolesForSubject(int subjectId, int[] roleIds) { - roleManager.setAssignedSubjectRoles(getSessionSubject(), subjectId, roleIds); + try { + roleManager.setAssignedSubjectRoles(getSessionSubject(), subjectId, roleIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java index cff798c..ae72b4c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java @@ -24,6 +24,7 @@ import org.rhq.core.domain.criteria.SavedSearchCriteria; import org.rhq.core.domain.search.SavedSearch; import org.rhq.core.domain.search.SearchSubsystem; import org.rhq.core.domain.search.SearchSuggestion; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.SearchGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.search.SavedSearchManagerLocal; @@ -35,36 +36,62 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class SearchGWTServiceImpl extends AbstractGWTServiceImpl implements SearchGWTService {
+ private static final long serialVersionUID = 1L; + private SavedSearchManagerLocal savedSearchManager = LookupUtil.getSavedSearchManager();
public List<SearchSuggestion> getTabAwareSuggestions(SearchSubsystem searchSubsystem, String expression, int caretPosition, String tab) { - SearchAssistManager searchAssistManager = new SearchAssistManager(getSessionSubject(), searchSubsystem); - List<SearchSuggestion> results = searchAssistManager.getTabAwareSuggestions(expression, caretPosition, tab); - return results; + try { + SearchAssistManager searchAssistManager = new SearchAssistManager(getSessionSubject(), searchSubsystem); + List<SearchSuggestion> results = searchAssistManager.getTabAwareSuggestions(expression, caretPosition, tab); + return results; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public List<SearchSuggestion> getSuggestions(SearchSubsystem searchSubsystem, String expression, int caretPosition) { - SearchAssistManager searchAssistManager = new SearchAssistManager(getSessionSubject(), searchSubsystem); - List<SearchSuggestion> results = searchAssistManager.getSuggestions(expression, caretPosition); - return results; + try { + SearchAssistManager searchAssistManager = new SearchAssistManager(getSessionSubject(), searchSubsystem); + List<SearchSuggestion> results = searchAssistManager.getSuggestions(expression, caretPosition); + return results; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public int createSavedSearch(SavedSearch savedSearch) { - return savedSearchManager.createSavedSearch(getSessionSubject(), savedSearch); + try { + return savedSearchManager.createSavedSearch(getSessionSubject(), savedSearch); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateSavedSearch(SavedSearch savedSearch) { - savedSearchManager.updateSavedSearch(getSessionSubject(), savedSearch); + try { + savedSearchManager.updateSavedSearch(getSessionSubject(), savedSearch); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void deleteSavedSearch(int savedSearchId) { - savedSearchManager.deleteSavedSearch(getSessionSubject(), savedSearchId); + try { + savedSearchManager.deleteSavedSearch(getSessionSubject(), savedSearchId); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public List<SavedSearch> findSavedSearchesByCriteria(SavedSearchCriteria criteria) { - return SerialUtility.prepare(savedSearchManager.findSavedSearchesByCriteria(getSessionSubject(), criteria), - "SearchService.findRolesByCriteria"); + try { + return SerialUtility.prepare(savedSearchManager.findSavedSearchesByCriteria(getSessionSubject(), criteria), + "SearchService.findRolesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java index 32e1d2c..6f86e45 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java @@ -21,35 +21,53 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.SubjectCriteria; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.SubjectGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.exception.LoginException; import org.rhq.enterprise.server.util.LookupUtil;
- /** * @author Greg Hinkle */ public class SubjectGWTServiceImpl extends AbstractGWTServiceImpl implements SubjectGWTService {
+ private static final long serialVersionUID = 1L; + private SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager();
public void changePassword(String username, String password) { - subjectManager.changePassword(getSessionSubject(), username, password); + try { + subjectManager.changePassword(getSessionSubject(), username, password); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void createPrincipal(String username, String password) { - subjectManager.createPrincipal(getSessionSubject(), username, password); + try { + subjectManager.createPrincipal(getSessionSubject(), username, password); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Subject createSubject(Subject subjectToCreate) { - return SerialUtility.prepare(subjectManager.createSubject(getSessionSubject(), subjectToCreate), + try { + return SerialUtility.prepare(subjectManager.createSubject(getSessionSubject(), subjectToCreate), "SubjectManager.createSubject"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void deleteSubjects(int[] subjectIds) { - subjectManager.deleteSubjects(getSessionSubject(),subjectIds); + try { + subjectManager.deleteSubjects(getSessionSubject(), subjectIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Subject login(String username, String password) { @@ -61,15 +79,28 @@ public class SubjectGWTServiceImpl extends AbstractGWTServiceImpl implements Sub }
public void logout(Subject subject) { - subjectManager.logout(subject.getSessionId()); + try { + subjectManager.logout(subject.getSessionId()); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Subject updateSubject(Subject subjectToModify) { - return SerialUtility.prepare(subjectManager.updateSubject(getSessionSubject(), subjectToModify), + try { + return SerialUtility.prepare(subjectManager.updateSubject(getSessionSubject(), subjectToModify), "SubjectManager.updateSubject"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<Subject> findSubjectsByCriteria(SubjectCriteria criteria) { - return SerialUtility.prepare(subjectManager.findSubjectsByCriteria(getSessionSubject(), criteria), "SubjectManager.findSubjectsByCriteria"); + try { + return SerialUtility.prepare(subjectManager.findSubjectsByCriteria(getSessionSubject(), criteria), + "SubjectManager.findSubjectsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java index af12a6a..43431c7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import org.rhq.core.domain.common.ProductInfo; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.SystemGWTService; import org.rhq.enterprise.server.system.SystemManagerLocal; import org.rhq.enterprise.server.util.LookupUtil; @@ -27,9 +28,16 @@ import org.rhq.enterprise.server.util.LookupUtil; * @author Ian Springer */ public class SystemGWTServiceImpl extends AbstractGWTServiceImpl implements SystemGWTService { + + private static final long serialVersionUID = 1L; + private SystemManagerLocal systemManager = LookupUtil.getSystemManager();
public ProductInfo getProductInfo() { - return this.systemManager.getProductInfo(getSessionSubject()); + try { + return this.systemManager.getProductInfo(getSessionSubject()); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/TagGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/TagGWTServiceImpl.java index 20add85..7ab6941 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/TagGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/TagGWTServiceImpl.java @@ -28,6 +28,7 @@ import org.rhq.core.domain.criteria.TagCriteria; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.tagging.compsite.TagReportComposite; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.TagGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.tagging.TagManagerLocal; @@ -38,49 +39,90 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class TagGWTServiceImpl extends AbstractGWTServiceImpl implements TagGWTService {
+ private static final long serialVersionUID = 1L; + private TagManagerLocal tagManager = LookupUtil.getTagManager();
public PageList<Tag> findTagsByCriteria(TagCriteria tagCriteria) { - return SerialUtility.prepare(tagManager.findTagsByCriteria(getSessionSubject(), tagCriteria), + try { + return SerialUtility.prepare(tagManager.findTagsByCriteria(getSessionSubject(), tagCriteria), "TagService.findTagsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public Set<Tag> addTags(Set<Tag> tags) { - return SerialUtility.prepare( - tagManager.addTags(getSessionSubject(), tags), - "TagService.addTags"); + try { + return SerialUtility.prepare(tagManager.addTags(getSessionSubject(), tags), "TagService.addTags"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void removeTags(Set<Tag> tags) { - tagManager.removeTags(getSessionSubject(), tags); + try { + tagManager.removeTags(getSessionSubject(), tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateResourceTags(int resourceId, Set<Tag> tags) { - tagManager.updateResourceTags(getSessionSubject(), resourceId, tags); + try { + tagManager.updateResourceTags(getSessionSubject(), resourceId, tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateResourceGroupTags(int resourceGroupId, Set<Tag> tags) { - tagManager.updateResourceGroupTags(getSessionSubject(), resourceGroupId, tags); + try { + tagManager.updateResourceGroupTags(getSessionSubject(), resourceGroupId, tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateBundleTags(int bundleId, Set<Tag> tags) { - tagManager.updateBundleTags(getSessionSubject(), bundleId, tags); + try { + tagManager.updateBundleTags(getSessionSubject(), bundleId, tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateBundleVersionTags(int bundleVersionId, Set<Tag> tags) { - tagManager.updateBundleVersionTags(getSessionSubject(), bundleVersionId, tags); + try { + tagManager.updateBundleVersionTags(getSessionSubject(), bundleVersionId, tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateBundleDeploymentTags(int bundleDeploymentId, Set<Tag> tags) { - tagManager.updateBundleDeploymentTags(getSessionSubject(), bundleDeploymentId, tags); + try { + tagManager.updateBundleDeploymentTags(getSessionSubject(), bundleDeploymentId, tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public void updateBundleDestinationTags(int bundleDestinationId, Set<Tag> tags) { - tagManager.updateBundleDestinationTags(getSessionSubject(), bundleDestinationId, tags); + try { + tagManager.updateBundleDestinationTags(getSessionSubject(), bundleDestinationId, tags); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
public PageList<TagReportComposite> findTagReportCompositesByCriteria(TagCriteria tagCriteria) { - return SerialUtility.prepare(tagManager.findTagReportCompositesByCriteria(getSessionSubject(), tagCriteria), + try { + return SerialUtility.prepare( + tagManager.findTagReportCompositesByCriteria(getSessionSubject(), tagCriteria), "TagService.findTagReportCompositesByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } }
commit 4027a3a94c8399ce08485df9043a4386f668cf2b 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 be66cb9..8d8db75 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 @@ -270,7 +270,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>>() { @@ -280,6 +285,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 e577491..1c73198 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; }
@@ -352,9 +341,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); @@ -371,21 +362,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())); } @@ -394,6 +376,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 dd657e98f4d906e6bb6b58b3948d1b7d7282b4ec 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 9cfec33df4ca3f5975a2a6ba72c6b6a5ddc09cdd Author: John Sanda jsanda@redhat.com Date: Thu Sep 30 16:47:49 2010 -0400
Updating tests
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 bc0d6c5..5e2913b 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 @@ -24,11 +24,13 @@ package org.rhq.enterprise.server.configuration.metadata;
import javax.persistence.EntityManager; +import javax.transaction.SystemException;
import org.testng.annotations.BeforeClass; 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.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertyGroupDefinition; @@ -91,6 +93,20 @@ 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) + public void addNewGroup() { + initConfigDefs("servers[name='GroupTests']", "GroupTests"); + + assertNotNull("The new property should be added to the configuration definition", + findGroup("newGroup", originalConfigDef)); + } + // void assertGroupDefinitionExists() { // for (PropertyGroupDefinition groupDef : originalConfigurationDef.getGroupDefinitions()) { // if (groupDef.getName().equals("groupToBeRemoved")) { @@ -107,17 +123,24 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test {
private void loadAndPersistConfigDefs(String path, String configName) { originalConfigDef = loadPluginConfigDefFor(originalDescriptor, path, configName); + assertNotNull(originalConfigDef); updatedConfigDef = loadPluginConfigDefFor(updatedDescriptor, path, configName); + assertNotNull(updatedConfigDef);
try { getTransactionManager().begin();
EntityManager entityMgr = getEntityManager(); entityMgr.persist(originalConfigDef); - entityMgr.persist(updatedConfigDef); + //entityMgr.persist(updatedConfigDef);
getTransactionManager().commit(); } catch (Exception e) { + try { + getTransactionManager().rollback(); + } catch (SystemException e1) { + throw new RuntimeException(e1); + } throw new RuntimeException(e); } } @@ -131,6 +154,11 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test {
getTransactionManager().commit(); } catch (Exception e) { + try { + getTransactionManager().rollback(); + } catch (SystemException e1) { + throw new RuntimeException(e1); + } throw new RuntimeException(e); } } @@ -139,6 +167,15 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { return "/" + getClass().getPackage().getName().replace('.', '/') + "/"; }
+ private PropertyGroupDefinition findGroup(String name, ConfigurationDefinition configDef) { + for (PropertyGroupDefinition groupDef : configDef.getGroupDefinitions()) { + if (groupDef.getName().equals(name)) { + return groupDef; + } + } + return null; + } + void assertPropertyDefinitionMatches(String msg, PropertyDefinitionSimple expected, PropertyDefinitionSimple actual) { AssertUtils.assertPropertiesMatch(msg, expected, actual, "id", "configurationDefinition"); 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 131cff7..dd8fcfa 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 @@ -18,4 +18,12 @@ description="This property exists only in version 1 of the plugin"/> </plugin-configuration> </server> + + <server name="GroupTests"> + <plugin-configuration> + <c:group name="existingGroup"> + <c:simple-property name="existingGroupProperty"/> + </c:group> + </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 2c94f72..d090e76 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 @@ -25,4 +25,21 @@ summary="false"/> </plugin-configuration> </server> + + <server name="GroupTests"> + <plugin-configuration> + <c:group name="existingGroup"> + <c:simple-property name="existingGroupProperty"/> + </c:group> + + <c:group name="newGroup"> + <c:simple-property name="newGroupProperty" + description="A new, grouped property" + activationPolicy="immediate" + default="new grouped property" + displayName="New Group Property" + readOnly="true"/> + </c:group> + </plugin-configuration> + </server> </plugin>
commit efd0a83daf83a5e667dbf0f0352aa28f03b806ef Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 30 16:44:44 2010 -0400
add authz checks to resource and plugin config views - if the user doesn't have the needed perms, the config editor is put in read-only mode and a transient message is displayed to inform them why the config is not editable
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index b2c532d..05c37b6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -238,7 +238,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.inventoryTab, this.inventoryChildren, canvas, visible, true); visible = facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION); canvas = (visible) ? new PluginConfigurationEditView(this.inventoryTab.extendLocatorId("PluginConfigView"), - resource) : null; + resourceComposite) : null; updateSubTab(this.inventoryTab, this.inventoryConn, canvas, visible, true); updateSubTab(this.inventoryTab, this.inventoryGroups, ResourceGroupListView.getGroupsOf(this.inventoryTab .extendLocatorId("GroupsView"), resource.getId()), true, true); @@ -275,7 +275,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), resourcePermissions .isConfigureRead())) { updateSubTab(this.configurationTab, this.configCurrent, new ResourceConfigurationEditView(this - .extendLocatorId("ResourceConfigView"), resource), true, true); + .extendLocatorId("ResourceConfigView"), resourceComposite), true, true); updateSubTab(this.configurationTab, this.configHistory, ConfigurationHistoryView.getHistoryOf( resource.getId()), true, true); } 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 9843339..b002f0b 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 @@ -29,6 +29,8 @@ import com.smartgwt.client.widgets.toolbar.ToolStrip; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; 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.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.ValidationStateChangeListener; @@ -45,13 +47,15 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class ResourceConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { private Resource resource; + private ResourcePermission resourcePermission; private ConfigurationEditor editor; private IButton saveButton;
- public ResourceConfigurationEditView(String locatorId, Resource resource) { + public ResourceConfigurationEditView(String locatorId, ResourceComposite resourceComposite) { super(locatorId);
- this.resource = resource; + this.resource = resourceComposite.getResource(); + this.resourcePermission = resourceComposite.getResourcePermission(); }
@Override @@ -78,9 +82,14 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements V editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId()); editor.setOverflow(Overflow.AUTO); editor.addValidationStateChangeListener(this); + editor.setReadOnly(!this.resourcePermission.isConfigureWrite());
addMember(toolStrip); addMember(editor); + + Message message = new TransientMessage("You do not have permission to edit this Resource's configuration.", + Message.Severity.Info, true); + CoreGUI.getMessageCenter().notify(message); }
private void save() { 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 d179046..1483cfa 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 @@ -28,6 +28,8 @@ import com.smartgwt.client.widgets.toolbar.ToolStrip; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PluginConfigurationUpdate; 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.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.ValidationStateChangeListener; @@ -44,13 +46,15 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class PluginConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { private Resource resource; + private ResourcePermission resourcePermission; private ConfigurationEditor editor; private LocatableIButton saveButton;
- public PluginConfigurationEditView(String locatorId, Resource resource) { + public PluginConfigurationEditView(String locatorId, ResourceComposite resourceComposite) { super(locatorId);
- this.resource = resource; + this.resource = resourceComposite.getResource(); + this.resourcePermission = resourceComposite.getResourcePermission(); }
@Override @@ -60,7 +64,6 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Val }
public void build() { - ToolStrip toolStrip = new ToolStrip(); toolStrip.setWidth100();
@@ -79,9 +82,14 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Val ConfigurationEditor.ConfigType.plugin); editor.setOverflow(Overflow.AUTO); editor.addValidationStateChangeListener(this); + editor.setReadOnly(!this.resourcePermission.isInventory());
addMember(toolStrip); addMember(editor); + + Message message = new TransientMessage("You do not have permission to edit this Resource's connection properties.", + Message.Severity.Info, true); + CoreGUI.getMessageCenter().notify(message); }
private void save() {
commit 29888fd3a7ed804c812b299f1509ae5980321b3a Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 30 16:18:14 2010 -0400
populate the notif drop down with all sender names
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 1711bd5..5da3c43 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 @@ -26,6 +26,7 @@ package org.rhq.enterprise.gui.coregui.client.alert.definitions; import java.util.ArrayList; import java.util.LinkedHashMap;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.FormItemIfFunction; @@ -38,6 +39,8 @@ 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.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
/** @@ -70,18 +73,39 @@ public class NewNotificationEditor extends LocatableDynamicForm {
notificationSenderSelectItem = new SelectItem("notificationSender", "Notification Sender");
- LinkedHashMap<String, String> senders = new LinkedHashMap<String, String>(); if (notificationToEdit != null) { // we were given a notification to edit, you can't change the sender type, its the only option - senders.put(notificationToEdit.getSenderName(), notificationToEdit.getSenderName()); notificationSenderSelectItem.setDisabled(true); + LinkedHashMap<String, String> senders = new LinkedHashMap<String, String>(1); + senders.put(notificationToEdit.getSenderName(), notificationToEdit.getSenderName()); + notificationSenderSelectItem.setValueMap(senders); } else { + notificationSenderSelectItem.setValueMap("Loading..."); + notificationSenderSelectItem.setDisabled(true); // we are creating a new notification, need to provide all senders as options - senders.put("System Users", "System Users"); - senders.put("dummySender", "Dummy Sender"); + GWTServiceLookup.getAlertDefinitionService().getAllAlertSenders(new AsyncCallback<String[]>() { + @Override + public void onSuccess(String[] result) { + if (result != null && result.length > 0) { + LinkedHashMap<String, String> senders = new LinkedHashMap<String, String>(result.length); + for (String senderName : result) { + senders.put(senderName, senderName); + } + notificationSenderSelectItem.setValueMap(senders); + notificationSenderSelectItem.setDisabled(false); + notificationSenderSelectItem.redraw(); + } else { + CoreGUI.getErrorHandler().handleError("No alert senders available"); + } + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Cannot get alert senders", caught); + } + }); }
- notificationSenderSelectItem.setValueMap(senders); notificationSenderSelectItem.setDefaultToFirstOption(true); notificationSenderSelectItem.setWrapTitle(false); notificationSenderSelectItem.setRedrawOnChange(true); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java index 4819bac..ee93aed 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java @@ -41,4 +41,6 @@ public interface AlertDefinitionGWTService extends RemoteService { int removeAlertDefinitions(Integer[] alertDefinitionIds) throws Exception;
String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws Exception; + + String[] getAllAlertSenders() throws Exception; } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java index d1f492b..b906473 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java @@ -18,6 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
+import java.util.List; + import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; @@ -26,12 +28,14 @@ import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.AlertDefinitionGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.alert.AlertDefinitionManagerLocal; +import org.rhq.enterprise.server.alert.AlertNotificationManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implements AlertDefinitionGWTService { private static final long serialVersionUID = 1L;
private AlertDefinitionManagerLocal alertDefManager = LookupUtil.getAlertDefinitionManager(); + private AlertNotificationManagerLocal alertNotifManager = LookupUtil.getAlertNotificationManager();
@Override public PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria) { @@ -106,4 +110,16 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ @Override + public String[] getAllAlertSenders() throws Exception { + try { + List<String> results = alertNotifManager.listAllAlertSenders(); + if (results == null) { + return null; + } + return SerialUtility.prepare(results.toArray(new String[results.size()]), "getAllAlertSenders"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } } \ No newline at end of file
commit b973891c83704c9d19f3fdf9f7a1515d275771c7 Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 30 15:48:59 2010 -0400
comment out some debug println's
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..e577491 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 @@ -216,14 +216,14 @@ public class ResourceTreeDatasource extends DataSource { Resource parentResource = resource.getParentResource(); ResourceSubCategory subcategory = type.getSubCategory(); if (subcategory != null) { - System.out.println("Processing " + subcategory + "..."); + //System.out.println("Processing " + subcategory + "..."); do { String subcategoryNodeId = SubCategoryTreeNode.idOf(subcategory, parentResource); if (!subcategoryNodes.containsKey(subcategoryNodeId)) { SubCategoryTreeNode subcategoryNode = new SubCategoryTreeNode(subcategory, parentResource); subcategoryNodes.put(subcategoryNode.getID(), subcategoryNode); - System.out.println("Adding " + subcategoryNode + " to tree..."); + //System.out.println("Adding " + subcategoryNode + " to tree..."); updatedNodes.add(subcategoryNode); } } while ((subcategory = subcategory.getParentSubCategory()) != null); @@ -232,7 +232,7 @@ public class ResourceTreeDatasource extends DataSource { if (!type.isSingleton()) { AutoGroupTreeNode autogroupNode = new AutoGroupTreeNode(resource); autogroupNodes.put(autogroupNodeId, autogroupNode); - System.out.println("Adding " + autogroupNode + " to tree..."); + //System.out.println("Adding " + autogroupNode + " to tree..."); updatedNodes.add(autogroupNode); } } @@ -330,10 +330,12 @@ public class ResourceTreeDatasource extends DataSource { }
/** - * Given a Resource, generate a unique ID for the AGNode. + * Given an autogroup's parent Resource and member ResourceType, generate a unique ID for an autogroup TreeNode. * - * @param resource requires resourceType field be set. requires parentResource field be set (null for no parent) - * @return The name string or null if the parentResource is null; + * @param parentResource requires resourceType field be set. requires parentResource field be set (null for no parent) + * @param resourceType the member ResourceType + * + * @return The name string or null if the parentResource is null */ public static String idOf(Resource parentResource, ResourceType resourceType) { return (parentResource != null) ? "autogroup_" + resourceType.getId() + "_" + parentResource.getId() : null; 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 f4137b2..1184697 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 @@ -245,7 +245,7 @@ public abstract class RPCDataSource<T> extends DataSource {
@SuppressWarnings("unchecked") public static <S> S[] getArrayFilter(DSRequest request, String paramName, Class<S> type) { - System.out.println("Fetching array " + paramName + " (" + type + ")"); + //System.out.println("Fetching array " + paramName + " (" + type + ")"); Criteria criteria = request.getCriteria(); Map<String, Object> criteriaMap = criteria.getValues();
@@ -272,14 +272,14 @@ public abstract class RPCDataSource<T> extends DataSource { throw new IllegalArgumentException("No support for passing array filters of type " + type); }
- System.out.println("Result array = " + resultArray); + //System.out.println("Result array = " + resultArray);
return resultArray; }
@SuppressWarnings("unchecked") public static <S> S getFilter(DSRequest request, String paramName, Class<S> type) { - System.out.println("Fetching " + paramName + " (" + type + ")"); + //System.out.println("Fetching " + paramName + " (" + type + ")"); Criteria criteria = request.getCriteria(); Map<String, Object> criteriaMap = criteria.getValues();
@@ -301,7 +301,7 @@ public abstract class RPCDataSource<T> extends DataSource { } }
- System.out.println("Result = " + result); + //System.out.println("Result = " + result);
return result; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java index 434d06d..2064f63 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java @@ -31,7 +31,6 @@ import org.rhq.enterprise.gui.coregui.client.UserSessionManager; * @author Greg Hinkle */ public class MonitoringRequestCallback implements RequestCallback { - @SuppressWarnings("unused") private int id; private String name; @@ -56,11 +55,11 @@ public class MonitoringRequestCallback implements RequestCallback { if (STATUS_CODE_OK == response.getStatusCode()) { RPCManager.getInstance().succeedCall(this); callback.onResponseReceived(request, response); - System.out.println("MonitoringRequestCallback: OK"); + //System.out.println("MonitoringRequestCallback: OK"); } else { RPCManager.getInstance().failCall(this); callback.onResponseReceived(request, response); - System.out.println("MonitoringRequestCallback: " + response.getStatusCode() + "/" + System.err.println("MonitoringRequestCallback: " + response.getStatusCode() + "/" + response.getStatusText());
// if we have a rich and coordinated client-side loggedIn state, do we need to check upon failure here? @@ -72,7 +71,7 @@ public class MonitoringRequestCallback implements RequestCallback {
@Override public void onFailure(Throwable caught) { - SC.say("Unable to determine login status, check server status"); + SC.say("Unable to determine login status - check Server status."); } }); }
commit 6415ed10e3b0d967b712a7be0aa0a3fcf4ce95cb Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 30 15:40:37 2010 -0400
fix bug in core-domain StringUtils.deCamelCase() and add unit test for that method; add support for transient messages to the message center - transient messages are displayed in the header and generally auto-clear after 30 seconds
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java index 938b07f..01a6ddb 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java @@ -33,8 +33,14 @@ import java.util.Set; public class StringUtils { private static final Set<String> LOWERCASE_WORDS = new HashSet<String>(); static { + // conjunctions LOWERCASE_WORDS.add("And"); LOWERCASE_WORDS.add("Or"); + + // articles + LOWERCASE_WORDS.add("A"); + LOWERCASE_WORDS.add("An"); + LOWERCASE_WORDS.add("The"); }
/* @@ -65,39 +71,47 @@ public class StringUtils { + target.substring(nextDash + 2); }
- StringBuilder currentWord = new StringBuilder(); char currentChar; - char previousChar = 0; - for (int i = 0; i < target.length(); i++) { + // Always make the first char upper case. + char previousChar = Character.toUpperCase(target.charAt(0)); + StringBuilder currentWord = new StringBuilder(); + currentWord.append(previousChar); + for (int i = 1; i < target.length(); i++) { currentChar = target.charAt(i);
// Make sure to insert spaces in the middle of acronyms or multi-digit numbers. - if ((i != 0) && - ((Character.isDigit(currentChar) && !Character.isDigit(previousChar)) + if ((previousChar == ' ' && currentChar != ' ') + || (Character.isDigit(currentChar) && !Character.isDigit(previousChar)) || (Character.isUpperCase(currentChar) && (!Character.isUpperCase(previousChar) - || ((i < (target.length() - 1)) && Character.isLowerCase(target.charAt(i + 1))))))) { + || ((i < (target.length() - 1)) && Character.isLowerCase(target.charAt(i + 1)))))) { // We're at the start of a new word. - appendWord(result, currentWord); + appendWord(result, currentWord.toString()); currentWord = new StringBuilder(); // Append a space before the next word. result.append(' '); }
- currentWord.append(currentChar); + if (currentChar != ' ') { + currentWord.append(currentChar); + } previousChar = currentChar; } // Append the final word. - appendWord(result, currentWord); + appendWord(result, currentWord.toString());
return result.toString(); }
- private static void appendWord(StringBuilder result, StringBuilder nextWord) { - String word = nextWord.toString(); - if (LOWERCASE_WORDS.contains(word)) { - result.append(word.toLowerCase()); - } else { - result.append(word); + private static void appendWord(StringBuilder result, String word) { + if (word.length() >= 1) { + if (LOWERCASE_WORDS.contains(word)) { + result.append(word.toLowerCase()); + } else { + result.append(Character.toUpperCase(word.charAt(0))); + if (word.length() > 1) { + result.append(word.substring(1)); + } + } } }
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/util/StringUtilsTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/util/StringUtilsTest.java new file mode 100644 index 0000000..fde0c6b --- /dev/null +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/util/StringUtilsTest.java @@ -0,0 +1,47 @@ +/* + * 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.util; + +import static org.testng.Assert.*; + +import org.testng.annotations.Test; + +/** + * Tests for {@link StringUtils}. + * + * @author Ian Springer + */ +public class StringUtilsTest { + @Test + public void testDeCamelCase() { + testDeCamelCase("RedGreenBlue", "Red Green Blue"); + testDeCamelCase("redGreenBlue", "Red Green Blue"); + testDeCamelCase("Red Green Blue", "Red Green Blue"); + testDeCamelCase("red green blue", "Red Green Blue"); + testDeCamelCase("RHQServer", "RHQ Server"); + testDeCamelCase("Blink182", "Blink 182"); + testDeCamelCase("SimonAndGarfunkel", "Simon and Garfunkel"); + } + + private void testDeCamelCase(String input, String expectedResult) { + String result = StringUtils.deCamelCase(input); + assertEquals(result, expectedResult, "For input "" + input + "": "); + } +} 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 e342b11..bb39f2d 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 @@ -47,6 +47,7 @@ import org.rhq.enterprise.gui.coregui.client.report.ReportTopView; import org.rhq.enterprise.gui.coregui.client.report.tag.TaggedView; import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.WidgetUtility; +import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
@@ -61,6 +62,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
private static ErrorHandler errorHandler = new ErrorHandler();
+ private static MessageBar messageBar; + private static BreadcrumbTrailPane breadCrumbTrailPane;
private static MessageCenter messageCenter; @@ -130,6 +133,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { MenuBarView menuBarView = new MenuBarView("TopMenu"); menuBarView.setWidth("100%");
+ messageBar = new MessageBar(); + breadCrumbTrailPane = new BreadcrumbTrailPane();
Canvas canvas = new Canvas(CONTENT_CANVAS_ID); @@ -139,9 +144,11 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { rootCanvas = new RootCanvas(); rootCanvas.setOverflow(Overflow.HIDDEN); rootCanvas.addMember(menuBarView); + + rootCanvas.addMember(messageBar); rootCanvas.addMember(breadCrumbTrailPane); rootCanvas.addMember(canvas); - rootCanvas.addMember(new Footer("CoreFooter")); + rootCanvas.addMember(new Footer()); rootCanvas.draw();
History.addValueChangeHandler(this); @@ -267,8 +274,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { }
private class RootCanvas extends VLayout implements BookmarkableView { - ViewId currentViewId; - Canvas currentCanvas; + private ViewId currentViewId; + private Canvas currentCanvas;
private RootCanvas() { setWidth100(); @@ -280,14 +287,20 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // default view History.newItem(DEFAULT_VIEW_PATH); } else { - if (!viewPath.getCurrent().equals(currentViewId)) { - currentViewId = viewPath.getCurrent(); + messageBar.clearMessage();
- currentCanvas = createContent(viewPath.getCurrent().getPath()); - setContent(currentCanvas); + ViewId topLevelViewId = viewPath.getCurrent(); // e.g. Administration + if (!topLevelViewId.equals(this.currentViewId)) { + this.currentViewId = topLevelViewId; + this.currentCanvas = createContent(this.currentViewId.getPath()); + setContent(this.currentCanvas); } - if (currentCanvas instanceof BookmarkableView) { - ((BookmarkableView) currentCanvas).renderView(viewPath.next()); // e.g. + + 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/Footer.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java index 36514aa..d7121e3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java @@ -40,9 +40,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip; * @author Joseph Marques */ public class Footer extends LocatableToolStrip { + private static final String LOCATOR_ID = "CoreFooter";
- public Footer(String locatorId) { - super(locatorId); + public Footer() { + super(LOCATOR_ID); setHeight(30); setAlign(VerticalAlignment.CENTER); // setPadding(5); @@ -55,7 +56,7 @@ public class Footer extends LocatableToolStrip { super.onDraw();
final UserSessionState userSessionState = new UserSessionState("UserSessionState"); - final MessageCenterView recentMessage = new MessageCenterView(extendLocatorId("MessageCenter")); + final MessageCenterView recentMessage = new MessageCenterView(extendLocatorId(MessageCenterView.LOCATOR_ID)); recentMessage.setWidth("*"); final FavoritesButton favoritesButton = new FavoritesButton(extendLocatorId("Favorites")); final AlertsMessage alertsMessage = new AlertsMessage(extendLocatorId("Alerts")); 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 432cd2b..544ded9 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 @@ -65,6 +65,7 @@ import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; 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.RegExpValidator; @@ -136,7 +137,6 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Ian Springer */ public class ConfigurationEditor extends LocatableVLayout { - private ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService();
private TabSet tabSet; @@ -854,7 +854,7 @@ public class ConfigurationEditor extends LocatableVLayout {
valueItem.setRequired(propertyDefinition.isRequired());
- List<Validator> validators = buildValidators(propertyDefinition, valueItem); + List<Validator> validators = buildValidators(propertyDefinition, property); valueItem.setValidators(validators.toArray(new Validator[validators.size()]));
/* @@ -879,6 +879,7 @@ public class ConfigurationEditor extends LocatableVLayout { finalValueItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { boolean wasValidBefore = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); + propertySimple.setErrorMessage(null); if (changedEvent.getItem().validate()) { ConfigurationEditor.this.invalidPropertyNames.remove(propertySimple.getName()); propertySimple.setValue(changedEvent.getValue()); @@ -888,7 +889,7 @@ public class ConfigurationEditor extends LocatableVLayout { boolean isValidNow = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); if (isValidNow != wasValidBefore) { for (ValidationStateChangeListener validationStateChangeListener : ConfigurationEditor.this.validationStateChangeListeners) { - validationStateChangeListener.validateStateChanged(isValidNow); + validationStateChangeListener.validationStateChanged(isValidNow); } } } @@ -913,7 +914,7 @@ public class ConfigurationEditor extends LocatableVLayout { return valueItem; }
- private List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, FormItem valueItem) { + private List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, Property property) { List<Validator> validators = new ArrayList<Validator>(); if (propertyDefinition.getConstraints() != null) { Set<Constraint> constraints = propertyDefinition.getConstraints(); @@ -941,11 +942,16 @@ public class ConfigurationEditor extends LocatableVLayout { validators.add(validator); } else if (constraint instanceof RegexConstraint) { RegExpValidator validator = - new RegExpValidator("^" + ((RegexConstraint) constraint).getDetails() + "$"); + new RegExpValidator("^" + constraint.getDetails() + "$"); validators.add(validator); } } } + if (property.getErrorMessage() != null) { + this.invalidPropertyNames.add(property.getName()); + PluginReportedErrorValidator validator = new PluginReportedErrorValidator(property); + validators.add(validator); + } return validators; }
@@ -1043,4 +1049,22 @@ public class ConfigurationEditor extends LocatableVLayout { return new Integer(o1.getOrder()).compareTo(o2.getOrder()); } } + + private class PluginReportedErrorValidator extends CustomValidator { + private Property property; + + public PluginReportedErrorValidator(Property property) { + this.property = property; + } + + @Override + protected boolean condition(Object value) { + String errorMessage = this.property.getErrorMessage(); + boolean valid = (errorMessage != null); + if (!valid) { + setErrorMessage(errorMessage); + } + return valid; + } + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java index d8f7a85..154c731 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java @@ -23,5 +23,5 @@ package org.rhq.enterprise.gui.coregui.client.components.configuration; * @author Ian Springer */ public interface ValidationStateChangeListener { - void validateStateChanged(boolean isValid); + void validationStateChanged(boolean isValid); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/AbstractWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/AbstractWizard.java index 9c8e513..57d29b5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/AbstractWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/AbstractWizard.java @@ -18,15 +18,13 @@ */ package org.rhq.enterprise.gui.coregui.client.components.wizard;
-import java.util.ArrayList; import java.util.Collections; import java.util.List;
import com.smartgwt.client.widgets.IButton;
public abstract class AbstractWizard implements Wizard { - - private ArrayList<WizardStep> steps; + private List<WizardStep> steps; private WizardView view; private String windowTitle = ""; private String title = ""; @@ -63,7 +61,7 @@ public abstract class AbstractWizard implements Wizard { return steps; }
- public void setSteps(ArrayList<WizardStep> steps) { + public void setSteps(List<WizardStep> steps) { this.steps = steps; }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java index fbbf71e..1008b83 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java @@ -30,18 +30,21 @@ import com.smartgwt.client.widgets.IButton;
import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizard; import org.rhq.enterprise.gui.coregui.client.components.wizard.WizardStep; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGroupGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupListView; import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage;
/** + * A wizard for creating a new Resource group. + * * @author Greg Hinkle */ public class GroupCreateWizard extends AbstractWizard { - private ResourceGroupListView resourceGroupListView;
private GroupCreateStep createStep; @@ -50,7 +53,7 @@ public class GroupCreateWizard extends AbstractWizard { public GroupCreateWizard(ResourceGroupListView resourceGroupListView) { this.resourceGroupListView = resourceGroupListView;
- ArrayList<WizardStep> steps = new ArrayList<WizardStep>(); + List<WizardStep> steps = new ArrayList<WizardStep>();
steps.add(createStep = new GroupCreateStep()); steps.add(memberStep = new GroupMembersStep(this)); @@ -84,13 +87,18 @@ public class GroupCreateWizard extends AbstractWizard { groupService.createResourceGroup(createStep.getGroup(), memberStep.getSelectedResourceIds(), new AsyncCallback<ResourceGroup>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create resource group", caught); + CoreGUI.getErrorHandler().handleError("Failed to create Resource group.", caught); }
public void onSuccess(ResourceGroup result) { + String groupUrl = LinkManager.getResourceGroupLink(result.getId()); CoreGUI.getMessageCenter().notify( - new Message("Saved new group " + result.getName(), Message.Severity.Info)); - + new TransientMessage("Resource group created. [<a href='" + groupUrl + "'>View Group</a>]", + Message.Severity.Info)); + CoreGUI.getMessageCenter().notify( + new Message("Created new " + result.getGroupCategory().name().toLowerCase() + " Resource group '" + + result.getName() + "' with " + memberStep.getSelectedResourceIds().length + " members.", + Message.Severity.Info)); resourceGroupListView.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 7964a74..9843339 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 @@ -34,18 +34,19 @@ import org.rhq.enterprise.gui.coregui.client.components.configuration.Configurat import org.rhq.enterprise.gui.coregui.client.components.configuration.ValidationStateChangeListener; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.message.Message; -import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; +import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; +import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle + * @author Ian Springer */ public class ResourceConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { private Resource resource; private ConfigurationEditor editor; private IButton saveButton; - private MessageBar messageBar;
public ResourceConfigurationEditView(String locatorId, Resource resource) { super(locatorId); @@ -74,14 +75,11 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements V this.saveButton.disable(); toolStrip.addMember(saveButton);
- this.messageBar = new MessageBar(); - editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId()); editor.setOverflow(Overflow.AUTO); editor.addValidationStateChangeListener(this);
addMember(toolStrip); - addMember(this.messageBar); addMember(editor); }
@@ -91,12 +89,12 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements V GWTServiceLookup.getConfigurationService().updateResourceConfiguration(resource.getId(), updatedConfiguration, new AsyncCallback<ResourceConfigurationUpdate>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to update configuration", caught); + CoreGUI.getErrorHandler().handleError("Failed to update configuration.", caught); }
public void onSuccess(ResourceConfigurationUpdate result) { CoreGUI.getMessageCenter().notify( - new Message("Configuration updated for resource [" + resource.getName() + "]", + new Message("Configuration updated for Resource [" + resource.getName() + "].", Message.Severity.Info));
} @@ -104,14 +102,16 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements V }
@Override - public void validateStateChanged(boolean isValid) { + public void validationStateChanged(boolean isValid) { + MessageCenter messageCenter = CoreGUI.getMessageCenter(); + Message message; if (isValid) { this.saveButton.enable(); - this.messageBar.hide(); + message = new TransientMessage("All configuration properties now have valid values, so the configuration can now be saved.", Message.Severity.Info); } else { this.saveButton.disable(); - Message message = new Message("One or more properties have invalid values. The values must be fixed before the configuration can be saved.", Message.Severity.Error); - this.messageBar.setMessage(message); + message = new TransientMessage("One or more configuration properties have invalid values. The values must be corrected before the configuration can be saved.", Message.Severity.Error, true); } + 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 357255a..d179046 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 @@ -33,19 +33,19 @@ import org.rhq.enterprise.gui.coregui.client.components.configuration.Configurat import org.rhq.enterprise.gui.coregui.client.components.configuration.ValidationStateChangeListener; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.message.Message; -import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; +import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; +import org.rhq.enterprise.gui.coregui.client.util.message.TransientMessage; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle + * @author Ian Springer */ public class PluginConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { - private Resource resource; private ConfigurationEditor editor; private LocatableIButton saveButton; - private MessageBar messageBar;
public PluginConfigurationEditView(String locatorId, Resource resource) { super(locatorId); @@ -75,15 +75,12 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Val this.saveButton.disable(); toolStrip.addMember(saveButton);
- this.messageBar = new MessageBar(); - editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin); editor.setOverflow(Overflow.AUTO); editor.addValidationStateChangeListener(this);
addMember(toolStrip); - addMember(this.messageBar); addMember(editor); }
@@ -103,18 +100,19 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Val
} }); - }
@Override - public void validateStateChanged(boolean isValid) { + public void validationStateChanged(boolean isValid) { + MessageCenter messageCenter = CoreGUI.getMessageCenter(); + Message message; if (isValid) { this.saveButton.enable(); - this.messageBar.hide(); + message = new TransientMessage("All connection properties now have valid values, so the configuration can now be saved.", Message.Severity.Info); } else { this.saveButton.disable(); - Message message = new Message("One or more properties have invalid values. The values must be fixed before the configuration can be saved.", Message.Severity.Error); - this.messageBar.setMessage(message); + message = new TransientMessage("One or more connection properties have invalid values. The values must be corrected before the configuration can be saved.", Message.Severity.Error, true); } + messageCenter.notify(message); } } \ No newline at end of file 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 905b0c7..97cc7ab 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 @@ -23,8 +23,8 @@ import java.util.Date; /** * @author Greg Hinkle */ +@SuppressWarnings({"UnnecessarySemicolon"}) public class Message { - protected String title; protected String detail; protected Date fired = new Date(); 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 e025ab1..b03499f 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 @@ -22,52 +22,114 @@ package org.rhq.enterprise.gui.coregui.client.util.message; import java.util.HashMap; import java.util.Map;
+import com.google.gwt.user.client.Timer; +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Label;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; + /** * A bar for displaying a message at the top of a page - the equivalent of the JSF h:messages component. + * The message will be displayed for 30 seconds and then will be automatically cleared. * * @author Ian Springer */ -public class MessageBar extends Label { - public static final Map<Message.Severity, String> SEVERITY_TO_STYLE_NAME_MAP = new HashMap(); +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 Map<Message.Severity, String> SEVERITY_TO_STYLE_NAME_MAP = + new HashMap<Message.Severity, String>(); static { SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Info, "InfoBlock"); SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Warning, "WarnBlock"); SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Error, "ErrorBlock"); }
+ private static final Map<Message.Severity, String> SEVERITY_TO_ICON_MAP = + new HashMap<Message.Severity, String>(); + static { + SEVERITY_TO_ICON_MAP.put(Message.Severity.Info, "info/icn_info_blue.png"); + SEVERITY_TO_ICON_MAP.put(Message.Severity.Warning, "info/icn_info_orange.png"); + SEVERITY_TO_ICON_MAP.put(Message.Severity.Error, "info/icn_info_red.png"); + } + + private Label label; + + public MessageBar() { + super(LOCATOR_ID); + + setOverflow(Overflow.VISIBLE); + } + @Override protected void onDraw() { super.onDraw();
setWidth100(); setAutoHeight(); + setHeight(40);
- hide(); + setAlign(Alignment.CENTER); + + CoreGUI.getMessageCenter().addMessageListener(this); }
- public void setMessage(Message message) { + @Override + public void onMessage(Message message) { + if (message instanceof TransientMessage) { + TransientMessage transientMessage = (TransientMessage)message; + + // First clear any previous message. + clearMessage(); + + this.label = createLabel(transientMessage); + addMember(this.label); + markForRedraw();
- String contents; - if (message != null) { - contents = message.getTitle(); - if (message.getDetail() != null) { - contents += ": " + message.getDetail(); + // Auto-clear the message after 30 seconds unless it's been designated as sticky. + if (!transientMessage.isSticky()) { + Timer hideTimer = new Timer() { + @Override + public void run() { + clearMessage(); + } + }; + hideTimer.schedule(AUTO_HIDE_DELAY_MILLIS); } - } else { - contents = null; } - setContents(contents); - if (contents != null) { - String styleName = SEVERITY_TO_STYLE_NAME_MAP.get(message.getSeverity()); - setStyleName(styleName); + } + + public void clearMessage() { + if (this.label != null) { + this.label.destroy(); + removeMember(this.label); + markForRedraw(); } - markForRedraw(); - if (contents != null) { - show(); - } else { - hide(); + } + + private Label createLabel(Message message) { + Label label = new Label(); + + String contents = message.getTitle(); + if (message.getDetail() != null) { + contents += ": " + message.getDetail(); } + label.setContents(contents); + + String styleName = (contents != null) ? SEVERITY_TO_STYLE_NAME_MAP.get(message.getSeverity()) : null; + label.setStyleName(styleName); + + label.setAutoHeight(); + label.setHeight(35); + label.setAutoWidth(); + label.setWidth("75%"); + + String icon = (contents != null) ? SEVERITY_TO_ICON_MAP.get(message.getSeverity()) : null; + label.setIcon(icon); + + return label; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java index afce657..a3c29dd 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java @@ -20,15 +20,14 @@ package org.rhq.enterprise.gui.coregui.client.util.message;
import java.util.ArrayList; import java.util.LinkedList; +import java.util.List;
/** * @author Greg Hinkle */ public class MessageCenter { - private LinkedList<Message> messages = new LinkedList<Message>(); - - private ArrayList<MessageListener> listeners = new ArrayList<MessageListener>(); + private List<MessageListener> listeners = new ArrayList<MessageListener>();
private static final int MAX_MESSAGES = 100;
@@ -46,7 +45,7 @@ public class MessageCenter { this.listeners.add(listener); }
- public LinkedList<Message> getMessages() { + public List<Message> getMessages() { return messages; }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java index 7b6d850..5d81646 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java @@ -18,7 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.util.message;
-import java.util.LinkedList; +import java.util.List;
import com.google.gwt.user.client.Timer; import com.smartgwt.client.types.Alignment; @@ -53,6 +53,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow; * @author Greg Hinkle */ public class MessageCenterView extends LocatableHLayout implements MessageCenter.MessageListener { + public static final String LOCATOR_ID = "MessageCenter";
public MessageCenterView(String locatorId) { super(locatorId, 5); @@ -78,16 +79,16 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter
recentEventsButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { - LinkedList<Message> messages = CoreGUI.getMessageCenter().getMessages(); + List<Message> messages = CoreGUI.getMessageCenter().getMessages(); if (messages.isEmpty()) { - recentEventsMenu.setItems(new MenuItem("No recent messages")); + recentEventsMenu.setItems(new MenuItem("No recent messages.")); } else { MenuItem[] items = new MenuItem[messages.size()]; - int i = 0; - for (final Message message : messages) { + for (int i = 0, messagesSize = messages.size(); i < messagesSize; i++) { + final Message message = messages.get(i); MenuItem messageItem = new MenuItem(message.title, getSeverityIcon(message.severity));
- items[i++] = messageItem; + items[i] = messageItem;
messageItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() { public void onClick(MenuItemClickEvent event) { @@ -156,38 +157,40 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter }
public void onMessage(final Message message) { - final Label label = new Label(message.title); - label.setMargin(5); - label.setAutoFit(true); - label.setHeight(25); - label.setWrap(false); + if (!(message instanceof TransientMessage)) { + final Label label = new Label(message.title); + label.setMargin(5); + label.setAutoFit(true); + label.setHeight(25); + label.setWrap(false);
- String iconSrc = getSeverityIcon(message.severity); + String iconSrc = getSeverityIcon(message.severity);
- label.setIcon(iconSrc); + label.setIcon(iconSrc);
- label.setTooltip(message.detail); + label.setTooltip(message.detail);
- label.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - showDetails(message); - } - }); - - addMember(label, 1); - redraw(); - - Timer hideTimer = new Timer() { - @Override - public void run() { - label.animateHide(AnimationEffect.FADE, new AnimationCallback() { - public void execute(boolean b) { - label.destroy(); - } - }); - } - }; - hideTimer.schedule(10000); + label.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + showDetails(message); + } + }); + + addMember(label, 1); + redraw(); + + Timer hideTimer = new Timer() { + @Override + public void run() { + label.animateHide(AnimationEffect.FADE, new AnimationCallback() { + public void execute(boolean b) { + label.destroy(); + } + }); + } + }; + hideTimer.schedule(10000); + } }
private String getSeverityIcon(Message.Severity severity) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/TransientMessage.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/TransientMessage.java new file mode 100644 index 0000000..318c4a5 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/TransientMessage.java @@ -0,0 +1,48 @@ +/* + * 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.util.message; + +/** + * @author Ian Springer + */ +public class TransientMessage extends Message { + private boolean sticky; + + public TransientMessage(String title, Severity severity) { + super(title, severity); + } + + public TransientMessage(String title, String detail, Severity severity) { + super(title, detail, severity); + } + + public TransientMessage(String title, Severity severity, boolean sticky) { + this(title, null, severity, sticky); + } + + public TransientMessage(String title, String detail, Severity severity, boolean sticky) { + super(title, detail, severity); + this.sticky = sticky; + } + + public boolean isSticky() { + return this.sticky; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css index c5d324e..85d1b83 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css +++ b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css @@ -361,29 +361,29 @@ a:hover { }
.InfoBlock,.ConfirmationBlock,.WarnBlock,.ErrorBlock,.FatalBlock { - padding: 4px; + /*padding: 4px;*/ border-width: 1px; - border-top-style: solid; - font-size: 10px; + border-style: solid; + /*font-size: 10px;*/ color: #000000; }
.InfoBlock,.ConfirmationBlock { background-color: #BFF1B5; /* light green */ - border-top-color: #00AC3D; /* medium green */ + border-color: #00AC3D; /* medium green */ }
.WarnBlock { background-color: #FFFD99; /* light yellow */ - border-top-color: #FF9C15; /* medium orange */ + border-color: #FF9C15; /* medium orange */ }
.ErrorBlock { background-color: #FF9999; /* light red */ - border-top-color: #EE4444; /* medium red */ + border-color: #EE4444; /* medium red */ }
.FatalBlock { background-color: #FF6666; /* slightly darker light red */ - border-top-color: #EE1111; /* slightly darker medium red */ + border-color: #EE1111; /* slightly darker medium red */ }
commit cf57ff1d2706723c74d1a66c914a69e4d68f0b91 Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 30 14:48:49 2010 -0400
introduce the start of the new notification editor.
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 new file mode 100644 index 0000000..1711bd5 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.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, 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.LinkedHashMap; + +import com.smartgwt.client.types.Alignment; +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.FormItem; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; +import com.smartgwt.client.widgets.form.fields.events.ClickEvent; +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.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; + +/** + * @author John Mazzitelli + */ +public class NewNotificationEditor extends LocatableDynamicForm { + + private final AlertDefinition alertDefinition; // the definition we are adding the notification to + private final ArrayList<AlertNotification> notifications; // if we are creating a new notification, it gets added to this list + private final AlertNotification notificationToEdit; // the notification that this editor is editing (may be null) + private final Runnable closeFunction; // this is called after a button is pressed and the editor should close + + private SelectItem notificationSenderSelectItem; + + public NewNotificationEditor(String locatorId, AlertDefinition alertDefinition, + ArrayList<AlertNotification> notifs, AlertNotification notifToEdit, Runnable closeFunc) { + + super(locatorId); + this.alertDefinition = alertDefinition; + this.notifications = notifs; + this.notificationToEdit = notifToEdit; + this.closeFunction = closeFunc; + } + + @Override + protected void onInit() { + super.onInit(); + + setMargin(20); + + notificationSenderSelectItem = new SelectItem("notificationSender", "Notification Sender"); + + LinkedHashMap<String, String> senders = new LinkedHashMap<String, String>(); + if (notificationToEdit != null) { + // we were given a notification to edit, you can't change the sender type, its the only option + senders.put(notificationToEdit.getSenderName(), notificationToEdit.getSenderName()); + notificationSenderSelectItem.setDisabled(true); + } else { + // we are creating a new notification, need to provide all senders as options + senders.put("System Users", "System Users"); + senders.put("dummySender", "Dummy Sender"); + } + + notificationSenderSelectItem.setValueMap(senders); + notificationSenderSelectItem.setDefaultToFirstOption(true); + notificationSenderSelectItem.setWrapTitle(false); + notificationSenderSelectItem.setRedrawOnChange(true); + notificationSenderSelectItem.setWidth("*"); + + SpacerItem spacer1 = new SpacerItem(); + spacer1.setColSpan(2); + spacer1.setHeight(5); + + SpacerItem spacer2 = new SpacerItem(); + spacer2.setColSpan(2); + spacer2.setHeight(5); + + ButtonItem ok = new ButtonItem("okButtonItem", "OK"); + ok.setEndRow(false); + ok.setAlign(Alignment.RIGHT); + ok.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + if (validate(false)) { + saveNewNotification(); + closeFunction.run(); + } + } + }); + + ButtonItem cancel = new ButtonItem("cancelButtonItem", "Cancel"); + cancel.setStartRow(false); + cancel.setAlign(Alignment.LEFT); + cancel.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + closeFunction.run(); + } + }); + + ArrayList<FormItem> formItems = new ArrayList<FormItem>(); + formItems.add(notificationSenderSelectItem); + formItems.add(spacer1); + // TODO put config editor here + formItems.add(spacer2); + formItems.add(ok); + formItems.add(cancel); + + setFields(formItems.toArray(new FormItem[formItems.size()])); + }; + + private void saveNewNotification() { + AlertNotification notif; + + if (notificationToEdit == null) { + // we are adding a new notification - we just add it to the end of the list + String selectedSender = notificationSenderSelectItem.getValue().toString(); + notif = new AlertNotification(selectedSender); + notif.setAlertDefinition(alertDefinition); + notifications.add(notif); + } else { + notif = notificationToEdit; + } + + // notif.setConfiguration(configuration); + // notif.setExtraConfiguration(extraConfiguration); + } + + private class ShowIfSenderFunction implements FormItemIfFunction { + private final String senderName; + + public ShowIfSenderFunction(String senderName) { + this.senderName = senderName; + } + + public boolean execute(FormItem item, Object value, DynamicForm form) { + String selectedSenderString = form.getValue("notificationSender").toString(); + return senderName.equals(selectedSenderString); + } + } +} 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 b8e4644..bc585ac 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 @@ -123,6 +123,11 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement
@Override public void saveAlertDefinition() { + if (notifications != null && notifications.size() > 0) { + for (AlertNotification notif : notifications) { + notif.setAlertDefinition(alertDefinition); + } + } alertDefinition.setAlertNotifications(notifications);
// make our own new internal copy since we gave ours to the definition object @@ -184,7 +189,6 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement record.setAttribute(FIELD_SENDER, from.getSenderName()); // our executeFetch will fill in the real value for FIELD_CONFIGURATION record.setAttribute(FIELD_CONFIGURATION, "(unknown)"); - // TODO what's the extraConfiguration the notification? return record; }
@@ -290,15 +294,15 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement } });
- // NewNotificationEditor newEditor = new NewNotificationEditor( - // extendLocatorId("newNotificationEditor"), notifications, new Runnable() { - // @Override - // public void run() { - // winModal.markForDestroy(); - // table.refresh(); - // } - // }); - /// winModal.addItem(newEditor); + NewNotificationEditor newEditor = new NewNotificationEditor(extendLocatorId("newNotificationEditor"), + alertDefinition, notifications, notifToEdit, new Runnable() { + @Override + public void run() { + winModal.markForDestroy(); + table.refresh(); + } + }); + winModal.addItem(newEditor); winModal.show(); } }
commit 0b06e79336f625dcd36e15004d746ee2228e13aa Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 30 14:48:26 2010 -0400
add cancel button
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java index 3fcc64e..361ad78 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java @@ -96,14 +96,15 @@ public class NewConditionEditor extends LocatableDynamicForm { private boolean supportsOperations = false; private boolean supportsEvents = false; private boolean supportsResourceConfig = false; - private Runnable okFunction; // this is called after the OK button is pressed and a new condition is saved + private Runnable closeFunction; // this is called after a button is pressed and the editor should close private ResourceType resourceType;
- public NewConditionEditor(String locatorId, HashSet<AlertCondition> conditions, ResourceType rtype, Runnable okFunc) { + public NewConditionEditor(String locatorId, HashSet<AlertCondition> conditions, ResourceType rtype, + Runnable closeFunc) {
super(locatorId); this.conditions = conditions; - this.okFunction = okFunc; + this.closeFunction = closeFunc; this.resourceType = rtype;
this.supportsEvents = (rtype.getEventDefinitions() != null && rtype.getEventDefinitions().size() > 0); @@ -174,26 +175,40 @@ public class NewConditionEditor extends LocatableDynamicForm { conditionTypeSelectItem.setRedrawOnChange(true); conditionTypeSelectItem.setWidth("*");
- SpacerItem spacer = new SpacerItem(); - spacer.setColSpan(2); - spacer.setHeight(5); + SpacerItem spacer1 = new SpacerItem(); + spacer1.setColSpan(2); + spacer1.setHeight(5);
- ButtonItem ok = new ButtonItem("buttonItem", "OK"); - ok.setColSpan(2); - ok.setAlign(Alignment.CENTER); + SpacerItem spacer2 = new SpacerItem(); + spacer2.setColSpan(2); + spacer2.setHeight(5); + + ButtonItem ok = new ButtonItem("okButtonItem", "OK"); + ok.setEndRow(false); + ok.setAlign(Alignment.RIGHT); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (validate(false)) { saveNewCondition(); - okFunction.run(); + closeFunction.run(); } } });
+ ButtonItem cancel = new ButtonItem("cancelButtonItem", "Cancel"); + cancel.setStartRow(false); + cancel.setAlign(Alignment.LEFT); + cancel.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + closeFunction.run(); + } + }); + ArrayList<FormItem> formItems = new ArrayList<FormItem>(); formItems.add(conditionTypeSelectItem); - formItems.add(spacer); + formItems.add(spacer1); formItems.addAll(buildAvailabilityChangeFormItems()); if (supportsMetrics) { formItems.addAll(buildMetricThresholdFormItems()); @@ -216,7 +231,9 @@ public class NewConditionEditor extends LocatableDynamicForm { if (supportsResourceConfig) { formItems.addAll(buildResourceConfigChangeFormItems()); } + formItems.add(spacer2); formItems.add(ok); + formItems.add(cancel);
setFields(formItems.toArray(new FormItem[formItems.size()])); };
commit 5135c435804aef06ae9f37b1cebe72f2d79f580e Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 30 12:19:04 2010 -0400
get notification tab ready to support editing an existing notif as well as adding new ones. this adds double click handler
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 cffdd78..b8e4644 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 @@ -34,6 +34,9 @@ import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Window; import com.smartgwt.client.widgets.events.CloseClickHandler; import com.smartgwt.client.widgets.events.CloseClientEvent; +import com.smartgwt.client.widgets.events.DoubleClickEvent; +import com.smartgwt.client.widgets.events.DoubleClickHandler; +import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
@@ -42,7 +45,6 @@ import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; -import org.rhq.enterprise.gui.coregui.client.components.table.Table.SelectionEnablement; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; @@ -140,57 +142,6 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement if (!formBuilt) {
table = new NotificationTable(extendLocatorId("notificationsTable")); - table.setShowHeader(false); - - final NotificationDataSource dataSource = new NotificationDataSource(); - table.setDataSource(dataSource); - - table.addTableAction(this.extendLocatorId("add"), "Add", SelectionEnablement.ALWAYS, null, - new TableAction() { - @Override - public void executeAction(ListGridRecord[] selection) { - final Window winModal = new LocatableWindow(NotificationsAlertDefinitionForm.this - .extendLocatorId("newNotificationEditorWindow")); - winModal.setTitle("Add Notification"); - winModal.setOverflow(Overflow.VISIBLE); - winModal.setShowMinimizeButton(false); - winModal.setIsModal(true); - winModal.setShowModalMask(true); - winModal.setAutoSize(true); - winModal.setAutoCenter(true); - //winModal.setShowResizer(true); - //winModal.setCanDragResize(true); - winModal.centerInPage(); - winModal.addCloseClickHandler(new CloseClickHandler() { - @Override - public void onCloseClick(CloseClientEvent event) { - winModal.markForDestroy(); - } - }); - - // NewNotificationEditor newEditor = new NewNotificationEditor( - // extendLocatorId("newNotificationEditor"), notifications, new Runnable() { - // @Override - // public void run() { - // winModal.markForDestroy(); - // table.refresh(); - // } - // }); - /// winModal.addItem(newEditor); - winModal.show(); - } - }); - table.addTableAction(this.extendLocatorId("delete"), "Delete", SelectionEnablement.ANY, "Are you sure?", - new TableAction() { - @Override - public void executeAction(ListGridRecord[] selection) { - for (ListGridRecord record : selection) { - AlertNotification notif = dataSource.copyValues(record); - notifications.remove(notif); - } - table.refresh(); - } - });
addMember(table);
@@ -268,6 +219,10 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement private class NotificationTable extends Table { public NotificationTable(String locatorId) { super(locatorId); + setShowHeader(false); + + final NotificationDataSource dataSource = new NotificationDataSource(); + setDataSource(dataSource); }
@Override @@ -277,6 +232,74 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement ListGridField configField = new ListGridField(FIELD_CONFIGURATION, "Configuration"); configField.setWidth("75%"); getListGrid().setFields(senderField, configField); + + getListGrid().addDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + ListGrid listGrid = (ListGrid) event.getSource(); + ListGridRecord[] selectedRows = listGrid.getSelection(); + if (selectedRows != null && selectedRows.length == 1) { + AlertNotification notif = ((NotificationDataSource) getDataSource()) + .copyValues(selectedRows[0]); + popupNotificationEditor(notif); + } + } + }); + + addTableAction(this.extendLocatorId("add"), "Add", SelectionEnablement.ALWAYS, null, new TableAction() { + @Override + public void executeAction(ListGridRecord[] selection) { + popupNotificationEditor(null); + } + }); + + addTableAction(this.extendLocatorId("delete"), "Delete", SelectionEnablement.ANY, "Are you sure?", + new TableAction() { + @Override + public void executeAction(ListGridRecord[] selection) { + for (ListGridRecord record : selection) { + AlertNotification notif = ((NotificationDataSource) getDataSource()).copyValues(record); + notifications.remove(notif); + } + table.refresh(); + } + }); + } + + private void popupNotificationEditor(AlertNotification notifToEdit) { + final Window winModal = new LocatableWindow(NotificationsAlertDefinitionForm.this + .extendLocatorId("notificationEditorWindow")); + if (notifToEdit == null) { + winModal.setTitle("Add Notification"); + } else { + winModal.setTitle("Edit Notification"); + } + winModal.setOverflow(Overflow.VISIBLE); + winModal.setShowMinimizeButton(false); + winModal.setIsModal(true); + winModal.setShowModalMask(true); + winModal.setAutoSize(true); + winModal.setAutoCenter(true); + //winModal.setShowResizer(true); + //winModal.setCanDragResize(true); + winModal.centerInPage(); + winModal.addCloseClickHandler(new CloseClickHandler() { + @Override + public void onCloseClick(CloseClientEvent event) { + winModal.markForDestroy(); + } + }); + + // NewNotificationEditor newEditor = new NewNotificationEditor( + // extendLocatorId("newNotificationEditor"), notifications, new Runnable() { + // @Override + // public void run() { + // winModal.markForDestroy(); + // table.refresh(); + // } + // }); + /// winModal.addItem(newEditor); + winModal.show(); } } }
commit 7f0ee950e729a69708326e6ad7b5c8df7ebd749f Author: John Sanda jsanda@redhat.com Date: Thu Sep 30 11:01:51 2010 -0400
Adding more tests
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 1658e18..bc0d6c5 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 @@ -24,8 +24,6 @@ package org.rhq.enterprise.server.configuration.metadata;
import javax.persistence.EntityManager; -import javax.transaction.NotSupportedException; -import javax.transaction.SystemException;
import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -38,12 +36,11 @@ import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.util.LookupUtil; import org.rhq.test.AssertUtils;
-import static org.rhq.enterprise.server.configuration.metadata.PluginDescriptorUtil.*; +import static org.rhq.enterprise.server.configuration.metadata.PluginDescriptorUtil.loadPluginConfigDefFor; +import static org.rhq.enterprise.server.configuration.metadata.PluginDescriptorUtil.loadPluginDescriptor;
public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test {
- EntityManager entityMgr; - PluginDescriptor originalDescriptor;
PluginDescriptor updatedDescriptor; @@ -63,16 +60,37 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { }
@Test - public void newUngroupedPropertyDefsShouldBeAddedToConfigurationDef() throws Exception { + public void addNewUngroupedPropertyDef() { initConfigDefs("servers[name='MyServer1']", "test");
- PropertyDefinitionSimple expected = updatedConfigDef.getPropertyDefinitionSimple("bar"); - PropertyDefinitionSimple actual = originalConfigDef.getPropertyDefinitionSimple("bar"); + String propertyName = "newUngroupedProperty"; + PropertyDefinitionSimple expected = updatedConfigDef.getPropertyDefinitionSimple(propertyName); + PropertyDefinitionSimple actual = originalConfigDef.getPropertyDefinitionSimple(propertyName);
assertPropertyDefinitionMatches("New ungrouped property defs should be added to the configuration definition", expected, actual); }
+ @Test + public void removePropertyDefThatIsNotInNewDescriptor() { + initConfigDefs("servers[name='MyServer1']", "test"); + + assertNull("The property exists in version 1 but not in version 2 of the plugin; therefore, it should be " + + "removed the configuration definition", originalConfigDef.get("v1OnlyProperty")); + } + + @Test + public void doNotModifyExistingPropertyDefThatIsNotModifiedInUpgrade() { + initConfigDefs("servers[name='MyServer1']", "test"); + + String propertyName = "myExistingProperty"; + PropertyDefinitionSimple expected = updatedConfigDef.getPropertyDefinitionSimple(propertyName); + PropertyDefinitionSimple actual = originalConfigDef.getPropertyDefinitionSimple(propertyName); + + assertPropertyDefinitionMatches("Existing property that is not changed in new version of pluign should " + + "not change", expected, actual); + } + // void assertGroupDefinitionExists() { // for (PropertyGroupDefinition groupDef : originalConfigurationDef.getGroupDefinitions()) { // if (groupDef.getName().equals("groupToBeRemoved")) { 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 0c7d362..131cff7 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 @@ -7,7 +7,15 @@
<server name="MyServer1"> <plugin-configuration> - <c:simple-property name="myProperty1"/> + <c:simple-property name="myExistingProperty" + type="integer" + units="megabytes" + default="256" + required="true" + description="My Existing Property"/> + + <c:simple-property name="v1OnlyProperty" + description="This property exists only in version 1 of the plugin"/> </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 8997f8f..2c94f72 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 @@ -7,8 +7,22 @@
<server name="MyServer1"> <plugin-configuration> - <c:simple-property name="myProperty1"/> - <c:simple-property name="bar" description="bar property"/> + <c:simple-property name="myExistingProperty" + type="integer" + units="megabytes" + default="256" + required="true" + description="My Existing Property"/> + + <c:simple-property name="newUngroupedProperty" + description="A new, ungrouped property" + activationPolicy="immediate" + default="new property" + required="true" + displayName="My New Ungrouped Property" + readOnly="true" + type="longString" + summary="false"/> </plugin-configuration> </server> </plugin>
commit 423bfa5e3c976746bd61d917464eff8da2cbac46 Author: John Sanda jsanda@redhat.com Date: Thu Sep 30 09:52:34 2010 -0400
Guarding against hibernate exception that can occur when using delete-orphan
While adding/updating tests I was running into,
HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance
The solution is to make sure that the managed collection references do not change
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 101d894..782dc99 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 @@ -78,7 +78,7 @@ public class PropertyDefinitionSimple extends PropertyDefinition { @Cascade( { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN }) @IndexColumn(name = "order_index") @OneToMany(mappedBy = "propertyDefinitionSimple", fetch = FetchType.EAGER) - private List<PropertyDefinitionEnumeration> enumeratedValues; + private List<PropertyDefinitionEnumeration> enumeratedValues = new ArrayList<PropertyDefinitionEnumeration>();
/** * This property's default value. This field should have a non-null value for properties whose @@ -122,10 +122,6 @@ public class PropertyDefinitionSimple extends PropertyDefinition { */ @NotNull public Set<Constraint> getConstraints() { - if (this.constraints == null) { - this.constraints = new LinkedHashSet<Constraint>(); - } - return this.constraints; }
@@ -148,15 +144,11 @@ public class PropertyDefinitionSimple extends PropertyDefinition { */ @NotNull public List<PropertyDefinitionEnumeration> getEnumeratedValues() { - if (this.enumeratedValues == null) { - this.enumeratedValues = new ArrayList<PropertyDefinitionEnumeration>(); - } - return this.enumeratedValues; }
public void setEnumeratedValues(List<PropertyDefinitionEnumeration> enumeratedValues, boolean allowCustomEnumValue) { - this.enumeratedValues = enumeratedValues; + addEnumeratedValues(enumeratedValues.toArray(new PropertyDefinitionEnumeration[enumeratedValues.size()])); this.allowCustomEnumeratedValue = allowCustomEnumValue; ensureOrdering(); }
commit d6f69c80499f3e959825ab50b613ad45cd472404 Merge: b56a7c0... 3c5a00e... Author: John Sanda jsanda@redhat.com Date: Thu Sep 30 09:21:43 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit b56a7c0af0071ebee3b350ac1769a52e8a8b3a75 Author: John Sanda jsanda@redhat.com Date: Thu Sep 30 09:17:01 2010 -0400
Getting infrastructure in place for testing plugin upgrade code
Trying to clean up and get tests in ConfigurationMetadataManagerBean in a working, maintainable state.
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 a27b677..101d894 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 @@ -23,6 +23,7 @@ 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; @@ -69,7 +70,7 @@ public class PropertyDefinitionSimple extends PropertyDefinition {
@Cascade( { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN }) @OneToMany(mappedBy = "propertyDefinitionSimple", cascade = { CascadeType.ALL }, fetch = FetchType.EAGER) - private Set<Constraint> constraints; + private Set<Constraint> constraints = new HashSet<Constraint>();
/** * The <options> within <property-options> for a <simple-property> diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index 4c4e9a5..b54dfd8 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -400,6 +400,13 @@ <version>1.8</version> <scope>test</scope> </dependency> + + <dependency> + <groupId>commons-jxpath</groupId> + <artifactId>commons-jxpath</artifactId> + <version>1.3</version> + <scope>test</scope> + </dependency>
</dependencies>
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 87d254a..1658e18 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,113 +23,102 @@
package org.rhq.enterprise.server.configuration.metadata;
-import org.rhq.core.clientapi.agent.metadata.ConfigurationMetadataParser; -import org.rhq.core.clientapi.descriptor.DescriptorPackages; -import org.rhq.core.clientapi.descriptor.configuration.ConfigurationDescriptor; +import javax.persistence.EntityManager; +import javax.transaction.NotSupportedException; +import javax.transaction.SystemException; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + import org.rhq.core.clientapi.descriptor.plugin.PluginDescriptor; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertyGroupDefinition; -import org.rhq.core.domain.resource.ResourceType; -import org.rhq.enterprise.server.resource.metadata.test.UpdateSubsytemTestBase; import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.util.LookupUtil; import org.rhq.test.AssertUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test;
-import javax.persistence.EntityManager; -import javax.transaction.TransactionManager; -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.util.ValidationEventCollector; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import java.io.FileNotFoundException; -import java.net.URL; +import static org.rhq.enterprise.server.configuration.metadata.PluginDescriptorUtil.*;
public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test {
- ConfigurationMetadataManagerLocal configurationMetadataMgr; - EntityManager entityMgr;
- ConfigurationDefinition originalConfigurationDef; + PluginDescriptor originalDescriptor; + + PluginDescriptor updatedDescriptor;
- ConfigurationDefinition newConfigurationDef; + ConfigurationDefinition originalConfigDef;
- @BeforeClass(enabled = false) - public void setupClass() throws Exception { + ConfigurationDefinition updatedConfigDef; + + @BeforeClass + public void setupClass() { String pluginFileBaseName = "configuration_metadata_manager_bean_test"; String version1 = pluginFileBaseName + "_v1.xml"; String version2 = pluginFileBaseName + "_v2.xml";
- getTransactionManager().begin(); - entityMgr = getEntityManager(); + originalDescriptor = loadPluginDescriptor(getPackagePath() + version1); + updatedDescriptor = loadPluginDescriptor(getPackagePath() + version2); + }
- configurationMetadataMgr = LookupUtil.getConfigurationMetadataManager(); + @Test + public void newUngroupedPropertyDefsShouldBeAddedToConfigurationDef() throws Exception { + initConfigDefs("servers[name='MyServer1']", "test");
- originalConfigurationDef = createAndSaveConfigurationDef(version1); - newConfigurationDef = loadPluginConfigurationFromFile(version2); + PropertyDefinitionSimple expected = updatedConfigDef.getPropertyDefinitionSimple("bar"); + PropertyDefinitionSimple actual = originalConfigDef.getPropertyDefinitionSimple("bar");
- assertGroupDefinitionExists(); + assertPropertyDefinitionMatches("New ungrouped property defs should be added to the configuration definition", + expected, actual); + }
- originalConfigurationDef = entityMgr.getReference(ConfigurationDefinition.class, - originalConfigurationDef.getId()); +// void assertGroupDefinitionExists() { +// for (PropertyGroupDefinition groupDef : originalConfigurationDef.getGroupDefinitions()) { +// if (groupDef.getName().equals("groupToBeRemoved")) { +// assertTrue(groupDef.getId() != 0); +// assertNotNull(entityMgr.find(PropertyGroupDefinition.class, groupDef.getId())); +// } +// } +// } + + private void initConfigDefs(String path, String configName) { + loadAndPersistConfigDefs(path, configName); + updateConfigDef(); + }
- configurationMetadataMgr.updateConfigurationDefinition(newConfigurationDef, originalConfigurationDef); + private void loadAndPersistConfigDefs(String path, String configName) { + originalConfigDef = loadPluginConfigDefFor(originalDescriptor, path, configName); + updatedConfigDef = loadPluginConfigDefFor(updatedDescriptor, path, configName);
- originalConfigurationDef = entityMgr.find(ConfigurationDefinition.class, originalConfigurationDef.getId()); + try { + getTransactionManager().begin();
- assertNotNull(originalConfigurationDef); - } + EntityManager entityMgr = getEntityManager(); + entityMgr.persist(originalConfigDef); + entityMgr.persist(updatedConfigDef);
- void assertGroupDefinitionExists() { - for (PropertyGroupDefinition groupDef : originalConfigurationDef.getGroupDefinitions()) { - if (groupDef.getName().equals("groupToBeRemoved")) { - assertTrue(groupDef.getId() != 0); - assertNotNull(entityMgr.find(PropertyGroupDefinition.class, groupDef.getId())); - } + getTransactionManager().commit(); + } catch (Exception e) { + throw new RuntimeException(e); } }
- @AfterClass(enabled = false) - public void tearDownClass() throws Exception { - getTransactionManager().rollback(); - } - - private ConfigurationDefinition createAndSaveConfigurationDef(String file) throws Exception { - ConfigurationDefinition configurationDef = loadPluginConfigurationFromFile(file); - entityMgr.persist(configurationDef); - return configurationDef; - } + private void updateConfigDef() { + try { + getTransactionManager().begin();
- private ConfigurationDefinition loadPluginConfigurationFromFile(String file) throws Exception { - PluginDescriptor pluginDescriptor = loadPluginDescriptor(file); - ConfigurationDescriptor configurationDescriptor = pluginDescriptor.getServers().get(0).getPluginConfiguration(); - return ConfigurationMetadataParser.parse("test", configurationDescriptor); - } + ConfigurationMetadataManagerLocal configMetadataMgr = LookupUtil.getConfigurationMetadataManager(); + configMetadataMgr.updateConfigurationDefinition(updatedConfigDef, originalConfigDef);
- private PluginDescriptor loadPluginDescriptor(String file) throws Exception { - URL pluginDescriptorURL = getClass().getResource(file); - if (pluginDescriptorURL == null) { - throw new FileNotFoundException("File " + file + " not found"); + getTransactionManager().commit(); + } catch (Exception e) { + throw new RuntimeException(e); } + }
- JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN); - URL pluginSchemaURL = this.getClass().getClassLoader().getResource("rhq-plugin.xsd"); - Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(pluginSchemaURL); - - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - ValidationEventCollector vec = new ValidationEventCollector(); - unmarshaller.setEventHandler(vec); - unmarshaller.setSchema(pluginSchema); - - return (PluginDescriptor) unmarshaller.unmarshal(pluginDescriptorURL.openStream()); + private String getPackagePath() { + return "/" + getClass().getPackage().getName().replace('.', '/') + "/"; }
void assertPropertyDefinitionMatches(String msg, PropertyDefinitionSimple expected, @@ -138,18 +127,9 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { }
@Test(enabled = false) - public void newUngroupedPropertyDefsShouldBeAddedToConfigurationDef() throws Exception { - PropertyDefinitionSimple expected = newConfigurationDef.getPropertyDefinitionSimple("bar"); - PropertyDefinitionSimple actual = originalConfigurationDef.getPropertyDefinitionSimple("bar"); - - assertPropertyDefinitionMatches("New ungrouped property defs shoould be added to the configuration definition", - expected, actual); - } - - @Test(enabled = false) public void existingUngroupedPropertyDefShouldBeUpdated() throws Exception { - PropertyDefinitionSimple expected = newConfigurationDef.getPropertyDefinitionSimple("foo"); - PropertyDefinitionSimple actual = originalConfigurationDef.getPropertyDefinitionSimple("foo"); + PropertyDefinitionSimple expected = updatedConfigDef.getPropertyDefinitionSimple("foo"); + PropertyDefinitionSimple actual = originalConfigDef.getPropertyDefinitionSimple("foo");
assertPropertyDefinitionMatches("Existing ungrouped property defs should be updated", expected, actual); } @@ -158,13 +138,13 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { 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", - originalConfigurationDef.getPropertyDefinitionSimple("propertyToBeRemoved") + originalConfigDef.getPropertyDefinitionSimple("propertyToBeRemoved") ); }
@Test(enabled = false) public void propertyGroupDefNotInNewConfigurationDefShouldBeRemoved() throws Exception { - for (PropertyGroupDefinition def : originalConfigurationDef.getGroupDefinitions()) { + 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/java/org/rhq/enterprise/server/configuration/metadata/PluginDescriptorUtil.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/PluginDescriptorUtil.java new file mode 100644 index 0000000..8eb4632 --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/PluginDescriptorUtil.java @@ -0,0 +1,70 @@ +package org.rhq.enterprise.server.configuration.metadata; + +import java.io.FileNotFoundException; +import java.net.URL; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.util.ValidationEventCollector; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.apache.commons.jxpath.JXPathContext; + +import org.rhq.core.clientapi.agent.metadata.ConfigurationMetadataParser; +import org.rhq.core.clientapi.descriptor.DescriptorPackages; +import org.rhq.core.clientapi.descriptor.plugin.PluginDescriptor; +import org.rhq.core.clientapi.descriptor.plugin.ResourceDescriptor; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; + +public class PluginDescriptorUtil { + + public static PluginDescriptor loadPluginDescriptor(String file) { + try { + URL pluginDescriptorURL = PluginDescriptorUtil.class.getResource(file); + if (pluginDescriptorURL == null) { + throw new FileNotFoundException("File " + file + " not found"); + } + + JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN); + URL pluginSchemaURL = PluginDescriptorUtil.class.getClassLoader().getResource("rhq-plugin.xsd"); + Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( + pluginSchemaURL); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + ValidationEventCollector vec = new ValidationEventCollector(); + unmarshaller.setEventHandler(vec); + unmarshaller.setSchema(pluginSchema); + + return (PluginDescriptor) unmarshaller.unmarshal(pluginDescriptorURL.openStream()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static Object find(PluginDescriptor descriptor, String path) { + JXPathContext context = JXPathContext.newContext(descriptor); + return context.getValue(path); + } + + public static ConfigurationDefinition loadPluginConfigDefFor(PluginDescriptor descriptor, String path, + String configName) { + try { + ResourceDescriptor resourceDescriptor = (ResourceDescriptor) find(descriptor, path); + return ConfigurationMetadataParser.parse(configName, resourceDescriptor.getPluginConfiguration()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static ConfigurationDefinition loadResourceConfigDefFor(PluginDescriptor descriptor, String path, + String configName) { + try { + ResourceDescriptor resourceDescriptor = (ResourceDescriptor) find(descriptor, path); + return ConfigurationMetadataParser.parse(configName, resourceDescriptor.getResourceConfiguration()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} 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 new file mode 100644 index 0000000..0c7d362 --- /dev/null +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml @@ -0,0 +1,13 @@ +<plugin name="ConfigurationMetadataManagerBeanTest" + package="org.rhq.enterprise.server.confiuguration.metadata" + version="2.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <server name="MyServer1"> + <plugin-configuration> + <c:simple-property name="myProperty1"/> + </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 new file mode 100644 index 0000000..8997f8f --- /dev/null +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml @@ -0,0 +1,14 @@ +<plugin name="ConfigurationMetadataManagerBeanTest" + package="org.rhq.enterprise.server.confiuguration.metadata" + version="2.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <server name="MyServer1"> + <plugin-configuration> + <c:simple-property name="myProperty1"/> + <c:simple-property name="bar" description="bar property"/> + </plugin-configuration> + </server> +</plugin>
commit 941fa0bcc0d7c177f7c0c2094a63a22c87727453 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 30 01:53:39 2010 -0400
EventCompositeHistoryView: disable flexRowDisplay and fix column widths
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 a0487db..c933047 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 @@ -90,6 +90,7 @@ public class Table extends LocatableHLayout { private SortSpecifier[] sortSpecifiers; private String[] excludedFieldNames; private boolean autoFetchData; + private boolean flexRowDisplay = true;
private RPCDataSource dataSource;
@@ -165,6 +166,10 @@ public class Table extends LocatableHLayout { this.autoFetchData = autoFetchData; }
+ public void setFlexRowDisplay(boolean flexRowDisplay) { + this.flexRowDisplay = flexRowDisplay; + } + @Override protected void onInit() { super.onInit(); @@ -183,11 +188,14 @@ public class Table extends LocatableHLayout { } listGrid.setWidth100(); listGrid.setHeight100(); - listGrid.setAutoFitData(Autofit.HORIZONTAL); listGrid.setAlternateRecordStyles(true); listGrid.setResizeFieldsInRealTime(false); - listGrid.setWrapCells(true); - listGrid.setFixedRecordHeights(false); + + if (flexRowDisplay) { + listGrid.setAutoFitData(Autofit.HORIZONTAL); + listGrid.setWrapCells(true); + listGrid.setFixedRecordHeights(false); + }
// By default, SmartGWT will disable any rows that have a record named "enabled" with a value of false - setting // these fields to a bogus field name will disable this behavior. Note, setting them to null does *not* disable diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java index 954bac7..28e91f6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java @@ -32,6 +32,7 @@ import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; +import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.common.EntityContext; @@ -78,6 +79,13 @@ public class EventCompositeHistoryView extends TableSection { }
@Override + protected void onInit() { + setFlexRowDisplay(false); + + super.onInit(); + } + + @Override protected void configureTableFilters() { final TextItem sourceFilter = new TextItem("source", "Source Filter"); final TextItem detailsFilter = new TextItem("details", "Details Filter"); @@ -90,11 +98,31 @@ public class EventCompositeHistoryView extends TableSection { protected void configureTable() { ListGrid grid = getListGrid();
- grid.setWrapCells(true); - grid.setFixedRecordHeights(true); - // getListGrid().getField("id").setWidth(60);
+ ListGridField timestampField = new ListGridField("timestamp", "ID", 125); + ListGridField severityField = new ListGridField("severity", "Severity", 75); + severityField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { + return Canvas.imgHTML("subsystems/event/" + o + "_16.png", 16, 16) + o; + } + }); + ListGridField detailsField = new ListGridField("details-highlight", "Details"); + ListGridField sourceField = new ListGridField("source", "Source Location", 275); + sourceField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { + String sourceLocation = (String) o; + int length = sourceLocation.length(); + if (length > 40) { + return "..." + sourceLocation.substring(length - 40); // the last 40 chars + } + return sourceLocation; + } + }); + + grid.setFields(timestampField, severityField, detailsField, sourceField); + + /* grid.getField("timestamp").setWidth(125);
grid.getField("severity").setWidth(75); @@ -115,6 +143,7 @@ public class EventCompositeHistoryView extends TableSection { return sourceLocation; } }); + */
setupTableInteractions(); }
commit 9a77ce49fda241fc70ce3730ac21500fca584bf6 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 30 01:45:09 2010 -0400
InventoryView: tidy up labels, add tree node icons, add table header icons
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index 335d23c..a1683dc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -70,7 +70,7 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView private static final String PAGE_COMPATIBLE_GROUPS = "CompatibleGroups"; private static final String PAGE_DOWN = "DownServers"; private static final String PAGE_GROUPS = "AllGroups"; - private static final String PAGE_GROUP_DEFINITIONS = "DynamicGroupDefinitions"; + private static final String PAGE_GROUP_DEFINITIONS = "DynagroupManager"; private static final String PAGE_MIXED_GROUPS = "MixedGroups"; private static final String PAGE_PLATFORMS = "Platforms"; private static final String PAGE_PROBLEM_GROUPS = "ProblemGroups"; @@ -203,6 +203,7 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView final TreeNode inventory = new EnhancedTreeNode(SUBSECTION_GROUP_INVENTORY, onlyCompatible, onlyMixed);
final TreeNode problemGroups = new EnhancedTreeNode(PAGE_PROBLEM_GROUPS); + problemGroups.setIcon("types/Cluster_down_16.png"); final TreeNode savedSearches = new EnhancedTreeNode(SUBSECTION_SAVED_SEARCHES, problemGroups);
TreeGrid treeGrid = new LocatableTreeGrid(GROUPS_SECTION_VIEW_ID); @@ -272,7 +273,7 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView //TODO - there is no underlying support for this criteria. Also, there should not be an active // new button on this page. content = new ResourceGroupListView(extendLocatorId("DownGroups"), - new Criteria("availability", "down"), PAGE_PROBLEM_GROUPS); + new Criteria("availability", "down"), PAGE_PROBLEM_GROUPS, "types/Cluster_down_16.png"); } else { // selected the Inventory node itself content = new ResourceGroupListView(extendLocatorId("AllGroups"), null, PAGE_GROUPS, "types/Cluster_up_24.png", "types/Group_up_24.png");
commit 114cb5096cc46be1c78eeda894f8567b6a616306 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 29 19:23:13 2010 -0400
fix various bugs in config component; add new MessageBar component for displaying JSF-like messages
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java index 336aff1..938b07f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java @@ -27,6 +27,9 @@ import java.util.HashSet; import java.util.List; import java.util.Set;
+/** + * + */ public class StringUtils { private static final Set<String> LOWERCASE_WORDS = new HashSet<String>(); static { @@ -62,18 +65,17 @@ public class StringUtils { + target.substring(nextDash + 2); }
- result.append(Character.toUpperCase(target.charAt(0))); - StringBuilder currentWord = new StringBuilder(); char currentChar; - char previousChar = target.charAt(0); - for (int i = 1; i < target.length(); i++) { + char previousChar = 0; + for (int i = 0; i < target.length(); i++) { currentChar = target.charAt(i);
- // Obey multi-digit numbers and acronyms - if ((Character.isDigit(currentChar) && !Character.isDigit(previousChar)) + // Make sure to insert spaces in the middle of acronyms or multi-digit numbers. + if ((i != 0) && + ((Character.isDigit(currentChar) && !Character.isDigit(previousChar)) || (Character.isUpperCase(currentChar) && (!Character.isUpperCase(previousChar) - || ((i < (target.length() - 1)) && Character.isLowerCase(target.charAt(i + 1)))))) { + || ((i < (target.length() - 1)) && Character.isLowerCase(target.charAt(i + 1))))))) { // We're at the start of a new word. appendWord(result, currentWord); currentWord = new StringBuilder(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java index b82482c..c90ca57 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java @@ -25,7 +25,6 @@ import com.smartgwt.client.widgets.HTMLPane; * @author Greg Hinkle */ public class FullHTMLPane extends HTMLPane { - public FullHTMLPane() { setWidth100(); setHeight100(); @@ -34,8 +33,7 @@ public class FullHTMLPane extends HTMLPane {
public FullHTMLPane(String url) { this(); - System.out.println("Creating IFrame pane with URL [" + url + "]..."); + //System.out.println("Creating IFrame pane with URL [" + url + "]..."); setContentsURL(url); } - } 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 1de6dd2..432cd2b 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 @@ -23,6 +23,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -64,8 +65,10 @@ import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; +import com.smartgwt.client.widgets.form.validator.FloatRangeValidator; import com.smartgwt.client.widgets.form.validator.IntegerRangeValidator; import com.smartgwt.client.widgets.form.validator.RegExpValidator; +import com.smartgwt.client.widgets.form.validator.Validator; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -107,6 +110,7 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertyGroupDefinition; import org.rhq.core.domain.configuration.definition.PropertySimpleType; import org.rhq.core.domain.configuration.definition.constraint.Constraint; +import org.rhq.core.domain.configuration.definition.constraint.FloatRangeConstraint; import org.rhq.core.domain.configuration.definition.constraint.IntegerRangeConstraint; import org.rhq.core.domain.configuration.definition.constraint.RegexConstraint; import org.rhq.core.domain.resource.ResourceType; @@ -129,6 +133,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle + * @author Ian Springer */ public class ConfigurationEditor extends LocatableVLayout {
@@ -153,6 +158,9 @@ public class ConfigurationEditor extends LocatableVLayout { private IButton saveButton;
private boolean readOnly = false; + private Set<String> invalidPropertyNames = new HashSet<String>(); + private Set<ValidationStateChangeListener> validationStateChangeListeners = + new HashSet<ValidationStateChangeListener>();
public static enum ConfigType { plugin, resource @@ -206,6 +214,14 @@ public class ConfigurationEditor extends LocatableVLayout { return this.valuesManager.validate(); }
+ public boolean isValid() { + return this.valuesManager.hasErrors(); + } + + public void addValidationStateChangeListener(ValidationStateChangeListener validationStateChangeListener) { + this.validationStateChangeListeners.add(validationStateChangeListener); + } + @Override protected void onDraw() { super.onDraw(); @@ -286,7 +302,7 @@ public class ConfigurationEditor extends LocatableVLayout {
if (definition.getConfigurationFormat() == ConfigurationFormat.RAW || definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { - System.out.println("Loading files view"); + System.out.println("Loading files view..."); Tab tab = new LocatableTab("Files", "Files"); tab.setPane(buildRawPane()); tabSet.addTab(tab); @@ -294,7 +310,7 @@ public class ConfigurationEditor extends LocatableVLayout {
if (definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED || definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { - System.out.println("loading properties view"); + System.out.println("Loading properties view..."); Tab tab = new LocatableTab("Properties", "Properties"); tab.setPane(buildStructuredPane()); tabSet.addTab(tab); @@ -462,7 +478,7 @@ public class ConfigurationEditor extends LocatableVLayout { return section; }
- private DynamicForm buildPropertiesForm(String locatorId, ArrayList<PropertyDefinition> definitions, + private DynamicForm buildPropertiesForm(String locatorId, List<PropertyDefinition> definitions, AbstractPropertyMap propertyMap) { LocatableDynamicForm form = new LocatableDynamicForm(locatorId); form.setValuesManager(valuesManager); @@ -499,6 +515,7 @@ public class ConfigurationEditor extends LocatableVLayout { }
form.setFields(fields.toArray(new FormItem[fields.size()])); + return form; }
@@ -516,7 +533,7 @@ public class ConfigurationEditor extends LocatableVLayout {
fields.add(nameItem);
- FormItem valueItem = null; + FormItem valueItem; if (propertyDefinition instanceof PropertyDefinitionSimple) { valueItem = buildSimpleField(fields, (PropertyDefinitionSimple) propertyDefinition, oddRow, property); fields.add(valueItem); @@ -714,7 +731,7 @@ public class ConfigurationEditor extends LocatableVLayout { return rows; }
- private ListGridRecord buildSummaryRecord(ArrayList<PropertyDefinition> definitions, PropertyMap rowMap) { + private ListGridRecord buildSummaryRecord(List<PropertyDefinition> definitions, PropertyMap rowMap) { ListGridRecord record = new ListGridRecord(); for (PropertyDefinition subDef : definitions) { PropertyDefinitionSimple subDefSimple = (PropertyDefinitionSimple) subDef; @@ -778,7 +795,7 @@ public class ConfigurationEditor extends LocatableVLayout { }
List<PropertyDefinitionEnumeration> enumeratedValues = propertyDefinition.getEnumeratedValues(); - if (enumeratedValues != null && enumeratedValues.size() > 0) { + if (enumeratedValues != null && !enumeratedValues.isEmpty()) {
LinkedHashMap<String, String> valueOptions = new LinkedHashMap<String, String>(); for (PropertyDefinitionEnumeration option : propertyDefinition.getEnumeratedValues()) { @@ -837,24 +854,8 @@ public class ConfigurationEditor extends LocatableVLayout {
valueItem.setRequired(propertyDefinition.isRequired());
- if (propertyDefinition.getConstraints() != null) { - Set<Constraint> constraints = propertyDefinition.getConstraints(); - for (Constraint c : constraints) { - if (c instanceof IntegerRangeConstraint) { - IntegerRangeConstraint integerConstraint = ((IntegerRangeConstraint) c); - IntegerRangeValidator validator = new IntegerRangeValidator(); - - if (integerConstraint.getMinimum() != null) - validator.setMin(integerConstraint.getMinimum().intValue()); - if (integerConstraint.getMaximum() != null) - validator.setMax(integerConstraint.getMaximum().intValue()); - valueItem.setValidators(validator); - } else if (c instanceof RegexConstraint) { - - valueItem.setValidators(new RegExpValidator("^" + ((RegexConstraint) c).getDetails() + "$")); - } - } - } + List<Validator> validators = buildValidators(propertyDefinition, valueItem); + valueItem.setValidators(validators.toArray(new Validator[validators.size()]));
/* Click handlers seem to be turned off for disabled fields... need an alternative @@ -877,7 +878,19 @@ public class ConfigurationEditor extends LocatableVLayout {
finalValueItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { - propertySimple.setValue(changedEvent.getValue()); + boolean wasValidBefore = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); + if (changedEvent.getItem().validate()) { + ConfigurationEditor.this.invalidPropertyNames.remove(propertySimple.getName()); + propertySimple.setValue(changedEvent.getValue()); + } else { + ConfigurationEditor.this.invalidPropertyNames.add(propertySimple.getName()); + } + boolean isValidNow = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); + if (isValidNow != wasValidBefore) { + for (ValidationStateChangeListener validationStateChangeListener : ConfigurationEditor.this.validationStateChangeListeners) { + validationStateChangeListener.validateStateChanged(isValidNow); + } + } } });
@@ -900,10 +913,46 @@ public class ConfigurationEditor extends LocatableVLayout { return valueItem; }
+ private List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, FormItem valueItem) { + List<Validator> validators = new ArrayList<Validator>(); + if (propertyDefinition.getConstraints() != null) { + Set<Constraint> constraints = propertyDefinition.getConstraints(); + + for (Constraint constraint : constraints) { + if (constraint instanceof IntegerRangeConstraint) { + IntegerRangeConstraint integerConstraint = ((IntegerRangeConstraint) constraint); + IntegerRangeValidator validator = new IntegerRangeValidator(); + if (integerConstraint.getMinimum() != null) { + validator.setMin(integerConstraint.getMinimum().intValue()); + } + if (integerConstraint.getMaximum() != null) { + validator.setMax(integerConstraint.getMaximum().intValue()); + } + validators.add(validator); + } else if (constraint instanceof FloatRangeConstraint) { + FloatRangeConstraint floatConstraint = ((FloatRangeConstraint) constraint); + FloatRangeValidator validator = new FloatRangeValidator(); + if (floatConstraint.getMinimum() != null) { + validator.setMin(floatConstraint.getMinimum().floatValue()); + } + if (floatConstraint.getMaximum() != null) { + validator.setMax(floatConstraint.getMaximum().floatValue()); + } + validators.add(validator); + } else if (constraint instanceof RegexConstraint) { + RegExpValidator validator = + new RegExpValidator("^" + ((RegexConstraint) constraint).getDetails() + "$"); + validators.add(validator); + } + } + } + return validators; + } + private void displayMapEditor(String locatorId, final ListGrid summaryTable, final Record existingRecord, PropertyDefinitionMap definition, final PropertyList list, PropertyMap map) {
- final ArrayList<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(definition + final List<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(definition .getPropertyDefinitions().values());
Collections.sort(definitions, new PropertyDefinitionComparator()); @@ -994,5 +1043,4 @@ public class ConfigurationEditor extends LocatableVLayout { return new Integer(o1.getOrder()).compareTo(o2.getOrder()); } } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java new file mode 100644 index 0000000..d8f7a85 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ValidationStateChangeListener.java @@ -0,0 +1,27 @@ +/* + * 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; + +/** + * @author Ian Springer + */ +public interface ValidationStateChangeListener { + void validateStateChanged(boolean isValid); +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java index bbbcc1b..41e70c6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java @@ -36,7 +36,17 @@ public class EnhancedTreeNode extends TreeNode {
public EnhancedTreeNode(String name, TreeNode... children) { super(name, children); - setTitle(StringUtils.deCamelCase(name)); + if (name != null) { + setTitle(StringUtils.deCamelCase(name)); + } + } + + @Override + public void setName(String name) { + super.setName(name); + if (name != null && getTitle() == null) { + setTitle(StringUtils.deCamelCase(name)); + } }
public String getID() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index b2cadc1..b2c532d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -277,7 +277,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.configurationTab, this.configCurrent, new ResourceConfigurationEditView(this .extendLocatorId("ResourceConfigView"), resource), true, true); updateSubTab(this.configurationTab, this.configHistory, ConfigurationHistoryView.getHistoryOf( - configurationTab.extendLocatorId("HistoryView"), resource.getId()), true, true); + resource.getId()), true, true); }
if (updateTab(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT), true)) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryDataSource.java index 32e676a..f8387c9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryDataSource.java @@ -43,7 +43,6 @@ public class ConfigurationHistoryDataSource extends RPCDataSource<ResourceConfig
private ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService();
- public ConfigurationHistoryDataSource() { super();
@@ -76,8 +75,9 @@ public class ConfigurationHistoryDataSource extends RPCDataSource<ResourceConfig
criteria.setPageControl(getPageControl(request));
- if (request.getCriteria().getValues().get("resourceId") != null) { - criteria.addFilterResourceIds((Integer)request.getCriteria().getValues().get("resourceId")); + Integer resourceId = (Integer)request.getCriteria().getValues().get("resourceId"); + if (resourceId != null) { + criteria.addFilterResourceIds(resourceId); }
configurationService.findResourceConfigurationUpdatesByCriteria(criteria, diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java index 0e51bae..aa11b05 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java @@ -40,22 +40,36 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; */ public class ConfigurationHistoryView extends TableSection { public static final String VIEW_ID = "RecentConfigurationChanges"; + private static final String LOCATOR_ID = "ConfigurationHistory"; + private static final String TITLE = "Configuration History";
private Integer resourceId;
- public ConfigurationHistoryView(String locatorId) { - super("ConfigurationHistory", "Configuration History"); + /** + * Use this constructor to view config histories for all viewable Resources. + */ + public ConfigurationHistoryView() { + super(LOCATOR_ID, TITLE); final ConfigurationHistoryDataSource datasource = new ConfigurationHistoryDataSource(); setDataSource(datasource); }
- public ConfigurationHistoryView(String locatorId, final int resourceId) { - super("ConfigurationHistory", "Configuration History", new Criteria("resourceId", String.valueOf(resourceId))); + /** + * Use this constructor to view the config history for the Resource with the specified ID. + * + * @param resourceId a Resource ID + */ + public ConfigurationHistoryView(int resourceId) { + super(LOCATOR_ID, TITLE, createCriteria(resourceId)); this.resourceId = resourceId; - - final ConfigurationHistoryDataSource datasource = new ConfigurationHistoryDataSource(); + ConfigurationHistoryDataSource datasource = new ConfigurationHistoryDataSource(); setDataSource(datasource); + }
+ private static Criteria createCriteria(int resourceId) { + Criteria criteria = new Criteria(); + criteria.addCriteria("resourceId", Integer.valueOf(resourceId)); + return criteria; }
@Override @@ -143,11 +157,11 @@ public class ConfigurationHistoryView extends TableSection {
}
+ // -------- Static Utility loaders ------------
- public static ConfigurationHistoryView getHistoryOf(String locatorId, int resourceId) { - - return new ConfigurationHistoryView(locatorId, resourceId); + public static ConfigurationHistoryView getHistoryOf(int resourceId) { + return new ConfigurationHistoryView(resourceId); }
} 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 a0df3e9..7964a74 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 @@ -31,18 +31,21 @@ import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; import org.rhq.core.domain.resource.Resource; 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.ValidationStateChangeListener; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle */ -public class ResourceConfigurationEditView extends LocatableVLayout { - - Resource resource; - ConfigurationEditor editor; +public class ResourceConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener { + private Resource resource; + private ConfigurationEditor editor; + private IButton saveButton; + private MessageBar messageBar;
public ResourceConfigurationEditView(String locatorId, Resource resource) { super(locatorId); @@ -57,26 +60,28 @@ public class ResourceConfigurationEditView extends LocatableVLayout { }
public void build() { - ToolStrip toolStrip = new ToolStrip(); toolStrip.setWidth100();
toolStrip.addMember(new LayoutSpacer());
- IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); - saveButton.addClickHandler(new ClickHandler() { + this.saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + this.saveButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { save(); } }); - // saveButton.disable(); + this.saveButton.disable(); toolStrip.addMember(saveButton);
+ this.messageBar = new MessageBar(); + editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId()); editor.setOverflow(Overflow.AUTO); + editor.addValidationStateChangeListener(this);
addMember(toolStrip); - + addMember(this.messageBar); addMember(editor); }
@@ -96,6 +101,17 @@ public class ResourceConfigurationEditView extends LocatableVLayout {
} }); + }
+ @Override + public void validateStateChanged(boolean isValid) { + if (isValid) { + this.saveButton.enable(); + this.messageBar.hide(); + } else { + this.saveButton.disable(); + Message message = new Message("One or more properties have invalid values. The values must be fixed before the configuration can be saved.", Message.Severity.Error); + this.messageBar.setMessage(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 c11cca2..357255a 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 @@ -20,7 +20,6 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventor
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.LayoutSpacer; @@ -31,18 +30,22 @@ import org.rhq.core.domain.configuration.PluginConfigurationUpdate; import org.rhq.core.domain.resource.Resource; 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.ValidationStateChangeListener; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle */ -public class PluginConfigurationEditView extends LocatableVLayout { +public class PluginConfigurationEditView extends LocatableVLayout implements ValidationStateChangeListener {
private Resource resource; private ConfigurationEditor editor; + private LocatableIButton saveButton; + private MessageBar messageBar;
public PluginConfigurationEditView(String locatorId, Resource resource) { super(locatorId); @@ -63,21 +66,24 @@ public class PluginConfigurationEditView extends LocatableVLayout {
toolStrip.addMember(new LayoutSpacer());
- IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); - saveButton.addClickHandler(new ClickHandler() { + this.saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + this.saveButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { save(); } }); - // saveButton.disable(); + this.saveButton.disable(); toolStrip.addMember(saveButton);
+ this.messageBar = new MessageBar(); + editor = new ConfigurationEditor(this.getLocatorId(), resource.getId(), resource.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin); editor.setOverflow(Overflow.AUTO); + editor.addValidationStateChangeListener(this);
addMember(toolStrip); - + addMember(this.messageBar); addMember(editor); }
@@ -87,16 +93,28 @@ public class PluginConfigurationEditView extends LocatableVLayout { GWTServiceLookup.getConfigurationService().updatePluginConfiguration(resource.getId(), updatedConfiguration, new AsyncCallback<PluginConfigurationUpdate>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to update configuration", caught); + CoreGUI.getErrorHandler().handleError("Failed to update connection settings.", caught); }
public void onSuccess(PluginConfigurationUpdate result) { CoreGUI.getMessageCenter().notify( - new Message("Connection settings updated for resource [" + resource.getName() + "]", + new Message("Connection settings updated for Resource [" + resource.getName() + "].", Message.Severity.Info));
} });
} + + @Override + public void validateStateChanged(boolean isValid) { + if (isValid) { + this.saveButton.enable(); + this.messageBar.hide(); + } else { + this.saveButton.disable(); + Message message = new Message("One or more properties have invalid values. The values must be fixed before the configuration can be saved.", Message.Severity.Error); + this.messageBar.setMessage(message); + } + } } \ No newline at end of file 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 7627527..48a4455 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 @@ -214,7 +214,7 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView } else if (MeasurementOOBView.VIEW_ID.equals(pageName)) { content = new MeasurementOOBView(this.extendLocatorId("SuspectMetrics")); } else if (ConfigurationHistoryView.VIEW_ID.equals(pageName)) { - content = new ConfigurationHistoryView(this.extendLocatorId("RecentConfigChanges")); + content = new ConfigurationHistoryView(); } else if (OperationHistoryView.VIEW_ID.equals(pageName)) { content = new OperationHistoryView(this.extendLocatorId("RecentOps")); } else if (AlertsView.VIEW_ID.equals(pageName)) { 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 7e2eef4..905b0c7 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 @@ -34,14 +34,38 @@ public class Message { public enum Severity { Info, Warning, Error };
public Message(String title, Severity severity) { - this.title = title; - this.severity = severity; + this(title, null, severity); }
public Message(String title, String detail, Severity severity) { this.title = title; this.detail = detail; - this.severity = severity; + this.severity = (severity != null) ? severity : Severity.Info; + } + + public String getTitle() { + return title; + } + + public String getDetail() { + return detail; }
+ public Date getFired() { + return fired; + } + + public Severity getSeverity() { + return severity; + } + + @Override + public String toString() { + return "Message{" + + "title='" + title + ''' + + ", detail='" + detail + ''' + + ", fired=" + fired + + ", severity=" + severity + + '}'; + } } 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 new file mode 100644 index 0000000..e025ab1 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java @@ -0,0 +1,73 @@ +/* + * 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.util.message; + +import java.util.HashMap; +import java.util.Map; + +import com.smartgwt.client.widgets.Label; + +/** + * A bar for displaying a message at the top of a page - the equivalent of the JSF h:messages component. + * + * @author Ian Springer + */ +public class MessageBar extends Label { + public static final Map<Message.Severity, String> SEVERITY_TO_STYLE_NAME_MAP = new HashMap(); + static { + SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Info, "InfoBlock"); + SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Warning, "WarnBlock"); + SEVERITY_TO_STYLE_NAME_MAP.put(Message.Severity.Error, "ErrorBlock"); + } + + @Override + protected void onDraw() { + super.onDraw(); + + setWidth100(); + setAutoHeight(); + + hide(); + } + + public void setMessage(Message message) { + + String contents; + if (message != null) { + contents = message.getTitle(); + if (message.getDetail() != null) { + contents += ": " + message.getDetail(); + } + } else { + contents = null; + } + setContents(contents); + if (contents != null) { + String styleName = SEVERITY_TO_STYLE_NAME_MAP.get(message.getSeverity()); + setStyleName(styleName); + } + markForRedraw(); + if (contents != null) { + show(); + } else { + hide(); + } + } +} diff --git a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css index 305fcf8..c5d324e 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css +++ b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css @@ -359,3 +359,31 @@ a:hover { .editableText { color: #070; } + +.InfoBlock,.ConfirmationBlock,.WarnBlock,.ErrorBlock,.FatalBlock { + padding: 4px; + border-width: 1px; + border-top-style: solid; + font-size: 10px; + color: #000000; +} + +.InfoBlock,.ConfirmationBlock { + background-color: #BFF1B5; /* light green */ + border-top-color: #00AC3D; /* medium green */ +} + +.WarnBlock { + background-color: #FFFD99; /* light yellow */ + border-top-color: #FF9C15; /* medium orange */ +} + +.ErrorBlock { + background-color: #FF9999; /* light red */ + border-top-color: #EE4444; /* medium red */ +} + +.FatalBlock { + background-color: #FF6666; /* slightly darker light red */ + border-top-color: #EE1111; /* slightly darker medium red */ +}
commit cd8d92506dd5f31e8a340948e9ad6af0e2af2e1c Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 29 18:49:57 2010 -0400
add javadoc to explain what the extra properties are for (as well as what the normal config is)
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/alert/notification/AlertNotification.java b/modules/core/domain/src/main/java/org/rhq/core/domain/alert/notification/AlertNotification.java index 27da614..d93c81b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/alert/notification/AlertNotification.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/alert/notification/AlertNotification.java @@ -164,6 +164,14 @@ public class AlertNotification implements Serializable { this.senderName = senderName; }
+ /** + * The configuration containing the properties that each individual alert sender requires. + * The properties in this configuration should match the property definitions defined + * in the alert server plugin descriptor. + * + * @return the configuration for the alert notification (properties included in this + * configuration will be specific to the sender type). + */ public Configuration getConfiguration() { return configuration; } @@ -175,6 +183,17 @@ public class AlertNotification implements Serializable { this.configuration = configuration; }
+ /** + * These are extra configuration property values that a particular sender instance might need. + * These are only used/needed for specific alert implementations. One example where extra config is used + * is for the "resource operation" alert sender. If a particular notification uses this "resource operation" + * sender (where {@link #getConfiguration()} will include things like the operation name that is to be invoked), + * its possible that the selected operation to invoke requires parameters to be passed to it. The user can + * enter this "extra" data and those extra properties (that is, the configuration properties to be passed to the + * operation as parametesr) will be stored here. + * + * @return extra configuration properties or <code>null</code> if not set + */ public Configuration getExtraConfiguration() { return extraConfiguration; }
commit b6bf65f099863bb16d5bc920be9ad29eb5b1d3ce Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 29 17:30:21 2010 -0400
alert def / notification editor's list now shows the sender config preview in the config column
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 18931c0..cffdd78 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 @@ -26,6 +26,7 @@ package org.rhq.enterprise.gui.coregui.client.alert.definitions; import java.util.ArrayList; import java.util.List;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.fields.DataSourceTextField; @@ -38,9 +39,11 @@ import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.Table.SelectionEnablement; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow; @@ -226,20 +229,39 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement @Override public ListGridRecord copyValues(AlertNotification from) { ListGridRecord record = new ListGridRecord(); - record.setAttribute(FIELD_SENDER, from.getSenderName()); - record.setAttribute(FIELD_CONFIGURATION, from.getConfiguration().toString(false)); - // TODO configuration should be the string of - //getAlertManager().getAlertPluginManager().getAlertSenderForNotification(alertNotification).previewConfiguration() - // TODO what's this extra configuration in the notification? - record.setAttribute(FIELD_OBJECT, from); + record.setAttribute(FIELD_SENDER, from.getSenderName()); + // our executeFetch will fill in the real value for FIELD_CONFIGURATION + record.setAttribute(FIELD_CONFIGURATION, "(unknown)"); + // TODO what's the extraConfiguration the notification? return record; }
@Override - protected void executeFetch(DSRequest request, DSResponse response) { - response.setData(buildRecords(notifications)); - processResponse(request.getRequestId(), response); + protected void executeFetch(final DSRequest request, final DSResponse response) { + final ListGridRecord[] records = buildRecords(notifications); // partially builds the records, but we need to do another remote call to get the config preview + + AlertNotification[] notifs = notifications.toArray(new AlertNotification[notifications.size()]); + GWTServiceLookup.getAlertDefinitionService().getAlertNotificationConfigurationPreview(notifs, + new AsyncCallback<String[]>() { + @Override + public void onSuccess(String[] result) { + int i = 0; + for (ListGridRecord record : records) { + record.setAttribute(FIELD_CONFIGURATION, result[i++]); + } + response.setData(records); + processResponse(request.getRequestId(), response); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to get notification configuration preview", + caught); + response.setData(records); + processResponse(request.getRequestId(), response); + } + }); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java index e0d4e94..4819bac 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.client.gwt; import com.google.gwt.user.client.rpc.RemoteService;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.util.PageList;
@@ -38,4 +39,6 @@ public interface AlertDefinitionGWTService extends RemoteService { int disableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception;
int removeAlertDefinitions(Integer[] alertDefinitionIds) throws Exception; + + String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws Exception; } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java index 392e710..d1f492b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.exception.ThrowableUtil; @@ -32,6 +33,7 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem
private AlertDefinitionManagerLocal alertDefManager = LookupUtil.getAlertDefinitionManager();
+ @Override public PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria) { try { PageList<AlertDefinition> results = this.alertDefManager.findAlertDefinitionsByCriteria( @@ -42,6 +44,7 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ @Override public int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception { try { int results = alertDefManager.createAlertDefinition(getSessionSubject(), alertDefinition, resourceId); @@ -51,6 +54,7 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ @Override public AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, boolean updateInternals) throws Exception { try { @@ -62,6 +66,7 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ @Override public int enableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception { try { int results = alertDefManager.enableAlertDefinitions(getSessionSubject(), alertDefinitionIds); @@ -71,6 +76,7 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ @Override public int disableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception { try { int results = alertDefManager.disableAlertDefinitions(getSessionSubject(), alertDefinitionIds); @@ -80,6 +86,7 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ @Override public int removeAlertDefinitions(Integer[] alertDefinitionIds) throws Exception { try { int results = alertDefManager.removeAlertDefinitions(getSessionSubject(), alertDefinitionIds); @@ -88,4 +95,15 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } } + + @Override + public String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws Exception { + try { + String[] results = alertDefManager.getAlertNotificationConfigurationPreview(getSessionSubject(), notifs); + return SerialUtility.prepare(results, "getAlertNotificationConfigurationPreview"); + } 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/alert/AlertDefinitionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java index 3c41812..a221d96 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java @@ -32,6 +32,8 @@ import javax.persistence.Query; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
+import org.jboss.annotation.IgnoreDependency; + import org.rhq.core.domain.alert.AlertCondition; import org.rhq.core.domain.alert.AlertConditionCategory; import org.rhq.core.domain.alert.AlertConditionLog; @@ -55,6 +57,8 @@ import org.rhq.enterprise.server.alert.engine.AlertDefinitionEvent; import org.rhq.enterprise.server.authz.AuthorizationManagerLocal; import org.rhq.enterprise.server.authz.PermissionException; import org.rhq.enterprise.server.cloud.StatusManagerLocal; +import org.rhq.enterprise.server.plugin.pc.alert.AlertSender; +import org.rhq.enterprise.server.plugin.pc.alert.AlertSenderPluginManager; import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner;
@@ -74,6 +78,9 @@ public class AlertDefinitionManagerBean implements AlertDefinitionManagerLocal, private AuthorizationManagerLocal authorizationManager; @EJB private AlertDefinitionManagerLocal alertDefinitionManager; + @EJB + @IgnoreDependency + private AlertManagerLocal alertManager;
@EJB private StatusManagerLocal agentStatusManager; @@ -696,4 +703,27 @@ public class AlertDefinitionManagerBean implements AlertDefinitionManagerLocal, CriteriaQueryRunner<AlertDefinition> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); return queryRunner.execute(); } + + @Override + public String[] getAlertNotificationConfigurationPreview(Subject sessionSubject, AlertNotification[] notifications) { + if (notifications == null || notifications.length == 0) { + return new String[0]; + } + + AlertSenderPluginManager alertPluginManager = alertManager.getAlertPluginManager(); + + String[] previews = new String[notifications.length]; + int i = 0; + for (AlertNotification notif : notifications) { + AlertSender<?> sender = alertPluginManager.getAlertSenderForNotification(notif); + if (sender != null) { + previews[i++] = sender.previewConfiguration(); + } else { + previews[i++] = "n/a (unknown sender)"; + } + } + + return previews; + } + } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerLocal.java index 6908301..cca307f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerLocal.java @@ -23,6 +23,7 @@ import java.util.List; import javax.ejb.Local;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.composite.IntegerOptionItem; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; @@ -81,4 +82,6 @@ public interface AlertDefinitionManagerLocal { int disableAlertDefinitions(Subject subject, Integer[] alertDefinitionIds);
int removeAlertDefinitions(Subject subject, Integer[] alertDefinitionIds); + + String[] getAlertNotificationConfigurationPreview(Subject sessionSubject, AlertNotification[] notifications); } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerRemote.java index 3ed890b..3280d70 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerRemote.java @@ -25,6 +25,7 @@ import javax.jws.WebService; import javax.jws.soap.SOAPBinding;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.util.PageList; @@ -59,4 +60,9 @@ public interface AlertDefinitionManagerRemote { @WebParam(name = "subject") Subject subject, // @WebParam(name = "alertDefinitionIds") Integer[] alertDefinitionIds);
+ @WebMethod + String[] getAlertNotificationConfigurationPreview(// + @WebParam(name = "subject") Subject subject, // + @WebParam(name = "notifications") AlertNotification[] notifications); + } 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 0062843..d5f3cce 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 @@ -30,7 +30,6 @@ import java.util.Map; import java.util.Set;
import javax.ejb.Stateless; -import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; @@ -38,6 +37,7 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.rhq.core.domain.alert.Alert; import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.bundle.Bundle; @@ -166,7 +166,7 @@ import org.rhq.enterprise.server.util.LookupUtil; */ @Stateless @WebService(endpointInterface = "org.rhq.enterprise.server.webservices.WebservicesRemote", targetNamespace = ServerVersion.namespace) -@XmlSeeAlso({ PropertyDefinition.class, PropertyDefinitionSimple.class, PropertyDefinitionList.class, +@XmlSeeAlso( { PropertyDefinition.class, PropertyDefinitionSimple.class, PropertyDefinitionList.class, PropertyDefinitionMap.class }) public class WebservicesManagerBean implements WebservicesRemote {
@@ -229,6 +229,10 @@ public class WebservicesManagerBean implements WebservicesRemote { return alertDefinitionManager.removeAlertDefinitions(subject, alertDefinitionIds); }
+ public String[] getAlertNotificationConfigurationPreview(Subject subject, AlertNotification[] alertNotifications) { + return alertDefinitionManager.getAlertNotificationConfigurationPreview(subject, alertNotifications); + } + //ALERTDEFINITIONMANAGER: END ----------------------------------
//AVAILABILITYMANAGER: BEGIN ---------------------------------- @@ -784,14 +788,14 @@ public class WebservicesManagerBean implements WebservicesRemote { //REPOMANAGER: END ----------------------------------
//RESOURCEFACTORYMANAGER: BEGIN ---------------------------------- - public CreateResourceHistory createResource(Subject subject, int parentResourceId, int resourceTypeId, String resourceName, - Configuration pluginConfiguration, Configuration resourceConfiguration) { + public CreateResourceHistory createResource(Subject subject, int parentResourceId, int resourceTypeId, + String resourceName, Configuration pluginConfiguration, Configuration resourceConfiguration) { return resourceFactoryManager.createResource(subject, parentResourceId, resourceTypeId, resourceName, pluginConfiguration, resourceConfiguration); }
- public CreateResourceHistory createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, - String newResourceName,// + public CreateResourceHistory createPackageBackedResource(Subject subject, int parentResourceId, + int newResourceTypeId, String newResourceName,// @XmlJavaTypeAdapter(value = ConfigurationAdapter.class)// Configuration pluginConfiguration, String packageName, String packageVersion, Integer architectureId,// @XmlJavaTypeAdapter(value = ConfigurationAdapter.class)//
commit 6ecb7125e01e08584558b6d5176f85ef0ecf7e54 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 29 17:28:00 2010 -0400
fix NPE
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java index 88c08ee..336aff1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java @@ -38,6 +38,10 @@ public class StringUtils { * Take something that is camel-cased, add spaces between the words, and capitalize each word. */ public static String deCamelCase(String target) { + if (target == null) { + return null; + } + if (target.length() == 0) { return ""; }
commit 60549e9fd46e494a1eacfc0276b480c5027b19cc Author: Joseph Marques joseph@redhat.com Date: Wed Sep 29 16:06:48 2010 -0400
update javadoc
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 6fc72d8..5219213 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 @@ -40,9 +40,9 @@ import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility; import org.rhq.enterprise.gui.coregui.client.util.preferences.UserPreferences;
/** - * First time this class is loaded, local loggedIn bit will be false, which implies user is not logged in. + * Upon application load, if already loggedIn on the server-side, local loggedIn bit will be set to true. * - * If login successful, CoreGUI/SearchGUI will call setSessionSubject, which sets local loggedIn bit to true. + * If login successful, the local loggedIn bit will be set to true. * If user clicks logout explicitly, LoginView will be shown, which sets local loggedIn bit to false. * If count down timer expires, LoginView will be shown, which sets local loggedIn bit to false. *
commit 62f7518ae8dd868d4777400f37bc69b4368c4115 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 29 15:44:59 2010 -0400
fix remainder of session oddities:
* when applications loads, restore if user is logged in on the server-side * properly handle client-side sessions during timeout as well as logout action * fix the footer to refresh loggedIn and recent alerts label properly
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 a1d8475..e342b11 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 @@ -23,16 +23,10 @@ import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; -import com.google.gwt.http.client.Request; -import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.http.client.RequestCallback; -import com.google.gwt.http.client.RequestException; -import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Window.Location; -import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.core.KeyIdentifier; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.util.KeyCallback; @@ -41,22 +35,16 @@ import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.layout.VLayout;
-import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.common.ProductInfo; -import org.rhq.core.domain.criteria.SubjectCriteria; -import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.admin.AdministrationView; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.bundle.BundleTopView; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardsView; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupTopView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.InventoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTopView; import org.rhq.enterprise.gui.coregui.client.menu.MenuBarView; import org.rhq.enterprise.gui.coregui.client.report.ReportTopView; import org.rhq.enterprise.gui.coregui.client.report.tag.TaggedView; -import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility; import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.WidgetUtility; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; @@ -90,8 +78,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
private static Messages messages;
- private static ProductInfo productInfo; - public void onModuleLoad() { String hostPageBaseURL = GWT.getHostPageBaseURL(); if (hostPageBaseURL.indexOf("/coregui/") == -1) { @@ -127,124 +113,47 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
messages = GWT.create(Messages.class);
- checkLoginStatus(); + UserSessionManager.login();
// removing loading image, which can be seen if LoginView doesn't completely cover it Element loadingPanel = DOM.getElementById("Loading-Panel"); loadingPanel.removeFromParent(); }
- public static void checkLoginStatus() { - if (!UserSessionManager.isLoggedIn()) { - new LoginView().showLoginDialog(); - return; - } - - // String sessionIdString = com.google.gwt.user.client.Cookies.getCookie("RHQ_Sesssion"); - // if (sessionIdString == null) { - - BrowserUtility.forceIe6Hacks(); - - RequestBuilder b = new RequestBuilder(RequestBuilder.GET, "/sessionAccess"); - try { - b.setCallback(new RequestCallback() { - public void onResponseReceived(final Request request, final Response response) { - String sessionIdString = response.getText(); - if (sessionIdString != null && sessionIdString.length() > 0) { - - int subjectId = Integer.parseInt(sessionIdString.split(":")[0]); - final int sessionId = Integer.parseInt(sessionIdString.split(":")[1]); - - Subject subject = new Subject(); - subject.setId(subjectId); - subject.setSessionId(sessionId); - - GWTServiceLookup.registerSession(String.valueOf(subject.getSessionId())); - - // look up real user prefs - - SubjectCriteria criteria = new SubjectCriteria(); - criteria.fetchConfiguration(true); - criteria.addFilterId(subjectId); - //criteria.fetchRoles(true); - - GWTServiceLookup.getSubjectService().findSubjectsByCriteria(criteria, - new AsyncCallback<PageList<Subject>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load user's subject", caught); - new LoginView().showLoginDialog(); - } - - public void onSuccess(PageList<Subject> result) { - Subject subject = result.get(0); - subject.setSessionId(sessionId); - - // TODO this breaks because of reattach rules, bizarrely even in queries. - // gonna switch out to non-subject include apis - // - // Create a minimized session object for validation on requests - // Subject s = new Subject(subject.getName(),subject.getFactive(), subject.getFsystem()); - // s.setSessionId(subject.getSessionId()); - UserSessionManager.setSessionSubject(subject); - loadProductInfo(); - } - }); - } else { - new LoginView().showLoginDialog(); - } - } - - public void onError(Request request, Throwable exception) { - SC.say("Unable to determine login status, check server status"); - } - }); - b.send(); - } catch (RequestException e) { - SC.say("Unable to determine login status, check server status"); - e.printStackTrace(); - } finally { - BrowserUtility.unforceIe6Hacks(); - } + public static CoreGUI get() { + return coreGUI; }
- private void buildCoreUI() { + public void buildCoreUI() { // If the core gui is already built (eg. from previous login, just refire event) - if (this.rootCanvas == null) { - this.rootCanvas = new RootCanvas(); - rootCanvas.setOverflow(Overflow.HIDDEN); - - // HTMLPane menuPane = new HTMLPane(); - // menuPane.setWidth100(); - // menuPane.setHeight(26); - // menuPane.setContentsType(ContentsType.PAGE); - // menuPane.setContentsURL("/rhq/common/menu/menu.xhtml"); - // menuPane.setZIndex(400000); - // layout.addMember(menuPane); - + if (rootCanvas == null) { MenuBarView menuBarView = new MenuBarView("TopMenu"); menuBarView.setWidth("100%"); - // WidgetCanvas menuCanvas = new WidgetCanvas(menuBarView); - // menuCanvas.setTop(0); - // menuCanvas.setWidth100(); - // menuCanvas.draw(); - rootCanvas.addMember(menuBarView);
breadCrumbTrailPane = new BreadcrumbTrailPane(); - rootCanvas.addMember(breadCrumbTrailPane);
Canvas canvas = new Canvas(CONTENT_CANVAS_ID); canvas.setWidth100(); canvas.setHeight100(); - rootCanvas.addMember(canvas);
+ rootCanvas = new RootCanvas(); + rootCanvas.setOverflow(Overflow.HIDDEN); + rootCanvas.addMember(menuBarView); + rootCanvas.addMember(breadCrumbTrailPane); + rootCanvas.addMember(canvas); rootCanvas.addMember(new Footer("CoreFooter")); - rootCanvas.draw();
History.addValueChangeHandler(this); }
- History.fireCurrentHistoryState(); + if (History.getToken().equals("") || History.getToken().equals("LogOut")) { + // go to default view if user doesn't specify a history token + History.newItem(getDefaultView()); + } else { + // otherwise just fire an event for the bookmarked URL they are returning to + History.fireCurrentHistoryState(); + } }
public void onValueChange(ValueChangeEvent<String> stringValueChangeEvent) { @@ -262,7 +171,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
currentViewPath.setRefresh(true); coreGUI.rootCanvas.renderView(currentViewPath); - }
public Canvas createContent(String breadcrumbName) { @@ -283,8 +191,10 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { } else if (breadcrumbName.equals(BundleTopView.VIEW_ID)) { canvas = new BundleTopView("Bundle"); } else if (breadcrumbName.equals("LogOut")) { - canvas = new LoginView(); - UserSessionManager.logout(); + // TODO: don't make LogOut a history event, just perform the logout action by responding to click event + LoginView logoutView = new LoginView(); + canvas = logoutView; + logoutView.showLoginDialog(); } else if (breadcrumbName.equals(TaggedView.VIEW_ID)) { canvas = new TaggedView("Tag"); } else if (breadcrumbName.equals("Subsystems")) { @@ -356,34 +266,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { return messages; }
- public static ProductInfo getProductInfo() { - return productInfo; - } - - private static void loadProductInfo() { - GWTServiceLookup.getSystemService().getProductInfo(new AsyncCallback<ProductInfo>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load product information.", caught); - } - - public void onSuccess(ProductInfo result) { - productInfo = result; - coreGUI.buildCoreUI(); - - // After a user initiated logout start back at the default view - if ("LogOut".equals(CoreGUI.currentPath)) { - History.newItem(DEFAULT_VIEW_PATH); - } - } - }); - } - - public static void goToResourceOrGroupView(String newToken) { - - } - private class RootCanvas extends VLayout implements BookmarkableView { - ViewId currentViewId; Canvas currentCanvas;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java index 00050ad..36514aa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java @@ -22,7 +22,6 @@ import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.VerticalAlignment; -import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.toolbar.ToolStripSeparator; @@ -38,11 +37,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip;
/** * @author Greg Hinkle + * @author Joseph Marques */ public class Footer extends LocatableToolStrip {
- MessageCenterView recentMessage; - public Footer(String locatorId) { super(locatorId); setHeight(30); @@ -56,36 +54,35 @@ public class Footer extends LocatableToolStrip { protected void onDraw() { super.onDraw();
- Label loggedInAs = new Label("Logged in as " + UserSessionManager.getSessionSubject().getName()); - loggedInAs.setWrap(false); - loggedInAs.setMargin(5); - loggedInAs.setValign(VerticalAlignment.CENTER); - - addMember(loggedInAs); - addMember(new ToolStripSeparator()); - - recentMessage = new MessageCenterView(extendLocatorId("MessageCenter")); + final UserSessionState userSessionState = new UserSessionState("UserSessionState"); + final MessageCenterView recentMessage = new MessageCenterView(extendLocatorId("MessageCenter")); recentMessage.setWidth("*"); + final FavoritesButton favoritesButton = new FavoritesButton(extendLocatorId("Favorites")); + final AlertsMessage alertsMessage = new AlertsMessage(extendLocatorId("Alerts"));
+ addMember(userSessionState); + addMember(new ToolStripSeparator()); addMember(recentMessage); - addMember(new ToolStripSeparator()); + addMember(favoritesButton); + addMember(alertsMessage);
- addMember(new FavoritesButton(extendLocatorId("Favorites"))); - - addMember(new AlertsMessage(extendLocatorId("Alerts"))); - + userSessionState.schedule(15000); + alertsMessage.schedule(60000); }
- public static class AlertsMessage extends LocatableLabel { - public AlertsMessage(String locatorId) { + public abstract static class RefreshableLabel extends LocatableLabel { + public RefreshableLabel(String locatorId) { super(locatorId); - setHeight(30); - setPadding(5); + }
- setIcon("subsystems/alert/Alert_LOW_16.png"); - setIconSize(16); - setWrap(false); + // scheduling refreshes is sub-optimal, really need to move to a message bus architecture + public void schedule(int millis) { + new Timer() { + public void run() { + refresh(); + } + }.scheduleRepeating(millis); }
@Override @@ -93,15 +90,50 @@ public class Footer extends LocatableToolStrip { super.onInit();
refresh(); + }
- Timer t = new Timer() { - public void run() { - refresh(); - } - }; + public void refresh() { + if (UserSessionManager.isLoggedIn()) { + refreshLoggedIn(); + } else { + refreshLoggedOut(); + } + }
- // refresh every minute - t.scheduleRepeating(60000); + public abstract void refreshLoggedIn(); + + public void refreshLoggedOut() { + setContents(""); + setIcon(null); + } + } + + public static class UserSessionState extends RefreshableLabel { + public UserSessionState(String locatorId) { + super(locatorId); + setWrap(false); + setMargin(5); + setValign(VerticalAlignment.CENTER); + } + + public void refreshLoggedIn() { + setContents("Logged in as " + UserSessionManager.getSessionSubject().getName()); + } + + public void refreshLoggedOut() { + setContents("Logged out"); + } + } + + public static class AlertsMessage extends RefreshableLabel { + public AlertsMessage(String locatorId) { + super(locatorId); + setHeight(30); + setPadding(5); + + setIcon("subsystems/alert/Alert_LOW_16.png"); + setIconSize(16); + setWrap(false);
addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { @@ -110,11 +142,7 @@ public class Footer extends LocatableToolStrip { }); }
- public void refresh() { - if (!UserSessionManager.isLoggedIn()) { - return; - } - + public void refreshLoggedIn() { AlertCriteria alertCriteria = new AlertCriteria(); alertCriteria.setPaging(1, 1); // last eight hours @@ -127,22 +155,15 @@ public class Footer extends LocatableToolStrip { }
public void onSuccess(PageList<Alert> result) { - drawAlerts(result); + if (result.isEmpty()) { + setContents("no recent alerts"); + setIcon("subsystems/alert/Alert_LOW_16.png"); + } else { + setContents(result.getTotalSize() + " recent alerts"); + setIcon("subsystems/alert/Alert_HIGH_16.png"); + } } }); - - } - - public void drawAlerts(PageList<Alert> alerts) { - if (alerts.isEmpty()) { - setContents("no recent alerts"); - setIcon("subsystems/alert/Alert_LOW_16.png"); - - } else { - - setContents(alerts.getTotalSize() + " recent alerts"); - setIcon("subsystems/alert/Alert_HIGH_16.png"); - } } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index f6758e9..24ef812 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -22,6 +22,9 @@ */ package org.rhq.enterprise.gui.coregui.client;
+import java.util.EnumSet; +import java.util.Map; + import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; @@ -44,6 +47,8 @@ import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent; import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
+import org.rhq.core.domain.resource.ResourceType; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility;
/** @@ -150,8 +155,7 @@ public class LoginView extends Canvas { if (statusCode == 200) { window.destroy(); loginShowing = false; - UserSessionManager.refresh(); - CoreGUI.checkLoginStatus(); + UserSessionManager.login(); } else { handleError(statusCode); } @@ -167,33 +171,16 @@ public class LoginView extends Canvas { } finally { BrowserUtility.unforceIe6Hacks(); } + }
- /* - SubjectGWTServiceAsync subjectService = SubjectGWTServiceAsync.Util.getInstance(); - - subjectService.login(user, password, new AsyncCallback<Subject>() { - public void onFailure(Throwable caught) { - System.out.println("Failed to login - cause: " + caught); - Label loginFailed = new Label("Failed to login - cause: " + caught); - loginFailed.draw(); - } - - public void onSuccess(Subject result) { - System.out.println("Logged in: " + result.getSessionId()); - CoreGUI.setSessionSubject(result); - - *//* We can cache all metadata right here - ResourceTypeRepository.Cache.getInstance().getResourceTypes( - (Integer[]) null, EnumSet.allOf(ResourceTypeRepository.MetadataType.class), new ResourceTypeRepository.TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { - System.out.println("Preloaded [" + types.size() + "] resource types"); - buildCoreUI(); - } - }); - *//* - } - }); */ - + @SuppressWarnings("unused") + private void preloadAllTypeMetadata() { + ResourceTypeRepository.Cache.getInstance().getResourceTypes((Integer[]) null, + EnumSet.allOf(ResourceTypeRepository.MetadataType.class), new ResourceTypeRepository.TypesLoadedCallback() { + public void onTypesLoaded(Map<Integer, ResourceType> types) { + System.out.println("Preloaded [" + types.size() + "] resource types"); + } + }); }
private void handleError(int statusCode) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java index 6312e93..2266993 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java @@ -19,20 +19,10 @@ package org.rhq.enterprise.gui.coregui.client;
import com.google.gwt.core.client.EntryPoint; -import com.google.gwt.http.client.Request; -import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.http.client.RequestCallback; -import com.google.gwt.http.client.RequestException; -import com.google.gwt.http.client.Response; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.util.SC;
-import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.criteria.SubjectCriteria; -import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.search.SearchBar; -import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility;
/** * @author Joseph Marques @@ -55,100 +45,25 @@ public class SearchGUI implements EntryPoint { return; }
- checkLoginStatus(); + UserSessionManager.checkLoginStatus(new AsyncCallback<Void>() { + @Override + public void onFailure(Throwable caught) { + SC.say("Unable to determine login status, check server status"); + } + + @Override + public void onSuccess(Void result) { + singleton.buildSearchGUI(); + } + }); }
public void buildSearchGUI() { searchBar = new SearchBar(); }
- public static void checkLoginStatus() { - - BrowserUtility.forceIe6Hacks(); - - RequestBuilder b = new RequestBuilder(RequestBuilder.GET, "/sessionAccess"); - try { - b.setCallback(new RequestCallback() { - public void onResponseReceived(final Request request, final Response response) { - String sessionIdString = response.getText(); - if (sessionIdString != null && sessionIdString.length() > 0) { - - int subjectId = Integer.parseInt(sessionIdString.split(":")[0]); - final int sessionId = Integer.parseInt(sessionIdString.split(":")[1]); - - Subject subject = new Subject(); - subject.setId(subjectId); - subject.setSessionId(sessionId); - - GWTServiceLookup.registerSession(String.valueOf(subject.getSessionId())); - - // look up real user prefs - - SubjectCriteria criteria = new SubjectCriteria(); - criteria.addFilterId(subjectId); - - GWTServiceLookup.getSubjectService().findSubjectsByCriteria(criteria, - new AsyncCallback<PageList<Subject>>() { - public void onFailure(Throwable caught) { - // can't use this until gwt frame is always present, reserve for futureu - //CoreGUI.getErrorHandler().handleError("Failed to load user's subject", caught); - //SC.say("Failed to load user's subject."); - //new LoginView().showLoginDialog(); - - System.out.println("Failed to load user's subject"); - } - - public void onSuccess(PageList<Subject> result) { - Subject subject = result.get(0); - subject.setSessionId(sessionId); - UserSessionManager.setSessionSubject(subject); - singleton.buildSearchGUI(); - } - }); - } else { - new LoginView().showLoginDialog(); - } - } - - public void onError(Request request, Throwable exception) { - SC.say("Unable to determine login status, check server status"); - } - }); - b.send(); - } catch (RequestException e) { - SC.say("Unable to determine login status, check server status"); - e.printStackTrace(); - } finally { - BrowserUtility.unforceIe6Hacks(); - } - - } - public SearchBar getSearchBar() { return searchBar; }
- /** - * Detects IE6. - * <p/> - * This is a nasty hack; but it's extremely reliable when running with other - * js libraries on the same page at the same time as gwt. - */ - public static native boolean detectIe6() /*-{ - if (typeof $doc.body.style.maxHeight != "undefined") - return(false); - else - return(true); - }-*/; - - public static native void forceIe6Hacks() /*-{ - $wnd.XMLHttpRequestBackup = $wnd.XMLHttpRequest; - $wnd.XMLHttpRequest = null; - }-*/; - - public static native void unforceIe6Hacks() /*-{ - $wnd.XMLHttpRequest = $wnd.XMLHttpRequestBackup; - $wnd.XMLHttpRequestBackup = null; - }-*/; - } 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 0bc285d..6fc72d8 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 @@ -22,11 +22,21 @@ */ package org.rhq.enterprise.gui.coregui.client;
+import com.google.gwt.http.client.Request; +import com.google.gwt.http.client.RequestBuilder; +import com.google.gwt.http.client.RequestCallback; +import com.google.gwt.http.client.RequestException; +import com.google.gwt.http.client.Response; +import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.util.SC;
import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.criteria.SubjectCriteria; +import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility; import org.rhq.enterprise.gui.coregui.client.util.preferences.UserPreferences;
/** @@ -46,15 +56,12 @@ 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 = 30 * 1000; // 30 seconds + private static int LOGOUT_DELAY = 15 * 1000; // wait 15 seconds for in-flight requests to complete before logout
+ public static final String SESSION_NAME = "RHQ_Sesssion"; private static Subject sessionSubject; private static UserPreferences userPreferences;
- private UserSessionManager() { - // static access only - } - private static boolean loggedIn = false; private static Timer sessionTimer = new Timer() { @Override @@ -70,7 +77,134 @@ public class UserSessionManager { } };
+ private UserSessionManager() { + // static access only + } + + public static void checkLoginStatus(final AsyncCallback<Void> callback) { + BrowserUtility.forceIe6Hacks(); + + RequestBuilder b = new RequestBuilder(RequestBuilder.GET, "/sessionAccess"); + try { + b.setCallback(new RequestCallback() { + public void onResponseReceived(final Request request, final Response response) { + System.out.println("response text = " + response.getText()); + String sessionIdString = response.getText(); + if (sessionIdString != null && sessionIdString.length() > 0) { + + String[] parts = sessionIdString.split(":"); + final int subjectId = Integer.parseInt(parts[0]); + final String sessionId = parts[1]; // not null + final long lastAccess = Long.parseLong(parts[2]); + System.out.println("sessionAccess-subjectId: " + subjectId); + System.out.println("sessionAccess-sessionId: " + sessionId); + System.out.println("sessionAccess-lastAccess: " + lastAccess); + + String previousSessionId = getPreviousSessionId(); // may be null + System.out.println("sessionAccess-previousSessionId: " + previousSessionId); + if (previousSessionId == null || previousSessionId.equals(sessionId) == false) { + + // persist sessionId if different from previously saved sessionId + System.out.println("sessionAccess-savingSessionId: " + sessionId); + saveSessionId(sessionId); + + // new sessions get the full 29 minutes to expire + System.out.println("sessionAccess-schedulingSessionTimeout: " + SESSION_TIMEOUT); + sessionTimer.schedule(SESSION_TIMEOUT); + } else { + + // existing sessions should expire 29 minutes from the previous access time + long expiryTime = lastAccess + SESSION_TIMEOUT; + long expiryMillis = expiryTime - System.currentTimeMillis(); + + // can not schedule a time with millis less than or equal to 0 + if (expiryMillis < 1) { + expiryMillis = 1; // expire VERY quickly + } else if (expiryMillis > SESSION_TIMEOUT) { + expiryMillis = SESSION_TIMEOUT; // guarantees maximum is 29 minutes + } + + System.out.println("sessionAccess-reschedulingSessionTimeout: " + expiryMillis); + sessionTimer.schedule((int) expiryMillis); + } + + // set the session subject, so the fetch to load the configuration works + Subject subject = new Subject(); + subject.setId(subjectId); + subject.setSessionId(Integer.valueOf(sessionId)); + sessionSubject = subject; + + SubjectCriteria criteria = new SubjectCriteria(); + criteria.fetchConfiguration(true); + criteria.addFilterId(subjectId); + + GWTServiceLookup.getSubjectService().findSubjectsByCriteria(criteria, + new AsyncCallback<PageList<Subject>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "UserSessionManager: Failed to load user's subject", caught); + System.out.println("Failed to load user's subject"); + new LoginView().showLoginDialog(); + } + + public void onSuccess(PageList<Subject> result) { + System.out.println("Found subject"); + Subject subject = result.get(0); + subject.setSessionId(Integer.valueOf(sessionId)); + + // reset the session subject to the latest, for wrapping in user preferences + sessionSubject = subject; + userPreferences = new UserPreferences(sessionSubject); + refresh(); + + callback.onSuccess((Void) null); + } + }); + } else { + new LoginView().showLoginDialog(); + } + } + + public void onError(Request request, Throwable exception) { + callback.onFailure(exception); + } + }); + b.send(); + } catch (RequestException e) { + callback.onFailure(e); + } finally { + BrowserUtility.unforceIe6Hacks(); + } + } + + public static void login() { + checkLoginStatus(new AsyncCallback<Void>() { + @Override + public void onSuccess(Void result) { + // will build UI if necessary, then fires history event + CoreGUI.get().buildCoreUI(); + } + + @Override + public void onFailure(Throwable caught) { + SC.say("Unable to determine login status, check server status"); + } + }); + } + + private static void saveSessionId(String sessionId) { + Cookies.setCookie(SESSION_NAME, sessionId); + } + + private static String getPreviousSessionId() { + return Cookies.getCookie(SESSION_NAME); + } + public static void refresh() { + refresh(SESSION_TIMEOUT); + } + + private static void refresh(int millis) { // if quickly logging back in, first cancel the logout timer so that we // don't have race conditions to the server where the login request beats // the logout request, which would appear to the user for the login to @@ -80,7 +214,7 @@ public class UserSessionManager { // now continue with the rest of the login logic loggedIn = true; System.out.println("Refreshing Session Timer"); - sessionTimer.schedule(SESSION_TIMEOUT); + sessionTimer.schedule(millis); }
public static void logout() { @@ -124,13 +258,19 @@ public class UserSessionManager { return sessionSubject; }
- public static void setSessionSubject(Subject subject) { - sessionSubject = subject; - userPreferences = new UserPreferences(sessionSubject); - refresh(); + public static String getSessionId() { + if (sessionSubject == null) { + return null; + } + Integer sessionId = sessionSubject.getSessionId(); + if (sessionId == null) { + return null; + } + return sessionId.toString(); }
public static UserPreferences getUserPreferences() { return userPreferences; } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/AboutModalWindow.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/AboutModalWindow.java index 2611435..5dc5b91 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/AboutModalWindow.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/AboutModalWindow.java @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.components;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.Version; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VerticalAlignment; @@ -29,21 +30,23 @@ import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout; + import org.rhq.core.domain.common.ProductInfo; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.Messages; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
/** * The "About RHQ" modal window. * * @author Ian Springer + * @author Joseph Marques */ public class AboutModalWindow extends Window { private static final Messages MESSAGES = CoreGUI.getMessages(); - private static final ProductInfo PRODUCT_INFO = CoreGUI.getProductInfo(); + private static ProductInfo PRODUCT_INFO;
public AboutModalWindow() { - setTitle(MESSAGES.about_title(PRODUCT_INFO.getFullName())); setWidth(300); setHeight(300); setOverflow(Overflow.VISIBLE); @@ -59,29 +62,42 @@ public class AboutModalWindow extends Window { @Override protected void onInit() { super.onInit(); - + + if (PRODUCT_INFO == null) { + GWTServiceLookup.getSystemService().getProductInfo(new AsyncCallback<ProductInfo>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load product information.", caught); + } + + public void onSuccess(ProductInfo result) { + PRODUCT_INFO = result; + setTitle(MESSAGES.about_title(PRODUCT_INFO.getFullName())); + + finishOnInit(); + } + }); + } else { + finishOnInit(); + } + } + + private void finishOnInit() { VLayout contentPane = new VLayout(); contentPane.setPadding(15); contentPane.setMembersMargin(25); - + HTMLFlow htmlFlow = new HTMLFlow(); - String html = - "<span class="DisplaySubhead">\n" + - " <a href="" + PRODUCT_INFO.getUrl() + "" title="" + PRODUCT_INFO.getFullName() + " " - + MESSAGES.about_homepage() + "" target="_blank">" + PRODUCT_INFO.getFullName() + "</a>\n" + - "</span><br/>\n" + - "<span class="DisplayLabel">" + MESSAGES.about_version() + " " + PRODUCT_INFO.getVersion() - + "</span><br/>\n" + - "<span class="DisplayLabel">" + MESSAGES.about_buildNumber() + " " + PRODUCT_INFO.getBuildNumber() - + "</span><p/>\n" + - "<span class="DisplayLabel">GWT version: " + MESSAGES.gwt_version() - + "</span><br/>\n" + - "<span class="DisplayLabel">SmartGWT version: " + Version.getVersion() - + "</span><br/>\n" + - "<p><a href="http://jboss.org/%5C" title="JBoss " + MESSAGES.about_homepage() + "">\n" + - " <img height="55" alt="" + MESSAGES.about_jbossByRedHat() + "" src="/images/jboss_logo.png">\n" + - "</a></p>\n" + - "<div style="top-margin: 10px">" + MESSAGES.about_allRightsReserved() + "</div>\n"; + String html = "<span class="DisplaySubhead">\n" + " <a href="" + PRODUCT_INFO.getUrl() + "" title="" + + PRODUCT_INFO.getFullName() + " " + MESSAGES.about_homepage() + "" target="_blank">" + + PRODUCT_INFO.getFullName() + "</a>\n" + "</span><br/>\n" + "<span class="DisplayLabel">" + + MESSAGES.about_version() + " " + PRODUCT_INFO.getVersion() + "</span><br/>\n" + + "<span class="DisplayLabel">" + MESSAGES.about_buildNumber() + " " + PRODUCT_INFO.getBuildNumber() + + "</span><p/>\n" + "<span class="DisplayLabel">GWT version: " + MESSAGES.gwt_version() + + "</span><br/>\n" + "<span class="DisplayLabel">SmartGWT version: " + Version.getVersion() + + "</span><br/>\n" + "<p><a href="http://jboss.org/%5C" title="JBoss " + MESSAGES.about_homepage() + + "">\n" + " <img height="55" alt="" + MESSAGES.about_jbossByRedHat() + + "" src="/images/jboss_logo.png">\n" + "</a></p>\n" + "<div style="top-margin: 10px">" + + MESSAGES.about_allRightsReserved() + "</div>\n"; htmlFlow.setContents(html); contentPane.addMember(htmlFlow);
@@ -106,6 +122,6 @@ public class AboutModalWindow extends Window {
// NOTE: Since this is a subclass of Window, we MUST use addItem(), rather than addMember() from the // Layout class. - addItem(contentPane); + addItem(contentPane); } } 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 373f87c..4a9c639 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 @@ -19,10 +19,10 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.rpc.RpcRequestBuilder; import com.google.gwt.user.client.rpc.ServiceDefTarget;
+import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.util.rpc.MonitoringRequestCallback;
/** @@ -34,8 +34,6 @@ import org.rhq.enterprise.gui.coregui.client.util.rpc.MonitoringRequestCallback; */ public class GWTServiceLookup {
- public static final String SESSION_NAME = "RHQ_Sesssion"; - public static AlertDefinitionGWTServiceAsync getAlertDefinitionService() { return secure(AlertDefinitionGWTServiceAsync.Util.getInstance()); } @@ -128,6 +126,7 @@ public class GWTServiceLookup { return secure(ClusterGWTServiceAsync.Util.getInstance()); }
+ @SuppressWarnings("unchecked") private static <T> T secure(Object sdt) { if (!(sdt instanceof ServiceDefTarget)) return null; @@ -137,10 +136,6 @@ public class GWTServiceLookup { return (T) sdt; }
- public static void registerSession(String sessionId) { - Cookies.setCookie(SESSION_NAME, sessionId); - } - public static class SessionRpcRequestBuilder extends RpcRequestBuilder {
@Override @@ -155,9 +150,9 @@ public class GWTServiceLookup { // TODO Don't use the expensive determineName except in dev mode rb.setCallback(new MonitoringRequestCallback(determineName(), rb.getCallback()));
- String sid = Cookies.getCookie(SESSION_NAME); - if (sid != null) { - rb.setHeader(SESSION_NAME, sid); + String sessionId = UserSessionManager.getSessionId(); + if (sessionId != null) { + rb.setHeader(UserSessionManager.SESSION_NAME, sessionId); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java index 62c88dd..bfffc33 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java @@ -18,13 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.util.preferences;
-import com.google.gwt.user.client.rpc.AsyncCallback; -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.gwt.SubjectGWTServiceAsync; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -33,6 +26,14 @@ import java.util.List; import java.util.Set; import java.util.TreeSet;
+import com.google.gwt.user.client.rpc.AsyncCallback; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.gwt.SubjectGWTServiceAsync; + /** * @author Greg Hinkle * @author Ian Springer @@ -47,9 +48,8 @@ public class UserPreferences {
private ArrayList<UserPreferenceChangeListener> changeListeners = new ArrayList<UserPreferenceChangeListener>();
- public UserPreferences(Subject subject) { - this.subject = subject; + this.subject = subject; this.userConfiguration = subject.getUserConfiguration(); }
@@ -71,14 +71,11 @@ public class UserPreferences { store(callback); }
- - - protected String getPreference(String name) { return userConfiguration.getSimpleValue(name, null); }
- protected void setPreference(String name, Collection value) { + protected void setPreference(String name, Collection<?> value) { StringBuilder buffer = new StringBuilder(); boolean first = true; for (Object item : value) { @@ -108,24 +105,21 @@ public class UserPreferences { } }
- public void store(AsyncCallback<Subject> callback) { this.subjectService.updateSubject(this.subject, callback); }
- public Configuration getConfiguration() { return userConfiguration; }
- public List<String> getPreferenceAsList(String key) { String pref = null; try { pref = getPreference(key); } catch (IllegalArgumentException e) {
-// log.debug("A user preference named '" + key + "' does not exist."); + // log.debug("A user preference named '" + key + "' does not exist."); }
return (pref != null) ? Arrays.asList(pref.split(PREF_LIST_DELIM_REGEX)) : new ArrayList<String>(); @@ -149,7 +143,6 @@ public class UserPreferences { } }
- public void addChangeListener(UserPreferenceChangeListener listener) { changeListeners.add(listener); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java index 9b80112..434d06d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java @@ -21,14 +21,18 @@ package org.rhq.enterprise.gui.coregui.client.util.rpc; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; +import com.google.gwt.user.client.History; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.util.SC;
-import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager;
/** * @author Greg Hinkle */ public class MonitoringRequestCallback implements RequestCallback {
+ @SuppressWarnings("unused") private int id; private String name; private long start = System.currentTimeMillis(); @@ -52,11 +56,25 @@ public class MonitoringRequestCallback implements RequestCallback { if (STATUS_CODE_OK == response.getStatusCode()) { RPCManager.getInstance().succeedCall(this); callback.onResponseReceived(request, response); + System.out.println("MonitoringRequestCallback: OK"); } else { RPCManager.getInstance().failCall(this); callback.onResponseReceived(request, response); + System.out.println("MonitoringRequestCallback: " + response.getStatusCode() + "/" + + response.getStatusText());
- CoreGUI.checkLoginStatus(); + // if we have a rich and coordinated client-side loggedIn state, do we need to check upon failure here? + UserSessionManager.checkLoginStatus(new AsyncCallback<Void>() { + @Override + public void onSuccess(Void result) { + History.fireCurrentHistoryState(); + } + + @Override + public void onFailure(Throwable caught) { + SC.say("Unable to determine login status, check server status"); + } + }); } }
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 6aaafdd..ae1e85b 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 @@ -27,7 +27,7 @@ import javax.servlet.http.HttpServletResponse; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.rhq.core.domain.auth.Subject; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.util.HibernatePerformanceMonitor; import org.rhq.enterprise.server.util.LookupUtil; @@ -45,7 +45,7 @@ public abstract class AbstractGWTServiceImpl extends RemoteServiceServlet {
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String sid = req.getHeader(GWTServiceLookup.SESSION_NAME); + String sid = req.getHeader(UserSessionManager.SESSION_NAME); Subject subject = null; if (sid != null) { SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/authentication/SessionAccessServlet.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/authentication/SessionAccessServlet.java index 08911dd..6739824 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/authentication/SessionAccessServlet.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/authentication/SessionAccessServlet.java @@ -24,12 +24,8 @@ package org.rhq.enterprise.gui.authentication;
import java.io.IOException;
-import javax.servlet.Servlet; -import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -45,14 +41,15 @@ import org.rhq.enterprise.server.auth.SessionTimeoutException;
/** * @author Greg Hinkle + * @author Joseph Marques */ public class SessionAccessServlet extends HttpServlet {
+ private static final long serialVersionUID = 1L;
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- HttpServletResponse response = (HttpServletResponse) resp; HttpServletRequest request = (HttpServletRequest) req;
@@ -67,32 +64,24 @@ public class SessionAccessServlet extends HttpServlet { //if a session does not already exist this call will create one HttpSession session = request.getSession();
- /* check if the user object is in the session. - * if not then the user is not validated and should be forwarded to the login page + /* + * check if the user object is in the session. if not, then the user is not validated, the response output + * will not contain the "<subjectId>:<sessionId>:<lastAccess>", which will forward the user to the login page */ WebUser webUser = SessionUtils.getWebUser(session); - - if (webUser != null && webUser.getSubject() != null) {
// the web user exists, so update our SessionManager's session last-access-time Subject subject = webUser.getSubject();
try { - SessionManager.getInstance().getSubject(subject.getSessionId()); - + long lastAccess = SessionManager.getInstance().getlastAccess(subject.getSessionId());
ServletOutputStream out = response.getOutputStream(); - - String output = - String.valueOf(webUser.getSubject().getId()) + ":" + - String.valueOf(webUser.getSessionId()); - + String output = subject.getId() + ":" + webUser.getSessionId() + ":" + lastAccess;
out.write(output.getBytes()); - - } catch (SessionNotFoundException snfe) { session.removeAttribute(ParamConstants.USER_PARAM); SessionUtils.setWebUser(session, null); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/AuthSession.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/AuthSession.java index 55ef32e..ea5d48d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/AuthSession.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/AuthSession.java @@ -80,4 +80,8 @@ class AuthSession { protected boolean isExpired() { return System.currentTimeMillis() > (_lastAccess + _timeout); } + + public long getLastAccess() { + return _lastAccess; + } } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java index dce87b3..58cbe8b 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java @@ -200,6 +200,14 @@ public class SessionManager { return; }
+ public long getlastAccess(int sessionId) { + AuthSession session = _cache.get(sessionId); + if (session == null) { + return -1; + } + return session.getLastAccess(); + } + public Subject getOverlord() { if (overlordSubject == null) { overlordSubject = LookupUtil.getSubjectManager().getSubjectById(OVERLORD_SUBJECT_ID);
commit d3c6b01e6faaacae78153acd40ba2eaae076cbad Author: Joseph Marques joseph@redhat.com Date: Mon Sep 27 14:08:22 2010 -0400
centralize and simplify browser quirk handling
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 1dd1250..a1d8475 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 @@ -56,6 +56,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceT import org.rhq.enterprise.gui.coregui.client.menu.MenuBarView; import org.rhq.enterprise.gui.coregui.client.report.ReportTopView; import org.rhq.enterprise.gui.coregui.client.report.tag.TaggedView; +import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility; import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.WidgetUtility; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; @@ -142,9 +143,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // String sessionIdString = com.google.gwt.user.client.Cookies.getCookie("RHQ_Sesssion"); // if (sessionIdString == null) {
- if (detectIe6()) { - forceIe6Hacks(); - } + BrowserUtility.forceIe6Hacks();
RequestBuilder b = new RequestBuilder(RequestBuilder.GET, "/sessionAccess"); try { @@ -204,9 +203,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { SC.say("Unable to determine login status, check server status"); e.printStackTrace(); } finally { - if (detectIe6()) { - unforceIe6Hacks(); - } + BrowserUtility.unforceIe6Hacks(); } }
@@ -415,30 +412,4 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { } }
- /** - * Detects IE6. - * <p/> - * This is a nasty hack; but it's extremely reliable when running with other - * js libraries on the same page at the same time as gwt. - */ - public static native boolean detectIe6() - /*-{ - if (typeof $doc.body.style.maxHeight != "undefined") - return(false); - else - return(true); - }-*/; - - public static native void forceIe6Hacks() - /*-{ - $wnd.XMLHttpRequestBackup = $wnd.XMLHttpRequest; - $wnd.XMLHttpRequest = null; - }-*/; - - public static native void unforceIe6Hacks() - /*-{ - $wnd.XMLHttpRequest = $wnd.XMLHttpRequestBackup; - $wnd.XMLHttpRequestBackup = null; - }-*/; - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index 0f660c3..f6758e9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -44,6 +44,8 @@ import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent; import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
+import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility; + /** * @author Greg Hinkle * @author Joseph Marques @@ -135,9 +137,7 @@ public class LoginView extends Canvas { }
private void login(String user, String password) { - if (CoreGUI.detectIe6()) { - CoreGUI.forceIe6Hacks(); - } + BrowserUtility.forceIe6Hacks();
loginButton.setDisabled(true);
@@ -165,9 +165,7 @@ public class LoginView extends Canvas { } catch (Exception e) { handleError(0); } finally { - if (CoreGUI.detectIe6()) { - CoreGUI.unforceIe6Hacks(); - } + BrowserUtility.unforceIe6Hacks(); }
/* diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java index 3ec02b3..6312e93 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java @@ -32,6 +32,7 @@ import org.rhq.core.domain.criteria.SubjectCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.search.SearchBar; +import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility;
/** * @author Joseph Marques @@ -63,9 +64,7 @@ public class SearchGUI implements EntryPoint {
public static void checkLoginStatus() {
- if (CoreGUI.detectIe6()) { - CoreGUI.forceIe6Hacks(); - } + BrowserUtility.forceIe6Hacks();
RequestBuilder b = new RequestBuilder(RequestBuilder.GET, "/sessionAccess"); try { @@ -120,9 +119,7 @@ public class SearchGUI implements EntryPoint { SC.say("Unable to determine login status, check server status"); e.printStackTrace(); } finally { - if (CoreGUI.detectIe6()) { - CoreGUI.unforceIe6Hacks(); - } + BrowserUtility.unforceIe6Hacks(); }
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/BrowserUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/BrowserUtility.java new file mode 100644 index 0000000..f9549fb --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/BrowserUtility.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.enterprise.gui.coregui.client.util; + +/** + * Utility class for dealing with browser quirks. + * + * @author Joseph Marques + */ +public class BrowserUtility { + private BrowserUtility() { + // static access only + } + + /* + * Adapted from http://code.google.com/p/google-web-toolkit/issues/detail?id=3608 + * + * Should + */ + public static native void forceIe6Hacks() + /*-{ + if (typeof $doc.body.style.maxHeight == "undefined") { + $wnd.XMLHttpRequestBackup = $wnd.XMLHttpRequest; + $wnd.XMLHttpRequest = null; + } + }-*/; + + /* + * Adapted from http://code.google.com/p/google-web-toolkit/issues/detail?id=3608 + */ + public static native void unforceIe6Hacks() + /*-{ + if (typeof $doc.body.style.maxHeight == "undefined") { + $wnd.XMLHttpRequest = $wnd.XMLHttpRequestBackup; + $wnd.XMLHttpRequestBackup = null; + } + }-*/; +}
commit 71cb2ad0a3edc89631e781869e528107e97a9230 Author: Joseph Marques joseph@redhat.com Date: Sun Sep 26 11:44:23 2010 -0400
remove erroneous cast
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 b61458f..f4137b2 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 @@ -251,7 +251,7 @@ public abstract class RPCDataSource<T> extends DataSource {
S[] resultArray = null;
- Object value = (String) criteriaMap.get(paramName); + Object value = criteriaMap.get(paramName); if (value == null) { // nothing to do, result is already null } else if (type == Integer.class) {
commit 4cf00dc96f7cd2e784d9a5d7fc6779132f2ac0e1 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 29 15:16:11 2010 -0400
get the notification editor to show a list of notifs. very preliminary right now. can't edit - just read-only
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 db9aeaa..18931c0 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 @@ -23,18 +23,43 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.ArrayList; +import java.util.List; + +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.data.fields.DataSourceTextField; +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.CloseClickHandler; +import com.smartgwt.client.widgets.events.CloseClientEvent; +import com.smartgwt.client.widgets.grid.ListGridField; +import com.smartgwt.client.widgets.grid.ListGridRecord; + import org.rhq.core.domain.alert.AlertDefinition; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; +import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.enterprise.gui.coregui.client.components.table.Table; +import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; +import org.rhq.enterprise.gui.coregui.client.components.table.Table.SelectionEnablement; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
/** * @author John Mazzitelli */ -public class NotificationsAlertDefinitionForm extends LocatableDynamicForm implements EditAlertDefinitionForm { +public class NotificationsAlertDefinitionForm extends LocatableVLayout implements EditAlertDefinitionForm { + private static final String FIELD_OBJECT = "obj"; + private static final String FIELD_SENDER = "sender"; + private static final String FIELD_CONFIGURATION = "configuration";
private AlertDefinition alertDefinition; + private ArrayList<AlertNotification> notifications;
private boolean formBuilt = false;
+ private Table table; + public NotificationsAlertDefinitionForm(String locatorId) { this(locatorId, null); } @@ -42,6 +67,7 @@ public class NotificationsAlertDefinitionForm extends LocatableDynamicForm imple public NotificationsAlertDefinitionForm(String locatorId, AlertDefinition alertDefinition) { super(locatorId); this.alertDefinition = alertDefinition; + extractShallowCopyOfNotifications(this.alertDefinition); }
@Override @@ -69,7 +95,10 @@ public class NotificationsAlertDefinitionForm extends LocatableDynamicForm imple if (alertDef == null) { clearFormValues(); } else { - // TODO set values of the components + extractShallowCopyOfNotifications(alertDefinition); + if (table != null) { + table.refresh(); + } }
markForRedraw(); @@ -77,36 +106,155 @@ public class NotificationsAlertDefinitionForm extends LocatableDynamicForm imple
@Override public void makeEditable() { - // TODO Auto-generated method stub - + table.setTableActionDisableOverride(false); markForRedraw(); }
@Override public void makeViewOnly() { - // TODO Auto-generated method stub - + table.setTableActionDisableOverride(true); markForRedraw(); }
@Override public void saveAlertDefinition() { - // TODO Auto-generated method stub + alertDefinition.setAlertNotifications(notifications); + + // make our own new internal copy since we gave ours to the definition object + extractShallowCopyOfNotifications(alertDefinition); }
@Override public void clearFormValues() { - // TODO component.clearValue(); - + notifications.clear(); + if (table != null) { + table.refresh(); + } markForRedraw(); }
private void buildForm() { if (!formBuilt) { - // TODO buildNodes components - // TODO setFields(components); + + table = new NotificationTable(extendLocatorId("notificationsTable")); + table.setShowHeader(false); + + final NotificationDataSource dataSource = new NotificationDataSource(); + table.setDataSource(dataSource); + + table.addTableAction(this.extendLocatorId("add"), "Add", SelectionEnablement.ALWAYS, null, + new TableAction() { + @Override + public void executeAction(ListGridRecord[] selection) { + final Window winModal = new LocatableWindow(NotificationsAlertDefinitionForm.this + .extendLocatorId("newNotificationEditorWindow")); + winModal.setTitle("Add Notification"); + winModal.setOverflow(Overflow.VISIBLE); + winModal.setShowMinimizeButton(false); + winModal.setIsModal(true); + winModal.setShowModalMask(true); + winModal.setAutoSize(true); + winModal.setAutoCenter(true); + //winModal.setShowResizer(true); + //winModal.setCanDragResize(true); + winModal.centerInPage(); + winModal.addCloseClickHandler(new CloseClickHandler() { + @Override + public void onCloseClick(CloseClientEvent event) { + winModal.markForDestroy(); + } + }); + + // NewNotificationEditor newEditor = new NewNotificationEditor( + // extendLocatorId("newNotificationEditor"), notifications, new Runnable() { + // @Override + // public void run() { + // winModal.markForDestroy(); + // table.refresh(); + // } + // }); + /// winModal.addItem(newEditor); + winModal.show(); + } + }); + table.addTableAction(this.extendLocatorId("delete"), "Delete", SelectionEnablement.ANY, "Are you sure?", + new TableAction() { + @Override + public void executeAction(ListGridRecord[] selection) { + for (ListGridRecord record : selection) { + AlertNotification notif = dataSource.copyValues(record); + notifications.remove(notif); + } + table.refresh(); + } + }); + + addMember(table);
formBuilt = true; } } + + private void extractShallowCopyOfNotifications(AlertDefinition alertDefinition) { + List<AlertNotification> notifs = null; + if (alertDefinition != null) { + notifs = alertDefinition.getAlertNotifications(); + } + + // make our own shallow copy of the collection + if (notifs != null) { + this.notifications = new ArrayList<AlertNotification>(notifs); + } else { + this.notifications = new ArrayList<AlertNotification>(); + } + } + + private class NotificationDataSource extends RPCDataSource<AlertNotification> { + public NotificationDataSource() { + DataSourceTextField senderField = new DataSourceTextField(FIELD_SENDER, "Sender"); + addField(senderField); + + DataSourceTextField configField = new DataSourceTextField(FIELD_CONFIGURATION, "Configuration"); + addField(configField); + } + + @Override + public AlertNotification copyValues(ListGridRecord from) { + return (AlertNotification) from.getAttributeAsObject(FIELD_OBJECT); + } + + @Override + public ListGridRecord copyValues(AlertNotification from) { + ListGridRecord record = new ListGridRecord(); + record.setAttribute(FIELD_SENDER, from.getSenderName()); + record.setAttribute(FIELD_CONFIGURATION, from.getConfiguration().toString(false)); + // TODO configuration should be the string of + //getAlertManager().getAlertPluginManager().getAlertSenderForNotification(alertNotification).previewConfiguration() + // TODO what's this extra configuration in the notification? + + record.setAttribute(FIELD_OBJECT, from); + return record; + } + + @Override + protected void executeFetch(DSRequest request, DSResponse response) { + response.setData(buildRecords(notifications)); + processResponse(request.getRequestId(), response); + } + } + + private class NotificationTable extends Table { + public NotificationTable(String locatorId) { + super(locatorId); + } + + @Override + protected void configureTable() { + ListGridField senderField = new ListGridField(FIELD_SENDER, "Sender"); + senderField.setWidth("25%"); + ListGridField configField = new ListGridField(FIELD_CONFIGURATION, "Configuration"); + configField.setWidth("75%"); + getListGrid().setFields(senderField, configField); + } + } }
commit f7be27b6647ae745914ffa08435058e4fef00dc7 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 29 12:56:25 2010 -0400
add support for generating the runs-inside element within a server or service element
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java index 69587d0..be39d9d 100644 --- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java +++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java @@ -308,7 +308,7 @@ public class PluginGen { }
/** - * Translate a packgage into a filesystem path + * Translate a package into a filesystem path * @param pkg Package in standard notation like com.acme.plugins * @param separator File separator * @return a path suitable to pass to File diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java index a657f42..bc1fc64 100644 --- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java +++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java @@ -1,6 +1,6 @@ /* * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. + * Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -71,14 +71,14 @@ public class Props { private boolean deleteChildren; /** Use externals chars in the plugin jar ? */ private boolean usesExternalJarsInPlugin; - /** Does it support manuall add of children ? */ + /** Does it support manual add of children ? */ private boolean manualAddOfResourceType; /** Does it use the PluginLifecycleListener api ? */ private boolean usePluginLifecycleListenerApi; /** Depends on JMX plugin ? */ private boolean dependsOnJmxPlugin; /** What version of RHQ should this plugin's pom use ? */ - private String rhqVersion = "1.4.0-SNAPSHOT"; + private String rhqVersion = "3.0.0";
/** Embedded children */ private Set<Props> children = new HashSet<Props>(); @@ -91,6 +91,8 @@ public class Props {
private Set<OperationProps> operations = new LinkedHashSet<OperationProps>();;
+ private Set<TypeKey> runsInsides = new LinkedHashSet<TypeKey>();; + private String pluginName; private String pluginDescription;
@@ -326,7 +328,15 @@ public class Props { this.pluginDescription = pluginDescription; }
- public void populateMetrics(List<Class> classes) { + public Set<TypeKey> getRunsInsides() { + return runsInsides; + } + + public void setRunsInsides(Set<TypeKey> runsInsides) { + this.runsInsides = runsInsides; + } + + public void populateMetrics(List<Class> classes) { for (Class<?> clazz : classes) { Metric metricAnnot = clazz.getAnnotation(Metric.class); if (metricAnnot != null) { @@ -372,10 +382,37 @@ public class Props { sb.append(", children=").append(children); sb.append(", simpleProps=").append(simpleProps); sb.append(", templates=").append(templates); + sb.append(", runsInsides=").append(runsInsides); sb.append('}'); return sb.toString(); }
+ public static class TypeKey { + private String name; + private String pluginName; + + public TypeKey(String name, String pluginName) { + this.name = name; + this.pluginName = pluginName; + } + + public String getPluginName() { + return pluginName; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "TypeKey{" + + "name='" + name + ''' + + ", pluginName='" + pluginName + ''' + + '}'; + } + } + public static class SimpleProperty { private final String name; private String description; @@ -431,7 +468,6 @@ public class Props { public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } - }
public static class Template { @@ -519,7 +555,6 @@ public class Props { public String getProperty() { return property; } - }
public static class OperationProps { diff --git a/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl b/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl index 0343787..b650f7a 100644 --- a/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl +++ b/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl @@ -1,7 +1,7 @@ <#-- /* * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. + * Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -24,7 +24,7 @@ platform/server/service. It is called by descriptor.ftl
--> -name="${props.name}" <#-- TODO separate out plugin name and service name --> +name="${props.name}" discovery="${props.discoveryClass}" class="${props.componentClass}" <#if props.singleton>singleton="true"</#if> @@ -32,6 +32,14 @@ name="${props.name}" <#-- TODO separate out plugin name and service name --> <#if props.createChildren && props.deleteChildren>createDeletePolicy="both"<#elseif props.createChildren && !props.deleteChildren>createDeletePolicy="create-only"<#elseif !props.createChildren && props.deleteChildren>createDeletePolicy="delete-only"<#else > <#-- Dont mention it, as 'neither' is default --></#if> >
+ <#if props.runsInsides?has_content> + <runs-inside> + <#list props.runsInsides as typeKey> + <parent-resource-type name="${typeKey.name}" plugin="${typeKey.pluginName}"/> + </#list> + </runs-inside> + </#if> + <#if props.simpleProps?has_content> <plugin-configuration> <#list props.simpleProps as simpleProps>
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 c99febcffec0ca846f5463f863434cb7e6d9cf86 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 28 18:00:02 2010 -0400
get rid of spaces in view IDs, and use camelCase instead; add more view ID constants; misc minor refactoring
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java index 676ae61..88c08ee 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/StringUtils.java @@ -1,6 +1,6 @@ /* * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. + * Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -23,11 +23,19 @@ package org.rhq.core.domain.util;
import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set;
public class StringUtils { + private static final Set<String> LOWERCASE_WORDS = new HashSet<String>(); + static { + LOWERCASE_WORDS.add("And"); + LOWERCASE_WORDS.add("Or"); + } + /* - * Take somethin that is camel-cased, add spaces between the words, and capitalize each word + * Take something that is camel-cased, add spaces between the words, and capitalize each word. */ public static String deCamelCase(String target) { if (target.length() == 0) { @@ -44,7 +52,7 @@ public class StringUtils { target = target.substring(0, target.length() - 1); }
- int nextDash = 0; + int nextDash; while ((nextDash = target.indexOf('-')) > 0) { target = target.substring(0, nextDash) + Character.toUpperCase(target.charAt(nextDash + 1)) + target.substring(nextDash + 2); @@ -52,26 +60,41 @@ public class StringUtils {
result.append(Character.toUpperCase(target.charAt(0)));
- char next; - char last = target.charAt(0); + StringBuilder currentWord = new StringBuilder(); + char currentChar; + char previousChar = target.charAt(0); for (int i = 1; i < target.length(); i++) { - next = target.charAt(i); + currentChar = target.charAt(i);
// Obey multi-digit numbers and acronyms - if ((Character.isDigit(next) && !Character.isDigit(last)) - || (Character.isUpperCase(next) && (!Character.isUpperCase(last) || ((i < (target.length() - 1)) && Character - .isLowerCase(target.charAt(i + 1)))))) { - // at the start of another word, add a space + if ((Character.isDigit(currentChar) && !Character.isDigit(previousChar)) + || (Character.isUpperCase(currentChar) && (!Character.isUpperCase(previousChar) + || ((i < (target.length() - 1)) && Character.isLowerCase(target.charAt(i + 1)))))) { + // We're at the start of a new word. + appendWord(result, currentWord); + currentWord = new StringBuilder(); + // Append a space before the next word. result.append(' '); }
- result.append(next); - last = next; + currentWord.append(currentChar); + previousChar = currentChar; } + // Append the final word. + appendWord(result, currentWord);
return result.toString(); }
+ private static void appendWord(StringBuilder result, StringBuilder nextWord) { + String word = nextWord.toString(); + if (LOWERCASE_WORDS.contains(word)) { + result.append(word.toLowerCase()); + } else { + result.append(word); + } + } + public static List<String> getStringAsList(String input, String regexSplitter, boolean ignoreEmptyTokens) { List<String> results = new ArrayList<String>();
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 b0cd874..37770eb 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 @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.client.admin; import java.util.LinkedHashMap; import java.util.Map;
+import com.google.gwt.user.client.History; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -40,6 +41,7 @@ import org.rhq.enterprise.gui.coregui.client.admin.agent.install.RemoteAgentInst import org.rhq.enterprise.gui.coregui.client.admin.roles.RolesView; import org.rhq.enterprise.gui.coregui.client.admin.users.UsersView; import org.rhq.enterprise.gui.coregui.client.components.FullHTMLPane; +import org.rhq.enterprise.gui.coregui.client.components.tree.EnhancedTreeNode; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; @@ -59,6 +61,10 @@ 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); } @@ -80,30 +86,37 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable sectionStack.setWidth(250); sectionStack.setHeight100();
- treeGrids.put("Security", buildSecuritySection()); - treeGrids.put("Configuration", buildSystemConfigurationSection()); - treeGrids.put("Cluster", buildManagementClusterSection()); + addSection(buildSecuritySection()); + addSection(buildSystemConfigurationSection()); + addSection(buildManagementClusterSection());
- for (final String name : treeGrids.keySet()) { - TreeGrid grid = treeGrids.get(name); + addMember(sectionStack); + addMember(contentCanvas); + }
- grid.addSelectionChangedHandler(new SelectionChangedHandler() { - public void onSelectionChanged(SelectionEvent selectionEvent) { - if (selectionEvent.getState()) { - CoreGUI.goToView("Administration/" + name + "/" + selectionEvent.getRecord().getAttribute("name")); + private void addSection(TreeGrid treeGrid) { + final String sectionName = treeGrid.getTree().getRoot().getName(); + this.treeGrids.put(sectionName, treeGrid); + + treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { + public void onSelectionChanged(SelectionEvent selectionEvent) { + if (selectionEvent.getState()) { + TreeNode node = (TreeNode)selectionEvent.getRecord(); + String pageName = node.getName(); + String viewPath = AdministrationView.VIEW_ID + "/" + sectionName + "/" + pageName; + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); } } - }); - - SectionStackSection section = new SectionStackSection(name); - section.setExpanded(true); - section.addItem(grid); + } + });
- sectionStack.addSection(section); - } + SectionStackSection section = new SectionStackSection(sectionName); + section.setExpanded(true); + section.addItem(treeGrid);
- addMember(sectionStack); - addMember(contentCanvas); + this.sectionStack.addSection(section); }
private HTMLFlow defaultView() { @@ -117,21 +130,23 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
private TreeGrid buildSecuritySection() {
- final TreeGrid securityTreeGrid = new LocatableTreeGrid("Security"); + final TreeGrid securityTreeGrid = new LocatableTreeGrid(SECURITY_SECTION_VIEW_ID); securityTreeGrid.setLeaveScrollbarGap(false); securityTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode manageUsersNode = new TreeNode("Manage Users"); + final TreeNode manageUsersNode = new EnhancedTreeNode(UsersView.VIEW_ID); manageUsersNode.setIcon("global/User_16.png");
- final TreeNode manageRolesNode = new TreeNode("Manage Roles"); + final TreeNode manageRolesNode = new EnhancedTreeNode(RolesView.VIEW_ID); manageRolesNode.setIcon("global/Role_16.png");
- final TreeNode remoteAgentInstall = new TreeNode("Remote Agent Install"); + final TreeNode remoteAgentInstall = new EnhancedTreeNode(RemoteAgentInstallView.VIEW_ID); remoteAgentInstall.setIcon("global/Agent_16.png");
- tree.setRoot(new TreeNode("security", manageUsersNode, manageRolesNode, remoteAgentInstall)); + TreeNode rootNode = new EnhancedTreeNode(SECURITY_SECTION_VIEW_ID, manageUsersNode, manageRolesNode, + remoteAgentInstall); + tree.setRoot(rootNode);
securityTreeGrid.setData(tree);
@@ -140,18 +155,19 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
private TreeGrid buildManagementClusterSection() {
- final TreeGrid mgmtClusterTreeGrid = new LocatableTreeGrid("Topology"); + final TreeGrid mgmtClusterTreeGrid = new LocatableTreeGrid(TOPOLOGY_SECTION_VIEW_ID); mgmtClusterTreeGrid.setLeaveScrollbarGap(false); mgmtClusterTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode manageServersNode = new TreeNode("Servers"); - final TreeNode manageAgentsNode = new TreeNode("Agents"); - final TreeNode manageAffinityGroupsNode = new TreeNode("Affinity Groups"); - final TreeNode managePartitionEventsNode = new TreeNode("Partition Events"); + final TreeNode manageServersNode = new EnhancedTreeNode("Servers"); + final TreeNode manageAgentsNode = new EnhancedTreeNode("Agents"); + final TreeNode manageAffinityGroupsNode = new EnhancedTreeNode("AffinityGroups"); + final TreeNode managePartitionEventsNode = new EnhancedTreeNode("PartitionEvents");
- tree.setRoot(new TreeNode("clustering", manageServersNode, manageAgentsNode, manageAffinityGroupsNode, - managePartitionEventsNode)); + TreeNode rootNode = new EnhancedTreeNode(TOPOLOGY_SECTION_VIEW_ID, manageServersNode, manageAgentsNode, + manageAffinityGroupsNode, managePartitionEventsNode); + tree.setRoot(rootNode);
mgmtClusterTreeGrid.setData(tree);
@@ -160,19 +176,20 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
private TreeGrid buildSystemConfigurationSection() {
- final TreeGrid systemConfigTreeGrid = new LocatableTreeGrid("Config"); + final TreeGrid systemConfigTreeGrid = new LocatableTreeGrid(CONFIGURATION_SECTION_VIEW_ID); systemConfigTreeGrid.setLeaveScrollbarGap(false); systemConfigTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode manageSettings = new TreeNode("System Settings"); - final TreeNode manageTemplates = new TreeNode("Templates"); - final TreeNode manageDownloads = new TreeNode("Downloads"); - final TreeNode manageLicense = new TreeNode("License"); - final TreeNode managePlugins = new TreeNode("Plugins"); + 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");
- tree.setRoot(new TreeNode("System Configuration", manageSettings, manageTemplates, manageDownloads, - manageLicense, managePlugins)); + TreeNode rootNode = new EnhancedTreeNode(CONFIGURATION_SECTION_VIEW_ID, manageSettings, manageTemplates, manageDownloads, + manageLicense, managePlugins); + tree.setRoot(rootNode);
systemConfigTreeGrid.setData(tree);
@@ -180,11 +197,8 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable }
public void setContent(Canvas newContent) { - - if (contentCanvas.getChildren().length > 0) { - for (Canvas child : contentCanvas.getChildren()) { - child.destroy(); - } + for (Canvas child : contentCanvas.getChildren()) { + child.destroy(); }
contentCanvas.addChild(newContent); @@ -193,58 +207,56 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable }
private void renderContentView(ViewPath viewPath) { - currentSectionViewId = viewPath.getCurrent(); currentPageViewId = viewPath.getNext();
- String section = currentSectionViewId.getPath(); - String page = currentPageViewId.getPath(); + String sectionName = currentSectionViewId.getPath(); + String pageName = currentPageViewId.getPath();
Canvas content = null; - if ("Security".equals(section)) { + if (SECURITY_SECTION_VIEW_ID.equals(sectionName)) {
- if ("Manage Users".equals(page)) { + if (UsersView.VIEW_ID.equals(pageName)) { content = new UsersView(this.extendLocatorId("Users")); - } else if ("Manage Roles".equals(page)) { + } else if (RolesView.VIEW_ID.equals(pageName)) { content = new RolesView(this.extendLocatorId("Roles")); - } else if ("Remote Agent Install".equals(page)) { + } else if (RemoteAgentInstallView.VIEW_ID.equals(pageName)) { content = new RemoteAgentInstallView(this.extendLocatorId("RemoteAgentInstall")); } - } else if ("Configuration".equals(section)) { + } else if (CONFIGURATION_SECTION_VIEW_ID.equals(sectionName)) {
String url = null; - if ("System Settings".equals(page)) { + if ("SystemSettings".equals(pageName)) { url = "/admin/config/Config.do?mode=edit"; - } else if ("Templates".equals(page)) { + } else if ("Templates".equals(pageName)) { url = "/admin/config/EditDefaults.do?mode=monitor&viewMode=all"; - } else if ("Downloads".equals(page)) { + } else if ("Downloads".equals(pageName)) { url = "/rhq/admin/downloads-body.xhtml"; - } else if ("License".equals(page)) { + } else if ("License".equals(pageName)) { url = "/admin/license/LicenseAdmin.do?mode=view"; - } else if ("Plugins".equals(page)) { + } else if ("Plugins".equals(pageName)) { url = "/rhq/admin/plugin/plugin-list-plain.xhtml"; } url = addQueryStringParam(url, "nomenu=true"); content = new FullHTMLPane(url);
- } else if ("Cluster".equals(section)) { + } else if (TOPOLOGY_SECTION_VIEW_ID.equals(sectionName)) { String url = null; - if ("Servers".equals(page)) { + if ("Servers".equals(pageName)) { url = "/rhq/ha/listServers-plain.xhtml"; - } else if ("Agents".equals(page)) { + } else if ("Agents".equals(pageName)) { url = "/rhq/ha/listAgents-plain.xhtml"; - } else if ("Affinity Groups".equals(page)) { + } else if ("Affinity Groups".equals(pageName)) { url = "/rhq/ha/listAffinityGroups-plain.xhtml"; - } else if ("Partition Events".equals(page)) { + } else if ("Partition Events".equals(pageName)) { url = "/rhq/ha/listPartitionEvents-plain.xhtml"; } content = new FullHTMLPane(url); }
for (String name : treeGrids.keySet()) { - TreeGrid treeGrid = treeGrids.get(name); - if (name.equals(section)) { + if (name.equals(sectionName)) { // treeGrid.setSelectedPaths(page); } else { treeGrid.deselectAllRecords(); @@ -259,13 +271,10 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable ((BookmarkableView) content).renderView(viewPath.next().next()); } } - }
public void renderView(ViewPath viewPath) { - if (!viewPath.isCurrent(currentSectionViewId) || !viewPath.isNext(currentPageViewId)) { - if (viewPath.isEnd()) { // Display default view setContent(defaultView()); @@ -276,7 +285,6 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable if (this.currentContent instanceof BookmarkableView) { ((BookmarkableView) this.currentContent).renderView(viewPath.next().next()); } - } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/agent/install/RemoteAgentInstallView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/agent/install/RemoteAgentInstallView.java index 78aba28..b808fc8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/agent/install/RemoteAgentInstallView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/agent/install/RemoteAgentInstallView.java @@ -58,7 +58,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Greg Hinkle */ public class RemoteAgentInstallView extends LocatableVLayout { - + public static final String VIEW_ID = "RemoteAgentInstall"; + private RemoteInstallGWTServiceAsync remoteInstallService = GWTServiceLookup.getRemoteInstallService();
private DynamicForm connectionForm; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesView.java index a9ea8b3..9e38e63 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesView.java @@ -30,6 +30,7 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; * @author Greg Hinkle */ public class RolesView extends TableSection implements BookmarkableView { + public static final String VIEW_ID = "Roles";
public RolesView(String locatorId) { super(locatorId, "Roles"); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java index e1de74d..51a0b8a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java @@ -30,6 +30,7 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; * @author Greg Hinkle */ public class UsersView extends TableSection { + public static final String VIEW_ID = "Users";
public UsersView(String locatorId) { super(locatorId, "Users"); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java index 1a5e44a..8d2a36c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java @@ -56,6 +56,8 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellForma * @author Heiko W. Rupp */ public class AlertsView extends Table { + public static final String VIEW_ID = "RecentAlerts"; + private static final String TITLE = "Alerts";
private static final SortSpecifier[] SORT_SPECIFIERS = new SortSpecifier[] { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java index 50ed0ae..b82482c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/FullHTMLPane.java @@ -34,6 +34,7 @@ public class FullHTMLPane extends HTMLPane {
public FullHTMLPane(String url) { this(); + System.out.println("Creating IFrame pane with URL [" + url + "]..."); setContentsURL(url); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java index 11a78dc..bbbcc1b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java @@ -20,19 +20,23 @@ package org.rhq.enterprise.gui.coregui.client.components.tree;
import com.smartgwt.client.widgets.tree.TreeNode;
+import org.rhq.core.domain.util.StringUtils; + /** * @author Ian Springer */ public class EnhancedTreeNode extends TreeNode { public EnhancedTreeNode() { + this(null); }
public EnhancedTreeNode(String name) { - super(name); + this(name, new TreeNode[0]); }
public EnhancedTreeNode(String name, TreeNode... children) { super(name, children); + setTitle(StringUtils.deCamelCase(name)); }
public String getID() { @@ -46,9 +50,16 @@ public class EnhancedTreeNode extends TreeNode { @Override public String toString() { StringBuilder buffer = new StringBuilder(); - String className = this.getClass().getName(); - String simpleClassName = className.substring(className.lastIndexOf(".") + 1); - String innerClassName = simpleClassName.substring(simpleClassName.lastIndexOf("$") + 1); + String innerClassName; + try { + String className = this.getClass().getName(); + String simpleClassName = className.substring(className.lastIndexOf(".") + 1); + innerClassName = simpleClassName.substring(simpleClassName.lastIndexOf("$") + 1); + } + catch (RuntimeException e) { + innerClassName = "EnhancedTreeNode"; + } + buffer.append(innerClassName).append("["); String id = getID(); buffer.append("id=").append(id); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformPortletView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformPortletView.java index a02cdd4..ea9cbc4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformPortletView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformPortletView.java @@ -58,6 +58,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableListGrid; * @author Greg Hinkle */ public class PlatformPortletView extends LocatableListGrid implements Portlet { + public static final String VIEW_ID = "CpuAndMemoryUtilization";
private MeasurementDataGWTServiceAsync measurementService = GWTServiceLookup.getMeasurementDataService(); private ResourceTypeGWTServiceAsync typeService = GWTServiceLookup.getResourceTypeGWTService(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index a4fac9f..f7c37ee 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -47,7 +47,7 @@ import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; public class GroupDefinitionListView extends TableSection {
public GroupDefinitionListView(String locatorId, String headerIcon) { - super(locatorId, "Group Definitions"); + super(locatorId, "Dynamic Group Definitions");
setHeaderIcon(headerIcon);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index e102771..335d23c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -43,6 +43,7 @@ import org.rhq.enterprise.gui.coregui.client.BookmarkableView; 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.components.tree.EnhancedTreeNode; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupListView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions.GroupDefinitionListView; @@ -58,22 +59,22 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; public class InventoryView extends LocatableHLayout implements BookmarkableView { public static final String VIEW_ID = "Inventory";
- private static final String SECTION_GROUPS = "Groups"; - private static final String SECTION_RESOURCES = "Resources"; + private static final String GROUPS_SECTION_VIEW_ID = "Groups"; + private static final String RESOURCES_SECTION_VIEW_ID = "Resources";
private static final String SUBSECTION_RESOURCE_INVENTORY = "Resources"; private static final String SUBSECTION_GROUP_INVENTORY = "Groups"; - private static final String SUBSECTION_SAVED_SEARCHES = "Saved Searches"; - - private static final String PAGE_ADQ = "Discovery Manager"; - private static final String PAGE_COMPATIBLE_GROUPS = "Compatible Groups"; - private static final String PAGE_DOWN = "Down Servers"; - private static final String PAGE_GROUPS = "All Groups"; - private static final String PAGE_GROUP_DEFINITIONS = "DynaGroup Manager"; - private static final String PAGE_MIXED_GROUPS = "Mixed Groups"; + private static final String SUBSECTION_SAVED_SEARCHES = "SavedSearches"; + + private static final String PAGE_ADQ = "DiscoveryManager"; + private static final String PAGE_COMPATIBLE_GROUPS = "CompatibleGroups"; + private static final String PAGE_DOWN = "DownServers"; + private static final String PAGE_GROUPS = "AllGroups"; + private static final String PAGE_GROUP_DEFINITIONS = "DynamicGroupDefinitions"; + private static final String PAGE_MIXED_GROUPS = "MixedGroups"; private static final String PAGE_PLATFORMS = "Platforms"; - private static final String PAGE_PROBLEM_GROUPS = "Problem Groups"; - private static final String PAGE_RESOURCES = "All Resources"; + private static final String PAGE_PROBLEM_GROUPS = "ProblemGroups"; + private static final String PAGE_RESOURCES = "AllResources"; private static final String PAGE_SERVERS = "Servers"; private static final String PAGE_SERVICES = "Services";
@@ -110,7 +111,7 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { @Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Could not determine user's global permissions, assuming none", + CoreGUI.getErrorHandler().handleError("Could not determine user's global permissions - assuming none.", caught); finishOnInit(EnumSet.noneOf(Permission.class)); } @@ -123,104 +124,98 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView }
private void finishOnInit(Set<Permission> globalPermissions) { - buildResourcesSection(globalPermissions); - buildGroupsSection(globalPermissions); - - for (final String sectionName : treeGrids.keySet()) { - TreeGrid grid = treeGrids.get(sectionName); - - grid.addSelectionChangedHandler(new SelectionChangedHandler() { - public void onSelectionChanged(SelectionEvent selectionEvent) { - if (selectionEvent.getState()) { - String pageName = selectionEvent.getRecord().getAttribute("name"); - String viewPath = "Inventory/" + sectionName + "/" + pageName; - String currentViewPath = History.getToken(); - if (!currentViewPath.startsWith(viewPath)) { - CoreGUI.goToView(viewPath); - } - } - } - }); - - SectionStackSection section = new SectionStackSection(sectionName); - section.setExpanded(true); - section.addItem(grid); - - sectionStack.addSection(section); - } + addSection(buildResourcesSection(globalPermissions)); + addSection(buildGroupsSection(globalPermissions));
addMember(sectionStack); addMember(contentCanvas); }
- private SectionStackSection buildResourcesSection(Set<Permission> globalPermissions) { + private void addSection(TreeGrid treeGrid) { + final String sectionName = treeGrid.getTree().getRoot().getName(); + this.treeGrids.put(sectionName, treeGrid); + + treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { + public void onSelectionChanged(SelectionEvent selectionEvent) { + if (selectionEvent.getState()) { + TreeNode node = (TreeNode)selectionEvent.getRecord(); + String pageName = node.getName(); + String viewPath = InventoryView.VIEW_ID + "/" + sectionName + "/" + pageName; + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); + } + } + } + });
- final SectionStackSection section = new SectionStackSection(SECTION_RESOURCES); + SectionStackSection section = new SectionStackSection(sectionName); section.setExpanded(true); + section.addItem(treeGrid); + + this.sectionStack.addSection(section); + }
- final TreeNode discoveryQueue = new TreeNode(PAGE_ADQ); + private TreeGrid buildResourcesSection(Set<Permission> globalPermissions) { + final TreeNode discoveryQueue = new EnhancedTreeNode(PAGE_ADQ); discoveryQueue.setEnabled(globalPermissions.contains(Permission.MANAGE_INVENTORY)); discoveryQueue.setIcon("global/Recent_16.png");
- final TreeNode onlyPlatforms = new TreeNode(PAGE_PLATFORMS); + final TreeNode onlyPlatforms = new EnhancedTreeNode(PAGE_PLATFORMS); onlyPlatforms.setIcon("types/Platform_up_16.png");
- final TreeNode onlyServers = new TreeNode(PAGE_SERVERS); + final TreeNode onlyServers = new EnhancedTreeNode(PAGE_SERVERS); onlyServers.setIcon("types/Server_up_16.png");
- final TreeNode onlyServices = new TreeNode(PAGE_SERVICES); + final TreeNode onlyServices = new EnhancedTreeNode(PAGE_SERVICES); onlyServices.setIcon("types/Service_up_16.png");
- final TreeNode inventory = new TreeNode(SUBSECTION_RESOURCE_INVENTORY, onlyPlatforms, onlyServers, onlyServices); + final TreeNode inventory = new EnhancedTreeNode(SUBSECTION_RESOURCE_INVENTORY, onlyPlatforms, onlyServers, onlyServices);
- final TreeNode downServers = new TreeNode(PAGE_DOWN); + final TreeNode downServers = new EnhancedTreeNode(PAGE_DOWN); downServers.setIcon("types/Server_down_16.png");
- final TreeNode savedSearches = new TreeNode(SUBSECTION_SAVED_SEARCHES, downServers); + final TreeNode savedSearches = new EnhancedTreeNode(SUBSECTION_SAVED_SEARCHES, downServers);
- TreeGrid treeGrid = new LocatableTreeGrid(SECTION_RESOURCES); + TreeGrid treeGrid = new LocatableTreeGrid(RESOURCES_SECTION_VIEW_ID); treeGrid.setShowHeader(false); Tree tree = new Tree(); - tree.setRoot(new TreeNode(SECTION_RESOURCES, discoveryQueue, inventory, savedSearches)); + TreeNode rootNode = new TreeNode(RESOURCES_SECTION_VIEW_ID, discoveryQueue, inventory, savedSearches); + tree.setRoot(rootNode); treeGrid.setData(tree);
treeGrid.getTree().openAll(); - treeGrids.put(SECTION_RESOURCES, treeGrid); - - section.addItem(treeGrid); + treeGrids.put(RESOURCES_SECTION_VIEW_ID, treeGrid);
- return section; + return treeGrid; }
- private SectionStackSection buildGroupsSection(Set<Permission> globalPermissions) { - final SectionStackSection section = new SectionStackSection(SECTION_GROUPS); - section.setExpanded(true); - - final TreeNode groupGroupDefinitions = new TreeNode(PAGE_GROUP_DEFINITIONS); + private TreeGrid buildGroupsSection(Set<Permission> globalPermissions) { + final TreeNode groupGroupDefinitions = new EnhancedTreeNode(PAGE_GROUP_DEFINITIONS); groupGroupDefinitions.setEnabled(globalPermissions.contains(Permission.MANAGE_INVENTORY)); groupGroupDefinitions.setIcon("types/GroupDefinition_16.png");
- final TreeNode onlyCompatible = new TreeNode(PAGE_COMPATIBLE_GROUPS); + final TreeNode onlyCompatible = new EnhancedTreeNode(PAGE_COMPATIBLE_GROUPS); onlyCompatible.setIcon("types/Cluster_up_16.png"); - final TreeNode onlyMixed = new TreeNode(PAGE_MIXED_GROUPS); + final TreeNode onlyMixed = new EnhancedTreeNode(PAGE_MIXED_GROUPS); onlyMixed.setIcon("types/Group_up_16.png");
- final TreeNode inventory = new TreeNode(SUBSECTION_GROUP_INVENTORY, onlyCompatible, onlyMixed); + final TreeNode inventory = new EnhancedTreeNode(SUBSECTION_GROUP_INVENTORY, onlyCompatible, onlyMixed);
- final TreeNode problemGroups = new TreeNode(PAGE_PROBLEM_GROUPS); - final TreeNode savedSearches = new TreeNode(SUBSECTION_SAVED_SEARCHES, problemGroups); + final TreeNode problemGroups = new EnhancedTreeNode(PAGE_PROBLEM_GROUPS); + final TreeNode savedSearches = new EnhancedTreeNode(SUBSECTION_SAVED_SEARCHES, problemGroups);
- TreeGrid treeGrid = new LocatableTreeGrid(SECTION_GROUPS); + TreeGrid treeGrid = new LocatableTreeGrid(GROUPS_SECTION_VIEW_ID); treeGrid.setShowHeader(false); Tree tree = new Tree(); - tree.setRoot(new TreeNode(SECTION_GROUPS, groupGroupDefinitions, inventory, savedSearches)); + TreeNode rootNode = new EnhancedTreeNode(GROUPS_SECTION_VIEW_ID, groupGroupDefinitions, inventory, savedSearches); + tree.setRoot(rootNode); treeGrid.setData(tree);
treeGrid.getTree().openAll(); - treeGrids.put(SECTION_GROUPS, treeGrid); - section.addItem(treeGrid); + treeGrids.put(GROUPS_SECTION_VIEW_ID, treeGrid);
- return section; + return treeGrid; }
public void setContent(Canvas newContent) { @@ -233,30 +228,29 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView }
private void renderContentView(ViewPath viewPath) { - currentSectionViewId = viewPath.getCurrent(); currentPageViewId = viewPath.getNext();
- String section = currentSectionViewId.getPath(); - String page = currentPageViewId.getPath(); + String sectionName = currentSectionViewId.getPath(); + String pageName = currentPageViewId.getPath();
Canvas content = null; - if (SECTION_RESOURCES.equals(section)) { - if (PAGE_PLATFORMS.equals(page)) { + if (RESOURCES_SECTION_VIEW_ID.equals(sectionName)) { + if (PAGE_PLATFORMS.equals(pageName)) { content = new ResourceSearchView(extendLocatorId("Platforms"), new Criteria( ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.PLATFORM.name()), PAGE_PLATFORMS, "types/Platform_up_24.png"); - } else if (PAGE_SERVERS.equals(page)) { + } else if (PAGE_SERVERS.equals(pageName)) { content = new ResourceSearchView(extendLocatorId("Servers"), new Criteria( ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.SERVER.name()), PAGE_SERVERS, "types/Server_up_24.png"); - } else if (PAGE_SERVICES.equals(page)) { + } else if (PAGE_SERVICES.equals(pageName)) { content = new ResourceSearchView(extendLocatorId("Services"), new Criteria( ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.SERVICE.name()), PAGE_SERVICES, "types/Service_up_24.png"); - } else if (PAGE_ADQ.equals(page)) { + } else if (PAGE_ADQ.equals(pageName)) { content = new ResourceAutodiscoveryView(this.extendLocatorId("ADQ")); - } else if (PAGE_DOWN.equals(page)) { + } else if (PAGE_DOWN.equals(pageName)) { Criteria criteria = new Criteria(ResourceDataSourceField.AVAILABILITY.propertyName(), AvailabilityType.DOWN.name()); criteria.addCriteria(ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.SERVER.name()); @@ -265,17 +259,16 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView content = new ResourceSearchView(extendLocatorId("AllResources"), null, PAGE_RESOURCES, "types/Platform_up_24.png", "types/Server_up_24.png", "types/Service_up_24.png"); } - - } else if (SECTION_GROUPS.equals(section)) { - if (PAGE_COMPATIBLE_GROUPS.equals(page)) { + } else if (GROUPS_SECTION_VIEW_ID.equals(sectionName)) { + if (PAGE_COMPATIBLE_GROUPS.equals(pageName)) { content = new ResourceGroupListView(extendLocatorId("Compatible"), new Criteria("category", "compatible"), PAGE_COMPATIBLE_GROUPS, "types/Cluster_up_24.png"); - } else if (PAGE_MIXED_GROUPS.equals(page)) { + } else if (PAGE_MIXED_GROUPS.equals(pageName)) { content = new ResourceGroupListView(extendLocatorId("Mixed"), new Criteria("category", "mixed"), PAGE_MIXED_GROUPS, "types/Group_up_24.png"); - } else if (PAGE_GROUP_DEFINITIONS.equals(page)) { + } else if (PAGE_GROUP_DEFINITIONS.equals(pageName)) { content = new GroupDefinitionListView(extendLocatorId("Definitions"), "types/GroupDefinition_16.png"); - } else if (PAGE_PROBLEM_GROUPS.equals(page)) { + } else if (PAGE_PROBLEM_GROUPS.equals(pageName)) { //TODO - there is no underlying support for this criteria. Also, there should not be an active // new button on this page. content = new ResourceGroupListView(extendLocatorId("DownGroups"), @@ -287,11 +280,10 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView }
for (String name : treeGrids.keySet()) { - TreeGrid treeGrid = treeGrids.get(name); - if (name.equals(section)) { + if (name.equals(sectionName)) { for (TreeNode node : treeGrid.getTree().getAllNodes()) { - if (page.equals(node.getName())) { + if (pageName.equals(node.getName())) { treeGrid.selectSingleRecord(node); } } @@ -308,7 +300,6 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView ((BookmarkableView) content).renderView(viewPath.next().next()); } } - }
public void renderView(ViewPath viewPath) { @@ -328,5 +319,4 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView } } } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java index 3339179..0e51bae 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ConfigurationHistoryView.java @@ -39,6 +39,7 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; * @author Greg Hinkle */ public class ConfigurationHistoryView extends TableSection { + public static final String VIEW_ID = "RecentConfigurationChanges";
private Integer resourceId;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java index 212a5ae..5e03c44 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java @@ -46,6 +46,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; * @author Greg Hinkle */ public class OperationHistoryView extends TableSection { + public static final String VIEW_ID = "RecentOperations";
private ResourceComposite composite; private Resource resource; 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 233637e..7627527 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 @@ -20,12 +20,13 @@ * 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.report;
import java.util.LinkedHashMap; +import java.util.Map;
import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.History; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -43,6 +44,7 @@ import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.components.FullHTMLPane; +import org.rhq.enterprise.gui.coregui.client.components.tree.EnhancedTreeNode; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.platform.PlatformPortletView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration.ConfigurationHistoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.OperationHistoryView; @@ -58,8 +60,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; public class ReportTopView extends LocatableHLayout implements BookmarkableView { public static final String VIEW_ID = "Reports";
- private static final String SECTION_INVENTORY = "Inventory"; - private static final String SECTION_REPORTS = "Reports"; + private static final String SUBSYSTEMS_SECTION_VIEW_ID = "Subsystems"; + private static final String INVENTORY_SECTION_VIEW_ID = "Inventory";
private ViewId currentSectionViewId; private ViewId currentPageViewId; @@ -68,7 +70,7 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView
private Canvas contentCanvas; private Canvas currentContent; - private LinkedHashMap<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>(); + private Map<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>();
public ReportTopView(String locatorId) { super(locatorId); @@ -91,30 +93,36 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView sectionStack.setWidth(250); sectionStack.setHeight100();
- treeGrids.put(SECTION_INVENTORY, buildInventorySection()); - treeGrids.put(SECTION_REPORTS, buildReportsSection()); + addSection(buildSubsystemsSection()); + addSection(buildInventorySection());
- for (final String name : treeGrids.keySet()) { - TreeGrid grid = treeGrids.get(name); + addMember(sectionStack); + addMember(contentCanvas); + }
- grid.addSelectionChangedHandler(new SelectionChangedHandler() { - public void onSelectionChanged(SelectionEvent selectionEvent) { - if (selectionEvent.getState()) { - CoreGUI.goToView("Reports/" + name + "/" + selectionEvent.getRecord().getAttribute("name")); + private void addSection(TreeGrid treeGrid) { + final String sectionName = treeGrid.getTree().getRoot().getName(); + this.treeGrids.put(sectionName, treeGrid); + + treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { + public void onSelectionChanged(SelectionEvent selectionEvent) { + if (selectionEvent.getState()) { + TreeNode node = (TreeNode)selectionEvent.getRecord(); + String pageName = node.getName(); + String viewPath = ReportTopView.VIEW_ID + "/" + sectionName + "/" + pageName; + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); } } - }); - - SectionStackSection section = new SectionStackSection(name); - section.setExpanded(true); - section.addItem(grid); - - sectionStack.addSection(section); - } + } + });
- addMember(sectionStack); - addMember(contentCanvas); + SectionStackSection section = new SectionStackSection(sectionName); + section.setExpanded(true); + section.addItem(treeGrid);
+ this.sectionStack.addSection(section); }
private HTMLFlow defaultView() { @@ -124,33 +132,32 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView return flow; }
- private TreeGrid buildInventorySection() { - - final TreeGrid inventoryTreeGrid = new LocatableTreeGrid(SECTION_INVENTORY); + private TreeGrid buildSubsystemsSection() { + final TreeGrid inventoryTreeGrid = new LocatableTreeGrid(SUBSYSTEMS_SECTION_VIEW_ID); inventoryTreeGrid.setLeaveScrollbarGap(false); inventoryTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode tagCloud = new TreeNode("Tag Cloud"); + final TreeNode tagCloud = new EnhancedTreeNode(TaggedView.VIEW_ID); tagCloud.setIcon("global/Cloud_16.png");
- final TreeNode suspectMetrics = new TreeNode("Suspect Metrics"); + final TreeNode suspectMetrics = new EnhancedTreeNode(MeasurementOOBView.VIEW_ID); suspectMetrics.setIcon("subsystems/monitor/Monitor_failed_16.png");
- final TreeNode recentConfigurationChanges = new TreeNode("Recent Configuration Changes"); + final TreeNode recentConfigurationChanges = new EnhancedTreeNode(ConfigurationHistoryView.VIEW_ID); recentConfigurationChanges.setIcon("subsystems/configure/Configure_16.png");
- final TreeNode recentOperations = new TreeNode("Recent Operations"); + final TreeNode recentOperations = new EnhancedTreeNode(OperationHistoryView.VIEW_ID); recentOperations.setIcon("subsystems/control/Operation_16.png");
- final TreeNode recentAlerts = new TreeNode("Recent Alerts"); + final TreeNode recentAlerts = new EnhancedTreeNode(AlertsView.VIEW_ID); recentAlerts.setIcon("subsystems/alert/Alert_LOW_16.png");
- final TreeNode alertDefinitions = new TreeNode("Alert Definitions"); + final TreeNode alertDefinitions = new EnhancedTreeNode("Alert Definitions"); alertDefinitions.setIcon("subsystems/alert/Alerts_16.png");
- TreeNode inventoryNode = new TreeNode(SECTION_INVENTORY, tagCloud, suspectMetrics, recentConfigurationChanges, - recentOperations, recentAlerts, alertDefinitions); + TreeNode inventoryNode = new EnhancedTreeNode(SUBSYSTEMS_SECTION_VIEW_ID, tagCloud, suspectMetrics, + recentConfigurationChanges, recentOperations, recentAlerts, alertDefinitions); tree.setRoot(inventoryNode);
inventoryTreeGrid.setData(tree); @@ -158,20 +165,20 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView return inventoryTreeGrid; }
- private TreeGrid buildReportsSection() { + private TreeGrid buildInventorySection() {
- final TreeGrid reportsTreeGrid = new LocatableTreeGrid(SECTION_REPORTS); + final TreeGrid reportsTreeGrid = new LocatableTreeGrid(INVENTORY_SECTION_VIEW_ID); reportsTreeGrid.setLeaveScrollbarGap(false); reportsTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode inventorySummary = new TreeNode("Inventory Summary"); + final TreeNode inventorySummary = new EnhancedTreeNode("InventorySummary"); inventorySummary.setIcon("subsystems/inventory/Inventory_16.png");
- final TreeNode platforms = new TreeNode("CPU & Memory Utilization"); + final TreeNode platforms = new EnhancedTreeNode(PlatformPortletView.VIEW_ID); platforms.setIcon("types/Platform_up_16.png");
- TreeNode reportsNode = new TreeNode(SECTION_REPORTS, inventorySummary, platforms); + TreeNode reportsNode = new EnhancedTreeNode(INVENTORY_SECTION_VIEW_ID, inventorySummary, platforms); tree.setRoot(reportsNode);
reportsTreeGrid.setData(tree); @@ -180,7 +187,6 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView }
public void setContent(Canvas newContent) { - if (contentCanvas.getChildren().length > 0) { for (Canvas child : contentCanvas.getChildren()) { child.destroy(); @@ -193,44 +199,41 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView }
private void renderContentView(ViewPath viewPath) { - currentSectionViewId = viewPath.getCurrent(); currentPageViewId = viewPath.getNext();
- String section = currentSectionViewId.getPath(); - String page = currentPageViewId.getPath(); + String sectionName = currentSectionViewId.getPath(); + String pageName = currentPageViewId.getPath();
- page = URL.decode(page); + pageName = URL.decode(pageName);
Canvas content = null; - if (SECTION_INVENTORY.equals(section)) { - - if ("Tag Cloud".equals(page)) { - content = new TaggedView(this.extendLocatorId("TagCloud")); - } else if ("Suspect Metrics".equals(page)) { + if (SUBSYSTEMS_SECTION_VIEW_ID.equals(sectionName)) { + if (TaggedView.VIEW_ID.equals(pageName)) { + content = new TaggedView(this.extendLocatorId("Tag")); + } else if (MeasurementOOBView.VIEW_ID.equals(pageName)) { content = new MeasurementOOBView(this.extendLocatorId("SuspectMetrics")); - } else if ("Recent Configuration Changes".equals(page)) { + } else if (ConfigurationHistoryView.VIEW_ID.equals(pageName)) { content = new ConfigurationHistoryView(this.extendLocatorId("RecentConfigChanges")); - } else if ("Recent Operations".equals(page)) { + } else if (OperationHistoryView.VIEW_ID.equals(pageName)) { content = new OperationHistoryView(this.extendLocatorId("RecentOps")); - } else if ("Recent Alerts".equals(page)) { + } else if (AlertsView.VIEW_ID.equals(pageName)) { content = new AlertsView(this.extendLocatorId("RecentAlerts")); - } else if ("Alert Definitions".equals(page)) { - //todo + } else if ("Alert Definitions".equals(pageName)) { + // TODO (mazz) } - - } else if (SECTION_REPORTS.equals(section)) { - if ("Inventory Summary".equals(page)) { + } else if (INVENTORY_SECTION_VIEW_ID.equals(sectionName)) { + if ("InventorySummary".equals(pageName)) { content = new FullHTMLPane("/rhq/admin/report/resourceInstallReport-body.xhtml"); - } else if ("CPU & Memory Utilization".equals(page)) { + } else if (PlatformPortletView.VIEW_ID.equals(pageName)) { content = new PlatformPortletView(this.extendLocatorId("Platforms")); } } - for (String name : treeGrids.keySet()) {
+ for (String name : treeGrids.keySet()) { TreeGrid treeGrid = treeGrids.get(name); - if (name.equals(section)) { - TreeNode node = treeGrid.getTree().find(page); + if (name.equals(sectionName)) { + TreeNode node = treeGrid.getTree().find(pageName); if (node != null) { treeGrid.selectSingleRecord(node); } @@ -249,22 +252,17 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView }
public void renderView(ViewPath viewPath) { - if (!viewPath.isCurrent(currentSectionViewId) || !viewPath.isNext(currentPageViewId)) { - if (viewPath.isEnd()) { // Display default view setContent(defaultView()); } else { - renderContentView(viewPath); } } else { if (this.currentContent instanceof BookmarkableView) { ((BookmarkableView) this.currentContent).renderView(viewPath.next().next()); } - } - } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBView.java index 9d68c48..e778e50 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBView.java @@ -31,7 +31,8 @@ import org.rhq.enterprise.gui.coregui.client.components.table.Table; * @author Greg Hinkle */ public class MeasurementOOBView extends Table { - + public static final String VIEW_ID = "SuspectMetrics"; + public MeasurementOOBView(String locatorId) { super(locatorId, "Suspect Metrics");
commit f0fffb5636ef2cdf89f6a1a1b1808e5d2fd98b6c Author: John Sanda jsanda@redhat.com Date: Tue Sep 28 17:15:48 2010 -0400
[BZ 619781] Handling more scenarios for settting connection properties to default values
Adding logic to handle three additional scenarios each of which involves connection properties that are required and specify a default value:
1) A new property is added to a new group 2) An existing property not part of a group added to an existing group 3) A property previously in a group moved outside of a group
There were also some scenarios when properties were moved into or out of a group and the group reference was not getting set or unset. ConfigurationMetadataManagerBean has been modifed to update these references.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationDefinitionUpdateReport.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationDefinitionUpdateReport.java index ad0c84b..ecad316 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationDefinitionUpdateReport.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationDefinitionUpdateReport.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.server.configuration.metadata;
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 java.util.HashSet; import java.util.Set; @@ -35,6 +36,8 @@ public class ConfigurationDefinitionUpdateReport {
private Set<PropertyDefinition> newPropertyDefs = new HashSet<PropertyDefinition>();
+ private Set<PropertyDefinition> updatedPropertyDefs = new HashSet<PropertyDefinition>(); + public ConfigurationDefinitionUpdateReport(ConfigurationDefinition configurationDefinition) { configurationDef = configurationDefinition; } @@ -44,11 +47,23 @@ public class ConfigurationDefinitionUpdateReport { }
public void addNewPropertyDefinition(PropertyDefinition propertyDef) { - newPropertyDefs.add(propertyDef); + if (propertyDef instanceof PropertyDefinitionSimple) { + newPropertyDefs.add(propertyDef); + } }
public Set<PropertyDefinition> getNewPropertyDefinitions() { return newPropertyDefs; }
+ public void addUpdatedPropertyDefinition(PropertyDefinition propertyDef) { + if (propertyDef instanceof PropertyDefinitionSimple) { + updatedPropertyDefs.add(propertyDef); + } + } + + public Set<PropertyDefinition> getUpdatedPropertyDefinitions() { + return updatedPropertyDefs; + } + } 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 8427c8b..04a3995 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 @@ -74,6 +74,7 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa PropertyDefinition existingProp = existingDefinition.get(newProperty.getName()); if (existingProp != null) { updatePropertyDefinition(existingProp, newProperty); + updateReport.addUpdatedPropertyDefinition(newProperty); } else { existingDefinition.put(newProperty); updateReport.addNewPropertyDefinition(newProperty); @@ -130,6 +131,7 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa PropertyDefinition existingProperty = existingDefinition.getPropertyDefinitions().get(nDef.getName()); if (existingProperty != null) { updatePropertyDefinition(existingProperty, nDef); + updateReport.addUpdatedPropertyDefinition(nDef); } else { existingDefinition.put(nDef); updateReport.addNewPropertyDefinition(nDef); @@ -157,6 +159,11 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa entityManager.persist(def); def.setPropertyGroupDefinition(group); def.setConfigurationDefinition(existingDefinition); + + if (!exPDefs.containsKey(def.getName())) { + updateReport.addNewPropertyDefinition(def); + } + exPDefs.put(def.getName(), def); } } @@ -309,6 +316,7 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa existingProperty.setRequired(newProperty.isRequired()); existingProperty.setReadOnly(newProperty.isReadOnly()); existingProperty.setSummary(newProperty.isSummary()); + existingProperty.setPropertyGroupDefinition(newProperty.getPropertyGroupDefinition());
/* * After the general things have been set, go through the subtypes of PropertyDefinition. If the new type is the diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java index a136561..ff81a6e 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java @@ -969,7 +969,8 @@ public class ResourceMetadataManagerBean implements ResourceMetadataManagerLocal .updateConfigurationDefinition(resourceType.getPluginConfigurationDefinition(), existingConfigurationDefinition);
- if (updateReport.getNewPropertyDefinitions().size() > 0) { + if (updateReport.getNewPropertyDefinitions().size() > 0 || + updateReport.getUpdatedPropertyDefinitions().size() > 0) { Subject overlord = subjectManager.getOverlord(); ResourceCriteria criteria = new ResourceCriteria(); criteria.addFilterResourceTypeId(existingType.getId()); @@ -991,6 +992,7 @@ public class ResourceMetadataManagerBean implements ResourceMetadataManagerLocal
private void updateResourcePluginConfiguration(Resource resource, ConfigurationDefinitionUpdateReport updateReport) { Configuration pluginConfiguration = resource.getPluginConfiguration(); + boolean modified = false; int numberOfProperties = pluginConfiguration.getProperties().size(); ConfigurationTemplate template = updateReport.getConfigurationDefinition().getDefaultTemplate(); Configuration templateConfiguration = template.getConfiguration(); @@ -999,10 +1001,23 @@ public class ResourceMetadataManagerBean implements ResourceMetadataManagerLocal if (propertyDef.isRequired()) { Property templateProperty = templateConfiguration.get(propertyDef.getName()); pluginConfiguration.put(templateProperty.deepCopy(false)); + modified = true; } }
- if (pluginConfiguration.getProperties().size() > numberOfProperties) { + for (PropertyDefinition propertyDef : updateReport.getUpdatedPropertyDefinitions()) { + if (propertyDef.isRequired()) { + String propertyValue = pluginConfiguration.getSimpleValue(propertyDef.getName(), null); + if (propertyValue == null) { + Property templateProperty = templateConfiguration.get(propertyDef.getName()); + pluginConfiguration.put(templateProperty.deepCopy(false)); + modified = true; + } + } + } + +// if (pluginConfiguration.getProperties().size() > numberOfProperties) { + if (modified) { resource.setMtime(new Date().getTime()); } }
commit 4a91718ee72e1a67eff794eb1a7e3c057c2d2716 Author: John Mazzitelli mazz@redhat.com Date: Tue Sep 28 14:45:46 2010 -0400
we now have a alert definition gwt service - and this is the more appropriate place for the getAlertDefinitionsByCriteria API
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java index bf38e6b..7a53dbe 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java @@ -120,7 +120,7 @@ public abstract class AbstractAlertDefinitionsDataSource extends RPCDataSource<A @Override protected void executeFetch(final DSRequest request, final DSResponse response) { AlertDefinitionCriteria criteria = getCriteria(request); - GWTServiceLookup.getAlertService().findAlertDefinitionsByCriteria(criteria, + GWTServiceLookup.getAlertDefinitionService().findAlertDefinitionsByCriteria(criteria, new AsyncCallback<PageList<AlertDefinition>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to load alert definition data", caught); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java index 818aaca..89a6c8b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java @@ -148,7 +148,7 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { final AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); criteria.addFilterId(id); criteria.fetchGroupAlertDefinition(true); - GWTServiceLookup.getAlertService().findAlertDefinitionsByCriteria(criteria, + GWTServiceLookup.getAlertDefinitionService().findAlertDefinitionsByCriteria(criteria, new AsyncCallback<PageList<AlertDefinition>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to load alert definition data", caught); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java index b539d0a..cf8af6a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java @@ -214,7 +214,7 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements private void loadAllAlertDefinitionsAndRefreshRecoverAlertSelection() { if (allAlertDefinitions == null) { AlertDefinitionCriteria criteria = alertDataSource.getSimpleCriteriaForAll(); - GWTServiceLookup.getAlertService().findAlertDefinitionsByCriteria(criteria, + GWTServiceLookup.getAlertDefinitionService().findAlertDefinitionsByCriteria(criteria, new AsyncCallback<PageList<AlertDefinition>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Cannot build recovery menu", caught); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java index 14c123c..e0d4e94 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java @@ -21,9 +21,13 @@ package org.rhq.enterprise.gui.coregui.client.gwt; import com.google.gwt.user.client.rpc.RemoteService;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.criteria.AlertDefinitionCriteria; +import org.rhq.core.domain.util.PageList;
public interface AlertDefinitionGWTService extends RemoteService {
+ PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria); + int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception;
AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertGWTService.java index 38b19ee..aac13a3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertGWTService.java @@ -19,12 +19,9 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
import com.google.gwt.user.client.rpc.RemoteService; + import org.rhq.core.domain.alert.Alert; -import org.rhq.core.domain.alert.AlertDefinition; -import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.criteria.AlertCriteria; -import org.rhq.core.domain.criteria.AlertDefinitionCriteria; -import org.rhq.core.domain.criteria.RoleCriteria; import org.rhq.core.domain.util.PageList;
/** @@ -57,9 +54,4 @@ public interface AlertGWTService extends RemoteService { * @param alertIds the ids of the Resource alerts to be acknowledged */ void acknowledgeResourceAlerts(Integer[] alertIds); - - - - PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria); - } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java index 606195b..392e710 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java @@ -19,6 +19,8 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.criteria.AlertDefinitionCriteria; +import org.rhq.core.domain.util.PageList; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.AlertDefinitionGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; @@ -30,6 +32,16 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem
private AlertDefinitionManagerLocal alertDefManager = LookupUtil.getAlertDefinitionManager();
+ public PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria) { + try { + PageList<AlertDefinition> results = this.alertDefManager.findAlertDefinitionsByCriteria( + getSessionSubject(), criteria); + return SerialUtility.prepare(results, "findAlertDefinitionsByCriteria"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + public int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception { try { int results = alertDefManager.createAlertDefinition(getSessionSubject(), alertDefinition, resourceId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java index bc0d32d..a1f47c9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java @@ -19,13 +19,10 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import org.rhq.core.domain.alert.Alert; -import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.criteria.AlertCriteria; -import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.AlertGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; -import org.rhq.enterprise.server.alert.AlertDefinitionManagerLocal; import org.rhq.enterprise.server.alert.AlertManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
@@ -33,12 +30,13 @@ import org.rhq.enterprise.server.util.LookupUtil; * @author Ian Springer */ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements AlertGWTService { + private static final long serialVersionUID = 1L; + private AlertManagerLocal alertManager = LookupUtil.getAlertManager(); - private AlertDefinitionManagerLocal alertDefinitionManager = LookupUtil.getAlertDefinitionManager();
public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) { return SerialUtility.prepare(this.alertManager.findAlertsByCriteria(getSessionSubject(), criteria), - "AlertService.findAlertsByCriteria"); + "AlertService.findAlertsByCriteria"); }
public void deleteResourceAlerts(Integer[] alertIds) { @@ -48,10 +46,4 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert public void acknowledgeResourceAlerts(Integer[] alertIds) { this.alertManager.acknowledgeAlerts(getSessionSubject(), alertIds); } - - - public PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria) { - return SerialUtility.prepare(this.alertDefinitionManager.findAlertDefinitionsByCriteria(getSessionSubject(), criteria), - "AlertService.findAlertDefinitionsByCriteria"); - } } \ No newline at end of file
commit ca46ea1e4f7dd5f1153b1082ad0b349b612556e9 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 28 14:36:25 2010 -0400
start using VIEW_ID constants for view id names
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..1dd1250 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 @@ -66,6 +66,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Ian Springer */ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { + private static final String DEFAULT_VIEW_PATH = DashboardsView.VIEW_ID;
public static final String CONTENT_CANVAS_ID = "BaseContent";
@@ -270,28 +271,28 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { public Canvas createContent(String breadcrumbName) { Canvas canvas;
- if (breadcrumbName.equals("Administration")) { + if (breadcrumbName.equals(AdministrationView.VIEW_ID)) { canvas = new AdministrationView("Admin"); - } else if (breadcrumbName.equals("Demo")) { + } else if (breadcrumbName.equals(DemoCanvas.VIEW_ID)) { canvas = new DemoCanvas(); - } else if (breadcrumbName.equals("Inventory")) { + } else if (breadcrumbName.equals(InventoryView.VIEW_ID)) { canvas = new InventoryView("Inventory"); - } else if (breadcrumbName.equals("Resource")) { + } else if (breadcrumbName.equals(ResourceTopView.VIEW_ID)) { canvas = new ResourceTopView("Resource"); - } else if (breadcrumbName.equals("ResourceGroup")) { + } else if (breadcrumbName.equals(ResourceGroupTopView.VIEW_ID)) { canvas = new ResourceGroupTopView("Group"); - } else if (breadcrumbName.equals("Dashboard")) { + } else if (breadcrumbName.equals(DashboardsView.VIEW_ID)) { canvas = new DashboardsView("Dashboard"); - } else if (breadcrumbName.equals("Bundles")) { + } else if (breadcrumbName.equals(BundleTopView.VIEW_ID)) { canvas = new BundleTopView("Bundle"); } else if (breadcrumbName.equals("LogOut")) { canvas = new LoginView(); UserSessionManager.logout(); - } else if (breadcrumbName.equals("Tag")) { + } else if (breadcrumbName.equals(TaggedView.VIEW_ID)) { canvas = new TaggedView("Tag"); } else if (breadcrumbName.equals("Subsystems")) { canvas = new AlertsView("Alert"); - } else if (breadcrumbName.equals("Reports")) { + } else if (breadcrumbName.equals(ReportTopView.VIEW_ID)) { canvas = new ReportTopView("Report"); } else { canvas = null; @@ -315,7 +316,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
private static String getDefaultView() { // TODO: should this be Dashboard or a User Preference? - return ""; + return DEFAULT_VIEW_PATH; }
public static void setContent(Canvas newContent) { @@ -336,7 +337,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // We're already there - just refresh the view. refresh(); } else { - if (viewPath.matches("(Resource|ResourceGroup)/[^/]*")) { + 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 - @@ -374,7 +375,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
// After a user initiated logout start back at the default view if ("LogOut".equals(CoreGUI.currentPath)) { - History.newItem(getDefaultView()); + History.newItem(DEFAULT_VIEW_PATH); } } }); @@ -397,7 +398,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { public void renderView(ViewPath viewPath) { if (viewPath.isEnd()) { // default view - History.newItem("Dashboard"); + History.newItem(DEFAULT_VIEW_PATH); } else { if (!viewPath.getCurrent().equals(currentViewId)) { currentViewId = viewPath.getCurrent(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java index 935f351..bd0aabe 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/DemoCanvas.java @@ -38,6 +38,7 @@ import org.rhq.enterprise.gui.coregui.client.report.tag.TagCloudView; * @author Greg Hinkle */ public class DemoCanvas extends Canvas { + public static final String VIEW_ID = "Demo";
@Override protected void onInit() { 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 9bede31..0bc285d 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 @@ -116,7 +116,7 @@ public class UserSessionManager { }
public static boolean isLoggedIn() { - System.out.println("isLoggedIn = " + loggedIn); + //System.out.println("isLoggedIn = " + loggedIn); return loggedIn; }
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 8715366..b0cd874 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 @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.admin;
import java.util.LinkedHashMap; +import java.util.Map;
import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.Canvas; @@ -47,8 +48,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; * @author Greg Hinkle */ public class AdministrationView extends LocatableHLayout implements BookmarkableView { - - public static final String VIEW_PATH = "Administration"; + public static final String VIEW_ID = "Administration";
private ViewId currentSectionViewId; private ViewId currentPageViewId; @@ -57,7 +57,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
private Canvas contentCanvas; private Canvas currentContent; - private LinkedHashMap<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>(); + private Map<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>();
public AdministrationView(String locatorId) { super(locatorId); @@ -104,7 +104,6 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
addMember(sectionStack); addMember(contentCanvas); - }
private HTMLFlow defaultView() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java index 20188dd..7da68cd 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java @@ -39,6 +39,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack * @author Greg Hinkle */ public class BundleTopView extends LocatableHLayout implements BookmarkableView { + public static final String VIEW_ID = "Bundles"; + private BundleTreeView bundleTreeView;
private VLayout contentCanvas; 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 bc6076a..fb382fa 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 @@ -66,8 +66,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTabSet; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
public class BundleView extends LocatableVLayout implements BookmarkableView { - - LocatableDynamicForm form; + private LocatableDynamicForm form;
private int bundleBeingViewed = 0; private HeaderLabel headerLabel; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java index c3dea19..7e0fb8e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java @@ -66,6 +66,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Greg Hinkle */ public class DashboardsView extends LocatableVLayout implements BookmarkableView { + public static final String VIEW_ID = "Dashboard";
private TabSet tabSet;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java index 361a1f7..0336a29 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java @@ -117,7 +117,7 @@ public class InventorySummaryView extends LocatableVLayout implements Portlet { item.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { // TODO Figure out to where the click events should be navigating - History.newItem(InventoryView.VIEW_PATH); + History.newItem(InventoryView.VIEW_ID); } });
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..be66cb9 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 @@ -61,7 +61,6 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTyp */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { public static final String AUTO_GROUP_VIEW_PATH = "Resource/AutoGroup"; - public static final String GROUP_VIEW_PATH = "ResourceGroup";
private Integer groupId; private ResourceGroupComposite groupComposite; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java index 3e87e03..5c8670e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java @@ -32,6 +32,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; * @author Greg Hinkle */ public class ResourceGroupTopView extends LocatableHLayout implements BookmarkableView { + public static final String VIEW_ID = "ResourceGroup";
private Canvas contentCanvas; private ResourceGroupTreeView treeView; @@ -48,8 +49,8 @@ public class ResourceGroupTopView extends LocatableHLayout implements Bookmarkab setWidth100(); setHeight100();
- treeView = new ResourceGroupTreeView(getLocatorId()); - detailView = new ResourceGroupDetailView(extendLocatorId("Detail"), ResourceGroupDetailView.GROUP_VIEW_PATH); + treeView = new ResourceGroupTreeView(extendLocatorId("Tree")); + detailView = new ResourceGroupDetailView(extendLocatorId("Detail"), ResourceGroupTopView.VIEW_ID); addMember(treeView);
contentCanvas = new Canvas(); 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 01511fb..6c9127b 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 @@ -119,7 +119,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka // The root group was selected. String groupId = selectedNode.getAttribute("id"); //System.out.println("Selecting group [" + groupId + "]..."); - String viewPath = "ResourceGroup/" + groupId; + String viewPath = ResourceGroupTopView.VIEW_ID + "/" + groupId; String currentViewPath = History.getToken(); if (!currentViewPath.startsWith(viewPath)) { CoreGUI.goToView(viewPath); @@ -250,7 +250,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka @Override public void onSuccess(ResourceGroup result) { int groupId = result.getId(); - History.newItem("ResourceGroup/" + groupId); + History.newItem(ResourceGroupTopView.VIEW_ID + "/" + groupId); } }); } @@ -274,7 +274,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka Tree tree = new Tree();
tree.setRoot(fakeRoot); - TreeUtility.printTree(tree); + //TreeUtility.printTree(tree);
treeGrid.setData(tree); treeGrid.markForRedraw(); @@ -316,7 +316,6 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
// Insert an autoTypeGroup node if the type is not a singleton. if (!childType.isSingleton()) { - // Otherwise insert an autoTypeGroup folder node to group all cluster groups of this type. TreeNode autoTypeGroupNode = createAutoTypeGroupNode(childType, nodesByType); nodesByType.clear(); nodesByType.add(autoTypeGroupNode); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index f94170b..e102771 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -56,8 +56,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; * @author Joseph Marques */ public class InventoryView extends LocatableHLayout implements BookmarkableView { - - public static final String VIEW_PATH = "Inventory"; + public static final String VIEW_ID = "Inventory";
private static final String SECTION_GROUPS = "Groups"; private static final String SECTION_RESOURCES = "Resources"; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 030eb2b..b2cadc1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -319,7 +319,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo new Message("Resource with id [" + resourceId + "] does not exist or is not accessible.", Message.Severity.Warning));
- CoreGUI.goToView(InventoryView.VIEW_PATH); + CoreGUI.goToView(InventoryView.VIEW_ID); }
public void onSuccess(PageList<ResourceComposite> result) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java index 01b72dd..836b35e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java @@ -29,6 +29,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; * @author Greg Hinkle */ public class ResourceTopView extends LocatableHLayout implements BookmarkableView { + public static final String VIEW_ID = "Resource";
private Canvas contentCanvas; private ResourceTreeView treeView; 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 f5f7dce..233637e 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 @@ -56,8 +56,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_PATH = "Reports"; + public static final String VIEW_ID = "Reports";
private static final String SECTION_INVENTORY = "Inventory"; private static final String SECTION_REPORTS = "Reports"; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java index 66ff323..20ddd34 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java @@ -42,6 +42,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Greg Hinkle */ public class TaggedView extends LocatableVLayout implements BookmarkableView { + public static final String VIEW_ID = "Tag";
private TagCloudView tagCloudView;
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 64abb7e08a090c0c44bdc64b31bb56adfdeb2805 Author: John Mazzitelli mazz@redhat.com Date: Tue Sep 28 08:35:16 2010 -0400
BZ 616918 - default the "detailed discovery" boolean parameter to true
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 22f4cb1..5a4a8a7 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 @@ -11,7 +11,7 @@ <!ENTITY platformOperations ' <operation name="discovery" displayName="Manual Autodiscovery" description="Run an immediate discovery to search for resources"> <parameters> - <c:simple-property name="detailedDiscovery" description="If true, search for detailed child resources in addition to parent servers." type="boolean"/> + <c:simple-property name="detailedDiscovery" description="If true, search for detailed child resources in addition to parent servers." type="boolean" default="true" required="true"/> </parameters> <results> <c:simple-property name="operationResult" type="longString"/>
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 3f9a45b1b1dbbcdfb07009c71c4dd2bc202eba45 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Sep 28 09:57:30 2010 +0200
fix for the rare NPE in the disambiguation which could happen in the views that contained multiple results for single resource (e.g. list of alert history across all resources)
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/Disambiguator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/Disambiguator.java index 617d4fd..01d60fc 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/Disambiguator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/Disambiguator.java @@ -34,6 +34,8 @@ import javax.persistence.Query;
import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.util.IntExtractor; +import org.rhq.enterprise.server.resource.disambiguation.MutableDisambiguationReport.Resource; +import org.rhq.enterprise.server.resource.disambiguation.MutableDisambiguationReport.ResourceType;
/** * This is basically a helper class that provides the disambiguation method. @@ -197,8 +199,8 @@ public class Disambiguator {
//update all the reports that correspond to this resourceId for (MutableDisambiguationReport<T> report : reportsByResourceId.get(resourceId)) { - report.resource = resource; - report.parents = parents; + report.resource = resource.clone(); + report.parents = deepCopy(parents);
partitionedReports.put(report); } @@ -290,4 +292,13 @@ public class Disambiguator { } } } + + private static List<Resource> deepCopy(List<Resource> original) { + ArrayList<Resource> copy = new ArrayList<Resource>(); + + for (Resource o : original) { + copy.add(o.clone()); + } + return copy; + } } 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 68995d9..3084285 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 @@ -38,7 +38,7 @@ import org.rhq.core.domain.resource.composite.DisambiguationReport; * @author Lukas Krejci */ public class MutableDisambiguationReport<T> { - public static class ResourceType { + public static class ResourceType implements Cloneable { public int id; public String name; public String plugin; @@ -51,9 +51,20 @@ public class MutableDisambiguationReport<T> { public String toString() { return "MutableResourceType[id=" + id + ", name='" + name + "', plugin='" + plugin + "', singleton=" + singleton + "]"; } + + @Override + public ResourceType clone() { + ResourceType ret = new ResourceType(); + ret.id = id; + ret.name = name; + ret.plugin = plugin; + ret.singleton = singleton; + + return ret; + } }
- public static class Resource { + public static class Resource implements Cloneable { public int id; public String name; public MutableDisambiguationReport.ResourceType resourceType; @@ -65,6 +76,16 @@ public class MutableDisambiguationReport<T> { public String toString() { return "MutableResource[id=" + id + ", name='" + name + ", resourceType=" + resourceType + "]"; } + + @Override + public Resource clone() { + Resource ret = new Resource(); + ret.id = id; + ret.name = name; + ret.resourceType = resourceType.clone(); + + return ret; + } }
public T original;
commit 6c22cc997a52ed1bc1f27244cfb3b548b952770d Author: Ian Springer ian.springer@redhat.com Date: Mon Sep 27 20:41:53 2010 -0400
add subcategory nodes to group tree
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java index 89583b4..11a78dc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java @@ -24,6 +24,17 @@ import com.smartgwt.client.widgets.tree.TreeNode; * @author Ian Springer */ public class EnhancedTreeNode extends TreeNode { + public EnhancedTreeNode() { + } + + public EnhancedTreeNode(String name) { + super(name); + } + + public EnhancedTreeNode(String name, TreeNode... children) { + super(name, children); + } + public String getID() { return getAttribute(Attributes.ID); } 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 f54ffd2..01511fb 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 @@ -23,6 +23,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail;
import java.util.ArrayList; +import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -42,6 +43,7 @@ import com.smartgwt.client.widgets.tree.events.NodeContextClickEvent; import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler;
import org.rhq.core.domain.criteria.ResourceGroupCriteria; +import org.rhq.core.domain.resource.ResourceSubCategory; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ClusterKey; import org.rhq.core.domain.resource.group.GroupCategory; @@ -53,9 +55,11 @@ import org.rhq.enterprise.gui.coregui.client.BookmarkableView; 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.components.tree.EnhancedTreeNode; 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.util.StringUtility; +import org.rhq.enterprise.gui.coregui.client.util.TreeUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -107,19 +111,23 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka if (selectionEvent.getState()) { Record selectedNode = selectionEvent.getRecord(); System.out.println("Node selected in tree: " + selectedNode); - ClusterKey key = (ClusterKey) selectedNode.getAttributeAsObject("key"); - if (key == null) { - // The root group was selected. - String groupId = selectedNode.getAttribute("id"); - //System.out.println("Selecting group [" + groupId + "]..."); - String viewPath = "ResourceGroup/" + groupId; - String currentViewPath = History.getToken(); - if (!currentViewPath.startsWith(viewPath)) { - CoreGUI.goToView(viewPath); + ResourceType type = (ResourceType) selectedNode.getAttributeAsObject("resourceType"); + if (type != null) { + // It's a cluster group node, not a subcategory node or an autoTypeGroup node. + ClusterKey key = (ClusterKey) selectedNode.getAttributeAsObject("key"); + if (key == null) { + // The root group was selected. + String groupId = selectedNode.getAttribute("id"); + //System.out.println("Selecting group [" + groupId + "]..."); + String viewPath = "ResourceGroup/" + groupId; + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); + } + } else { + //System.out.println("Selecting cluster group [" + key + "]..."); + selectClusterGroup(key); } - } else { - //System.out.println("Selecting cluster group [" + key + "]..."); - selectClusterGroup(key); } } } @@ -221,6 +229,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka getTreeTypes(root, typeIds);
ResourceTypeRepository.Cache.getInstance().getResourceTypes(typeIds.toArray(new Integer[typeIds.size()]), + EnumSet.of(ResourceTypeRepository.MetadataType.subCategory), new ResourceTypeRepository.TypesLoadedCallback() { @Override public void onTypesLoaded(Map<Integer, ResourceType> types) { @@ -261,10 +270,11 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
ClusterKey rootKey = new ClusterKey(root.getGroupId()); loadTree(rootNode, root, rootKey); - + Tree tree = new Tree();
tree.setRoot(fakeRoot); + TreeUtility.printTree(tree);
treeGrid.setData(tree); treeGrid.markForRedraw(); @@ -288,11 +298,13 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
// Second pass - process each of the sets of like-typed children created in the first pass. List<TreeNode> childNodes = new ArrayList<TreeNode>(); - for (ResourceType type : childrenByType.keySet()) { - List<ClusterFlyweight> children = childrenByType.get(type); + Map<String, TreeNode> subCategoryNodesByName = new HashMap<String, TreeNode>(); + Map<String, List<TreeNode>> subCategoryChildrenByName = new HashMap<String, List<TreeNode>>(); + for (ResourceType childType : childrenByType.keySet()) { + List<ClusterFlyweight> children = childrenByType.get(childType); List<TreeNode> nodesByType = new ArrayList<TreeNode>(); for (ClusterFlyweight child : children) { - TreeNode node = createClusterGroupNode(parentKey, type, child); + TreeNode node = createClusterGroupNode(parentKey, childType, child); nodesByType.add(node);
if (!child.getChildren().isEmpty()) { @@ -302,23 +314,66 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka } }
- // TODO (ips): Insert subcategory nodes. + // Insert an autoTypeGroup node if the type is not a singleton. + if (!childType.isSingleton()) { + // Otherwise insert an autoTypeGroup folder node to group all cluster groups of this type. + TreeNode autoTypeGroupNode = createAutoTypeGroupNode(childType, nodesByType); + nodesByType.clear(); + nodesByType.add(autoTypeGroupNode); + } + + // Insert subcategory node(s) if the type has a subcategory. + ResourceSubCategory subcategory = childType.getSubCategory(); + if (subcategory != null) { + TreeNode lastSubcategoryNode = null; + + ResourceSubCategory currentSubCategory = subcategory; + boolean currentSubcategoryNodeCreated = false; + do { + TreeNode currentSubcategoryNode = subCategoryNodesByName.get(currentSubCategory.getName()); + if (currentSubcategoryNode == null) { + currentSubcategoryNode = new EnhancedTreeNode(currentSubCategory.getName()); + // Note, subcategory names are typically already plural, so there's no need to pluralize them. + currentSubcategoryNode.setTitle(currentSubCategory.getDisplayName()); + currentSubcategoryNode.setIsFolder(true); + subCategoryNodesByName.put(currentSubCategory.getName(), currentSubcategoryNode); + subCategoryChildrenByName.put(currentSubCategory.getName(), new ArrayList<TreeNode>()); + + if (currentSubCategory.getParentSubCategory() == null) { + // It's a root subcategory - add a node for it to the tree. + childNodes.add(currentSubcategoryNode); + } + + currentSubcategoryNodeCreated = true; + } + + if (lastSubcategoryNode != null) { + List<TreeNode> currentSubcategoryChildren = subCategoryChildrenByName.get(currentSubcategoryNode.getName()); + currentSubcategoryChildren.add(lastSubcategoryNode); + } + lastSubcategoryNode = currentSubcategoryNode; + } while (currentSubcategoryNodeCreated && + (currentSubCategory = currentSubCategory.getParentSubCategory()) != null);
- if (type.isSingleton()) { - // If it's a singleton type, just insert the cluster group node as is. + List<TreeNode> subcategoryChildren = subCategoryChildrenByName.get(subcategory.getName()); + subcategoryChildren.addAll(nodesByType); + } else { childNodes.addAll(nodesByType); - } else { - // Otherwise insert an autoTypeGroup folder node to group all cluster groups of this type. - TreeNode autoTypeGroupNode = createAutoTypeGroupNode(type, nodesByType); - childNodes.add(autoTypeGroupNode); } } + + for (String subcategoryName : subCategoryNodesByName.keySet()) { + TreeNode subcategoryNode = subCategoryNodesByName.get(subcategoryName); + List<TreeNode> subcategoryChildren = subCategoryChildrenByName.get(subcategoryName); + subcategoryNode.setChildren(subcategoryChildren.toArray(new TreeNode[subcategoryChildren.size()])); + } + parentNode.setChildren(childNodes.toArray(new TreeNode[childNodes.size()])); } }
private TreeNode createClusterGroupNode(ClusterKey parentKey, ResourceType type, ClusterFlyweight child) { - TreeNode node = new TreeNode(child.getName()); + TreeNode node = new EnhancedTreeNode(child.getName());
ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight.getResourceKey()); @@ -335,16 +390,18 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
private TreeNode createAutoTypeGroupNode(ResourceType type, List<TreeNode> memberNodes) { String name = StringUtility.pluralize(type.getName()); - TreeNode autoTypeGroupNode = new TreeNode(name); + TreeNode autoTypeGroupNode = new EnhancedTreeNode(name); autoTypeGroupNode.setIsFolder(true); autoTypeGroupNode.setChildren(memberNodes.toArray(new TreeNode[memberNodes.size()])); return autoTypeGroupNode; }
public void renderView(ViewPath viewPath) { - currentViewId = viewPath.getCurrent(); - int groupId = Integer.parseInt(currentViewId.getPath()); - setSelectedGroup(groupId); + this.currentViewId = viewPath.getCurrent(); + if (this.currentViewId != null) { + int groupId = Integer.parseInt(this.currentViewId.getPath()); + setSelectedGroup(groupId); + } }
private void getTreeTypes(ClusterFlyweight clusterFlyweight, Set<Integer> typeIds) {
commit d6b4553df4da88b0964eb89b0dc8b4af49ae7d8b Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Sep 27 17:50:04 2010 -0400
If setting to platforms viewpath issue an event. Otherwise selecting 'Platforms' from the section stack does nothing as it is "invisibly" selected already. But, moreover, comment out the whole thing and don't display any content for the Inventory section, until the user chooses something from the left nav.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index 01f23a2..f94170b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -315,8 +315,10 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView public void renderView(ViewPath viewPath) { if (!viewPath.isCurrent(currentSectionViewId) || !viewPath.isNext(currentPageViewId)) { if (viewPath.isEnd()) { - // i.e. "Inventory" - display default view - History.newItem("Inventory/Resources/Platforms", false); + // i.e. "Inventory" + // Currently, leave content empty until the user selects something from section stack. To default + // to platform list uncomment following line. + // History.newItem("Inventory/Resources/Platforms", true); } else { // e.g. Inventory/Administration" renderContentView(viewPath);
commit 2deb29dd26fec00c9d28c6b6d75a823252f9c1c6 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Sep 27 16:35:32 2010 -0400
Introduce AutoGroup Context Menu. - Extracted ResourceGroupContextMenu out of ResourceGroupTreeContextMenu so that both autogroup and clustergroup backing groups could utilize the same ResourceGroup context menu code.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java new file mode 100644 index 0000000..b31c33e --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java @@ -0,0 +1,306 @@ +/* + * 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.inventory.groups.detail; + +import java.util.EnumSet; +import java.util.List; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.CloseClickHandler; +import com.smartgwt.client.widgets.events.CloseClientEvent; +import com.smartgwt.client.widgets.menu.Menu; +import com.smartgwt.client.widgets.menu.MenuItem; +import com.smartgwt.client.widgets.menu.MenuItemSeparator; +import com.smartgwt.client.widgets.menu.events.ClickHandler; +import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent; + +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.criteria.ResourceTypeCriteria; +import org.rhq.core.domain.dashboard.Dashboard; +import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.operation.OperationDefinition; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.resource.graph.GraphPortlet; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; + +/** + * @author Greg Hinkle + */ +public class ResourceGroupContextMenu extends Menu { + + private ResourceType currentType; + //private ResourceGroup group; + private ResourceGroup currentGroup; + + public void showContextMenu(ResourceGroup compatibleGroup) { + this.currentType = compatibleGroup.getResourceType(); + this.currentGroup = compatibleGroup; + + ResourceTypeRepository.Cache.getInstance().getResourceTypes( + currentType.getId(), + EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, + ResourceTypeRepository.MetadataType.subCategory, + ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, + ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), + new ResourceTypeRepository.TypeLoadedCallback() { + public void onTypesLoaded(ResourceType type) { + + currentType = type; + + buildResourceGroupContextMenu(currentGroup, type); + showContextMenu(); + } + }); + + } + + private void buildResourceGroupContextMenu(final ResourceGroup group, final ResourceType resourceType) { + setItems(new MenuItem(group.getName())); + + addItem(new MenuItem("Type: " + resourceType.getName())); + + MenuItem editPluginConfiguration = new MenuItem("Plugin Configuration"); + editPluginConfiguration.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + int groupId = group.getId(); + int resourceTypeId = resourceType.getId(); + + Window configEditor = new Window(); + // configEditor.setTitle("Edit " + group.getName() + " plugin configuration"); + configEditor.setWidth(800); + configEditor.setHeight(800); + configEditor.setIsModal(true); + configEditor.setShowModalMask(true); + configEditor.setCanDragResize(true); + configEditor.centerInPage(); + // TODO Group config editor + // configEditor.addItem(new ConfigurationEditor(resourceId, resourceTypeId, + // ConfigurationEditor.ConfigType.plugin)); + configEditor.show(); + + } + }); + editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); + addItem(editPluginConfiguration); + + MenuItem editResourceConfiguration = new MenuItem("Resource Configuration"); + editResourceConfiguration.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + int groupId = group.getId(); + int resourceTypeId = resourceType.getId(); + + final Window configEditor = new Window(); + configEditor.setTitle("Edit " + group.getName() + " resource configuration"); + configEditor.setWidth(800); + configEditor.setHeight(800); + configEditor.setIsModal(true); + configEditor.setShowModalMask(true); + configEditor.setCanDragResize(true); + configEditor.setShowResizer(true); + configEditor.centerInPage(); + configEditor.addCloseClickHandler(new CloseClickHandler() { + public void onCloseClick(CloseClientEvent closeClientEvent) { + configEditor.destroy(); + } + }); + // TODO group config editor + // configEditor.addItem(new ConfigurationEditor(resourceId, resourceTypeId, + // ConfigurationEditor.ConfigType.resource)); + configEditor.show(); + + } + }); + editResourceConfiguration.setEnabled(resourceType.getResourceConfigurationDefinition() != null); + addItem(editResourceConfiguration); + + addItem(new MenuItemSeparator()); + + // Operations Menu + MenuItem operations = new MenuItem("Operations"); + Menu opSubMenu = new Menu(); + if (resourceType.getOperationDefinitions() != null) { + for (final OperationDefinition operationDefinition : resourceType.getOperationDefinitions()) { + MenuItem operationItem = new MenuItem(operationDefinition.getDisplayName()); + operationItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + + // TODO Group version + // ResourceCriteria criteria = new ResourceCriteria(); + // criteria.addFilterId(selectedResourceId); + // + // GWTServiceLookup.getResourceService().findResourcesByCriteria(criteria, + // new AsyncCallback<PageList<Resource>>() { + // public void onFailure(Throwable caught) { + // CoreGUI.getErrorHandler() + // .handleError("Failed to get resource to run operation", caught); + // } + // + // public void onSuccess(PageList<Resource> result) { + // new OperationCreateWizard(result.get(0), operationDefinition).startOperationWizard(); + // } + // }); + + } + }); + opSubMenu.addItem(operationItem); + } + } + operations.setEnabled(resourceType.getOperationDefinitions() != null + && !resourceType.getOperationDefinitions().isEmpty()); + operations.setSubmenu(opSubMenu); + addItem(operations); + + addItem(buildMetricsMenu(resourceType)); + + /* TODO: We don't support group factory create + // Create Menu + MenuItem createChildMenu = new MenuItem("Create Child"); + Menu createChildSubMenu = new Menu(); + 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); + } + }); + + } + } + createChildMenu.setSubmenu(createChildSubMenu); + createChildMenu.setEnabled(createChildSubMenu.getItems().length > 0); + contextMenu.addItem(createChildMenu);*/ + + /* + // TODO We don't group manual import + // Manually Add Menu + MenuItem importChildMenu = new MenuItem("Import"); + Menu importChildSubMenu = new Menu(); + for (ResourceType childType : resourceType.getChildResourceTypes()) { + if (childType.isSupportsManualAdd()) { + importChildSubMenu.addItem(new MenuItem(childType.getName())); + } + } + if (resourceType.getCategory() == ResourceCategory.PLATFORM) { + loadManuallyAddServersToPlatforms(importChildSubMenu); + } + importChildMenu.setSubmenu(importChildSubMenu); + importChildMenu.setEnabled(importChildSubMenu.getItems().length > 0); + addItem(importChildMenu); + */ + } + + private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu) { + ResourceTypeGWTServiceAsync rts = GWTServiceLookup.getResourceTypeGWTService(); + + ResourceTypeCriteria criteria = new ResourceTypeCriteria(); + criteria.addFilterSupportsManualAdd(true); + criteria.fetchParentResourceTypes(true); + rts.findResourceTypesByCriteria(criteria, new AsyncCallback<PageList<ResourceType>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load platform manual add children", caught); + } + + public void onSuccess(PageList<ResourceType> result) { + for (ResourceType type : result) { + if (type.getParentResourceTypes() == null || type.getParentResourceTypes().isEmpty()) { + MenuItem item = new MenuItem(type.getName()); + manuallyAddMenu.addItem(item); + } + } + } + }); + } + + private MenuItem buildMetricsMenu(final ResourceType type) { + MenuItem measurements = new MenuItem("Measurements"); + final Menu measurementsSubMenu = new Menu(); + + GWTServiceLookup.getDashboardService().findDashboardsForSubject(new AsyncCallback<List<Dashboard>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load user dashboards", caught); + } + + public void onSuccess(List<Dashboard> result) { + + if (type.getMetricDefinitions() != null) { + for (final MeasurementDefinition def : type.getMetricDefinitions()) { + + MenuItem defItem = new MenuItem(def.getDisplayName()); + measurementsSubMenu.addItem(defItem); + Menu defSubItem = new Menu(); + defItem.setSubmenu(defSubItem); + + for (final Dashboard d : result) { + MenuItem addToDBItem = new MenuItem("Add chart to Dashboard: " + d.getName()); + defSubItem.addItem(addToDBItem); + + addToDBItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent menuItemClickEvent) { + + DashboardPortlet p = new DashboardPortlet(def.getDisplayName() + " Chart", + GraphPortlet.KEY, 250); + p.getConfiguration().put( + new PropertySimple(GraphPortlet.CFG_RESOURCE_GROUP_ID, currentGroup.getId())); + p.getConfiguration().put( + new PropertySimple(GraphPortlet.CFG_DEFINITION_ID, def.getId())); + + d.addPortlet(p, 0, 0); + + GWTServiceLookup.getDashboardService().storeDashboard(d, + new AsyncCallback<Dashboard>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failed to save dashboard to server", caught); + } + + public void onSuccess(Dashboard result) { + CoreGUI.getMessageCenter().notify( + new Message("Saved dashboard " + result.getName() + " to server", + Message.Severity.Info)); + } + }); + + } + }); + + } + + } + } + + } + }); + measurements.setSubmenu(measurementsSubMenu); + return measurements; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java index 8e1e178..16c6369 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java @@ -22,328 +22,53 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail;
-import java.util.EnumSet; -import java.util.List; - import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.widgets.Window; -import com.smartgwt.client.widgets.events.CloseClickHandler; -import com.smartgwt.client.widgets.events.CloseClientEvent; -import com.smartgwt.client.widgets.menu.Menu; -import com.smartgwt.client.widgets.menu.MenuItem; -import com.smartgwt.client.widgets.menu.MenuItemSeparator; -import com.smartgwt.client.widgets.menu.events.ClickHandler; -import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent; import com.smartgwt.client.widgets.tree.TreeNode;
-import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.ResourceGroupCriteria; -import org.rhq.core.domain.criteria.ResourceTypeCriteria; -import org.rhq.core.domain.dashboard.Dashboard; -import org.rhq.core.domain.dashboard.DashboardPortlet; -import org.rhq.core.domain.measurement.MeasurementDefinition; -import org.rhq.core.domain.operation.OperationDefinition; -import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ClusterKey; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.resource.graph.GraphPortlet; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTServiceAsync; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; -import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * @author Greg Hinkle */ -public class ResourceGroupTreeContextMenu extends Menu { - - private ResourceType currentType; - private ResourceGroup group; - private ResourceGroup currentGroup; +public class ResourceGroupTreeContextMenu extends ResourceGroupContextMenu {
public void showContextMenu(TreeNode node) {
- currentType = (ResourceType) node.getAttributeAsObject("resourceType"); - - final ClusterKey clusterKey = (ClusterKey) node.getAttributeAsObject("key"); if (clusterKey != null) { GWTServiceLookup.getClusterService().createAutoClusterBackingGroup(clusterKey, true, - new AsyncCallback<ResourceGroup>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create or update auto-cluster group: " + clusterKey, caught); - } + new AsyncCallback<ResourceGroup>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failed to create or update auto-cluster group: " + clusterKey, caught); + }
- @Override - public void onSuccess(ResourceGroup result) { - showContextMenu(result); - } - }); + @Override + public void onSuccess(ResourceGroup result) { + showContextMenu(result); + } + }); } else { ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(Integer.parseInt(node.getAttribute("id"))); GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, - new AsyncCallback<PageList<ResourceGroup>>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load group for context menu", caught); - } - - @Override - public void onSuccess(PageList<ResourceGroup> result) { - showContextMenu(result.get(0)); - } - }); - } - - - } - - private void showContextMenu(ResourceGroup group) { - this.currentGroup = group; - - ResourceTypeRepository.Cache.getInstance().getResourceTypes( - currentType.getId(), - EnumSet.of(ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.children, - ResourceTypeRepository.MetadataType.subCategory, - ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, - ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), - new ResourceTypeRepository.TypeLoadedCallback() { - public void onTypesLoaded(ResourceType type) { - - currentType = type; - - - buildResourceGroupContextMenu(currentGroup, type); - showContextMenu(); + new AsyncCallback<PageList<ResourceGroup>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load group for context menu", caught); } - }); - - } - - - private void buildResourceGroupContextMenu(final ResourceGroup group, final ResourceType resourceType) { - setItems(new MenuItem(group.getName())); - - addItem(new MenuItem("Type: " + resourceType.getName())); - - MenuItem editPluginConfiguration = new MenuItem("Plugin Configuration"); - editPluginConfiguration.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - int groupId = group.getId(); - int resourceTypeId = resourceType.getId(); - - Window configEditor = new Window(); -// configEditor.setTitle("Edit " + group.getName() + " plugin configuration"); - configEditor.setWidth(800); - configEditor.setHeight(800); - configEditor.setIsModal(true); - configEditor.setShowModalMask(true); - configEditor.setCanDragResize(true); - configEditor.centerInPage(); - // TODO Group config editor -// configEditor.addItem(new ConfigurationEditor(resourceId, resourceTypeId, -// ConfigurationEditor.ConfigType.plugin)); - configEditor.show();
- } - }); - editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); - addItem(editPluginConfiguration); - - MenuItem editResourceConfiguration = new MenuItem("Resource Configuration"); - editResourceConfiguration.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - int groupId = group.getId(); - int resourceTypeId = resourceType.getId(); - - final Window configEditor = new Window(); - configEditor.setTitle("Edit " + group.getName() + " resource configuration"); - configEditor.setWidth(800); - configEditor.setHeight(800); - configEditor.setIsModal(true); - configEditor.setShowModalMask(true); - configEditor.setCanDragResize(true); - configEditor.setShowResizer(true); - configEditor.centerInPage(); - configEditor.addCloseClickHandler(new CloseClickHandler() { - public void onCloseClick(CloseClientEvent closeClientEvent) { - configEditor.destroy(); + @Override + public void onSuccess(PageList<ResourceGroup> result) { + showContextMenu(result.get(0)); } }); - // TODO group config editor -// configEditor.addItem(new ConfigurationEditor(resourceId, resourceTypeId, -// ConfigurationEditor.ConfigType.resource)); - configEditor.show(); - - } - }); - editResourceConfiguration.setEnabled(resourceType.getResourceConfigurationDefinition() != null); - addItem(editResourceConfiguration); - - addItem(new MenuItemSeparator()); - - // Operations Menu - MenuItem operations = new MenuItem("Operations"); - Menu opSubMenu = new Menu(); - if (resourceType.getOperationDefinitions() != null) { - for (final OperationDefinition operationDefinition : resourceType.getOperationDefinitions()) { - MenuItem operationItem = new MenuItem(operationDefinition.getDisplayName()); - operationItem.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - - // TODO Group version -// ResourceCriteria criteria = new ResourceCriteria(); -// criteria.addFilterId(selectedResourceId); -// -// GWTServiceLookup.getResourceService().findResourcesByCriteria(criteria, -// new AsyncCallback<PageList<Resource>>() { -// public void onFailure(Throwable caught) { -// CoreGUI.getErrorHandler() -// .handleError("Failed to get resource to run operation", caught); -// } -// -// public void onSuccess(PageList<Resource> result) { -// new OperationCreateWizard(result.get(0), operationDefinition).startOperationWizard(); -// } -// }); - - } - }); - opSubMenu.addItem(operationItem); - } - } - operations.setEnabled(resourceType.getOperationDefinitions() != null && !resourceType.getOperationDefinitions().isEmpty()); - operations.setSubmenu(opSubMenu); - addItem(operations); - - addItem(buildMetricsMenu(resourceType)); - - /* TODO: We don't support group factory create - // Create Menu - MenuItem createChildMenu = new MenuItem("Create Child"); - Menu createChildSubMenu = new Menu(); - 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); - } - }); - - } - } - createChildMenu.setSubmenu(createChildSubMenu); - createChildMenu.setEnabled(createChildSubMenu.getItems().length > 0); - contextMenu.addItem(createChildMenu);*/ - - /* - // TODO We don't group manual import - // Manually Add Menu - MenuItem importChildMenu = new MenuItem("Import"); - Menu importChildSubMenu = new Menu(); - for (ResourceType childType : resourceType.getChildResourceTypes()) { - if (childType.isSupportsManualAdd()) { - importChildSubMenu.addItem(new MenuItem(childType.getName())); - } - } - if (resourceType.getCategory() == ResourceCategory.PLATFORM) { - loadManuallyAddServersToPlatforms(importChildSubMenu); } - importChildMenu.setSubmenu(importChildSubMenu); - importChildMenu.setEnabled(importChildSubMenu.getItems().length > 0); - addItem(importChildMenu); - */ - } - - private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu) { - ResourceTypeGWTServiceAsync rts = GWTServiceLookup.getResourceTypeGWTService(); - - ResourceTypeCriteria criteria = new ResourceTypeCriteria(); - criteria.addFilterSupportsManualAdd(true); - criteria.fetchParentResourceTypes(true); - rts.findResourceTypesByCriteria(criteria, new AsyncCallback<PageList<ResourceType>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load platform manual add children", caught); - } - - public void onSuccess(PageList<ResourceType> result) { - for (ResourceType type : result) { - if (type.getParentResourceTypes() == null || type.getParentResourceTypes().isEmpty()) { - MenuItem item = new MenuItem(type.getName()); - manuallyAddMenu.addItem(item); - } - } - } - }); - } - - private MenuItem buildMetricsMenu(final ResourceType type) { - MenuItem measurements = new MenuItem("Measurements"); - final Menu measurementsSubMenu = new Menu(); - - GWTServiceLookup.getDashboardService().findDashboardsForSubject(new AsyncCallback<List<Dashboard>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load user dashboards", caught); - } - - public void onSuccess(List<Dashboard> result) { - - if (type.getMetricDefinitions() != null) { - for (final MeasurementDefinition def : type.getMetricDefinitions()) { - - MenuItem defItem = new MenuItem(def.getDisplayName()); - measurementsSubMenu.addItem(defItem); - Menu defSubItem = new Menu(); - defItem.setSubmenu(defSubItem); - - for (final Dashboard d : result) { - MenuItem addToDBItem = new MenuItem("Add chart to Dashboard: " + d.getName()); - defSubItem.addItem(addToDBItem); - - addToDBItem.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent menuItemClickEvent) { - - DashboardPortlet p = new DashboardPortlet(def.getDisplayName() + " Chart", - GraphPortlet.KEY, 250); - p.getConfiguration().put( - new PropertySimple(GraphPortlet.CFG_RESOURCE_GROUP_ID, group.getId())); - p.getConfiguration().put( - new PropertySimple(GraphPortlet.CFG_DEFINITION_ID, def.getId())); - - d.addPortlet(p, 0, 0); - - GWTServiceLookup.getDashboardService().storeDashboard(d, - new AsyncCallback<Dashboard>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to save dashboard to server", - caught); - } - - public void onSuccess(Dashboard result) { - CoreGUI.getMessageCenter().notify( - new Message("Saved dashboard " + result.getName() + " to server", - Message.Severity.Info)); - } - }); - - } - }); - - } - - } - } - - } - }); - measurements.setSubmenu(measurementsSubMenu); - return measurements; } } 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 2c7a973..6a7cba9 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 @@ -75,6 +75,7 @@ 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.gwt.ResourceGroupGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupContextMenu; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.AutoGroupTreeNode; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.ResourceTreeNode; @@ -91,12 +92,14 @@ public class ResourceTreeView extends LocatableVLayout {
private TreeGrid treeGrid; private String selectedNodeId; - private Menu contextMenu;
private Resource rootResource;
private ViewId currentViewId;
+ private Menu resourceContextMenu; + private ResourceGroupContextMenu autoGroupContextMenu; + private List<ResourceSelectListener> selectListeners = new ArrayList<ResourceSelectListener>();
// Maps autogroup/type backing group ids to the corresponding autogroup/type nodes. @@ -131,7 +134,8 @@ public class ResourceTreeView extends LocatableVLayout {
treeGrid.setLeaveScrollbarGap(false);
- contextMenu = new Menu(); + resourceContextMenu = new Menu(); + autoGroupContextMenu = new ResourceGroupContextMenu();
treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { @@ -152,7 +156,15 @@ public class ResourceTreeView extends LocatableVLayout {
AutoGroupTreeNode agNode = (AutoGroupTreeNode) selectedRecord; selectedNodeId = agNode.getID(); - handleSelectedAutoGroupNode(agNode); + getAutoGroupBackingGroup(agNode, new AsyncCallback<ResourceGroup>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to select autogroup node", caught); + } + + public void onSuccess(ResourceGroup result) { + renderAutoGroup(result); + } + }); } else { System.out.println("Unhandled Node selected in tree: " + selectedRecord); } @@ -161,7 +173,7 @@ public class ResourceTreeView extends LocatableVLayout { });
// This constructs the context menu for the resource at the time of the click. - setContextMenu(contextMenu); + // setContextMenu(resourceContextMenu);
treeGrid.addNodeContextClickHandler(new NodeContextClickHandler() { public void onNodeContextClick(final NodeContextClickEvent event) { @@ -183,7 +195,7 @@ public class ResourceTreeView extends LocatableVLayout { }); }
- private void handleSelectedAutoGroupNode(final AutoGroupTreeNode agNode) { + private void getAutoGroupBackingGroup(final AutoGroupTreeNode agNode, final AsyncCallback<ResourceGroup> callback) { final ResourceGroupGWTServiceAsync resourceGroupService = GWTServiceLookup.getResourceGroupService();
// get the children tree nodes and build a child resourceId array @@ -223,7 +235,8 @@ public class ResourceTreeView extends LocatableVLayout { // store a map entry from backingGroupId to AGTreeNode so we can easily // get back to this node given the id of the backing group (from the viewpath) autoGroupNodeMap.put(result.getId(), agNode); - renderAutoGroup(result); + callback.onSuccess(result); + //renderAutoGroup(result); } }); } else { @@ -243,13 +256,12 @@ public class ResourceTreeView extends LocatableVLayout { }
public void onSuccess(Void result) { - renderAutoGroup(backingGroup); + callback.onSuccess(backingGroup); } }); } } }); - }
private void renderAutoGroup(ResourceGroup backingGroup) { @@ -290,9 +302,16 @@ public class ResourceTreeView extends LocatableVLayout { } }
- private void showContextMenu(AutoGroupTreeNode node) { - contextMenu.setItems(new MenuItem(node.getName())); - contextMenu.showContextMenu(); + private void showContextMenu(AutoGroupTreeNode agNode) { + getAutoGroupBackingGroup(agNode, new AsyncCallback<ResourceGroup>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to select AutoGroup node", caught); + } + + public void onSuccess(ResourceGroup result) { + autoGroupContextMenu.showContextMenu(result); + } + }); }
private void showContextMenu(final ResourceTreeNode node) { @@ -306,15 +325,15 @@ public class ResourceTreeView extends LocatableVLayout { new ResourceTypeRepository.TypeLoadedCallback() { public void onTypesLoaded(ResourceType type) { buildResourceContextMenu(node.getResource(), type); - contextMenu.showContextMenu(); + resourceContextMenu.showContextMenu(); } }); }
private void buildResourceContextMenu(final Resource resource, final ResourceType resourceType) { - contextMenu.setItems(new MenuItem(resource.getName())); + resourceContextMenu.setItems(new MenuItem(resource.getName()));
- contextMenu.addItem(new MenuItem("Type: " + resourceType.getName())); + resourceContextMenu.addItem(new MenuItem("Type: " + resourceType.getName()));
MenuItem editPluginConfiguration = new MenuItem("Plugin Configuration"); editPluginConfiguration.addClickHandler(new ClickHandler() { @@ -337,7 +356,7 @@ public class ResourceTreeView extends LocatableVLayout { } }); editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); - contextMenu.addItem(editPluginConfiguration); + resourceContextMenu.addItem(editPluginConfiguration);
MenuItem editResourceConfiguration = new MenuItem("Resource Configuration"); editResourceConfiguration.addClickHandler(new ClickHandler() { @@ -366,9 +385,9 @@ public class ResourceTreeView extends LocatableVLayout { } }); editResourceConfiguration.setEnabled(resourceType.getResourceConfigurationDefinition() != null); - contextMenu.addItem(editResourceConfiguration); + resourceContextMenu.addItem(editResourceConfiguration);
- contextMenu.addItem(new MenuItemSeparator()); + resourceContextMenu.addItem(new MenuItemSeparator());
// Operations Menu MenuItem operations = new MenuItem("Operations"); @@ -402,9 +421,9 @@ public class ResourceTreeView extends LocatableVLayout { } operations.setEnabled(!resourceType.getOperationDefinitions().isEmpty()); operations.setSubmenu(opSubMenu); - contextMenu.addItem(operations); + resourceContextMenu.addItem(operations);
- contextMenu.addItem(buildMetricsMenu(resourceType)); + resourceContextMenu.addItem(buildMetricsMenu(resourceType));
// Create Menu MenuItem createChildMenu = new MenuItem("Create Child"); @@ -423,7 +442,7 @@ public class ResourceTreeView extends LocatableVLayout { } createChildMenu.setSubmenu(createChildSubMenu); createChildMenu.setEnabled(createChildSubMenu.getItems().length > 0); - contextMenu.addItem(createChildMenu); + resourceContextMenu.addItem(createChildMenu);
// Manually Add Menu MenuItem importChildMenu = new MenuItem("Import"); @@ -439,7 +458,7 @@ public class ResourceTreeView extends LocatableVLayout { } importChildMenu.setSubmenu(importChildSubMenu); importChildMenu.setEnabled(importChildSubMenu.getItems().length > 0); - contextMenu.addItem(importChildMenu); + resourceContextMenu.addItem(importChildMenu); }
private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu) {
commit 4632def4a92d6edfaffe118e07abd5135eb84c70 Merge: 67570cc... ab9648b... Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Sep 27 15:00:56 2010 -0400
Merge branch 'master' into master-jay
Conflicts: modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java index d701852,aa854f8..f54ffd2 --- 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 @@@ -54,12 -56,13 +55,14 @@@ import org.rhq.enterprise.gui.coregui.c import org.rhq.enterprise.gui.coregui.client.ViewPath; 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.util.StringUtility; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle + * @author Ian Springer */ -public class ResourceGroupTreeView extends VLayout implements BookmarkableView { +public class ResourceGroupTreeView extends LocatableVLayout implements BookmarkableView {
private TreeGrid treeGrid;
@@@ -73,8 -76,7 +76,9 @@@ private Map<Integer, ResourceType> typeMap; private ResourceGroup selectedGroup;
- public ResourceGroupTreeView() { + public ResourceGroupTreeView(String locatorId) { + super(locatorId); ++ setWidth(250); setHeight100(); } @@@ -152,35 -154,33 +156,33 @@@ ResourceGroup group = result.get(0); ResourceGroupTreeView.this.selectedGroup = group;
- if (GroupCategory.MIXED == group.getGroupCategory()) { + GroupCategory groupCategory = group.getGroupCategory(); + switch (groupCategory) { - case MIXED: ++ case MIXED: + ResourceGroupTreeView.this.rootResourceGroup = group; + ResourceGroupTreeView.this.rootGroupId = rootResourceGroup.getId(); + TreeNode fakeRoot = new TreeNode("fakeRootNode"); + TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); + rootNode.setID(String.valueOf(rootResourceGroup.getId())); //getClusterKey().toString()); + fakeRoot.setChildren(new TreeNode[] { rootNode }); + Tree tree = new Tree(); + tree.setRoot(fakeRoot); + treeGrid.setData(tree); + treeGrid.markForRedraw(); - } else { ++ break; ++ case COMPATIBLE: + if (group.getClusterResourceGroup() == null) { ++ // This is a straight up compatible group. ResourceGroupTreeView.this.rootResourceGroup = group; - // This is a straight up group - loadGroup(groupId); - ResourceGroupTreeView.this.rootGroupId = rootResourceGroup.getId(); - TreeNode fakeRoot = new TreeNode("fakeRootNode"); - TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); - rootNode.setID(String.valueOf(rootResourceGroup.getId())); //getClusterKey().toString()); - fakeRoot.setChildren(new TreeNode[] { rootNode }); - Tree tree = new Tree(); - tree.setRoot(fakeRoot); - treeGrid.setData(tree); - treeGrid.markForRedraw(); - break; - case COMPATIBLE: - if (group.getClusterResourceGroup() == null) { - // This is a straight up compatible group. - ResourceGroupTreeView.this.rootResourceGroup = group; - } else { - // This is a cluster group beneath a real recursive compatible group. - ResourceGroupTreeView.this.rootResourceGroup = group.getClusterResourceGroup(); - } - loadGroup(ResourceGroupTreeView.this.rootResourceGroup.getId()); - break; + } else { - // Someone select a cluster group beneath a real recursive compatible group - - ResourceGroup rootGroup = group.getClusterResourceGroup(); - ResourceGroupTreeView.this.rootResourceGroup = rootGroup; - - loadGroup(rootGroup.getId()); ++ // This is a cluster group beneath a real recursive compatible group. ++ ResourceGroupTreeView.this.rootResourceGroup = group.getClusterResourceGroup(); + } ++ loadGroup(ResourceGroupTreeView.this.rootResourceGroup.getId()); ++ break; } - } }); - }
private void loadGroup(int groupId) { @@@ -277,44 -268,79 +270,77 @@@ treeGrid.markForRedraw(); }
- public void loadTree(TreeNode parent, ClusterFlyweight parentNode, ClusterKey parentKey) { - if (!parentNode.getChildren().isEmpty()) { - - // TODO Introduce type groups (Do we still like this model for recursive compatibles?) - - ArrayList<TreeNode> childNodes = new ArrayList<TreeNode>(); - - HashMap<Integer, TreeNode> typeNodes = new HashMap<Integer, TreeNode>(); - - for (ClusterFlyweight child : parentNode.getChildren()) { - TreeNode node = new TreeNode(child.getName()); - + public void loadTree(TreeNode parentNode, ClusterFlyweight parentClusterGroup, ClusterKey parentKey) { + if (!parentClusterGroup.getChildren().isEmpty()) { + // First pass - group the children by type. + Map<ResourceType, List<ClusterFlyweight>> childrenByType = new HashMap<ResourceType, List<ClusterFlyweight>>(); + for (ClusterFlyweight child : parentClusterGroup.getChildren()) { ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); - ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight - .getResourceKey());
ResourceType type = this.typeMap.get(keyFlyweight.getResourceTypeId()); + List<ClusterFlyweight> children = childrenByType.get(type); + if (children == null) { + children = new ArrayList<ClusterFlyweight>(); + childrenByType.put(type, children); + } + children.add(child); + }
- String icon = "types/" + type.getCategory().getDisplayName() + "_up_16.png"; - - node.setIcon(icon); + // Second pass - process each of the sets of like-typed children created in the first pass. + List<TreeNode> childNodes = new ArrayList<TreeNode>(); + for (ResourceType type : childrenByType.keySet()) { + List<ClusterFlyweight> children = childrenByType.get(type); + List<TreeNode> nodesByType = new ArrayList<TreeNode>(); + for (ClusterFlyweight child : children) { + TreeNode node = createClusterGroupNode(parentKey, type, child); + nodesByType.add(node); + + if (!child.getChildren().isEmpty()) { + // Recurse. - ClusterKey key = (ClusterKey)node.getAttributeAsObject("key"); ++ ClusterKey key = (ClusterKey) node.getAttributeAsObject("key"); + loadTree(node, child, key); + } + }
- node.setID(key.getKey()); - node.setAttribute("key", key); - node.setAttribute("resourceType", type); - childNodes.add(node); + // TODO (ips): Insert subcategory nodes.
- if (child.getChildren().isEmpty()) { - node.setIsFolder(false); + if (type.isSingleton()) { + // If it's a singleton type, just insert the cluster group node as is. + childNodes.addAll(nodesByType); - } - else { + } else { - node.setIsFolder(true); - loadTree(node, child, key); + // Otherwise insert an autoTypeGroup folder node to group all cluster groups of this type. + TreeNode autoTypeGroupNode = createAutoTypeGroupNode(type, nodesByType); + childNodes.add(autoTypeGroupNode); } } - parent.setChildren(childNodes.toArray(new TreeNode[childNodes.size()])); + parentNode.setChildren(childNodes.toArray(new TreeNode[childNodes.size()])); } }
+ private TreeNode createClusterGroupNode(ClusterKey parentKey, ResourceType type, ClusterFlyweight child) { + TreeNode node = new TreeNode(child.getName()); + + ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); - ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight - .getResourceKey()); ++ ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight.getResourceKey()); + String id = key.getKey(); + node.setID(id); + node.setAttribute("key", key); + node.setAttribute("resourceType", type); + node.setIsFolder(!child.getChildren().isEmpty()); + + String icon = "types/" + type.getCategory().getDisplayName() + "_up_16.png"; + node.setIcon(icon); + return node; + } + + private TreeNode createAutoTypeGroupNode(ResourceType type, List<TreeNode> memberNodes) { + String name = StringUtility.pluralize(type.getName()); + TreeNode autoTypeGroupNode = new TreeNode(name); + autoTypeGroupNode.setIsFolder(true); + autoTypeGroupNode.setChildren(memberNodes.toArray(new TreeNode[memberNodes.size()])); + return autoTypeGroupNode; + } + public void renderView(ViewPath viewPath) { currentViewId = viewPath.getCurrent(); int groupId = Integer.parseInt(currentViewId.getPath());
commit 67570cc0877700278ddac9588700699dd9b99129 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Sep 27 14:26:21 2010 -0400
Initial support for Group-Backed AutoGroups - A lot of work to integrate autogroup nodes into the resource tree view such that the group renders in the tabbed view while maintaining a resource tree (not a group tree). - Tried to pare down code in resourceTreeView to only what is necessary. - Some more work pending: breadcrumb issues, context menu not yet there, direct url (saved url) does not always expand tree. - minor, prevent adding "s" to singulars ending in "s" in pluralization code.
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 f5c14c5..00a27f0 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 @@ -51,7 +51,6 @@ import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.bundle.BundleTopView; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardsView; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.AutoGroupTopView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupTopView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.InventoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTopView; @@ -292,8 +291,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { canvas = new ResourceTopView("Resource"); } else if (breadcrumbName.equals("ResourceGroup")) { canvas = new ResourceGroupTopView("Group"); - } else if (breadcrumbName.equals("AutoGroup")) { - canvas = new AutoGroupTopView("AutoGroup"); } else if (breadcrumbName.equals("Dashboard")) { canvas = new DashboardsView("Dashboard"); } else if (breadcrumbName.equals("Bundles")) { 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 e00ecbe..e5bfc72 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 @@ -60,7 +60,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTyp * @author Ian Springer */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { - public static final String AUTO_GROUP_VIEW_PATH = "AutoGroup"; + public static final String AUTO_GROUP_VIEW_PATH = "Resource/AutoGroup"; public static final String GROUP_VIEW_PATH = "ResourceGroup";
private Integer groupId; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java index ec96874..01b72dd 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java @@ -22,6 +22,7 @@ import com.smartgwt.client.widgets.Canvas;
import org.rhq.enterprise.gui.coregui.client.BookmarkableView; import org.rhq.enterprise.gui.coregui.client.ViewPath; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupDetailView; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** @@ -32,7 +33,7 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie private Canvas contentCanvas; private ResourceTreeView treeView; private ResourceDetailView detailView = new ResourceDetailView(extendLocatorId("Detail")); - + private ResourceGroupDetailView autoGroupDetailView;
public ResourceTopView(String locatorId) { super(locatorId); @@ -49,7 +50,6 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie setContent(detailView); }
- public void setContent(Canvas newContent) { for (Canvas child : this.contentCanvas.getChildren()) { child.destroy(); @@ -58,10 +58,27 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie this.contentCanvas.markForRedraw(); }
- public void renderView(ViewPath viewPath) { - this.treeView.renderView(viewPath); - this.detailView.renderView(viewPath); + if ("AutoGroup".equals(viewPath.getCurrent().getPath())) { + if (null == autoGroupDetailView) { + this.autoGroupDetailView = new ResourceGroupDetailView(this.extendLocatorId("AutoGroupDetail"), + ResourceGroupDetailView.AUTO_GROUP_VIEW_PATH); + this.setContent(this.autoGroupDetailView); + this.detailView = null; + } + this.treeView.renderView(viewPath); + this.autoGroupDetailView.renderView(viewPath.next()); + } else { + // Resource + if (null == detailView) { + this.detailView = new ResourceDetailView(extendLocatorId("Detail")); + this.setContent(this.detailView); + this.autoGroupDetailView = null; + } + this.treeView.renderView(viewPath); + this.detailView.renderView(viewPath); + } + }
} 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 07995df..3ad6835 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 @@ -287,13 +287,9 @@ public class ResourceTreeDatasource extends DataSource {
String id = idOf(resource); setID(id); - setAttribute(Attributes.ID, id);
String parentId = parentIdOf(resource); setParentID(parentId); - setAttribute(Attributes.PARENT_ID, parentId); - - // setAttribute("parentKey", parentId);
ResourceType type = resource.getResourceType(); String name = StringUtility.pluralize(type.getName()); @@ -326,12 +322,21 @@ public class ResourceTreeDatasource extends DataSource { * Given a Resource, generate a unique ID for the AGNode. * * @param resource requires resourceType field be set. requires parentResource field be set (null for no parent) - * @return The name string or null if the R + * @return The name string or null if the parentResource is null. */ public static String idOf(Resource resource) { Resource parentResource = resource.getParentResource(); - return (parentResource != null) ? "autogroup_" + resource.getResourceType().getId() + "_" - + parentResource.getId() : null; + return idOf(parentResource, resource.getResourceType()); + } + + /** + * Given a Resource, generate a unique ID for the AGNode. + * + * @param resource requires resourceType field be set. requires parentResource field be set (null for no parent) + * @return The name string or null if the parentResource is null; + */ + 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 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 b20cfb3..2c7a973 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 @@ -24,7 +24,9 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail;
import java.util.ArrayList; import java.util.EnumSet; +import java.util.HashMap; import java.util.List; +import java.util.Map;
import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; @@ -74,10 +76,11 @@ import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGroupGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.AutoGroupTreeNode; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.ResourceTreeNode; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.create.OperationCreateWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.factory.ResourceFactoryCreateWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; -import org.rhq.enterprise.gui.coregui.client.util.TreeUtility; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
@@ -86,18 +89,18 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class ResourceTreeView extends LocatableVLayout {
- private int selectedResourceId; - - private Resource rootResource; - private TreeGrid treeGrid; + private String selectedNodeId; private Menu contextMenu;
+ private Resource rootResource; + private ViewId currentViewId;
private List<ResourceSelectListener> selectListeners = new ArrayList<ResourceSelectListener>();
- private boolean initialSelect = false; + // Maps autogroup/type backing group ids to the corresponding autogroup/type nodes. + Map<Integer, AutoGroupTreeNode> autoGroupNodeMap = new HashMap<Integer, AutoGroupTreeNode>();
public ResourceTreeView(String locatorId) { super(locatorId); @@ -133,20 +136,25 @@ public class ResourceTreeView extends LocatableVLayout { treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { if (!selectionEvent.isRightButtonDown() && selectionEvent.getState()) { - ListGridRecord selectedNode = treeGrid.getSelectedRecord(); - if (selectedNode instanceof ResourceTreeDatasource.ResourceTreeNode) { - System.out.println("Resource Node selected in tree: " + selectedNode); - ResourceTreeDatasource.ResourceTreeNode resourceNode = (ResourceTreeDatasource.ResourceTreeNode) selectedNode; + 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); } - } else if (selectedNode instanceof ResourceTreeDatasource.AutoGroupTreeNode) { - System.out.println("AutoGroup Node selected in tree: " + selectedNode); - handleSelectedAutoGroupNode((ResourceTreeDatasource.AutoGroupTreeNode) selectedNode); + } else if (selectedRecord instanceof AutoGroupTreeNode) { + System.out.println("AutoGroup Node selected in tree: " + selectedRecord); + + AutoGroupTreeNode agNode = (AutoGroupTreeNode) selectedRecord; + selectedNodeId = agNode.getID(); + handleSelectedAutoGroupNode(agNode); } else { - System.out.println("Unhandled Node selected in tree: " + selectedNode); + System.out.println("Unhandled Node selected in tree: " + selectedRecord); } } } @@ -160,31 +168,29 @@ public class ResourceTreeView extends LocatableVLayout { event.getNode(); event.cancel();
- if (event.getNode() instanceof ResourceTreeDatasource.AutoGroupTreeNode) { - showContextMenu((ResourceTreeDatasource.AutoGroupTreeNode) event.getNode()); - } else if (event.getNode() instanceof ResourceTreeDatasource.ResourceTreeNode) { - showContextMenu((ResourceTreeDatasource.ResourceTreeNode) event.getNode()); + if (event.getNode() instanceof AutoGroupTreeNode) { + showContextMenu((AutoGroupTreeNode) event.getNode()); + } else if (event.getNode() instanceof ResourceTreeNode) { + showContextMenu((ResourceTreeNode) event.getNode()); } } });
treeGrid.addDataArrivedHandler(new DataArrivedHandler() { public void onDataArrived(DataArrivedEvent dataArrivedEvent) { - if (!initialSelect) { - updateBreadcrumbs(); - } + updateSelection(); } }); }
- private void handleSelectedAutoGroupNode(final ResourceTreeDatasource.AutoGroupTreeNode agNode) { + private void handleSelectedAutoGroupNode(final AutoGroupTreeNode agNode) { final ResourceGroupGWTServiceAsync resourceGroupService = GWTServiceLookup.getResourceGroupService();
// get the children tree nodes and build a child resourceId array TreeNode[] children = treeGrid.getTree().getChildren(agNode); final int[] childIds = new int[children.length]; for (int i = 0, size = children.length; (i < size); ++i) { - childIds[i] = ((ResourceTreeDatasource.ResourceTreeNode) children[i]).getResource().getId(); + childIds[i] = ((ResourceTreeNode) children[i]).getResource().getId(); }
// get the backing group if it exists, otherwise create the group @@ -214,12 +220,21 @@ public class ResourceTreeView extends LocatableVLayout { }
public void onSuccess(ResourceGroup result) { + // store a map entry from backingGroupId to AGTreeNode so we can easily + // get back to this node given the id of the backing group (from the viewpath) + autoGroupNodeMap.put(result.getId(), agNode); renderAutoGroup(result); } }); } else { - // backing group found, make sure the members are correct + // backing group found final ResourceGroup backingGroup = result.get(0); + + // store a map entry from backingGroupId to AGTreeNode so we can easily + // get back to this node given the id of the backing group (from the viewpath) + autoGroupNodeMap.put(backingGroup.getId(), agNode); + + // make sure the members are correct before rendering resourceGroupService.setAssignedResources(backingGroup.getId(), childIds, false, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { @@ -238,24 +253,28 @@ public class ResourceTreeView extends LocatableVLayout { }
private void renderAutoGroup(ResourceGroup backingGroup) { - String viewPath = "AutoGroup/" + backingGroup.getId(); + String viewPath = "Resource/AutoGroup/" + backingGroup.getId(); String currentViewPath = History.getToken(); if (!currentViewPath.startsWith(viewPath)) { CoreGUI.goToView(viewPath); } }
- private void updateBreadcrumbs() { - TreeNode selectedNode = treeGrid.getTree().findById( - ResourceTreeDatasource.ResourceTreeNode.idOf(selectedResourceId)); - // System.out.println("Trying to preopen: " + selectedNode); - if (selectedNode != null) { + private void updateSelection() { + + TreeNode selectedNode = null; + if (treeGrid != null && treeGrid.getTree() != null + && (selectedNode = treeGrid.getTree().findById(selectedNodeId)) != null) { + TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); treeGrid.getTree().openFolders(parents); treeGrid.getTree().openFolder(selectedNode);
- treeGrid.selectRecord(selectedNode); - initialSelect = true; + if (!selectedNode.equals(treeGrid.getSelectedRecord())) { + treeGrid.deselectAllRecords(); + treeGrid.selectRecord(selectedNode); + } + treeGrid.markForRedraw();
// Update breadcrumbs @@ -271,12 +290,12 @@ public class ResourceTreeView extends LocatableVLayout { } }
- private void showContextMenu(ResourceTreeDatasource.AutoGroupTreeNode node) { + private void showContextMenu(AutoGroupTreeNode node) { contextMenu.setItems(new MenuItem(node.getName())); contextMenu.showContextMenu(); }
- private void showContextMenu(final ResourceTreeDatasource.ResourceTreeNode node) { + private void showContextMenu(final ResourceTreeNode node) { ResourceType type = node.getResource().getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( type.getId(), @@ -358,9 +377,11 @@ public class ResourceTreeView extends LocatableVLayout { MenuItem operationItem = new MenuItem(operationDefinition.getDisplayName()); operationItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { + int resourceId = ((ResourceTreeNode) treeGrid.getTree().findById(selectedNodeId)).getResource() + .getId();
ResourceCriteria criteria = new ResourceCriteria(); - criteria.addFilterId(selectedResourceId); + criteria.addFilterId(resourceId);
GWTServiceLookup.getResourceService().findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { @@ -467,11 +488,12 @@ public class ResourceTreeView extends LocatableVLayout {
addToDBItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent menuItemClickEvent) { + int resourceId = ((ResourceTreeNode) treeGrid.getTree().findById(selectedNodeId)) + .getResource().getId();
DashboardPortlet p = new DashboardPortlet(def.getDisplayName() + " Chart", GraphPortlet.KEY, 250); - p.getConfiguration().put( - new PropertySimple(GraphPortlet.CFG_RESOURCE_ID, selectedResourceId)); + p.getConfiguration().put(new PropertySimple(GraphPortlet.CFG_RESOURCE_ID, resourceId)); p.getConfiguration().put( new PropertySimple(GraphPortlet.CFG_DEFINITION_ID, def.getId()));
@@ -506,8 +528,8 @@ public class ResourceTreeView extends LocatableVLayout {
Resource getResource(int resourceId) { if (this.treeGrid != null && this.treeGrid.getTree() != null) { - ResourceTreeDatasource.ResourceTreeNode treeNode = (ResourceTreeDatasource.ResourceTreeNode) this.treeGrid - .getTree().findById(ResourceTreeDatasource.ResourceTreeNode.idOf(resourceId)); + ResourceTreeNode treeNode = (ResourceTreeNode) this.treeGrid.getTree().findById( + ResourceTreeNode.idOf(resourceId)); if (treeNode != null) { return treeNode.getResource(); } @@ -520,150 +542,129 @@ public class ResourceTreeView extends LocatableVLayout { }
public void setSelectedResource(final int selectedResourceId) { - this.selectedResourceId = selectedResourceId;
- TreeNode node; - final String resourceNodeId = ResourceTreeDatasource.ResourceTreeNode.idOf(selectedResourceId); - if (treeGrid != null && treeGrid.getTree() != null - && (node = treeGrid.getTree().findById(resourceNodeId)) != null) { + selectedNodeId = ResourceTreeNode.idOf(selectedResourceId);
+ if (treeGrid != null && treeGrid.getTree() != null && (treeGrid.getTree().findById(selectedNodeId)) != null) { // This is the case where the tree was previously loaded and we get fired to look at a different - // node in the same tree and just have to switch the selection - - TreeNode[] parents = treeGrid.getTree().getParents(node); - treeGrid.getTree().openFolders(parents); - treeGrid.getTree().openFolder(node); - - if (!node.equals(treeGrid.getSelectedRecord())) { - treeGrid.deselectAllRecords(); - treeGrid.selectRecord(node); - } + // node in the same tree and just have to switch the selection + updateSelection();
- TreeUtility.printTree(treeGrid.getTree()); - - updateBreadcrumbs(); } else { - // This is for cases where we have to load the tree fresh including down to the currently visible node + loadTree(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); + }
- if (!root.equals(ResourceTreeView.this.rootResource)) { + private void loadTree(final int selectedResourceId) { + selectedNodeId = ResourceTreeNode.idOf(selectedResourceId);
- if (treeGrid != null) { - treeGrid.destroy(); - } - buildTree(); + 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); + }
- setRootResource(root); + public void onSuccess(List<Resource> result) { + Resource root = result.get(0);
- ResourceTreeDatasource dataSource = new ResourceTreeDatasource(result); - treeGrid.setDataSource(dataSource); - // GH: couldn't get initial data to mix with the datasource... so i put the initial data in - // the first datasource request - // treeGrid.setInitialData(selectedLineage); + if (!root.equals(ResourceTreeView.this.rootResource)) {
- addMember(treeGrid); + if (treeGrid != null) { + treeGrid.destroy(); + } + buildTree();
- treeGrid.fetchData(treeGrid.getCriteria(), new DSCallback() { - public void execute(DSResponse response, Object rawData, DSRequest request) { - System.out.println("Done fetching data for tree."); - updateBreadcrumbs(); - } - }); + setRootResource(root);
- TreeUtility.printTree(treeGrid.getTree()); + // seed datasource with initial resource list + ResourceTreeDatasource dataSource = new ResourceTreeDatasource(result); + treeGrid.setDataSource(dataSource);
- TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); - // System.out.println("Trying to preopen: " + selectedNode); - if (selectedNode != null) { - // System.out.println("Preopen node!!!"); - TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); - treeGrid.getTree().openFolders(parents); - treeGrid.getTree().openFolder(selectedNode); + addMember(treeGrid);
- for (TreeNode p : parents) { - System.out.println("open? " + treeGrid.getTree().isOpen(p) + " node: " + p.getName()); - } + treeGrid.fetchData(treeGrid.getCriteria(), new DSCallback() { + public void execute(DSResponse response, Object rawData, DSRequest request) { + System.out.println("Done fetching data for tree."); + updateSelection(); + } + });
- updateBreadcrumbs(); + updateSelection();
- treeGrid.selectRecord(selectedNode); - initialSelect = true; - treeGrid.markForRedraw(); - } + } 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)); + }
- } else { + } + });
- initialSelect = false; - 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)); - - //TreeUtility.printTree(treeGrid.getTree()); - - TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); - if (selectedNode != null) { - treeGrid.deselectAllRecords(); - treeGrid.selectRecord(selectedNode); - - TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); - treeGrid.getTree().openFolders(parents); - treeGrid.getTree().openFolder(selectedNode); - - /* - todo deleteme - // Update breadcrumbs - viewId.getBreadcrumbs().clear(); - for (int i = parents.length - 1; i >= 0; i--) { - TreeNode n = parents[i]; - adjustBreadcrumb(n, viewId); - } - adjustBreadcrumb(selectedNode, viewId); - CoreGUI.refreshBreadCrumbTrail();*/ + } + } + }); + }
- } else { - CoreGUI.getMessageCenter().notify( - new Message("Failed to select Resource [" + selectedResourceId - + "] in tree.", Message.Severity.Warning)); - } + public void setSelectedAutoGroup(final Integer selectedAutoGroupId) {
- } - }); + AutoGroupTreeNode selectedNode = autoGroupNodeMap.get(selectedAutoGroupId); + if (treeGrid != null && treeGrid.getTree() != null && selectedNode != null) { + // This is the case where the tree was previously loaded and we get fired to look at a different + // node in the same tree and just have to switch the selection
- } + this.selectedNodeId = selectedNode.getID(); + updateSelection();
- TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); - // System.out.println("Trying to preopen: " + selectedNode); - if (selectedNode != null) { - TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); + } else { + // This is for cases where we have to load the tree fresh including down to the currently visible node
- // todo update viewPath's breadcrumbs - } + final ResourceGroupGWTServiceAsync resourceGroupService = GWTServiceLookup.getResourceGroupService(); + ResourceGroupCriteria criteria = new ResourceGroupCriteria(); + criteria.addFilterId(selectedAutoGroupId); + criteria.addFilterVisible(false); + criteria.fetchResourceType(true); + resourceGroupService.findResourceGroupsByCriteria(criteria, new AsyncCallback<PageList<ResourceGroup>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch autogroup backing group", caught); + }
- // CoreGUI.addBreadCrumb(new Place(String.valueOf(result.getId()), result.getName())); + public void onSuccess(PageList<ResourceGroup> result) { + ResourceGroup backingGroup = result.get(0); + // load the tree up to the autogroup's parent resource + loadTree(backingGroup.getAutoGroupParentResource().getId()); + + // 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(); } }); } }
private void adjustBreadcrumb(TreeNode node, ViewId viewId) { - if (node instanceof ResourceTreeDatasource.ResourceTreeNode) { + if (node instanceof ResourceTreeNode) {
- Resource nr = ((ResourceTreeDatasource.ResourceTreeNode) node).getResource(); + 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";
@@ -687,7 +688,7 @@ public class ResourceTreeView extends LocatableVLayout { c.addFilterParentResourceId(lineage.get(0).getId()); resourceService.findResourcesByCriteria(CoreGUI.getSessionSubject(), c, new AsyncCallback<PageList<Resource>>() { public void onFailure(Throwable caught) { - SC.say("SHit"); + SC.say("NotGood"); }
public void onSuccess(PageList<Resource> result) { @@ -708,7 +709,14 @@ public class ResourceTreeView extends LocatableVLayout {
public void renderView(ViewPath viewPath) { currentViewId = viewPath.getCurrent(); - Integer resourceId = Integer.parseInt(currentViewId.getPath()); - setSelectedResource(resourceId); + String currentViewIdPath = currentViewId.getPath(); + if ("AutoGroup".equals(currentViewIdPath)) { + ViewId nextViewId = viewPath.getNext(); + Integer autoGroupId = Integer.parseInt(nextViewId.getPath()); + setSelectedAutoGroup(autoGroupId); + } else { + Integer resourceId = Integer.parseInt(currentViewId.getPath()); + setSelectedResource(resourceId); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java index 00a2cf1..14ce7e6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java @@ -21,17 +21,21 @@ package org.rhq.enterprise.gui.coregui.client.util;
/** * A collection of utility methods for working with Strings. + * + * TODO: I18N. The logic here may need to be pluggable for different localizations. * * @author Ian Springer */ public class StringUtility { public static String pluralize(String singularNoun) { String pluralNoun; - if (singularNoun.endsWith("y") && !singularNoun.endsWith("ay") && !singularNoun.endsWith("ey") && - !singularNoun.endsWith("oy")) { + if (singularNoun.endsWith("y") && !singularNoun.endsWith("ay") && !singularNoun.endsWith("ey") + && !singularNoun.endsWith("oy")) { pluralNoun = singularNoun.substring(0, singularNoun.length() - 1) + "ies"; - } else { + } else if (!singularNoun.endsWith("s")) { pluralNoun = singularNoun + "s"; + } else { + pluralNoun = singularNoun; } return pluralNoun; }
commit ab9648bda9d733820cfc8037cc011e957e10fcfb Author: Joseph Marques joseph@redhat.com Date: Sun Sep 26 00:13:14 2010 -0400
enhance login and user session management experience:
* create formal notion of client-side loggedIn state * add logic for synchronization between client/server loggedIn state * "loading..." image is now dismissed upon app load, not upon login action * LoginView is recentered upon browser resizing * "recent alerts" no longer causes GWT service exceptions in the logs
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 00a27f0..b59edba 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 @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client;
import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Element; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.http.client.Request; @@ -30,10 +31,8 @@ import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.History; -import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.rpc.AsyncCallback; -import com.google.gwt.user.client.ui.RootPanel; import com.smartgwt.client.core.KeyIdentifier; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.util.KeyCallback; @@ -60,7 +59,6 @@ import org.rhq.enterprise.gui.coregui.client.report.tag.TaggedView; import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.WidgetUtility; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; -import org.rhq.enterprise.gui.coregui.client.util.preferences.UserPreferences; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** @@ -71,18 +69,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
public static final String CONTENT_CANVAS_ID = "BaseContent";
- private static Subject sessionSubject; - - private static Timer sessionTimer = new Timer() { - @Override - public void run() { - System.out.println("Session Timer Expired"); - new LoginView(true).showLoginDialog(); // log user out, show login dialog - } - }; - - private static UserPreferences userPreferences; - private static ErrorHandler errorHandler = new ErrorHandler();
private static BreadcrumbTrailPane breadCrumbTrailPane; @@ -140,9 +126,18 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { messages = GWT.create(Messages.class);
checkLoginStatus(); + + // removing loading image, which can be seen if LoginView doesn't completely cover it + Element loadingPanel = DOM.getElementById("Loading-Panel"); + loadingPanel.removeFromParent(); }
public static void checkLoginStatus() { + if (!UserSessionManager.isLoggedIn()) { + new LoginView().showLoginDialog(); + return; + } + // String sessionIdString = com.google.gwt.user.client.Cookies.getCookie("RHQ_Sesssion"); // if (sessionIdString == null) {
@@ -181,11 +176,17 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { }
public void onSuccess(PageList<Subject> result) { - Subject subject = result.get(0); subject.setSessionId(sessionId); - setSessionSubject(subject); - //System.out.println("Portal-War logged in"); + + // TODO this breaks because of reattach rules, bizarrely even in queries. + // gonna switch out to non-subject include apis + // + // Create a minimized session object for validation on requests + // Subject s = new Subject(subject.getName(),subject.getFactive(), subject.getFsystem()); + // s.setSessionId(subject.getSessionId()); + UserSessionManager.setSessionSubject(subject); + loadProductInfo(); } }); } else { @@ -208,16 +209,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { } }
- public static void refreshSessionTimer() { - System.out.println("Refreshing Session Timer"); - sessionTimer.schedule(29 * 60 * 1000); // 29 minutes from now, timeout before the http session timeout - } - - public static void destroySessionTimer() { - System.out.println("Destroying Session Timer"); - sessionTimer.cancel(); - } - private void buildCoreUI() { // If the core gui is already built (eg. from previous login, just refire event) if (this.rootCanvas == null) { @@ -243,8 +234,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { breadCrumbTrailPane = new BreadcrumbTrailPane(); rootCanvas.addMember(breadCrumbTrailPane);
- DOM.setInnerHTML(RootPanel.get("Loading-Panel").getElement(), ""); - Canvas canvas = new Canvas(CONTENT_CANVAS_ID); canvas.setWidth100(); canvas.setHeight100(); @@ -296,7 +285,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { } else if (breadcrumbName.equals("Bundles")) { canvas = new BundleTopView("Bundle"); } else if (breadcrumbName.equals("LogOut")) { - canvas = new LoginView(true); + canvas = new LoginView(); + UserSessionManager.logout(); } else if (breadcrumbName.equals("Tag")) { canvas = new TaggedView("Tag"); } else if (breadcrumbName.equals("Subsystems")) { @@ -319,32 +309,10 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { return errorHandler; }
- public static Subject getSessionSubject() { - return sessionSubject; - } - - public static UserPreferences getUserPreferences() { - return userPreferences; - } - public static void printWidgetTree() { WidgetUtility.printWidgetTree(coreGUI.rootCanvas); }
- public static void setSessionSubject(Subject subject) { - // TODO this breaks because of reattach rules, bizarrely even in queries. gonna switch out to non-subject include apis - // Create a minimized session object for validation on requests - // Subject s = new Subject(subject.getName(),subject.getFactive(), subject.getFsystem()); - // s.setSessionId(subject.getSessionId()); - CoreGUI.sessionSubject = subject; - CoreGUI.userPreferences = new UserPreferences(subject); - loadProductInfo(); - // After a user initiated logout start back at the default view - if ("LogOut".equals(CoreGUI.currentPath)) { - History.newItem(getDefaultView()); - } - } - private static String getDefaultView() { // TODO: should this be Dashboard or a User Preference? return ""; @@ -403,6 +371,11 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { public void onSuccess(ProductInfo result) { productInfo = result; coreGUI.buildCoreUI(); + + // After a user initiated logout start back at the default view + if ("LogOut".equals(CoreGUI.currentPath)) { + History.newItem(getDefaultView()); + } } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java index 66b94dc..00050ad 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java @@ -56,7 +56,7 @@ public class Footer extends LocatableToolStrip { protected void onDraw() { super.onDraw();
- Label loggedInAs = new Label("Logged in as " + CoreGUI.getSessionSubject().getName()); + Label loggedInAs = new Label("Logged in as " + UserSessionManager.getSessionSubject().getName()); loggedInAs.setWrap(false); loggedInAs.setMargin(5); loggedInAs.setValign(VerticalAlignment.CENTER); @@ -111,6 +111,9 @@ public class Footer extends LocatableToolStrip { }
public void refresh() { + if (!UserSessionManager.isLoggedIn()) { + return; + }
AlertCriteria alertCriteria = new AlertCriteria(); alertCriteria.setPaging(1, 1); @@ -127,6 +130,7 @@ public class Footer extends LocatableToolStrip { drawAlerts(result); } }); + }
public void drawAlerts(PageList<Alert> alerts) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index a19fcec..0f660c3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -27,7 +27,6 @@ import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; -import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.FormErrorOrientation; import com.smartgwt.client.widgets.Canvas; @@ -45,10 +44,9 @@ import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent; import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
-import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; - /** * @author Greg Hinkle + * @author Joseph Marques */ public class LoginView extends Canvas {
@@ -60,34 +58,12 @@ public class LoginView extends Canvas { private SubmitItem loginButton;
public LoginView() { - this(false); - } - - public LoginView(boolean logout) { - if (logout) { - CoreGUI.destroySessionTimer(); - if (CoreGUI.getSessionSubject() != null) { - GWTServiceLookup.getSubjectService().logout(CoreGUI.getSessionSubject(), new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to logout", caught); - CoreGUI.checkLoginStatus(); - } - - public void onSuccess(Void result) { - CoreGUI.checkLoginStatus(); - } - }); - } - } else { - CoreGUI.refreshSessionTimer(); - } - }
public void showLoginDialog() { - if (!loginShowing) { loginShowing = true; + UserSessionManager.logout();
form = new DynamicForm(); form.setMargin(25); @@ -143,8 +119,7 @@ public class LoginView extends Canvas { window.setCanDragReposition(false); window.setShowCloseButton(false); window.setShowMinimizeButton(false); - - window.centerInPage(); + window.setAutoCenter(true);
window.addItem(form); window.show(); @@ -157,11 +132,9 @@ public class LoginView extends Canvas { } }); } - }
private void login(String user, String password) { - if (CoreGUI.detectIe6()) { CoreGUI.forceIe6Hacks(); } @@ -177,6 +150,7 @@ public class LoginView extends Canvas { if (statusCode == 200) { window.destroy(); loginShowing = false; + UserSessionManager.refresh(); CoreGUI.checkLoginStatus(); } else { handleError(statusCode); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java index f4c52d7..3ec02b3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/SearchGUI.java @@ -39,7 +39,6 @@ import org.rhq.enterprise.gui.coregui.client.search.SearchBar; public class SearchGUI implements EntryPoint {
public static SearchGUI singleton = new SearchGUI(); - private static Subject sessionSubject; private SearchBar searchBar;
private SearchGUI() { @@ -101,12 +100,10 @@ public class SearchGUI implements EntryPoint { }
public void onSuccess(PageList<Subject> result) { - Subject subject = result.get(0); subject.setSessionId(sessionId); - SearchGUI.sessionSubject = subject; + UserSessionManager.setSessionSubject(subject); singleton.buildSearchGUI(); - } }); } else { @@ -130,10 +127,6 @@ public class SearchGUI implements EntryPoint {
}
- public static Subject getSessionSubject() { - return sessionSubject; - } - public SearchBar getSearchBar() { return searchBar; } 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 new file mode 100644 index 0000000..9bede31 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java @@ -0,0 +1,136 @@ +/* + * 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; + +import com.google.gwt.user.client.Timer; +import com.google.gwt.user.client.rpc.AsyncCallback; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.preferences.UserPreferences; + +/** + * First time this class is loaded, local loggedIn bit will be false, which implies user is not logged in. + * + * If login successful, CoreGUI/SearchGUI will call setSessionSubject, which sets local loggedIn bit to true. + * If user clicks logout explicitly, LoginView will be shown, which sets local loggedIn bit to false. + * If count down timer expires, LoginView will be shown, which sets local loggedIn bit to false. + * + * If error during GWT RPC Service, check local loggedIn status + * If loggedIn bit false, display LoginView + * Else check server-side logged in state + * If logged out on server-side, LoginView will be shown, which sets local loggedIn bit to false. + * + * @author Joseph Marques + */ +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 = 30 * 1000; // 30 seconds + + private static Subject sessionSubject; + private static UserPreferences userPreferences; + + private UserSessionManager() { + // static access only + } + + private static boolean loggedIn = false; + private static Timer sessionTimer = new Timer() { + @Override + public void run() { + System.out.println("Session Timer Expired"); + new LoginView().showLoginDialog(); // log user out, show login dialog + } + }; + private static Timer logoutTimer = new Timer() { + @Override + public void run() { + logoutServerSide(); + } + }; + + public static void refresh() { + // if quickly logging back in, first cancel the logout timer so that we + // don't have race conditions to the server where the login request beats + // the logout request, which would appear to the user for the login to + // have failed since it will boot them back to the login screen. + logoutTimer.cancel(); + + // now continue with the rest of the login logic + loggedIn = true; + System.out.println("Refreshing Session Timer"); + sessionTimer.schedule(SESSION_TIMEOUT); + } + + public static void logout() { + if (!loggedIn) { + return; // nothing to do, already called + } + + loggedIn = false; + System.out.println("Destroying Session Timer"); + sessionTimer.cancel(); + + // log out the web session on the server-side in a delayed fashion, + // allowing enough time to pass to let in-flight requests complete + logoutTimer.schedule(LOGOUT_DELAY); + } + + private static void logoutServerSide() { + try { + if (getSessionSubject() != null) { + GWTServiceLookup.getSubjectService().logout(UserSessionManager.getSessionSubject(), + new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to logout", caught); + } + + public void onSuccess(Void result) { + } + }); + } + } catch (Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to logout", caught); + } + } + + public static boolean isLoggedIn() { + System.out.println("isLoggedIn = " + loggedIn); + return loggedIn; + } + + public static Subject getSessionSubject() { + return sessionSubject; + } + + public static void setSessionSubject(Subject subject) { + sessionSubject = subject; + userPreferences = new UserPreferences(sessionSubject); + refresh(); + } + + public static UserPreferences getUserPreferences() { + return userPreferences; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleDistributionFileUploadForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleDistributionFileUploadForm.java index 65f2cc3..0d90b8a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleDistributionFileUploadForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleDistributionFileUploadForm.java @@ -31,6 +31,7 @@ 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.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
@@ -138,7 +139,7 @@ public class BundleDistributionFileUploadForm extends DynamicCallbackForm { super.onDraw();
HiddenItem sessionIdField = new HiddenItem("sessionid"); - sessionIdField.setValue(CoreGUI.getSessionSubject().getSessionId().intValue()); + sessionIdField.setValue(UserSessionManager.getSessionSubject().getSessionId().intValue());
setNumCols(4);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleFileUploadForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleFileUploadForm.java index cded781..3647913 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleFileUploadForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/BundleFileUploadForm.java @@ -32,6 +32,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import org.rhq.core.domain.bundle.BundleVersion; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
@@ -154,7 +155,7 @@ public class BundleFileUploadForm extends DynamicCallbackForm { super.onDraw();
HiddenItem sessionIdField = new HiddenItem("sessionid"); - sessionIdField.setValue(CoreGUI.getSessionSubject().getSessionId().intValue()); + sessionIdField.setValue(UserSessionManager.getSessionSubject().getSessionId().intValue());
HiddenItem bundleVersionIdField = new HiddenItem("bundleVersionId"); bundleVersionIdField.setValue(this.bundleVersion.getId()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/TextFileRetrieverForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/TextFileRetrieverForm.java index be0f0a9..31a8a23 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/TextFileRetrieverForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/upload/TextFileRetrieverForm.java @@ -30,6 +30,7 @@ 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.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
@@ -56,7 +57,7 @@ public class TextFileRetrieverForm extends DynamicCallbackForm { retrieveField.setValue(true);
HiddenItem sessionIdField = new HiddenItem("sessionid"); - sessionIdField.setValue(CoreGUI.getSessionSubject().getSessionId().intValue()); + sessionIdField.setValue(UserSessionManager.getSessionSubject().getSessionId().intValue());
setNumCols(4);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java index 72cf55e..13a35c0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java @@ -33,7 +33,7 @@ import com.smartgwt.client.widgets.grid.events.FieldStateChangedHandler;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; @@ -63,7 +63,7 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Port protected void configureTable() { super.configureTable();
- Set<Integer> favoriteIds = CoreGUI.getUserPreferences().getFavoriteResources(); + Set<Integer> favoriteIds = UserSessionManager.getUserPreferences().getFavoriteResources();
Integer[] favArray = favoriteIds.toArray(new Integer[favoriteIds.size()]);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/footer/FavoritesButton.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/footer/FavoritesButton.java index 4f5374c..5557d50 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/footer/FavoritesButton.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/footer/FavoritesButton.java @@ -33,6 +33,7 @@ import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIMenuButton;
@@ -56,7 +57,7 @@ public class FavoritesButton extends LocatableIMenuButton { // favorite Resources successfully. clickEvent.cancel();
- Set<Integer> favorites = CoreGUI.getUserPreferences().getFavoriteResources(); + Set<Integer> favorites = UserSessionManager.getUserPreferences().getFavoriteResources();
if (!favorites.isEmpty()) {
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTitleBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTitleBar.java index 431f52d..e78e3b6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTitleBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTitleBar.java @@ -36,6 +36,7 @@ import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.components.tagging.TagEditorView; import org.rhq.enterprise.gui.coregui.client.components.tagging.TagsChangedCallback; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; @@ -82,7 +83,7 @@ public class ResourceGroupTitleBar extends LocatableHLayout { this.favoriteButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { Set<Integer> favorites = toggleFavoriteLocally(); - CoreGUI.getUserPreferences().setFavoriteResources(favorites, new UpdateFavoritesCallback()); + UserSessionManager.getUserPreferences().setFavoriteResources(favorites, new UpdateFavoritesCallback()); } });
@@ -143,7 +144,7 @@ public class ResourceGroupTitleBar extends LocatableHLayout { this.title.setContents("<span class="SectionHeader">" + group.getName() + "</span> <span class="subtitle">" + group.getGroupCategory().name() + "</span>");
- Set<Integer> favorites = CoreGUI.getUserPreferences().getFavoriteResourceGroups(); + Set<Integer> favorites = UserSessionManager.getUserPreferences().getFavoriteResourceGroups(); this.favorite = favorites.contains(group.getId()); updateFavoriteButton();
@@ -167,7 +168,7 @@ public class ResourceGroupTitleBar extends LocatableHLayout {
private Set<Integer> toggleFavoriteLocally() { this.favorite = !this.favorite; - Set<Integer> favorites = CoreGUI.getUserPreferences().getFavoriteResourceGroups(); + Set<Integer> favorites = UserSessionManager.getUserPreferences().getFavoriteResourceGroups(); if (this.favorite) { favorites.add(group.getId()); } else { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTitleBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTitleBar.java index dcbcda6..bc1e0b7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTitleBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTitleBar.java @@ -36,6 +36,7 @@ import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.components.tagging.TagEditorView; import org.rhq.enterprise.gui.coregui.client.components.tagging.TagsChangedCallback; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; @@ -82,7 +83,7 @@ public class ResourceTitleBar extends LocatableHLayout { this.favoriteButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { Set<Integer> favorites = toggleFavoriteLocally(); - CoreGUI.getUserPreferences().setFavoriteResources(favorites, new UpdateFavoritesCallback()); + UserSessionManager.getUserPreferences().setFavoriteResources(favorites, new UpdateFavoritesCallback()); } });
@@ -142,7 +143,7 @@ public class ResourceTitleBar extends LocatableHLayout { this.title.setContents("<span class="SectionHeader">" + resource.getName() + "</span> <span class="subtitle">" + resource.getResourceType().getName() + "</span>");
- Set<Integer> favorites = CoreGUI.getUserPreferences().getFavoriteResources(); + Set<Integer> favorites = UserSessionManager.getUserPreferences().getFavoriteResources(); this.favorite = favorites.contains(resource.getId()); updateFavoriteButton();
@@ -168,7 +169,7 @@ public class ResourceTitleBar extends LocatableHLayout {
private Set<Integer> toggleFavoriteLocally() { this.favorite = !this.favorite; - Set<Integer> favorites = CoreGUI.getUserPreferences().getFavoriteResources(); + Set<Integer> favorites = UserSessionManager.getUserPreferences().getFavoriteResources(); int resourceId = this.resource.getId(); if (this.favorite) { favorites.add(resourceId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/FavoritesMenu.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/FavoritesMenu.java index a13e705..876f8d5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/FavoritesMenu.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/FavoritesMenu.java @@ -36,9 +36,9 @@ import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
- /** * @author Greg Hinkle */ @@ -56,7 +56,7 @@ public class FavoritesMenu extends MenuItem { }
public void refresh() { - Set<Integer> favorites = CoreGUI.getUserPreferences().getFavoriteResources(); + Set<Integer> favorites = UserSessionManager.getUserPreferences().getFavoriteResources();
if (!favorites.isEmpty()) {
@@ -80,33 +80,30 @@ public class FavoritesMenu extends MenuItem { ResourceCriteria criteria = new ResourceCriteria(); criteria.addFilterIds(resourceIds); GWTServiceLookup.getResourceService().findResourcesByCriteria(criteria, - new AsyncCallback<PageList<Resource>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load favorite Resources.", caught); - } + new AsyncCallback<PageList<Resource>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load favorite Resources.", caught); + }
- public void onSuccess(PageList<Resource> resources) { - for (Resource resource : resources) { - MenuItem item = idToMenuItemMap.get(resource.getId()); - // TODO: Ideally, we should use ResourceManagerLocal.disambiguate() here to obtain - // disambiguated Resource names. - item.setTitle(resource.getName()); + public void onSuccess(PageList<Resource> resources) { + for (Resource resource : resources) { + MenuItem item = idToMenuItemMap.get(resource.getId()); + // TODO: Ideally, we should use ResourceManagerLocal.disambiguate() here to obtain + // disambiguated Resource names. + item.setTitle(resource.getName());
- String category = resource.getResourceType().getCategory().getDisplayName(); + String category = resource.getResourceType().getCategory().getDisplayName();
- String avail = (resource.getCurrentAvailability() != null && resource.getCurrentAvailability().getAvailabilityType() != null) - ? (resource.getCurrentAvailability().getAvailabilityType().name().toLowerCase()) : "down"; - item.setIcon("types/" + category + "_" + avail + "_16.png"); - } - submenu.setItems(items); + String avail = (resource.getCurrentAvailability() != null && resource + .getCurrentAvailability().getAvailabilityType() != null) ? (resource + .getCurrentAvailability().getAvailabilityType().name().toLowerCase()) : "down"; + item.setIcon("types/" + category + "_" + avail + "_16.png"); } - }); + submenu.setItems(items); + } + }); }
- }
- } - - diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/favorites/SavedSearchManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/favorites/SavedSearchManager.java index 66260e8..ac069cb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/favorites/SavedSearchManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/favorites/SavedSearchManager.java @@ -29,7 +29,7 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.SavedSearchCriteria; import org.rhq.core.domain.search.SavedSearch; -import org.rhq.enterprise.gui.coregui.client.SearchGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.SearchGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.search.SearchBar; @@ -74,8 +74,8 @@ public class SavedSearchManager { public synchronized void updatePatternByName(final String name, final String pattern) { SavedSearch savedSearch = savedSearches.get(name); if (savedSearch == null) { // created case - final SavedSearch newSavedSearch = new SavedSearch(searchBar.getSearchSubsystem(), name, pattern, SearchGUI - .getSessionSubject()); + final SavedSearch newSavedSearch = new SavedSearch(searchBar.getSearchSubsystem(), name, pattern, + UserSessionManager.getSessionSubject()); searchService.createSavedSearch(newSavedSearch, new AsyncCallback<Integer>() {
public void onFailure(Throwable caught) { @@ -157,7 +157,7 @@ public class SavedSearchManager { }
private synchronized void load() { - Subject currentUser = SearchGUI.getSessionSubject(); + Subject currentUser = UserSessionManager.getSessionSubject(); SavedSearchCriteria criteria = new SavedSearchCriteria(); criteria.addFilterSubjectId(currentUser.getId()); criteria.addFilterSearchSubsystem(searchBar.getSearchSubsystem()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java index 4456c1c..9b80112 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/MonitoringRequestCallback.java @@ -21,7 +21,6 @@ package org.rhq.enterprise.gui.coregui.client.util.rpc; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; -import com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
@@ -42,11 +41,6 @@ public class MonitoringRequestCallback implements RequestCallback { this.name = name; id = RPCManager.getInstance().register(this); this.callback = callback; - if (callback instanceof RequestCallbackAdapter) { -// ((RequestCallbackAdapter)callback) - - } - }
public void onError(Request request, Throwable exception) { @@ -56,7 +50,6 @@ public class MonitoringRequestCallback implements RequestCallback {
public void onResponseReceived(Request request, Response response) { if (STATUS_CODE_OK == response.getStatusCode()) { - RPCManager.getInstance().succeedCall(this); callback.onResponseReceived(request, response); } else { @@ -67,7 +60,6 @@ public class MonitoringRequestCallback implements RequestCallback { } }
- public String getName() { return name; } diff --git a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html index fb46e97..5dd3c64 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html +++ b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html @@ -23,10 +23,9 @@ <script type="text/javascript" language="javascript" src="org.rhq.enterprise.gui.coregui.CoreGUI/org.rhq.enterprise.gui.coregui.CoreGUI.nocache.js"></script>
-<div id="Loading-Panel" style="width: 214px;height: 90px; margin-top: 300px; margin-left: auto;margin-right: auto;"> - +<div id="Loading-Panel" style="width: 214px; height: 90px; margin-top: 300px; margin-left: auto; margin-right: auto;"> <div style="text-align: center; border: 3px solid lightgray;"> - <img src="images/rhq_logo_animated_100px.gif" alt="loading" style="margin: 5px;"> + <img src="images/rhq_logo_animated_100px.gif" alt="Loading..." style="border: none;"> Loading... </div> </div>
commit 98807bb7626dd9f33fe5e60176f73e711808b973 Author: Joseph Marques joseph@redhat.com Date: Fri Sep 24 16:31:54 2010 -0400
fix login screen - disable drag/resize/move/minimize/close, better alignment
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index 077b692..a19fcec 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -39,6 +39,7 @@ import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.CanvasItem; import com.smartgwt.client.widgets.form.fields.HeaderItem; import com.smartgwt.client.widgets.form.fields.PasswordItem; +import com.smartgwt.client.widgets.form.fields.RowSpacerItem; import com.smartgwt.client.widgets.form.fields.SubmitItem; import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent; @@ -89,7 +90,8 @@ public class LoginView extends Canvas { loginShowing = true;
form = new DynamicForm(); - form.setMargin(10); + form.setMargin(25); + form.setAutoFocus(true); form.setShowErrorText(true); form.setErrorOrientation(FormErrorOrientation.BOTTOM);
@@ -98,11 +100,12 @@ public class LoginView extends Canvas { logo.setShowTitle(false);
HeaderItem header = new HeaderItem(); - header.setValue("RHQ Login"); + header.setValue("Please Login");
TextItem user = new TextItem("user", "User"); user.setRequired(true); user.setAttribute("autoComplete", "native"); + final PasswordItem password = new PasswordItem("password", "Password"); password.setRequired(true); password.setAttribute("autoComplete", "native"); @@ -126,21 +129,26 @@ public class LoginView extends Canvas { } });
- form.setFields(logo, header, user, password, loginButton); + form.setFields(logo, header, new RowSpacerItem(), user, password, loginButton);
window = new Window(); - window.setTitle("RHQ Login"); window.setWidth(400); - window.setHeight(250); + window.setHeight(275); + window.setTitle("Welcome"); + + // forced focused, static size, can't close / dismiss window.setIsModal(true); window.setShowModalMask(true); - window.setCanDragResize(true); + window.setCanDragResize(false); + window.setCanDragReposition(false); + window.setShowCloseButton(false); + window.setShowMinimizeButton(false); + window.centerInPage(); + window.addItem(form); window.show();
- form.focusInItem(user); - form.addSubmitValuesHandler(new SubmitValuesHandler() { public void onSubmitValues(SubmitValuesEvent submitValuesEvent) { if (form.validate()) {
commit 2493b2c730de20bd805f460e81f7a4e2ebfd3a97 Author: Joseph Marques joseph@redhat.com Date: Fri Sep 24 14:49:51 2010 -0400
fix error message during login
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index 6290eb7..077b692 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -220,7 +220,7 @@ public class LoginView extends Canvas { if (statusCode == 401) { form.setFieldErrors("login", "The username or password provided does not match our records", true); } else { - form.setFieldErrors("login", "The server could data source is unavailable", true); + form.setFieldErrors("login", "The backend data source is unavailable", true); } loginButton.setDisabled(false); }
commit 2fd87a1f7b9ad8e113d2e4448cb14b84d76da58a Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 23:46:10 2010 -0400
do not wrap cells, the contents could be enormous
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java index d185f40..954bac7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java @@ -90,6 +90,9 @@ public class EventCompositeHistoryView extends TableSection { protected void configureTable() { ListGrid grid = getListGrid();
+ grid.setWrapCells(true); + grid.setFixedRecordHeights(true); + // getListGrid().getField("id").setWidth(60);
grid.getField("timestamp").setWidth(125);
commit 35b45657af8e90730df664c8533c9384e4210002 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 23:36:19 2010 -0400
add headerIcon to discovery manager table view
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/ResourceAutodiscoveryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/ResourceAutodiscoveryView.java index 445d1cb..e1ea25e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/ResourceAutodiscoveryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/ResourceAutodiscoveryView.java @@ -24,8 +24,10 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DataSource; import com.smartgwt.client.types.SelectionAppearance; +import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.Img; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.form.DynamicForm; @@ -36,6 +38,7 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler; import com.smartgwt.client.widgets.grid.events.SelectionEvent; import com.smartgwt.client.widgets.layout.HLayout; +import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.toolbar.ToolStrip; import com.smartgwt.client.widgets.tree.TreeGrid; import com.smartgwt.client.widgets.tree.TreeGridField; @@ -59,11 +62,13 @@ public class ResourceAutodiscoveryView extends LocatableVLayout { private TreeGrid treeGrid; private ToolStrip footer; private DataSource dataSource = null; + private String headerIcon = "global/Recent_16.png";
private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService();
public ResourceAutodiscoveryView(String locatorId) { super(locatorId); + setWidth100(); setHeight100(); } @@ -78,8 +83,8 @@ public class ResourceAutodiscoveryView extends LocatableVLayout { super.onInit();
if (!simple) { - - HLayout titleLayout = new HLayout(150); + Img img = new Img(headerIcon, 24, 24); + img.setPadding(4);
HTMLFlow title = new HTMLFlow(); title.setWidth100(); @@ -87,14 +92,12 @@ public class ResourceAutodiscoveryView extends LocatableVLayout { title.setContents("Discovery Manager"); title.setPadding(4); title.setStyleName("HeaderLabel"); - titleLayout.addMember(title);
DynamicForm form = new LocatableDynamicForm(this.extendLocatorId("Status")); final SelectItem statusSelectItem = new SelectItem("status", "Status"); statusSelectItem.setValueMap("New", "Ignored", "New and Ignored"); statusSelectItem.setValue("New"); form.setItems(statusSelectItem); - titleLayout.addMember(form);
statusSelectItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { @@ -102,6 +105,15 @@ public class ResourceAutodiscoveryView extends LocatableVLayout { } });
+ HLayout titleLayout = new HLayout(); + titleLayout.setAutoHeight(); + titleLayout.setAlign(VerticalAlignment.BOTTOM); + + titleLayout.addMember(img); + titleLayout.addMember(title); + titleLayout.addMember(new LayoutSpacer()); + titleLayout.addMember(form); + addMember(titleLayout); }
commit 978e6463310bf0155ec4cd9d2ea6a4d23951b9c1 Author: Ian Springer ian.springer@redhat.com Date: Fri Sep 24 20:17:33 2010 -0400
conn props for various JVM services (Memory Pool, etc.) should be read-only (https://bugzilla.redhat.com/show_bug.cgi?id=601715)
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 2c7ca1d..dc5a4cf 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 @@ -119,9 +119,9 @@ createDeletePolicy="neither" singleton="true">
<plugin-configuration> - <c:simple-property name="objectName" default="java.lang:type=OperatingSystem"/> - <c:simple-property name="nameTemplate" default="Operating system information"/> - <c:simple-property name="descriptionTemplate" default="Operating system information provided by the JVM."/> + <c:simple-property name="objectName" readOnly="true" default="java.lang:type=OperatingSystem"/> + <c:simple-property name="nameTemplate" readOnly="true" default="Operating system information"/> + <c:simple-property name="descriptionTemplate" readOnly="true" default="Operating system information provided by the JVM."/> </plugin-configuration>
<metric displayName="Free Physical Memory" @@ -160,7 +160,7 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.lang:type=Threading"/> - <c:simple-property name="nameTemplate" default="Threading"/> + <c:simple-property name="nameTemplate" readOnly="true" default="Threading"/> </plugin-configuration>
<operation displayName="Reset Peak Thread Metrics" name="resetPeakThreadCount" @@ -250,7 +250,7 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.lang:type=Memory"/> - <c:simple-property name="nameTemplate" default="Memory Subsystem"/> + <c:simple-property name="nameTemplate" readOnly="true" default="Memory Subsystem"/> </plugin-configuration>
<operation name="gc" displayName="Run Garbage Collection" description="Runs the garbage collector."/> @@ -312,9 +312,9 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.lang:type=MemoryPool,name=%name%"/> - <c:simple-property name="nameTemplate" default="{name}"/> - <c:simple-property name="descriptionTemplate" default="The {name} memory pool for this VM."/> - <c:simple-property name="name" type="string" description="The memory pool's name"/> + <c:simple-property name="nameTemplate" readOnly="true" default="{name}"/> + <c:simple-property name="descriptionTemplate" readOnly="true" default="The {name} memory pool for this VM."/> + <c:simple-property name="name" type="string" readOnly="true" description="The memory pool's name"/> </plugin-configuration>
<metric displayName="Used" @@ -355,9 +355,9 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.lang:type=GarbageCollector,name=%name%"/> - <c:simple-property name="nameTemplate" default="{name}"/> - <c:simple-property name="descriptionTemplate" default="The {name} Garbage Collector for this VM."/> - <c:simple-property name="name" type="string" description="The garbage collector's name"/> + <c:simple-property name="nameTemplate" readOnly="true" default="{name}"/> + <c:simple-property name="descriptionTemplate" readOnly="true" default="The {name} Garbage Collector for this VM."/> + <c:simple-property name="name" type="string" readOnly="true" description="The garbage collector's name"/> </plugin-configuration>
<metric property="CollectionCount" @@ -384,7 +384,7 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.lang:type=Compilation"/> - <c:simple-property name="nameTemplate" default="Compilation"/> + <c:simple-property name="nameTemplate" readOnly="true" default="Compilation"/> </plugin-configuration>
<metric property="TotalCompilationTime" @@ -400,7 +400,7 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.lang:type=ClassLoading"/> - <c:simple-property name="nameTemplate" default="Class Loading"/> + <c:simple-property name="nameTemplate" readOnly="true" default="Class Loading"/> </plugin-configuration>
<metric displayName="Loaded Classes" @@ -428,7 +428,7 @@
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="java.util.logging:type=Logging"/> - <c:simple-property name="nameTemplate" default="Logging"/> + <c:simple-property name="nameTemplate" readOnly="true" default="Logging"/> <c:simple-property name="configManagementEnabled" type="boolean" default="false" description="When false, configuration reading for this resource will fail."/> </plugin-configuration>
commit da4d8fd6d57b787c612e829486f0ed83a582680f Author: Ian Springer ian.springer@redhat.com Date: Fri Sep 24 18:13:58 2010 -0400
cleanup/refactor group tree view code; add autotypegroup nodes to cluster group tree (still need to add subcategory nodes); delete unused ResourceGroupTreeDatasource class; add toString() impl to FileSystemInfo class
diff --git a/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java b/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java index f6415ba..2bde8ee 100644 --- a/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java +++ b/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java @@ -35,7 +35,7 @@ import org.hyperic.sigar.SigarProxy; * @author John Mazzitelli */ public class FileSystemInfo { - private final Log log = LogFactory.getLog(FileSystemInfo.class); + private final Log log = LogFactory.getLog(this.getClass());
private final String mountPoint; private FileSystem fs; @@ -91,4 +91,13 @@ public class FileSystemInfo { public FileSystemUsage getFileSystemUsage() { return this.fsUsage; } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "[" + + "mountPoint='" + mountPoint + ''' + + ", fs=" + fs + + ", fsUsage=" + fsUsage + + ']'; + } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeDatasource.java deleted file mode 100644 index 76b7b76..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeDatasource.java +++ /dev/null @@ -1,368 +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.inventory.groups.detail; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -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.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; -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.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; -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.inventory.resource.type.ResourceTypeRepository; - -/** - * This doesn't extend RPCDataSource because it is tree oriented and - * behaves different from normal list data sources in some places. - * - * @author Greg Hinkle - */ -public class ResourceGroupTreeDatasource extends DataSource { - - private boolean initialized = false; - int rootId; - List<Resource> initialData; - - private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); - - public ResourceGroupTreeDatasource(List<Resource> initialData) { - setClientOnly(false); - setDataProtocol(DSProtocol.CLIENTCUSTOM); - setDataFormat(DSDataFormat.CUSTOM); - - this.initialData = initialData; - - this.rootId = rootId; - - DataSourceField idDataField = new DataSourceTextField("id", "ID"); - idDataField.setPrimaryKey(true); - - DataSourceTextField nameDataField = new DataSourceTextField("name", "Name"); - nameDataField.setCanEdit(false); - - 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); - } - - @Override - protected Object transformRequest(DSRequest request) { - String requestId = request.getRequestId(); - DSResponse response = new DSResponse(); - response.setAttribute("clientContext", request.getAttributeAsObject("clientContext")); - // Asume success - response.setStatus(0); - switch (request.getOperationType()) { - case ADD: - //executeAdd(request, response); - break; - case FETCH: - executeFetch(requestId, request, response); - break; - case REMOVE: - //executeRemove(lstRec); - break; - case UPDATE: - //executeAdd(lstRec, false); - break; - - default: - break; - } - - return request.getData(); - } - - - public void executeFetch(final String requestId, final DSRequest request, final DSResponse response) { - final long start = System.currentTimeMillis(); - - String p = request.getCriteria().getAttribute("parentId"); - // System.out.println("All attributes: " + Arrays.toString(request.getCriteria().getAttributes())); - - ResourceCriteria criteria = new ResourceCriteria(); - - if (p == null) { - System.out.println("DataSourceTree: Loading initial data"); - - // criteria.addFilterId(rootId); - - processIncomingData(initialData, response, requestId); - return; - - } else { - System.out.println("DataSourceTree: Loading " + p); - - criteria.addFilterParentResourceId(Integer.parseInt(p)); - } - - // 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); - } - - public void onSuccess(PageList<Resource> result) { - processIncomingData(result, response, requestId); - } - }); - } - - private void processIncomingData(List<Resource> result, final DSResponse response, final String requestId) { - - 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) { - response.setData(build(result)); - processResponse(requestId, response); - - } - }); - } - - /** - * Construct a set of TreeNodes from a list of resources - * - * @param resources - * @return - */ - public static TreeNode[] build(List<Resource> resources) { - ResourceTreeNode[] records = new ResourceTreeNode[resources.size()]; - for (int x = 0; x < resources.size(); x++) { - Resource res = resources.get(x); - ResourceTreeNode record = new ResourceTreeNode(res); - records[x] = record; - } - - return introduceTypeFolders(records); - } - - private static TreeNode[] introduceTypeFolders(ResourceTreeNode[] nodes) { - ArrayList<TreeNode> built = new ArrayList<TreeNode>(); - HashMap<ResourceSubCategory, CategoryTreeNode> categories = new HashMap<ResourceSubCategory, CategoryTreeNode>(); - HashMap<ResourceType, TypeTreeNode> types = new HashMap<ResourceType, TypeTreeNode>(); - - - for (ResourceTreeNode node : nodes) { - built.add(node); - - if (!types.containsKey(node.getResourceType()) - && node.getResourceType().getCategory() != ResourceCategory.PLATFORM) { - - String parentResourceId = String.valueOf(node.getResource().getParentResource().getId()); - - CategoryTreeNode categoryNode = null; - - if (node.getResourceType().getSubCategory() != null) { - ResourceSubCategory category = node.getResourceType().getSubCategory(); - if (category.getName() != null) { - categoryNode = categories.get(category); - - if (categoryNode == null) { - categoryNode = new CategoryTreeNode(parentResourceId, category); - - categories.put(category, categoryNode); - built.add(categoryNode); - } - } - } - - String parentId = null; - if (categoryNode != null) { - parentId = categoryNode.getAttribute("id"); - } else { - parentId = parentResourceId; - } - - TypeTreeNode typeNode = new TypeTreeNode(parentId, parentResourceId, node.getResourceType().getName()); - built.add(typeNode); - types.put(node.getResourceType(), typeNode); - } - } - - return built.toArray(new TreeNode[built.size()]); - - } - - private static boolean sameTypes(ResourceTreeNode[] nodes) { - ResourceType first = nodes[0].getResourceType(); - for (ResourceTreeNode node : nodes) { - if (!first.equals(node)) { - return false; - } - } - return true; - } - - public static class CategoryTreeNode extends TreeNode { - public CategoryTreeNode(String parentId, ResourceSubCategory category) { - setID(parentId + "__" + category.getName()); - setParentID(parentId); - setName(category.getDisplayName()); - - setAttribute("id", parentId + "__" + category.getName()); - setAttribute("parentId", parentId); - setAttribute("name", category.getDisplayName()); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("CategoryTreeNode["); - String id = getAttribute("id"); - buffer.append("id=").append(id); - String parentId = getAttribute("parentId"); - buffer.append(", parentId=").append(parentId); - String name = getAttribute("name"); - buffer.append(", name=").append(name); - buffer.append("]"); - return buffer.toString(); - } - } - - - public static class TypeTreeNode extends TreeNode { - private TypeTreeNode(String parentId, String parentResourceId, String type) { - setID(parentId + "_" + type); - setParentID(parentId); - - setAttribute("id", parentResourceId + "_" + type); - setAttribute("parentId", parentId); - // setAttribute("parentKey", parentId); - setAttribute("name", type); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("TypeTreeNode["); - String id = getAttribute("id"); - buffer.append("id=").append(id); - String parentId = getAttribute("parentId"); - buffer.append(", parentId=").append(parentId); - String name = getAttribute("name"); - buffer.append(", name=").append(name); - buffer.append("]"); - return buffer.toString(); - } - } - - public static class ResourceTreeNode extends TreeNode { - private Resource resource; - - private ResourceTreeNode(Resource resource) { - this.resource = resource; - - String id = String.valueOf(resource.getId()); - String parentId = resource.getParentResource() == null ? null - : (resource.getParentResource().getId() + "_" + resource.getResourceType().getName()); - - // System.out.println(id + " / " + parentId); - - setID(id); - setParentID(parentId); - - setAttribute("id", id); - setAttribute("parentId", parentId); - - // setAttribute("parentKey", resource.getParentResource() == null ? 0 : (resource.getParentResource().getId() + resource.getResourceType().getName())); - - setAttribute("name", resource.getName()); - setAttribute("description", resource.getDescription()); - setAttribute( - "currentAvailability", - resource.getCurrentAvailability().getAvailabilityType() == AvailabilityType.UP ? "/images/icons/availability_green_16.png" - : "/images/icons/availability_red_16.png"); - - setIsFolder((resource.getResourceType().getChildResourceTypes() != null && !resource.getResourceType() - .getChildResourceTypes().isEmpty())); - } - - public Resource getResource() { - return resource; - } - - public void setResource(Resource resource) { - this.resource = resource; - } - - public ResourceType getResourceType() { - return resource.getResourceType(); - } - - public String getParentId() { - return getAttribute("parentId"); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("ResourceTreeNode["); - String id = getAttribute("id"); - buffer.append("id=").append(id); - String parentId = getAttribute("parentId"); - buffer.append(", parentId=").append(parentId); - String name = getAttribute("name"); - buffer.append(", name=").append(name); - buffer.append("]"); - return buffer.toString(); - } - } -} \ No newline at end of file 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 acaca4a..aa854f8 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 @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set;
@@ -55,9 +56,11 @@ import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; 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.util.StringUtility;
/** * @author Greg Hinkle + * @author Ian Springer */ public class ResourceGroupTreeView extends VLayout implements BookmarkableView {
@@ -143,7 +146,7 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { new AsyncCallback<PageList<ResourceGroup>>() { @Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load group", caught); + CoreGUI.getErrorHandler().handleError("Failed to load group with id [" + groupId + "].", caught); }
@Override @@ -151,64 +154,56 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { ResourceGroup group = result.get(0); ResourceGroupTreeView.this.selectedGroup = group;
- if (GroupCategory.MIXED == group.getGroupCategory()) { - ResourceGroupTreeView.this.rootResourceGroup = group; - ResourceGroupTreeView.this.rootGroupId = rootResourceGroup.getId(); - TreeNode fakeRoot = new TreeNode("fakeRootNode"); - TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); - rootNode.setID(String.valueOf(rootResourceGroup.getId())); //getClusterKey().toString()); - fakeRoot.setChildren(new TreeNode[] { rootNode }); - Tree tree = new Tree(); - tree.setRoot(fakeRoot); - treeGrid.setData(tree); - treeGrid.markForRedraw(); - } else { - if (group.getClusterResourceGroup() == null) { + GroupCategory groupCategory = group.getGroupCategory(); + switch (groupCategory) { + case MIXED: ResourceGroupTreeView.this.rootResourceGroup = group; - // This is a straight up group - loadGroup(groupId); - } else { - // Someone select a cluster group beneath a real recursive compatible group - - ResourceGroup rootGroup = group.getClusterResourceGroup(); - ResourceGroupTreeView.this.rootResourceGroup = rootGroup; - - loadGroup(rootGroup.getId()); - } + ResourceGroupTreeView.this.rootGroupId = rootResourceGroup.getId(); + TreeNode fakeRoot = new TreeNode("fakeRootNode"); + TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); + rootNode.setID(String.valueOf(rootResourceGroup.getId())); //getClusterKey().toString()); + fakeRoot.setChildren(new TreeNode[] { rootNode }); + Tree tree = new Tree(); + tree.setRoot(fakeRoot); + treeGrid.setData(tree); + treeGrid.markForRedraw(); + break; + case COMPATIBLE: + if (group.getClusterResourceGroup() == null) { + // This is a straight up compatible group. + ResourceGroupTreeView.this.rootResourceGroup = group; + } else { + // This is a cluster group beneath a real recursive compatible group. + ResourceGroupTreeView.this.rootResourceGroup = group.getClusterResourceGroup(); + } + loadGroup(ResourceGroupTreeView.this.rootResourceGroup.getId()); + break; } - } }); - }
private void loadGroup(int groupId) { - if (groupId == this.rootGroupId) { // Still looking at the same compat-recursive tree
// TODO reselect tree to selected node + TreeNode selectedNode; if (this.selectedGroup.getClusterKey() != null) { - TreeNode selectedNode = treeGrid.getTree().findById(this.selectedGroup.getClusterKey()); - TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); - treeGrid.getTree().openFolders(parents); - treeGrid.getTree().openFolder(selectedNode); - - treeGrid.selectRecord(selectedNode); + selectedNode = treeGrid.getTree().findById(this.selectedGroup.getClusterKey()); } else { - TreeNode selectedNode = treeGrid.getTree().findById(String.valueOf(this.selectedGroup.getId())); - TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); - treeGrid.getTree().openFolders(parents); - treeGrid.getTree().openFolder(selectedNode); - - treeGrid.selectRecord(selectedNode); + selectedNode = treeGrid.getTree().findById(String.valueOf(this.selectedGroup.getId())); } + TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); + treeGrid.getTree().openFolders(parents); + treeGrid.getTree().openFolder(selectedNode); + treeGrid.selectRecord(selectedNode);
} else { this.rootGroupId = groupId; GWTServiceLookup.getClusterService().getClusterTree(groupId, new AsyncCallback<ClusterFlyweight>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load tree", caught); + CoreGUI.getErrorHandler().handleError("Failed to load group tree.", caught); }
public void onSuccess(ClusterFlyweight result) { @@ -216,11 +211,10 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { } }); } - }
private void loadTreeTypes(final ClusterFlyweight root) { - HashSet<Integer> typeIds = new HashSet<Integer>(); + Set<Integer> typeIds = new HashSet<Integer>(); typeIds.add(this.rootResourceGroup.getResourceType().getId()); getTreeTypes(root, typeIds);
@@ -235,7 +229,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { }
private void selectClusterGroup(ClusterKey key) { - GWTServiceLookup.getClusterService().createAutoClusterBackingGroup(key, true, new AsyncCallback<ResourceGroup>() { @Override @@ -249,7 +242,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { History.newItem("ResourceGroup/" + groupId); } }); - }
private void loadTree(ClusterFlyweight root) { @@ -276,44 +268,79 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { treeGrid.markForRedraw(); }
- public void loadTree(TreeNode parent, ClusterFlyweight parentNode, ClusterKey parentKey) { - if (!parentNode.getChildren().isEmpty()) { - - // TODO Introduce type groups (Do we still like this model for recursive compatibles?) - - ArrayList<TreeNode> childNodes = new ArrayList<TreeNode>(); - - HashMap<Integer, TreeNode> typeNodes = new HashMap<Integer, TreeNode>(); - - for (ClusterFlyweight child : parentNode.getChildren()) { - TreeNode node = new TreeNode(child.getName()); - + public void loadTree(TreeNode parentNode, ClusterFlyweight parentClusterGroup, ClusterKey parentKey) { + if (!parentClusterGroup.getChildren().isEmpty()) { + // First pass - group the children by type. + Map<ResourceType, List<ClusterFlyweight>> childrenByType = new HashMap<ResourceType, List<ClusterFlyweight>>(); + for (ClusterFlyweight child : parentClusterGroup.getChildren()) { ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); - ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight - .getResourceKey());
ResourceType type = this.typeMap.get(keyFlyweight.getResourceTypeId()); + List<ClusterFlyweight> children = childrenByType.get(type); + if (children == null) { + children = new ArrayList<ClusterFlyweight>(); + childrenByType.put(type, children); + } + children.add(child); + }
- String icon = "types/" + type.getCategory().getDisplayName() + "_up_16.png"; - - node.setIcon(icon); + // Second pass - process each of the sets of like-typed children created in the first pass. + List<TreeNode> childNodes = new ArrayList<TreeNode>(); + for (ResourceType type : childrenByType.keySet()) { + List<ClusterFlyweight> children = childrenByType.get(type); + List<TreeNode> nodesByType = new ArrayList<TreeNode>(); + for (ClusterFlyweight child : children) { + TreeNode node = createClusterGroupNode(parentKey, type, child); + nodesByType.add(node); + + if (!child.getChildren().isEmpty()) { + // Recurse. + ClusterKey key = (ClusterKey)node.getAttributeAsObject("key"); + loadTree(node, child, key); + } + }
- node.setID(key.getKey()); - node.setAttribute("key", key); - node.setAttribute("resourceType", type); - childNodes.add(node); + // TODO (ips): Insert subcategory nodes.
- if (child.getChildren().isEmpty()) { - node.setIsFolder(false); - } else { - node.setIsFolder(true); - loadTree(node, child, key); + if (type.isSingleton()) { + // If it's a singleton type, just insert the cluster group node as is. + childNodes.addAll(nodesByType); + } + else { + // Otherwise insert an autoTypeGroup folder node to group all cluster groups of this type. + TreeNode autoTypeGroupNode = createAutoTypeGroupNode(type, nodesByType); + childNodes.add(autoTypeGroupNode); } } - parent.setChildren(childNodes.toArray(new TreeNode[childNodes.size()])); + parentNode.setChildren(childNodes.toArray(new TreeNode[childNodes.size()])); } }
+ private TreeNode createClusterGroupNode(ClusterKey parentKey, ResourceType type, ClusterFlyweight child) { + TreeNode node = new TreeNode(child.getName()); + + ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); + ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight + .getResourceKey()); + String id = key.getKey(); + node.setID(id); + node.setAttribute("key", key); + node.setAttribute("resourceType", type); + node.setIsFolder(!child.getChildren().isEmpty()); + + String icon = "types/" + type.getCategory().getDisplayName() + "_up_16.png"; + node.setIcon(icon); + return node; + } + + private TreeNode createAutoTypeGroupNode(ResourceType type, List<TreeNode> memberNodes) { + String name = StringUtility.pluralize(type.getName()); + TreeNode autoTypeGroupNode = new TreeNode(name); + autoTypeGroupNode.setIsFolder(true); + autoTypeGroupNode.setChildren(memberNodes.toArray(new TreeNode[memberNodes.size()])); + return autoTypeGroupNode; + } + public void renderView(ViewPath viewPath) { currentViewId = viewPath.getCurrent(); int groupId = Integer.parseInt(currentViewId.getPath());
commit 746f2b2b63bf1aef017a1bfba7410002dbb008c6 Merge: a0461ff... 34d531b... Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Sep 24 16:18:36 2010 -0400
Merge branch 'master' into master-jay
commit a0461ff51bd1cf36283b504083b9eece378254d8 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Sep 24 16:15:30 2010 -0400
Initial cut at adding autogroup support. autogroups will now have backing groups.
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 11ba639..02aa606 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.95</db.schema.version> + <db.schema.version>2.96</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 bf83991..6246880 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,13 @@
<column name="CATEGORY" type="VARCHAR2" size="20" required="true"/>
+ <!-- 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"/> - - <!-- These two only set if this is a backing group for a resource cluster --> <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 --> + <column name="AUTO_GROUP_PARENT_RESOURCE_ID" type="INTEGER" references="RHQ_RESOURCE"/> + <column name="VISIBLE" type="BOOLEAN"/>
<index name="RHQ_RES_GROUP_NAME" unique="false"> 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 ddb1974..f0940ab 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3215,6 +3215,20 @@ <schema-alterColumn table="RHQ_RESOURCE" column="VERSION" columnType="VARCHAR2" precision="100" /> </schemaSpec>
+ <schemaSpec version="2.96"> + <!-- Support autogroup backing groups --> + <schema-addColumn table="RHQ_RESOURCE_GROUP" column="AUTO_GROUP_PARENT_RESOURCE_ID" columnType="INTEGER" /> + <schema-directSQL> + <statement desc="Creating RHQ_RESOURCE_GROUP foreign key relation to RHQ_RESOURCE for autogroup backing groups"> + ALTER TABLE RHQ_RESOURCE_GROUP + ADD CONSTRAINT RHQ_RG_AG_PARENT_ID_FK + FOREIGN KEY (AUTO_GROUP_PARENT_RESOURCE_ID) + REFERENCES RHQ_RESOURCE (ID) + </statement> + </schema-directSQL> + + </schemaSpec> + </dbupgrade> </target> </project> 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 6f5c259..2278c7f 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 @@ -42,13 +42,14 @@ public class ResourceGroupCriteria extends TaggedCriteria { private static final long serialVersionUID = 1L;
private Integer filterId; - private Integer filterDownMemberCount; // required overrides private String filterName; private Boolean filterRecursive; private Integer filterResourceTypeId; // requires overrides private String filterResourceTypeName; // requires overrides + private Integer filterAutoGroupParentResourceId; // requires overrides private String filterPluginName; // requires overrides private GroupCategory filterGroupCategory; + private Integer filterDownMemberCount; // required overrides private List<Integer> filterExplicitResourceIds; // requires overrides private List<Integer> filterImplicitResourceIds; // requires overrides private ResourceCategory filterExplicitResourceCategory; // requires overrides @@ -71,6 +72,9 @@ public class ResourceGroupCriteria extends TaggedCriteria {
public ResourceGroupCriteria() { filterOverrides.put("resourceTypeId", "resourceType.id = ?"); + filterOverrides.put("resourceTypeName", "resourceType.name like ?"); + filterOverrides.put("autoGroupParentResourceId", "autoGroupParentResource.id = ?"); + filterOverrides.put("pluginName", "resourceType.plugin like ?"); filterOverrides.put("downMemberCount", "" // + "id IN ( SELECT implicitGroup.id " // + " FROM Resource res " // @@ -78,8 +82,6 @@ public class ResourceGroupCriteria extends TaggedCriteria { + " WHERE res.currentAvailability.availabilityType = 0 " // + " GROUP BY implicitGroup.id " // + " HAVING COUNT(res) >= ? )"); - filterOverrides.put("resourceTypeName", "resourceType.name like ?"); - filterOverrides.put("pluginName", "resourceType.plugin like ?"); filterOverrides.put("explicitResourceIds", "" // + "id IN ( SELECT explicitGroup.id " // + " FROM Resource res " // @@ -146,6 +148,10 @@ public class ResourceGroupCriteria extends TaggedCriteria { this.filterResourceTypeName = filterResourceTypeName; }
+ public void addFilterAutoGroupParentResourceId(Integer filterAutoGroupParentResourceId) { + this.filterAutoGroupParentResourceId = filterAutoGroupParentResourceId; + } + public void addFilterPluginName(String filterPluginName) { this.filterPluginName = filterPluginName; } 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 9355e30..6726bbb 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 @@ -1031,6 +1031,11 @@ public class Resource implements Comparable<Resource>, Serializable { @ManyToMany(mappedBy = "resources", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) private Set<Tag> tags;
+ // When a resource is removed any referring autgroup backing groups should also be removed + // bulk delete + @OneToMany(mappedBy = "autoGroupParentResource", fetch = FetchType.LAZY) + private List<ResourceGroup> autoGroupBackingGroups = null; + public Resource() {
} @@ -1629,6 +1634,14 @@ public class Resource implements Comparable<Resource>, Serializable { } }
+ public List<ResourceGroup> getAutoGroupBackingGroups() { + return autoGroupBackingGroups; + } + + public void setAutoGroupBackingGroups(List<ResourceGroup> autoGroupBackingGroups) { + this.autoGroupBackingGroups = autoGroupBackingGroups; + } + public int compareTo(Resource that) { return this.name.compareTo(that.getName()); } 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 d9ca343..46d6bcb 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 @@ -183,8 +183,7 @@ import org.rhq.core.domain.tagging.Tag; + " AND res.id NOT IN ( SELECT explicitRes.id " // + " FROM ResourceGroup rg " // + " JOIN rg.explicitResources explicitRes " // - + " WHERE rg.id = :groupId ) ") -}) + + " WHERE rg.id = :groupId ) ") }) @SequenceGenerator(name = "id", sequenceName = "RHQ_RESOURCE_GROUP_ID_SEQ") @Table(name = "RHQ_RESOURCE_GROUP") @XmlAccessorType(XmlAccessType.FIELD) @@ -441,13 +440,18 @@ public class ResourceGroup extends Group { @ManyToOne private ResourceGroup clusterResourceGroup = null;
- // When false hide this group from the UI. For example, for a Resource Cluster backing group. - private boolean visible = true; - - // When a compatible group is removed any referring backing groups should also be removed + // When a compatible group is removed any referring autocluster backing groups should also be removed @OneToMany(mappedBy = "clusterResourceGroup") private List<ResourceGroup> clusterBackingGroups = null;
+ // The parent resource for which this is an auto-group backing group + @JoinColumn(name = "AUTO_GROUP_PARENT_RESOURCE_ID", referencedColumnName = "ID", nullable = true) + @ManyToOne + private Resource autoGroupParentResource = null; + + // When false hide this group from the UI. For example, for an autocluster or autogroup backing group. + private boolean visible = true; + // bulk delete @OneToMany(mappedBy = "resource", cascade = { CascadeType.ALL }) @OneToMany(mappedBy = "resourceGroup", cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private Set<AlertDefinition> alertDefinitions = new LinkedHashSet<AlertDefinition>(); @@ -624,6 +628,14 @@ public class ResourceGroup extends Group { this.clusterResourceGroup = clusterResourceGroup; }
+ public Resource getAutoGroupParentResource() { + return autoGroupParentResource; + } + + public void setAutoGroupParentResource(Resource autoGroupParentResource) { + this.autoGroupParentResource = autoGroupParentResource; + } + public boolean isVisible() { return visible; } 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 00a27f0..f5c14c5 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 @@ -51,6 +51,7 @@ import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.bundle.BundleTopView; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardsView; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.AutoGroupTopView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupTopView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.InventoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTopView; @@ -291,6 +292,8 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { canvas = new ResourceTopView("Resource"); } else if (breadcrumbName.equals("ResourceGroup")) { canvas = new ResourceGroupTopView("Group"); + } else if (breadcrumbName.equals("AutoGroup")) { + canvas = new AutoGroupTopView("AutoGroup"); } else if (breadcrumbName.equals("Dashboard")) { canvas = new DashboardsView("Dashboard"); } else if (breadcrumbName.equals("Bundles")) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/AutoGroupTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/AutoGroupTopView.java new file mode 100644 index 0000000..384444f --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/AutoGroupTopView.java @@ -0,0 +1,106 @@ +/* + * 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.inventory.groups.detail; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.Canvas; + +import org.rhq.core.domain.criteria.ResourceGroupCriteria; +import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.BookmarkableView; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.ViewPath; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeView; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; + +/** + * @author Greg Hinkle + */ +public class AutoGroupTopView extends LocatableHLayout implements BookmarkableView { + + private Canvas contentCanvas; + private Integer parentResourceId; + private ResourceTreeView treeView; + private ResourceGroupDetailView detailView; + + public AutoGroupTopView(String locatorId) { + super(locatorId); + } + + @Override + protected void onInit() { + super.onInit(); + + setWidth100(); + setHeight100(); + + treeView = new ResourceTreeView(getLocatorId()); + detailView = new ResourceGroupDetailView(extendLocatorId("Detail"), + ResourceGroupDetailView.AUTO_GROUP_VIEW_PATH); + addMember(treeView); + + contentCanvas = new Canvas(); + addMember(contentCanvas); + + setContent(detailView); + } + + public void setContent(Canvas newContent) { + for (Canvas child : this.contentCanvas.getChildren()) { + child.destroy(); + } + this.contentCanvas.addChild(newContent); + this.contentCanvas.markForRedraw(); + } + + public void renderView(final ViewPath viewPath) { + // we need the backing group parent resource id to render the LHS resource tree. Once it's rendered leave + // it displayed but don't muck with it. A LHS user selection will drive a view change. + if (null == this.parentResourceId) { + final int backingGroupId = Integer.valueOf(viewPath.getCurrent().getPath()); + ResourceGroupCriteria criteria = new ResourceGroupCriteria(); + criteria.addFilterId(backingGroupId); + criteria.addFilterVisible(false); + GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, + new AsyncCallback<PageList<ResourceGroup>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch autogroup backing group", caught); + } + + public void onSuccess(PageList<ResourceGroup> result) { + if (result.isEmpty()) { + CoreGUI.getErrorHandler().handleError( + "Failed to find autogroup backing group: " + backingGroupId); + } else { + String parentResourceId = String + .valueOf(result.get(0).getAutoGroupParentResource().getId()); + treeView.renderView(new ViewPath(parentResourceId)); + } + } + }); + } + detailView.renderView(viewPath); + } +} 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 f273c40..e00ecbe 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 @@ -60,7 +60,8 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTyp * @author Ian Springer */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { - private static final String BASE_VIEW_PATH = "ResourceGroup"; + public static final String AUTO_GROUP_VIEW_PATH = "AutoGroup"; + public static final String GROUP_VIEW_PATH = "ResourceGroup";
private Integer groupId; private ResourceGroupComposite groupComposite; @@ -97,8 +98,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource private String currentTab; private String currentSubTab;
- public ResourceGroupDetailView(String locatorId) { - super(locatorId, BASE_VIEW_PATH); + public ResourceGroupDetailView(String locatorId, String baseViewPath) { + super(locatorId, baseViewPath); this.hide(); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java index ac0281c..3e87e03 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java @@ -41,7 +41,6 @@ public class ResourceGroupTopView extends LocatableHLayout implements Bookmarkab super(locatorId); }
- @Override protected void onInit() { super.onInit(); @@ -49,20 +48,16 @@ public class ResourceGroupTopView extends LocatableHLayout implements Bookmarkab setWidth100(); setHeight100();
- treeView = new ResourceGroupTreeView(); + treeView = new ResourceGroupTreeView(getLocatorId()); + detailView = new ResourceGroupDetailView(extendLocatorId("Detail"), ResourceGroupDetailView.GROUP_VIEW_PATH); addMember(treeView);
contentCanvas = new Canvas(); addMember(contentCanvas);
- detailView = new ResourceGroupDetailView(extendLocatorId("Detail")); - - // treeView.addResourceSelectListener(detailView); - setContent(detailView); }
- public void setContent(Canvas newContent) { for (Canvas child : this.contentCanvas.getChildren()) { child.destroy(); @@ -71,10 +66,8 @@ public class ResourceGroupTopView extends LocatableHLayout implements Bookmarkab this.contentCanvas.markForRedraw(); }
- - public void renderView(ViewPath viewPath) { - this.treeView.renderView(viewPath); - this.detailView.renderView(viewPath); + public void renderView(final ViewPath viewPath) { + treeView.renderView(viewPath); + detailView.renderView(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 acaca4a..d701852 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 @@ -34,7 +34,6 @@ import com.smartgwt.client.data.Record; import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler; import com.smartgwt.client.widgets.grid.events.SelectionEvent; -import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.tree.Tree; import com.smartgwt.client.widgets.tree.TreeGrid; import com.smartgwt.client.widgets.tree.TreeNode; @@ -55,11 +54,12 @@ import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; 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.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle */ -public class ResourceGroupTreeView extends VLayout implements BookmarkableView { +public class ResourceGroupTreeView extends LocatableVLayout implements BookmarkableView {
private TreeGrid treeGrid;
@@ -73,7 +73,8 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { private Map<Integer, ResourceType> typeMap; private ResourceGroup selectedGroup;
- public ResourceGroupTreeView() { + public ResourceGroupTreeView(String locatorId) { + super(locatorId); setWidth(250); setHeight100(); } 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 ca3f8e6..07995df 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 @@ -169,9 +169,7 @@ public class ResourceTreeDatasource extends DataSource {
ResourceTypeRepository.Cache.getInstance().loadResourceTypes( result, - EnumSet.of( - ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.children, + EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.subCategory), new ResourceTypeRepository.ResourceTypeLoadedCallback() { public void onResourceTypeLoaded(List<Resource> result) { @@ -204,7 +202,7 @@ public class ResourceTreeDatasource extends DataSource { List<TreeNode> updatedNodes = new ArrayList<TreeNode>(); // Maps category node IDs to the corresponding category nodes. Map<String, SubCategoryTreeNode> subcategoryNodes = new HashMap<String, SubCategoryTreeNode>(); - // Maps type node IDs to the corresponding type nodes. + // Maps autogroup/type node IDs to the corresponding autogroup/type nodes. Map<String, AutoGroupTreeNode> autogroupNodes = new HashMap<String, AutoGroupTreeNode>();
for (ResourceTreeNode resourceNode : resourceNodes) { @@ -222,7 +220,8 @@ public class ResourceTreeDatasource extends DataSource { do { String subcategoryNodeId = SubCategoryTreeNode.idOf(subcategory, parentResource); if (!subcategoryNodes.containsKey(subcategoryNodeId)) { - SubCategoryTreeNode subcategoryNode = new SubCategoryTreeNode(subcategory, parentResource); + SubCategoryTreeNode subcategoryNode = new SubCategoryTreeNode(subcategory, + parentResource); subcategoryNodes.put(subcategoryNode.getID(), subcategoryNode); System.out.println("Adding " + subcategoryNode + " to tree..."); updatedNodes.add(subcategoryNode); @@ -253,9 +252,8 @@ public class ResourceTreeDatasource extends DataSource { setAttribute(Attributes.ID, id);
ResourceSubCategory parentCategory = category.getParentSubCategory(); - String parentId = (parentCategory != null) ? - SubCategoryTreeNode.idOf(parentCategory, parentResource) : - ResourceTreeNode.idOf(parentResource); + String parentId = (parentCategory != null) ? SubCategoryTreeNode.idOf(parentCategory, parentResource) + : ResourceTreeNode.idOf(parentResource); setParentID(parentId); setAttribute(Attributes.PARENT_ID, parentId);
@@ -276,7 +274,17 @@ public class ResourceTreeDatasource extends DataSource { * The folder node for a Resource autogroup. */ public static class AutoGroupTreeNode extends EnhancedTreeNode { + + private Resource parentResource; + private ResourceType resourceType; + + /** + * @param resource requires resourceType field be set. requires parentResource field be set (null for no parent) + */ private AutoGroupTreeNode(Resource resource) { + this.parentResource = resource.getParentResource(); + this.resourceType = resource.getResourceType(); + String id = idOf(resource); setID(id); setAttribute(Attributes.ID, id); @@ -295,20 +303,44 @@ public class ResourceTreeDatasource extends DataSource { setAttribute(Attributes.DESCRIPTION, type.getDescription()); }
+ public Resource getParentResource() { + return parentResource; + } + + public ResourceType getResourceType() { + return resourceType; + } + + /** + * Generates a backing group name based on the resource type name and parent resource name. It may not be unique + * so should not be used to query for the group (use rtId and parentResId). The name may be displayed to the + * user. + * + * @return The name of the backing group. + */ + public String getBackingGroupName() { + return this.getParentResource().getName() + " ( " + this.getResourceType().getName() + " )"; + } + + /** + * Given a Resource, generate a unique ID for the AGNode. + * + * @param resource requires resourceType field be set. requires parentResource field be set (null for no parent) + * @return The name string or null if the R + */ public static String idOf(Resource resource) { Resource parentResource = resource.getParentResource(); - return (parentResource != null) ? - "autogroup" + resource.getResourceType().getId() + "_" + parentResource.getId() : - null; + return (parentResource != null) ? "autogroup_" + resource.getResourceType().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()); - } + return (parentCategory != null) ? SubCategoryTreeNode.idOf(parentCategory, resource.getParentResource()) + : ResourceTreeNode.idOf(resource.getParentResource()); + } }
public static class ResourceTreeNode extends EnhancedTreeNode { @@ -324,11 +356,9 @@ public class ResourceTreeDatasource extends DataSource { Resource parentResource = resource.getParentResource(); String parentId; if (parentResource != null) { - parentId = resource.getResourceType().isSingleton() ? - AutoGroupTreeNode.parentIdOf(resource) : - AutoGroupTreeNode.idOf(resource); - } - else { + parentId = resource.getResourceType().isSingleton() ? AutoGroupTreeNode.parentIdOf(resource) + : AutoGroupTreeNode.idOf(resource); + } else { parentId = null; } setParentID(parentId); 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 a03acaf..b20cfb3 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 @@ -52,6 +52,7 @@ import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.ResourceCriteria; +import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.dashboard.Dashboard; import org.rhq.core.domain.dashboard.DashboardPortlet; @@ -60,6 +61,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.group.ResourceGroup; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.Breadcrumb; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -69,6 +71,7 @@ import org.rhq.enterprise.gui.coregui.client.components.configuration.Configurat import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.resource.graph.GraphPortlet; 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.gwt.ResourceGroupGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.create.OperationCreateWizard; @@ -131,15 +134,19 @@ public class ResourceTreeView extends LocatableVLayout { public void onSelectionChanged(SelectionEvent selectionEvent) { if (!selectionEvent.isRightButtonDown() && selectionEvent.getState()) { ListGridRecord selectedNode = treeGrid.getSelectedRecord(); - System.out.println("Node selected in tree: " + selectedNode); if (selectedNode instanceof ResourceTreeDatasource.ResourceTreeNode) { - ResourceTreeDatasource.ResourceTreeNode resourceNode = - (ResourceTreeDatasource.ResourceTreeNode) selectedNode; + System.out.println("Resource Node selected in tree: " + selectedNode); + ResourceTreeDatasource.ResourceTreeNode resourceNode = (ResourceTreeDatasource.ResourceTreeNode) selectedNode; String viewPath = "Resource/" + resourceNode.getResource().getId(); String currentViewPath = History.getToken(); if (!currentViewPath.startsWith(viewPath)) { CoreGUI.goToView(viewPath); } + } else if (selectedNode instanceof ResourceTreeDatasource.AutoGroupTreeNode) { + System.out.println("AutoGroup Node selected in tree: " + selectedNode); + handleSelectedAutoGroupNode((ResourceTreeDatasource.AutoGroupTreeNode) selectedNode); + } else { + System.out.println("Unhandled Node selected in tree: " + selectedNode); } } } @@ -170,9 +177,77 @@ public class ResourceTreeView extends LocatableVLayout { }); }
+ private void handleSelectedAutoGroupNode(final ResourceTreeDatasource.AutoGroupTreeNode agNode) { + final ResourceGroupGWTServiceAsync resourceGroupService = GWTServiceLookup.getResourceGroupService(); + + // get the children tree nodes and build a child resourceId array + TreeNode[] children = treeGrid.getTree().getChildren(agNode); + final int[] childIds = new int[children.length]; + for (int i = 0, size = children.length; (i < size); ++i) { + childIds[i] = ((ResourceTreeDatasource.ResourceTreeNode) children[i]).getResource().getId(); + } + + // get the backing group if it exists, otherwise create the group + ResourceGroupCriteria criteria = new ResourceGroupCriteria(); + criteria.addFilterResourceTypeId(agNode.getResourceType().getId()); + criteria.addFilterAutoGroupParentResourceId(agNode.getParentResource().getId()); + criteria.addFilterVisible(false); + resourceGroupService.findResourceGroupsByCriteria(criteria, new AsyncCallback<PageList<ResourceGroup>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch autogroup backing group", caught); + } + + public void onSuccess(PageList<ResourceGroup> result) { + if (result.isEmpty()) { + // Not found, create new backing group + // the backing group name is a display name using a unique parentResource-resourceType combo + final String backingGroupName = agNode.getBackingGroupName(); + ResourceGroup backingGroup = new ResourceGroup(backingGroupName); + backingGroup.setAutoGroupParentResource(agNode.getParentResource()); + backingGroup.setResourceType(agNode.getResourceType()); + backingGroup.setVisible(false); + backingGroup.setRecursive(false); + resourceGroupService.createResourceGroup(backingGroup, childIds, + new AsyncCallback<ResourceGroup>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to create resource autogroup", caught); + } + + public void onSuccess(ResourceGroup result) { + renderAutoGroup(result); + } + }); + } else { + // backing group found, make sure the members are correct + final ResourceGroup backingGroup = result.get(0); + resourceGroupService.setAssignedResources(backingGroup.getId(), childIds, false, + new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failed to set assigned members for autogroup backing group", caught); + } + + public void onSuccess(Void result) { + renderAutoGroup(backingGroup); + } + }); + } + } + }); + + } + + private void renderAutoGroup(ResourceGroup backingGroup) { + String viewPath = "AutoGroup/" + backingGroup.getId(); + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); + } + }
private void updateBreadcrumbs() { - TreeNode selectedNode = treeGrid.getTree().findById(ResourceTreeDatasource.ResourceTreeNode.idOf(selectedResourceId)); + TreeNode selectedNode = treeGrid.getTree().findById( + ResourceTreeDatasource.ResourceTreeNode.idOf(selectedResourceId)); // System.out.println("Trying to preopen: " + selectedNode); if (selectedNode != null) { TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); @@ -205,9 +280,7 @@ public class ResourceTreeView extends LocatableVLayout { ResourceType type = node.getResource().getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( type.getId(), - EnumSet.of( - ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.children, + EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.subCategory, ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), @@ -509,8 +582,7 @@ public class ResourceTreeView extends LocatableVLayout {
TreeUtility.printTree(treeGrid.getTree());
- TreeNode selectedNode = - treeGrid.getTree().findById(resourceNodeId); + TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); // System.out.println("Trying to preopen: " + selectedNode); if (selectedNode != null) { // System.out.println("Preopen node!!!"); 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 c9b4420..0528b06 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 @@ -146,6 +146,8 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage @EJB private ResourceManagerLocal resourceManager; // ourself, for xactional semantic consistency @EJB + private ResourceGroupManagerLocal resourceGroupManager; + @EJB private ResourceTypeManagerLocal typeManager; @EJB @IgnoreDependency @@ -397,6 +399,26 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage log.debug("Overlord is asynchronously deleting resource [" + attachedResource + "]"); }
+ // one more thing, delete any autogroup backing groups + List<ResourceGroup> backingGroups = attachedResource.getAutoGroupBackingGroups(); + if (!backingGroups.isEmpty()) { + int size = backingGroups.size(); + int[] backingGroupIds = new int[size]; + for (int i = 0; (i < size); ++i) { + backingGroupIds[i] = backingGroups.get(i).getId(); + } + try { + resourceGroupManager.deleteResourceGroups(user, backingGroupIds); + } catch (Throwable t) { + if (log.isDebugEnabled()) { + log.error("Bulk delete error for autogroup backing group deletion for " + backingGroupIds, t); + } else { + log.error("Bulk delete error for autogroup backing group deletion for " + backingGroupIds + ": " + + t.getMessage()); + } + } + } + // now we can purge the resource, let cascading do the rest entityManager.remove(attachedResource);
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 34d531bf2b41cdb2b100903f984d0fa313984250 Merge: c8ecb19... 03c0fa9... Author: John Sanda jsanda@redhat.com Date: Thu Sep 23 13:00:22 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 03c0fa915be672fe82c8afd01c00e5ac1a5e6605 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 20:57:46 2010 -0400
convert EventCompositeDetailsView into a singleton, update callers appropriately
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeDetailsView.java index 343947b..3581a59 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeDetailsView.java @@ -45,31 +45,16 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; public class EventCompositeDetailsView extends VLayout implements BookmarkableView {
private int eventId; - private EventComposite composite; - private ViewId viewId;
- public EventCompositeDetailsView(int eventId) { - this.eventId = eventId; - } + private static EventCompositeDetailsView INSTANCE = new EventCompositeDetailsView();
- public EventCompositeDetailsView(EventComposite composite) { - this.composite = composite; + public static EventCompositeDetailsView getInstance() { + return INSTANCE; }
- @Override - protected void onDraw() { - super.onDraw(); - - for (Canvas child : getMembers()) { - child.destroy(); - } - - if (this.composite != null) { - show(composite); - } else { - show(eventId); - } + private EventCompositeDetailsView() { + // access through the static singleton only }
private void show(int eventId) { @@ -96,12 +81,10 @@ public class EventCompositeDetailsView extends VLayout implements BookmarkableVi }
if (this.viewId != null) { - viewId.getBreadcrumbs().get(0).setDisplayName("Event Details"); + viewId.getBreadcrumbs().get(0).setDisplayName("Details"); CoreGUI.refreshBreadCrumbTrail(); }
- this.composite = composite; - DynamicForm form = new DynamicForm(); form.setWidth100(); form.setHeight100(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java index b9434f0..d185f40 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeHistoryView.java @@ -173,6 +173,6 @@ public class EventCompositeHistoryView extends TableSection {
@Override public Canvas getDetailsView(int eventId) { - return new EventCompositeDetailsView(eventId); + return EventCompositeDetailsView.getInstance(); } }
commit e17220ef6827775b472f95e1d81417d12d61f5f9 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 20:57:41 2010 -0400
revert to old monitor>graphs page until new charting library chosen
* update embedded resource/group links * disabled embedded links to full-screen graph * update embedded links to event details
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 7236d4b..030eb2b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -53,7 +53,6 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configura import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration.ResourceConfigurationEditView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory.PluginConfigurationEditView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory.ResourceResourceGroupsView; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.GraphListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.schedules.SchedulesView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.traits.TraitsView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.OperationHistoryView; @@ -213,7 +212,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo "/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()), true, true);
visible = hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT); - canvas = (visible) ? new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource) : null; + //canvas = (visible) ? new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource) : null; + canvas = (visible) ? new FullHTMLPane("/rhq/resource/monitor/graphs-plain.xhtml?id=" + resource.getId()) : null; updateSubTab(this.monitoringTab, this.monitorGraphs, canvas, visible, true); // visible = same test as above canvas = (visible) ? new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId()) : null; @@ -221,6 +221,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo visible = hasMetricsOfType(this.resourceComposite, DataType.TRAIT); canvas = (visible) ? new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId()) : null; updateSubTab(this.monitoringTab, this.monitorTraits, canvas, visible, true); + updateSubTab(this.monitoringTab, this.monitorAvail, new FullHTMLPane( "/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId()), true, true); updateSubTab(this.monitoringTab, this.monitorSched, new SchedulesView(monitoringTab diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/common/events/EventDetailsAction.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/common/events/EventDetailsAction.java index 8403297..df45f52 100755 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/common/events/EventDetailsAction.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/common/events/EventDetailsAction.java @@ -86,6 +86,7 @@ public class EventDetailsAction extends BaseAction { int groupId = WebUtility.getOptionalIntRequestParameter(request, ParamConstants.GROUP_ID_PARAM, -1); int parent = WebUtility.getOptionalIntRequestParameter(request, "parent", -1); int type = WebUtility.getOptionalIntRequestParameter(request, "type", -1); + String mode = WebUtility.getOptionalRequestParameter(request, "mode", "normal");
EventManagerLocal eventManager = LookupUtil.getEventManager();
@@ -124,7 +125,7 @@ public class EventDetailsAction extends BaseAction { } html.append(" ");
- createLinkForResource(resourceId, groupId, parent, type, html, event, ridBadChars(event + createLinkForResource(mode, resourceId, groupId, parent, type, html, event, ridBadChars(event .getEventDetail())); html.append("</li>"); } @@ -133,7 +134,7 @@ public class EventDetailsAction extends BaseAction { if (events.getTotalSize() > MAX_EVENTS_PER_DOT) { EventComposite event = events.get(events.size() - 1); // take the last one to initialize the list html.append("<p/>"); - createLinkForResource(resourceId, groupId, parent, type, html, event, res + createLinkForResource(mode, resourceId, groupId, parent, type, html, event, res .getMessage("resource.common.monitor.text.events.MoreEvents")); html.append("<p/>"); } @@ -149,30 +150,41 @@ public class EventDetailsAction extends BaseAction { return mapping.findForward(RetCodeConstants.SUCCESS_URL); }
- private void createLinkForResource(int resourceId, int groupId, int parent, int type, StringBuffer html, - EventComposite event, String text) { + private void createLinkForResource(String mode, int resourceId, int groupId, int parent, int type, + StringBuffer html, EventComposite event, String text) {
- //html.append("<a href="/resource/common/Events.do?mode=events&eventId="); - html.append("<a href="/rhq/resource/events/history.xhtml?eventId="); - html.append(event.getEventId()); - if (resourceId > -1) { - html.append("&id=").append(event.getResourceId()); - } else if (groupId > -1) { - html.append("&groupId=").append(groupId); + log.info("mode = " + mode); + if (mode.equals("plain")) { + String context = (resourceId > -1) ? "Resource/" : "ResourceGroup/"; + int contextId = (resourceId > -1) ? resourceId : groupId; + + html.append("<a target="_top" href="/coregui/CoreGUI.html#").append(context).append(contextId); + html.append("/Events/History/").append(event.getEventId()).append("">"); + html.append(text); + html.append("</a> "); } else { - html.append("&parent=").append(parent).append("&type=").append(type); - } - html.append("">"); - //html.append(event.getEventId()); - if (text.contains("\n")) { - text = text.substring(0, text.indexOf("\n")); - } - if (text.length() > DETAIL_MAX_LEN) { - text = text.substring(0, DETAIL_MAX_LEN - 1); + //html.append("<a href="/resource/common/Events.do?mode=events&eventId="); + html.append("<a href="/rhq/resource/events/history.xhtml?eventId="); + html.append(event.getEventId()); + if (resourceId > -1) { + html.append("&id=").append(event.getResourceId()); + } else if (groupId > -1) { + html.append("&groupId=").append(groupId); + } else { + html.append("&parent=").append(parent).append("&type=").append(type); + } + html.append("">"); + //html.append(event.getEventId()); + if (text.contains("\n")) { + text = text.substring(0, text.indexOf("\n")); + } + if (text.length() > DETAIL_MAX_LEN) { + text = text.substring(0, DETAIL_MAX_LEN - 1); + } + html.append(text); + html.append("</a>"); + html.append(" "); } - html.append(text); - html.append("</a>"); - html.append(" ");
}
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/events/data-plain.xhtml b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/events/data-plain.xhtml new file mode 100644 index 0000000..068f97b --- /dev/null +++ b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/events/data-plain.xhtml @@ -0,0 +1,180 @@ +<?xml version="1.0"?> + +<!DOCTYPE html + PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<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:rich="http://richfaces.ajax4jsf.org/rich" + xmlns:onc="http://jboss.org/on/component" + xmlns:onf="http://jboss.org/on/function%22%3E + +ui:composition + +<script type="text/javascript" src="/js/monitorGraphs.js" /> +<!-- need to include this function directly in the facelet so that parameter resolution happens at render-time --> +<script type="text/javascript"> + function showEventsDetails(time, status) { + initEventDetails(); + eventsTime = time; + var detail = $('eventsSummary'); + detail.innerHTML = ""; + + if (status != null) + ajaxEngine.sendRequest( 'getEventDetails', + 'id=#{param.id}', + 'groupId=#{param.groupId}', + 'parent=#{param.parent}', + 'type=#{param.type}', + 'mode=plain', + 'begin=' + time, + 'status=' + status); + else + ajaxEngine.sendRequest( 'getEventDetails', + 'id=#{param.id}', + 'groupId=#{param.groupId}', + 'parent=#{param.parent}', + 'type=#{param.type}', + 'mode=plain', + 'begin=' + time); + + showEventsCallback(); + } +</script> + +<div id="overlay" class="overlay"></div> + +<table cellpadding="0" cellspacing="0" border="0" width="100%"> + + <c:if test="#{not empty EventsTimelineUIBean.data}"> + <tr> + <td colspan="62" style="height: 2px;"></td> + </tr> + + <tr style="height: 12px;"> + <td></td> + <c:forEach var="timeTick" items="#{EventsTimelineUIBean.data}" varStatus="status"> + <c:set var="count" value="#{status.index}"/> + <c:set var="icon" value="/images/no_event.gif"/> + <c:if test="#{not empty timeTick.severity}"> + <c:set var="sev" value="#{timeTick.severity.ordinal}"/> + <c:choose> + <c:when test="#{sev == 0 }"> + <c:set var="icon" value="/images/event_debug.gif"/> + </c:when> + <c:when test="#{sev == 1 }"> + <c:set var="icon" value="/images/event_info.gif"/> + </c:when> + <c:when test="#{sev == 2 }"> + <c:set var="icon" value="/images/event_warn.gif"/> + </c:when> + <c:when test="#{sev == 3 }"> + <c:set var="icon" value="/images/event_error.gif"/> + </c:when> + <c:when test="#{sev == 4 }"> + <c:set var="icon" value="/images/event_fatal.gif"/> + </c:when> + <c:otherwise> + <c:set var="icon" value="/images/no_event.gif"/> + </c:otherwise> + </c:choose> + </c:if> + + <!-- put onmousedown in table data element not the div, which gives the user a larger clickable area --> + <c:if test="#{empty timeTick.severity}"> + <td style="background-image: url(#{icon}); background-repeat:no-repeat;" align="center" valign="middle"> + </td> + </c:if> + + <c:if test="#{not empty timeTick.severity}"> + <ui:param name="formattedTimeTick" value="#{onf:formatTimestamp(timeTick.time)}"/> + <td style="background-image: url(#{icon}); background-repeat:no-repeat;" align="center" valign="middle" + onmousedown="detailsShowing=true;overlay.moveOverlay(this);overlay.showTimePopup('#{count}','#{formattedTimeTick}');showEventsDetails(#{timeTick.time});"> + </td> + </c:if> + + </c:forEach> + <td style="margin: 0 0 0 5;"> + <h:outputFormat value="#{msg['resource.common.monitor.label.elc']}" /> + </td> + </tr> + + <tr> + <td colspan="62" valign="top"> + <a name="eventDetail"></a> + <div id="eventDetailTable" + style="position: relative; height: 230px; display: none; "> + <div class="eventDetails"> + <table cellspacing="0" width="100%"> + <tr> + <td class="eventsTabOn" nowrap="nowrap"> + <h:outputFormat value="#{msg['resource.common.monitor.events.ListOfEvents']}" /> + </td> + <td valign="top" style="text-align: right; border-bottom: solid; border-width: 1px; border-color: #000000;"> + <img src="/images/dash-icon_delete.gif" + onclick="detailsShowing=false;new Effect.Fade($('eventDetailTable'), {afterFinish: function (obj) { maxIndicatorDivHeight(); overlay.moveOverlay(this); }})"/> + </td> + </tr> + <tr> + <td colspan="8"> + <div id="eventsSummary" style="height:200px; overflow:auto;"></div> + </td> + </tr> + </table> + </div> + </div> + </td> + </tr> + + <tr> + <td colspan="62" style="height: 3px;"></td> + </tr> + </c:if> + + <tr> + <td width="10"> + <div id="timetop"></div> + <img src="/images/timeline_ll.gif" height="10"/> + </td> + <c:forEach var="timeTick" items="#{EventsTimelineUIBean.data}" varStatus="status"> + <c:set var="count" value="#{status.index}"/> + <ui:param name="formattedTimeTick" value="#{onf:formatTimestamp(timeTick.time)}"/> + <td width="12"> + <div id="timePopup_#{count}" + onmouseover="overlay.moveOverlay(this);overlay.showTimePopup('#{count}','#{formattedTimeTick}')" > + <img src="/images/timeline_off.gif" height="10" width="9" + onmouseover="imageSwap(this, imagePath + 'timeline', '_on')" + onmouseout="imageSwap(this, imagePath + 'timeline', '_off');" + onmousedown="imageSwap(this, imagePath + 'timeline', '_down')" /> + </div> + </td> + </c:forEach> + <td width="100%"> + <img src="/images/timeline_lr.gif" height="10"/> + </td> + </tr> + + <tr> + <td></td> + <td colspan="30" valign="top"> + <h:outputText value="#{EventsTimelineUIBean.data[0].time}"> + <f:converter converterId="UserDateTimeConverter" /> + </h:outputText> + <div id="timePopup" class="timepopup" onmousedown="overlay.hideTimePopup()"></div> + </td> + <td colspan="30" align="right" valign="top"> + <h:outputText value="#{EventsTimelineUIBean.data[59].time}"> + <f:converter converterId="UserDateTimeConverter" /> + </h:outputText> + </td> + <td></td> + </tr> +</table> + +</ui:composition> + +</html> \ No newline at end of file diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/graphs-plain.xhtml b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/graphs-plain.xhtml new file mode 100644 index 0000000..acb697e --- /dev/null +++ b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/graphs-plain.xhtml @@ -0,0 +1,123 @@ +<ui:composition + 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:onc="http://jboss.org/on/component" + xmlns:onf="http://jboss.org/on/function" + xmlns:s="http://jboss.com/products/seam/taglib" + xmlns:a4j="https://ajax4jsf.dev.java.net/ajax" + xmlns:rich="http://richfaces.ajax4jsf.org/rich%22%3E + +<table border="0" cellpadding="0" cellspacing="0" width="100%"> + <!-- chart actions --> + <tr class="BlockContent"> + <td align="right"> + <ui:include src="measurement/views.xhtml"/> + </td> + </tr> + + <tr class="BlockContent"> + <td> + <ui:include src="availability/data.xhtml"/> + </td> + </tr> + + <tr class="BlockContent"> + <td> + <div id="indicatorDiv" style="width: 750px; height: 400px; border: 1; overflow-x: hidden; overflow-y: scroll;"> + <ui:include src="measurement/data-plain.xhtml"/> + </div> + </td> + </tr> + +<tr class="BlockContent"> + <td width="550px"> + <div id="eventsDiv"> + <ui:include src="events/data-plain.xhtml"/> + </div> + </td> +</tr> + +<!-- spacer for date/time overlay, so it doesn't overlap metric display range --> +<tr class="BlockContent"> + <td> + <br /> + <br /> + </td> +</tr> + +<tr class="BlockContent"> + <td> + <h:form id="MetricComponentForm"> + <c:if test="#{IndicatorChartsUIBean.context.resourceId != -1}"> + <input type="hidden" name="id" value="#{IndicatorChartsUIBean.context.resourceId}" /> + </c:if> + <c:if test="#{IndicatorChartsUIBean.context.groupId != -1}"> + <input type="hidden" name="groupId" value="#{IndicatorChartsUIBean.context.groupId}" /> + </c:if> + <c:if test="#{IndicatorChartsUIBean.context.parentResourceId != -1}"> + <input type="hidden" name="parent" value="#{IndicatorChartsUIBean.context.parentResourceId}" /> + </c:if> + <c:if test="#{IndicatorChartsUIBean.context.resourceTypeId != -1}"> + <input type="hidden" name="type" value="#{IndicatorChartsUIBean.context.resourceTypeId}" /> + </c:if> + <table> + <tr> + <td><onc:metric optionList="m,h,d" /></td> + <td> + <h:commandLink rendered="#{not MetricComponentUtilityUIBean.readOnly}" + action="#{MetricComponentUtilityUIBean.update}" > + <img src="/images/dash-button_go-arrow.gif" alt="Apply Metric Settings "/> + </h:commandLink> + <h:commandLink rendered="#{MetricComponentUtilityUIBean.readOnly}" + action="#{MetricComponentUtilityUIBean.switchToSimpleMode}"> + <h:outputText value="Switch to Simple Mode" /> + </h:commandLink> + </td> + </tr> + </table> + </h:form> + </td> +</tr> + +<!-- footerDiv used purely for calculating the height for the overlay --> +<tr class="BlockContent"> + <td> + <div id="footerDiv"></div> + </td> +</tr> +</table> + +<script type="text/javascript"> + function maxIndicatorDivHeight() { + var indicatorDiv = getElementCrossBrowser("indicatorDiv"); + var eventsDiv = getElementCrossBrowser("eventsDiv"); + var footerDiv = getElementCrossBrowser("footerDiv"); + + //IE6 returns 0 for document.documentElement.clientHeight + var browserHeight = document.documentElement.clientHeight || document.body.clientHeight; + var indicatorTopPos = getElementTopPos(indicatorDiv); + var eventsTopPos = getElementTopPos(eventsDiv); + var footerTopPos = getElementTopPos(footerDiv) ; + var eventsDivHeight = footerTopPos - eventsTopPos; + + var newIndicatorDivHeight = browserHeight - indicatorTopPos - eventsDivHeight - 2; + + //accomodating for the IE measurement difficulties + if (Prototype.Browser.IE) { + newIndicatorDivHeight -= 4; + } + + //if the inidicator div would be too small, let the whole content pane scroll instead + if (newIndicatorDivHeight > 50) { + indicatorDiv.style.height = newIndicatorDivHeight + "px"; + } + } + + addWindowOnLoadEvent(maxIndicatorDivHeight); + addWindowOnResizeEvent(maxIndicatorDivHeight); +</script> + +</ui:composition> \ No newline at end of file diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/measurement/data-plain.xhtml b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/measurement/data-plain.xhtml new file mode 100644 index 0000000..d944499 --- /dev/null +++ b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/common/monitor/measurement/data-plain.xhtml @@ -0,0 +1,197 @@ +<?xml version="1.0"?> + +<!DOCTYPE html + PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<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:rich="http://richfaces.ajax4jsf.org/rich" + xmlns:a4j="https://ajax4jsf.dev.java.net/ajax" + xmlns:s="http://jboss.com/products/seam/taglib" + xmlns:onc="http://jboss.org/on/component" + xmlns:onf="http://jboss.org/on/function%22%3E + +ui:composition + +<!-- NOTE: rico.js is used for the AJAX stuff below (i.e. the ajaxEngine object). --> +<a4j:loadScript src="/js/rico.js"/> + +<script language="JavaScript"> + + var baseUrl = "/resource/common/monitor/visibility/IndicatorCharts.do"; + baseUrl += '?'; + baseUrl += "#{onf:contextFragmentURLForIndicatorsChart()}" + baseUrl += '&view='; + baseUrl += "#{IndicatorChartsUIBean.view}"; + + // Register the remove metric chart method + ajaxEngine.registerRequest( 'indicatorCharts', baseUrl ); + + function addMetric(token) { + ajaxEngine.sendRequest( + 'indicatorCharts', + 'metric=' + token, + 'action=addChart', + 'view=' + '#{IndicatorChartsUIBean.view}'); + } + + function removeMetric(token) { + ajaxEngine.sendRequest( + 'indicatorCharts', + 'metric=' + token, + 'action=remove', + 'view=' + '#{IndicatorChartsUIBean.view}'); + new Effect.Fade(token); + } + + function moveMetricUp(token) { + ajaxEngine.sendRequest( + 'indicatorCharts', + 'metric=' + token, + 'action=moveUp', + 'view=' + '#{IndicatorChartsUIBean.view}'); + var root = $('root'); + var elem = $(token); + moveElementUp(elem, root); + } + + function moveMetricDown(token) { + ajaxEngine.sendRequest( + 'indicatorCharts', + 'metric=' + token, + 'action=moveDown', + 'view=' + '#{IndicatorChartsUIBean.view}'); + + var root = $('root'); + var elem = $(token); + moveElementDown(elem, root); + } + +</script> + +<form id="metricViewsForm"> + +<ul id="root" class="boxy"> + +<ui:param name="tableBorder" value="0" /> <!-- used for quick debugging --> +<ui:param name="context" value="#{IndicatorChartsUIBean.context}" /> +<c:forEach var="metric" varStatus="status" items="#{IndicatorChartsUIBean.data}"> + + <li id="#{metric.metricToken}"> + <table width="100%" border="#{tableBorder}" cellpadding="0" cellspacing="0"> + <tr> + <td> + <rich:panel bodyClass="BlockContent" style="border: 0px; margin: 0; padding: 0;"> + <font class="BoldText"> + ui:remove + <h:outputLink value="/resource/common/monitor/Visibility.do"> + <f:param name="m" value="#{metric.definitionId}"/> + <c:choose> + <c:when test="#{context.resourceTypeId > 0}"> + <f:param name="mode" value="chartSingleMetricMultiResource"/> + <f:param name="type" value="#{context.resourceTypeId}"/> + <f:param name="parent" value="#{context.parentResourceId}"/> + </c:when> + <c:when test="#{context.groupId > 0}"> + <f:param name="mode" value="chartSingleMetricMultiResource"/> + <f:param name="groupId" value="#{context.groupId}"/> + </c:when> + <c:otherwise> + <f:param name="mode" value="chartSingleMetricSingleResource"/> + <f:param name="id" value="#{context.resourceId}"/> + </c:otherwise> + </c:choose> + <h:outputText value="#{metric.label} " /> + </h:outputLink> + </ui:remove> + <h:outputText value="#{metric.label} " /> + + <c:choose> + <c:when test="#{context.groupId > 0}"> + <h:outputLink target="_top" value="/coregui/CoreGUI.html#ResourceGroup/#{metric.groupId}"> + <h:outputFormat value="#{msg['common.value.parenthesis']}"> + <f:param value="#{metric.metricSource}" /> + </h:outputFormat> + </h:outputLink> + </c:when> + <c:otherwise> + <h:outputLink target="_top" value="/coregui/CoreGUI.html#Resource/#{metric.metricSourceId}"> + <h:outputFormat value="#{msg['common.value.parenthesis']}"> + <f:param value="#{metric.metricSource}" /> + </h:outputFormat> + </h:outputLink> + </c:otherwise> + </c:choose> + </font> + <rich:toolTip followMouse="true" showDelay="500"> + <h:outputText value="#{metric.description}" rendered="#{not empty metric.description}" /> + <h:outputText value="No description of this metric available" rendered="#{empty metric.description}" /> + </rich:toolTip> + </rich:panel> + </td> + + <td width="400"> + <table cellpadding="0" cellspacing="0" border="#{tableBorder}" width="100%"> + <tr> + <td width="33%" nowrap="nowrap"> + <h:outputFormat style="font-weight: bold;" value="#{msg['resource.common.monitor.visibility.LowTH']}" />: + <h:outputText value="#{metric.minMetric.valueFmt}"/> + </td> + <td width="34%" nowrap="nowrap"> + <h:outputFormat style="font-weight: bold;" value="#{msg['resource.common.monitor.visibility.AvgTH']}" />: + <h:outputText value="#{metric.avgMetric.valueFmt}"/> + </td> + <td width="33%" nowrap="nowrap"> + <h:outputFormat style="font-weight: bold;" value="#{msg['resource.common.monitor.visibility.PeakTH']}" />: + <h:outputText value="#{metric.maxMetric.valueFmt}"/> + </td> + </tr> + </table> + </td> + + <td width="1"> + <table cellpadding="0" cellspacing="0" border="#{tableBorder}" width="100%" style="margin-right: 2px;"> + <tr> + <td width="33%"> + <a href="javascript:moveMetricUp('#{metric.metricToken}')"> + <img src="/images/dash_icon_up.gif" border="0"/> + </a> + </td> + <td width="33%"> + <a href="javascript:moveMetricDown('#{metric.metricToken}')"> + <img src="/images/dash_icon_down.gif" border="0"/> + </a> + </td> + <td width="34%"> + <a href="javascript:removeMetric('#{metric.metricToken}')"> + <img src="/images/dash-icon_delete.gif" border="0"/> + </a> + </td> + </tr> + </table> + </td> + </tr> + + <tr> + <td colspan="3"> + <h:graphicImage value="/resource/HighLowChart?#{onf:getChartURLParams(metric)}" + width="647" height="100" /> + </td> + </tr> + </table> + + </li> + +</c:forEach> + +</ul> + +</form> + +</ui:composition> + +</html> \ No newline at end of file diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/group/monitor/graphs-plain.xhtml b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/group/monitor/graphs-plain.xhtml index 14f6b68..c2c594f 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/group/monitor/graphs-plain.xhtml +++ b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/group/monitor/graphs-plain.xhtml @@ -12,7 +12,7 @@
<ui:define name="content">
- <ui:include src="/rhq/common/monitor/graphs.xhtml" /> + <ui:include src="/rhq/common/monitor/graphs-plain.xhtml" />
</ui:define>
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/resource/monitor/graphs-plain.xhtml b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/resource/monitor/graphs-plain.xhtml new file mode 100644 index 0000000..9aabd00 --- /dev/null +++ b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/resource/monitor/graphs-plain.xhtml @@ -0,0 +1,19 @@ +<ui:composition template="/rhq/resource/layout/main-plain.xhtml" + 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:onc="http://jboss.org/on/component" + xmlns:onf="http://jboss.org/on/function" + xmlns:s="http://jboss.com/products/seam/taglib" + xmlns:a4j="https://ajax4jsf.dev.java.net/ajax" + xmlns:rich="http://richfaces.ajax4jsf.org/rich%22%3E + + <ui:define name="content"> + + <ui:include src="/rhq/common/monitor/graphs-plain.xhtml" /> + + </ui:define> + +</ui:composition> \ No newline at end of file
commit 3cbc6823b6c9592c227b18018bfad6cd75caa927 Merge: e84012c... 6eea739... Author: Simeon Pinder spinder@redhat.com Date: Thu Sep 23 19:23:02 2010 -0400
Merge branch 'master' of ssh://spinder@git.fedorahosted.org/git/rhq/rhq into track-master
commit e84012cf010751c9eb71439d954f56170c060306 Author: Simeon Pinder spinder@redhat.com Date: Thu Sep 23 19:01:52 2010 -0400
various locatable selenium fixes, cleanup refactoring, refresh fix for InventorySummary portlet.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java index 11ce54c..3a09d44 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java @@ -75,13 +75,26 @@ public class PortletFactory { // TODO: Note, we're using a sequence generated ID here as a locatorId. This is not optimal for repeatable // tests as a change in the number of default portlets, or a change in test order could make a test // non-repeatable. But, at the moment we lack the infrastructure to generate a unique, predictable id. - Portlet view = viewFactory.getInstance(storedPortlet.getPortletKey() + "-" + Portlet view = viewFactory.getInstance(replaceSpaces(storedPortlet.getPortletKey()) + "-" + Integer.toString(storedPortlet.getId())); view.configure(portletWindow, storedPortlet);
return view; }
+ /** Translated spaces to underscore. Spaces not allowed in locator ids. + * + * @param portletKey + * @return + */ + private static String replaceSpaces(String portletKey) { + String translated = portletKey; + if (portletKey != null) { + translated = portletKey.replaceAll(" ", "_"); + } + return translated; + } + @SuppressWarnings("unchecked") public static List<String> getRegisteredPortlets() {
@@ -89,4 +102,5 @@ public class PortletFactory { Collections.sort(portlets); return portlets; } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java index 8159d23..062b882 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java @@ -18,6 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.queue;
+import static org.rhq.enterprise.gui.coregui.client.util.WidgetsField.UNLIMITED; + import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -37,6 +39,7 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; import org.rhq.enterprise.gui.coregui.client.inventory.resource.discovery.AutodiscoveryQueueDataSource; import org.rhq.enterprise.gui.coregui.client.inventory.resource.discovery.ResourceAutodiscoveryView; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** @@ -44,12 +47,14 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; */ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements CustomSettingsPortlet {
+ //ui attributes/properties/indentifiers public static final String KEY = "Discovery Queue"; private static final String AUTODISCOVERY_PLATFORM_MAX = "auto-discovery-platform-max"; - private String unlimited = "unlimited"; + private String unlimited = UNLIMITED.propertyName(); private String defaultValue = unlimited; + //portlet settings and datasource elements private DashboardPortlet storedPortlet; - private int maximumPlatformsToDisplay = -1; + private AutodiscoveryQueueDataSource dataSource;
public AutodiscoveryPortlet(String locatorId) { super(locatorId, true); @@ -59,26 +64,35 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C protected void onInit() { super.onInit(); //initialize the datasource to include Portlet instance - if (getTreeGrid() != null) { - getTreeGrid().setDataSource(new AutodiscoveryQueueDataSource(this)); + this.dataSource = new AutodiscoveryQueueDataSource(); + if ((getTreeGrid() != null) && (getDataSource() != null)) { + getTreeGrid().setDataSource(getDataSource()); } }
- /** Implement configure action. + /** Implements configure action. Stores reference to the initiating DashboardPortlet. + * Method loads i)initial portlet settings OR ii)retrieves previous settings and adds to + * the datasource. */ @Override public void configure(PortletWindow portletWindow, DashboardPortlet storedPortlet) { this.storedPortlet = storedPortlet; + String retrieved = null; + //if settings already exist for this portlet if (storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX) != null) { //retrieve and translate to int - String retrieved = storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX).getStringValue(); + retrieved = storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX).getStringValue(); + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(AUTODISCOVERY_PLATFORM_MAX, defaultValue)); + retrieved = defaultValue; + } + + if (getDataSource() != null) { if (retrieved.equals(unlimited)) { - setMaximumPlatformsToDisplay(-1); + getDataSource().setMaximumPlatformsToDisplay(-1); } else { - setMaximumPlatformsToDisplay(Integer.parseInt(retrieved)); + getDataSource().setMaximumPlatformsToDisplay(Integer.parseInt(retrieved)); } - } else {//create setting - storedPortlet.getConfiguration().put(new PropertySimple(AUTODISCOVERY_PLATFORM_MAX, defaultValue)); } }
@@ -91,29 +105,28 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C * */ public DynamicForm getCustomSettingsForm() { - - final DynamicForm form = new DynamicForm(); + final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("Settings")); form.setLayoutAlign(VerticalAlignment.CENTER);
//horizontal display component - LocatableHLayout row = new LocatableHLayout("auto-discovery.configuration"); - BlurbItem label = new BlurbItem("discovery-platform-count-label"); + LocatableHLayout row = new LocatableHLayout(extendLocatorId("auto-discovery.configuration")); + BlurbItem label = new BlurbItem(form.extendLocatorId("discovery-platform-count-label")); label.setValue("Number of platforms to display"); + label.setWrap(false);
//-------------combobox for number of platforms to display on the dashboard - final SelectItem maximumPlatformsComboBox = new SelectItem(AUTODISCOVERY_PLATFORM_MAX); - maximumPlatformsComboBox.setTitle(""); + final SelectItem maximumPlatformsComboBox = new SelectItem(form.extendLocatorId(AUTODISCOVERY_PLATFORM_MAX), ""); //spinder 9/3/10: the following is required workaround to disable editability of combobox. maximumPlatformsComboBox.setType("selection"); //define acceptable values for display amount - String[] acceptableDisplayValues = { "1", "2", "5", "10", unlimited }; - maximumPlatformsComboBox.setValueMap(acceptableDisplayValues); + String[] displayValues = { "1", "2", "5", "10", unlimited }; + maximumPlatformsComboBox.setValueMap(displayValues); //set width of dropdown display region maximumPlatformsComboBox.setWidth(100); maximumPlatformsComboBox.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { String selectedItem = "" + event.getValue(); - //stuff into the master form for retrieval + //store in master form for retrieval form.setValue(AUTODISCOVERY_PLATFORM_MAX, selectedItem); } }); @@ -129,12 +142,11 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C
//default selected value to 'unlimited'(live lists) and check both combobox settings here. String selectedValue = defaultValue; - if (storedPortlet != null) { - //if property exists retrieve it - if (storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX) != null) { - selectedValue = storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX).getStringValue(); - } else {//insert default value - storedPortlet.getConfiguration().put(new PropertySimple(AUTODISCOVERY_PLATFORM_MAX, defaultValue)); + if (getDataSource() != null) { + if (getDataSource().getMaximumPlatformsToDisplay() == -1) { + selectedValue = unlimited; + } else { + selectedValue = String.valueOf(getDataSource().getMaximumPlatformsToDisplay()); } } //prepopulate the combobox with the previously stored selection @@ -144,9 +156,10 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C
//submit handler form.addSubmitValuesHandler(new SubmitValuesHandler() { - @Override + //specify submit action. public void onSubmitValues(SubmitValuesEvent event) { if (form.getValue(AUTODISCOVERY_PLATFORM_MAX) != null) { + //persist this value to configuration storedPortlet.getConfiguration().put( new PropertySimple(AUTODISCOVERY_PLATFORM_MAX, form.getValue(AUTODISCOVERY_PLATFORM_MAX))); } @@ -164,11 +177,7 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C } }
- public int getMaximumPlatformsToDisplay() { - return maximumPlatformsToDisplay; - } - - public void setMaximumPlatformsToDisplay(int maximumPlatformsToDisplay) { - this.maximumPlatformsToDisplay = maximumPlatformsToDisplay; + public AutodiscoveryQueueDataSource getDataSource() { + return dataSource; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index f318cf4..18d262c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@ -36,7 +36,6 @@ import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.events.DataArrivedEvent; import com.smartgwt.client.widgets.grid.events.DataArrivedHandler; -import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.alert.AlertPriority; @@ -50,9 +49,9 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; -import org.rhq.enterprise.gui.coregui.client.inventory.groups.wizard.GroupMembersStep; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector; import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel;
@@ -98,8 +97,9 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor private AlertResourceSelectorRegion resourceSelector; private DashboardPortlet storedPortlet = null; private AlertPortletDataSource dataSource; + //instance ui widgets private Canvas containerCanvas; - private HLayout resourceSelectionLabelRow; + private LocatableHLayout resourceSelectionLabelRow;
public RecentAlertsPortlet(String locatorId) { this(locatorId, null, null); @@ -264,7 +264,7 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor public DynamicForm getCustomSettingsForm() {
//root dynamic form instance - final DynamicForm form = new DynamicForm(); + final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("custom-settings")); form.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH + 40);//largest widget display + 40 for buttons form.setHeight(450); form.setMargin(5); @@ -276,7 +276,7 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor LocatableLabel alertRangeLabel = new LocatableLabel("DynamicForm_Label_Alert_Range", "<b>Alert Range</b>");
//horizontal layout - LocatableHLayout row = new LocatableHLayout("alert-range-settings-row-1"); + LocatableHLayout row = new LocatableHLayout(extendLocatorId("alert-range-settings-row-1")); row.setMembersMargin(10);
//-------------combobox for number of completed scheduled ops to display on the dashboard @@ -352,9 +352,10 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor row.addMember(wrappedPriority);
//horizontal layout - LocatableHLayout row2 = new LocatableHLayout("alert-range-settings-row-2"); + LocatableHLayout row2 = new LocatableHLayout(extendLocatorId("alert-range-settings-row-2"));
- Label alertRangeSpanLabel = new Label("<b>within the past<b>"); + LocatableLabel alertRangeSpanLabel = new LocatableLabel(extendLocatorId("range-span-label"), + "<b>within the past<b>"); //------------- Build second combobox for timeframe for problem resources search. final SelectItem alertRangeTimeComboBox = new SelectItem(ALERT_RANGE_TIME_VALUE); alertRangeTimeComboBox.setTitle(""); @@ -444,49 +445,53 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor row2.addMember(resourceSelectionWrapper);
//Row 3 of labels for the alert selected resources area - resourceSelectionLabelRow = new HLayout(); + resourceSelectionLabelRow = new LocatableHLayout(extendLocatorId("resource-selection-label")); resourceSelectionLabelRow.setHeight(30); resourceSelectionLabelRow.setMembersMargin(5); resourceSelectionLabelRow.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH);//ui size + fixed button widths - Label availableResourcesLabel = new Label("<b>" + ALERT_LABEL_AVAILABLE_RESOURCES + "</b>"); + LocatableLabel availableResourcesLabel = new LocatableLabel(extendLocatorId("available-resources"), "<b>" + + ALERT_LABEL_AVAILABLE_RESOURCES + "</b>"); availableResourcesLabel.setHeight(20); availableResourcesLabel.setWrap(false); resourceSelectionLabelRow.addMember(availableResourcesLabel); Label spacer = new Label(""); spacer.setWidth(400); - Label selectedResourcesLabel = new Label("<b>" + ALERT_LABEL_SELECTED_RESOURCES + "</b>"); + LocatableLabel selectedResourcesLabel = new LocatableLabel(extendLocatorId("selected-resources"), "<b>" + + ALERT_LABEL_SELECTED_RESOURCES + "</b>"); selectedResourcesLabel.setHeight(20); selectedResourcesLabel.setWrap(false); resourceSelectionLabelRow.addMember(spacer); resourceSelectionLabelRow.addMember(selectedResourcesLabel);
- //##### if portlet config setting exist, then retrieve############# + //if portlet config setting exist, then retrieve Integer[] alertFilterResourceIds = null; alertFilterResourceIds = getDataSource().extractFilterResourceIds(storedPortlet, alertFilterResourceIds); if (alertFilterResourceIds != null) { getDataSource().setAlertFilterResourceId(alertFilterResourceIds); }
- HLayout row4 = new HLayout(); - row4.setID("row4"); - // resourceSelector = new MemberSelect(); + LocatableHLayout resourceSelectionRegion = new LocatableHLayout(extendLocatorId("selection-canvas")); resourceSelector = new AlertResourceSelectorRegion(alertFilterResourceIds); - row4.setWidth100(); + resourceSelectionRegion.setWidth100(); + + //instantiate canvas area to display empty or rich resource selection based on dropdown selection containerCanvas = new Canvas(); - String retProp = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE).getStringValue(); + String previousAlertFilterChoice = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE) + .getStringValue();
//reload the ResourceSelectionRegion if user has chosen to focus on specific resources with alerts - if (retProp.equals(RESOURCES_SELECTED)) { + if (previousAlertFilterChoice.equals(RESOURCES_SELECTED)) { containerCanvas.addChild(resourceSelector.getCanvas()); - } else { + } else {// define empty canvas containerCanvas.addChild(new Canvas()); //iterate over children of row3 and make invisible for (Canvas c : resourceSelectionLabelRow.getMembers()) { c.setVisible(false); } } + //add contain resource selection region. - row4.addMember(containerCanvas); + resourceSelectionRegion.addMember(containerCanvas);
//finish construction of the layout column.addMember(row); @@ -497,7 +502,7 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor spacerWrapper.setItems(verticalSpace); column.addMember(spacerWrapper); column.addMember(resourceSelectionLabelRow); - column.addMember(row4); + column.addMember(resourceSelectionRegion); form.addChild(column);
//submit handler @@ -525,7 +530,7 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor storedPortlet.getConfiguration().put(new PropertyList(ALERT_RANGE_RESOURCE_IDS, list)); getDataSource().setAlertFilterResourceId(resourceSelector.getCurrentlyAssignedIds()); } - refresh();// + refresh();//reload form with new data selections markForRedraw(); } }); @@ -564,25 +569,13 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor } }
-class CustomizedResourceSelector extends ResourceSelector { - public CustomizedResourceSelector(String locatorId) { - super(locatorId); - } - - public CustomizedResourceSelector(String locatorId, ResourceType rtFilter, boolean forceRtFilter) { - super(locatorId, rtFilter, forceRtFilter); - } +/** Bundles a ResourceSelector instance with labelling in Canvas for display. + * Also modifies the AssignedGrid to listen for AvailbleGrid completion and act accordingly. + */ +class AlertResourceSelectorRegion {
- public void addAvailableGridSelectionsToAssignedGrid() { - assignedGrid.transferSelectedData(availableGrid); - select(assignedGrid.getSelection()); - updateButtons(); - } -} + private ResourceSelector selector = null;
-class AlertResourceSelectorRegion extends GroupMembersStep { - // private ResourceSelector selector = null; - private CustomizedResourceSelector selector = null; private Integer[] currentlyAssignedIds;
public Integer[] getCurrentlyAssignedIds() { @@ -605,20 +598,20 @@ class AlertResourceSelectorRegion extends GroupMembersStep { }
public AlertResourceSelectorRegion(Integer[] assigned) { - super(null); this.currentlyAssignedIds = assigned; }
public Canvas getCanvas() { if (selector == null) { - // selector = new ResourceSelector(getName()); - selector = new CustomizedResourceSelector(getName(), ResourceType.ANY_PLATFORM_TYPE, true); + selector = new ResourceSelector("Select Members", ResourceType.ANY_PLATFORM_TYPE, true); selector.setWidth100(); selector.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH); //widget ui updates selector.getAvailableGrid().setTitle("Available Resources"); selector.getAvailableGrid().setEmptyMessage("Loading data..."); selector.getAssignedGrid().setTitle("Selected Resources"); + //disable display typeFilter. + selector.setDisplayResourceTypeFilter(false);
//populate fields for grid. ListGridField nameField = new ListGridField("name", "Name"); @@ -634,12 +627,14 @@ class AlertResourceSelectorRegion extends GroupMembersStep { if ((getCurrentlyAssignedIds() != null) && (getCurrentlyAssignedIds().length > 0)) { //retrieve the loaded data and add to the table itself RecordList recordList = selector.getAvailableGrid().getDataAsRecordList(); + //for each of the resource ids loaded from settings, select that row for transfer. for (int ci : getCurrentlyAssignedIds()) { int located = recordList.findIndex("id", ci); if (located > -1) { selector.getAvailableGrid().selectRecord(located); } } + //simulate 'add' button push. selector.addAvailableGridSelectionsToAssignedGrid(); selector.getAssignedGrid().invalidateCache(); selector.getAssignedGrid().markForRedraw(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationsPortlet.java index 54647a1..2484d63 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationsPortlet.java @@ -21,7 +21,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.operatio
import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; -import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; @@ -43,7 +42,9 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; import org.rhq.enterprise.gui.coregui.client.operation.RecentOperationsDataSource; import org.rhq.enterprise.gui.coregui.client.operation.ScheduledOperationsDataSource; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableListGrid; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
@@ -193,17 +194,17 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting public DynamicForm getCustomSettingsForm() {
//root dynamic form instance - final DynamicForm form = new DynamicForm(); + final LocatableDynamicForm form = new LocatableDynamicForm("custom-settings");
//vertical layout VStack column = new VStack();
//label - Label operationRange = new Label("Operation Range"); + LocatableLabel operationRange = new LocatableLabel(extendLocatorId("operation-range"), "Operation Range"); column.addMember(operationRange);
//horizontal layout - LocatableHLayout row = new LocatableHLayout("enable.completed.operations"); + LocatableHLayout row = new LocatableHLayout(extendLocatorId("enable.completed.operations"));
//checkbox indicating whether to apply completed operations grouping settings final CheckboxItem enableCompletedOperationsGrouping = new CheckboxItem(); @@ -266,7 +267,7 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting row.addMember(item2);
//horizontal layout - LocatableHLayout row2 = new LocatableHLayout("enable.scheduled.operations"); + LocatableHLayout sheduledOperationsLayout = new LocatableHLayout(extendLocatorId("enable.scheduled.operations"));
final CheckboxItem enableScheduledOperationsGrouping = new CheckboxItem(); enableScheduledOperationsGrouping.setName(OPERATIONS_RANGE_SCHEDULED_ENABLED); @@ -282,7 +283,7 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting //wrap field item in dynamicform for addition DynamicForm fieldWrapper = new DynamicForm(); fieldWrapper.setFields(enableScheduledOperationsGrouping); - row2.addMember(fieldWrapper); + sheduledOperationsLayout.addMember(fieldWrapper);
//retrieve previous value otherwise initialize to true(live unlimited list) retrieved = storedPortlet.getConfiguration().getSimple(OPERATIONS_RANGE_SCHEDULED_ENABLED); @@ -321,9 +322,9 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting maximumScheduledOperationsComboBox.setDefaultValue(selectedValue); DynamicForm fieldWrapper2 = new DynamicForm(); fieldWrapper2.setFields(maximumScheduledOperationsComboBox); - row2.addMember(fieldWrapper2); + sheduledOperationsLayout.addMember(fieldWrapper2); column.addMember(row); - column.addMember(row2); + column.addMember(sheduledOperationsLayout); form.addChild(column);
//submit handler diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java index 2778c59..d233d5b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java @@ -26,7 +26,6 @@ import java.util.List; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; -import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; @@ -46,7 +45,9 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; import org.rhq.enterprise.gui.coregui.client.resource.ProblemResourcesDataSource; import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel;
/** * A view that displays a paginated table of Resources with alerts, @@ -157,7 +158,7 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort */ public DynamicForm getCustomSettingsForm() {
- final DynamicForm form = new DynamicForm(); + final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("custom-settings"));
//-------------combobox for number of resource to display on the dashboard final SelectItem maximumProblemResourcesComboBox = new SelectItem(PROBLEM_RESOURCE_SHOW_MAX); @@ -289,7 +290,7 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort * @author spinder */ class TimeRange extends LocatableHLayout implements TableWidget { - private Label label = new Label(); + private LocatableLabel label = new LocatableLabel(extendLocatorId("time-range-label")); private ProblemResourcesPortlet portlet = null;
public TimeRange(String locatorId, ProblemResourcesPortlet problemResourcesPortlet) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java index 859a7d5..361a1f7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryView.java @@ -45,25 +45,30 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceBossGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.inventory.resource.InventoryView; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
public class InventorySummaryView extends LocatableVLayout implements Portlet {
private ResourceBossGWTServiceAsync resourceBossService = GWTServiceLookup.getResourceBossService();
- private DynamicForm form; + private LocatableDynamicForm form; public static final String KEY = "Summary Counts";
public InventorySummaryView(String locatorId) { super(locatorId);
+ loadInventoryViewDiata(); + } + + private void loadInventoryViewDiata() { resourceBossService.getInventorySummaryForLoggedInUser(new AsyncCallback<InventorySummary>() { public void onFailure(Throwable throwable) { CoreGUI.getErrorHandler().handleError("Failed to retrieve inventory summary", throwable); }
public void onSuccess(InventorySummary summary) { - form = new DynamicForm(); + form = new LocatableDynamicForm("Portlet_Inventory_Summary"); List<FormItem> formItems = new ArrayList<FormItem>();
// HeaderItem headerItem = new HeaderItem("header"); @@ -131,6 +136,17 @@ public class InventorySummaryView extends LocatableVLayout implements Portlet { return null; // TODO: Implement this method. }
+ /** Custom refresh operation as we are not directly extending Table + */ + @Override + public void redraw() { + super.redraw(); + //destroy form + form.destroy(); + //now reload the data + loadInventoryViewDiata(); + } + public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/AutodiscoveryQueueDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/AutodiscoveryQueueDataSource.java index 63ed782..a881444 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/AutodiscoveryQueueDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/AutodiscoveryQueueDataSource.java @@ -39,8 +39,6 @@ import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageOrdering; import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; -import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.queue.AutodiscoveryPortlet; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTServiceAsync;
@@ -49,15 +47,10 @@ import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTServiceAsync; */ public class AutodiscoveryQueueDataSource extends DataSource {
- private Portlet portlet = null; private int unlimited = -1; + private int maximumPlatformsToDisplay = -1; private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService();
- public AutodiscoveryQueueDataSource(Portlet portlet) { - this(); - this.portlet = portlet; - } - public AutodiscoveryQueueDataSource() { setClientOnly(false); setDataProtocol(DSProtocol.CLIENTCUSTOM); @@ -159,10 +152,8 @@ public class AutodiscoveryQueueDataSource extends DataSource { protected PageControl getPageControl(DSRequest request) { // Initialize paging. PageControl pageControl; - //retrieve portlet.configurationInformation - if ((this.portlet != null) || (this.portlet instanceof AutodiscoveryPortlet)) {//using default - AutodiscoveryPortlet settings = (AutodiscoveryPortlet) this.portlet; - pageControl = new PageControl(0, settings.getMaximumPlatformsToDisplay()); + if (getMaximumPlatformsToDisplay() > -1) {//using default + pageControl = new PageControl(0, getMaximumPlatformsToDisplay()); } else { pageControl = new PageControl(0, unlimited); } @@ -221,4 +212,13 @@ public class AutodiscoveryQueueDataSource extends DataSource { return getAttribute("parentId"); } } + + public int getMaximumPlatformsToDisplay() { + return maximumPlatformsToDisplay; + } + + public void setMaximumPlatformsToDisplay(int maximumPlatformsToDisplay) { + this.maximumPlatformsToDisplay = maximumPlatformsToDisplay; + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java index 0047b1f..432ca27 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java @@ -49,6 +49,7 @@ public class ResourceSelector extends AbstractSelector<Resource> {
private ResourceType resourceTypeFilter; private boolean forceResourceTypeFilter; + private boolean displayResourceTypeFilter = true; private IPickTreeItem typeSelectItem;
public ResourceSelector(String locatorId) { @@ -80,6 +81,9 @@ public class ResourceSelector extends AbstractSelector<Resource> { if (this.forceResourceTypeFilter) { typeSelectItem.setDisabled(true); } + if (!isDisplayResourceTypeFilter()) { + typeSelectItem.setVisible(false); + }
categorySelect = new SelectItem("category", "Category"); categorySelect.setValueMap("Platform", "Server", "Service"); @@ -126,6 +130,14 @@ public class ResourceSelector extends AbstractSelector<Resource> { return criteria; }
+ /** transfers selected data to the assigned grid. This operation mimics button click from ResourceSelection. + */ + public void addAvailableGridSelectionsToAssignedGrid() { + assignedGrid.transferSelectedData(availableGrid); + select(assignedGrid.getSelection()); + updateButtons(); + } + // protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { // String search = (String) availableFilterForm.getValue("search"); // String type = availableFilterForm.getValueAsString("type"); @@ -183,4 +195,12 @@ public class ResourceSelector extends AbstractSelector<Resource> { }
} + + public boolean isDisplayResourceTypeFilter() { + return displayResourceTypeFilter; + } + + public void setDisplayResourceTypeFilter(boolean displayResourceTypeFilter) { + this.displayResourceTypeFilter = displayResourceTypeFilter; + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/operation/RecentOperationsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/operation/RecentOperationsDataSource.java index 2c02f25..863afe2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/operation/RecentOperationsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/operation/RecentOperationsDataSource.java @@ -48,6 +48,7 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; */ public class RecentOperationsDataSource extends RPCDataSource<DisambiguationReport<ResourceOperationLastCompletedComposite>> { + //ui keys public static final String resource = "resource"; public static final String location = "location"; public static final String operation = "operation"; @@ -58,7 +59,6 @@ public class RecentOperationsDataSource extends //config attributes private boolean operationsRangeLastEnabled = false; private int operationsRangeCompleted = -1; - private boolean dataRangeDisabled = true; public static String RANGE_DISABLED_MESSAGE = "(Results currently disabled. Change settings to enable results.)";
/** Build list of fields for the datasource and then adds them to it. diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetsField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetsField.java new file mode 100644 index 0000000..ba8413a --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/WidgetsField.java @@ -0,0 +1,63 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License, 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.util; + +public enum WidgetsField { + + UNLIMITED("unlimited", "Unlimited"); + + // DESCRIPTION("description", "Description"), + // + // TYPE("resourceType.name", "Type"), + // + // PLUGIN("pluginName", "Plugin"), + // + // CATEGORY("resourceType.category", "Category"), + // + // AVAILABILITY("currentAvailability", "Availability"); + + /** + * Corresponds to a property name of Resource + */ + private String propertyName; + + /** + * The display name for the field or property + */ + private String title; + + private WidgetsField(String propertyName, String title) { + this.propertyName = propertyName; + this.title = title; + } + + public String propertyName() { + return propertyName; + } + + public String title() { + return title; + } + +}
commit 6eea739a198db967a5bb26567b0133b77b363466 Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 23 12:15:32 2010 -0400
finish the dampening editor
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java index 87eecea..1942004 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java @@ -30,6 +30,8 @@ import com.smartgwt.client.widgets.form.fields.SpinnerItem; 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.ItemHoverEvent; +import com.smartgwt.client.widgets.form.fields.events.ItemHoverHandler;
import org.rhq.core.domain.alert.AlertDampening; import org.rhq.core.domain.alert.AlertDefinition; @@ -109,10 +111,12 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement alertDefinition.setAlertDampening(alertDampening); }
- dampeningRuleSelection.setValue(alertDampening.getCategory().name()); - dampeningRuleStatic.setValue(getCategoryTitle(alertDampening.getCategory())); + Category category = alertDampening.getCategory(); + dampeningRuleSelection.setValue(category.name()); + dampeningRuleStatic.setValue(getCategoryTitle(category)); + dampeningRuleStatic.setTooltip(getCategoryHelp(category.name()));
- switch (alertDampening.getCategory()) { + switch (category) { case NONE: { break; } @@ -141,8 +145,7 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement break; } default: { - throw new IllegalStateException("Invalid category - please report this as a bug: " - + alertDampening.getCategory()); // should never happen + throw new IllegalStateException("Invalid category - please report this as a bug: " + category); // should never happen } } } @@ -380,8 +383,6 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement
private void buildForm() { if (!formBuilt) { - setNumCols(3); - dampeningRuleSelection = new SelectItem("dampeningRule", "Dampening Rule"); LinkedHashMap<String, String> rules = new LinkedHashMap<String, String>(4); rules.put(AlertDampening.Category.NONE.name(), getCategoryTitle(AlertDampening.Category.NONE)); @@ -395,79 +396,86 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement dampeningRuleSelection.setDefaultValue(AlertDampening.Category.NONE.name()); dampeningRuleSelection.setWrapTitle(false); dampeningRuleSelection.setRedrawOnChange(true); - dampeningRuleSelection.setColSpan(2); + dampeningRuleSelection.setHoverWidth(300); + dampeningRuleSelection.addItemHoverHandler(new ItemHoverHandler() { + @Override + public void onItemHover(ItemHoverEvent event) { + String selection = dampeningRuleSelection.getValue().toString(); + dampeningRuleSelection.setTooltip(getCategoryHelp(selection)); + } + }); + dampeningRuleStatic = new StaticTextItem("dampeningRuleStatic", "Dampening Rule"); - dampeningRuleStatic.setColSpan(2); dampeningRuleStatic.setWrapTitle(false); + dampeningRuleStatic.setHoverWidth(300);
// NONE // nothing to do - the none category has no ui components to render
// CONSECUTIVE_COUNT consecutiveOccurrencesSpinner = new SpinnerItem("consecutiveOccurrencesSpinner", "Occurrences"); - consecutiveOccurrencesSpinner.setColSpan(2); consecutiveOccurrencesSpinner.setWrapTitle(false); consecutiveOccurrencesSpinner.setMin(1); consecutiveOccurrencesSpinner.setMax(999999); consecutiveOccurrencesSpinner.setStep(1); consecutiveOccurrencesSpinner.setDefaultValue(1); + consecutiveOccurrencesSpinner.setHoverWidth(300); consecutiveOccurrencesSpinner .setTooltip("The number of times the condition set must be consecutively true before the alert is triggered."); consecutiveOccurrencesStatic = new StaticTextItem("consecutiveOccurrencesStatic", "Occurrences"); - consecutiveOccurrencesStatic.setColSpan(2); consecutiveOccurrencesStatic.setWrapTitle(false);
// PARTIAL_COUNT partialOccurrencesSpinner = new SpinnerItem("partialOccurrencesSpinner", "Occurrences"); - partialOccurrencesSpinner.setColSpan(2); partialOccurrencesSpinner.setWrapTitle(false); partialOccurrencesSpinner.setMin(1); partialOccurrencesSpinner.setMax(999999); partialOccurrencesSpinner.setStep(1); partialOccurrencesSpinner.setDefaultValue(1); + partialOccurrencesSpinner.setHoverWidth(300); partialOccurrencesSpinner .setTooltip("The number of times the condition set must be true during the last N evaluations before the alert is triggered."); partialOccurrencesStatic = new StaticTextItem("partialOccurrencesStatic", "Occurrences"); - partialOccurrencesStatic.setColSpan(2); partialOccurrencesStatic.setWrapTitle(false);
partialEvaluationsSpinner = new SpinnerItem("partialEvaluationsSpinner", "Evaluations"); - partialEvaluationsSpinner.setColSpan(2); partialEvaluationsSpinner.setWrapTitle(false); partialEvaluationsSpinner.setMin(1); partialEvaluationsSpinner.setMax(999999); partialEvaluationsSpinner.setStep(1); partialEvaluationsSpinner.setDefaultValue(1); + partialEvaluationsSpinner.setHoverWidth(300); + partialEvaluationsSpinner + .setTooltip("The total number of times the condition set will be tested to see if the given number of occurrences are true."); partialEvaluationsStatic = new StaticTextItem("partialEvaluationStatic", "Evaluations"); - partialEvaluationsStatic.setColSpan(2); partialEvaluationsStatic.setWrapTitle(false);
// DURATION_COUNT durationOccurrencesSpinner = new SpinnerItem("durationOccurrencesSpinner", "Occurrences"); - durationOccurrencesSpinner.setColSpan(2); durationOccurrencesSpinner.setWrapTitle(false); durationOccurrencesSpinner.setMin(1); durationOccurrencesSpinner.setMax(999999); durationOccurrencesSpinner.setStep(1); durationOccurrencesSpinner.setDefaultValue(1); + durationOccurrencesSpinner.setHoverWidth(300); durationOccurrencesSpinner .setTooltip("The number of times the condition set must be true during the given time period before the alert is triggered."); durationOccurrencesStatic = new StaticTextItem("durationOccurrencesStatic", "Occurrences"); - durationOccurrencesStatic.setColSpan(2); durationOccurrencesStatic.setWrapTitle(false);
durationTimePeriodSpinner = new SpinnerItem("durationTimePeriodSpinner", "Time Period"); - durationTimePeriodSpinner.setEndRow(false); durationTimePeriodSpinner.setWrapTitle(false); durationTimePeriodSpinner.setMin(1); durationTimePeriodSpinner.setMax(999999); durationTimePeriodSpinner.setStep(1); durationTimePeriodSpinner.setDefaultValue(1); + durationTimePeriodSpinner.setHoverWidth(300); + durationTimePeriodSpinner + .setTooltip("The time span in which the condition set will be tested to see if the given number of occurrences are true."); durationTimePeriodStatic = new StaticTextItem("durationTimePeriodStatic", "Time Period"); - durationTimePeriodStatic.setEndRow(false); durationTimePeriodStatic.setWrapTitle(false);
- durationTimeUnitsSelection = new SelectItem("durationTimeUnits"); + durationTimeUnitsSelection = new SelectItem("durationTimeUnits", ""); LinkedHashMap<String, String> units = new LinkedHashMap<String, String>(4); units.put(AlertDampening.TimeUnits.MINUTES.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.MINUTES)); units.put(AlertDampening.TimeUnits.HOURS.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.HOURS)); @@ -475,13 +483,7 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement units.put(AlertDampening.TimeUnits.WEEKS.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.WEEKS)); durationTimeUnitsSelection.setValueMap(units); durationTimeUnitsSelection.setDefaultValue(AlertDampening.TimeUnits.MINUTES.name()); - durationTimeUnitsSelection.setStartRow(false); - durationTimeUnitsSelection.setEndRow(true); - durationTimeUnitsSelection.setShowTitle(false); - durationTimeUnitsStatic = new StaticTextItem("durationTimeUnitsStatic"); - durationTimeUnitsStatic.setStartRow(false); - durationTimeUnitsStatic.setEndRow(true); - durationTimeUnitsStatic.setShowTitle(false); + durationTimeUnitsStatic = new StaticTextItem("durationTimeUnitsStatic", "");
dampeningRuleSelection.addChangedHandler(new ChangedHandler() { @Override @@ -582,4 +584,18 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement } } } + + private String getCategoryHelp(String categorySelection) { + if (AlertDampening.Category.NONE.name().equals(categorySelection)) { + return "Dampening is disabled. Every time the condition set is true, an alert will be triggered."; + } else if (AlertDampening.Category.CONSECUTIVE_COUNT.name().equals(categorySelection)) { + return "An alert is triggered once every X occurrences the condition set is true consecutively."; + } else if (AlertDampening.Category.PARTIAL_COUNT.name().equals(categorySelection)) { + return "An alert is triggered once every X occurrences the condition set is true during the last N evaluations of the condition set."; + } else if (AlertDampening.Category.DURATION_COUNT.name().equals(categorySelection)) { + return "An alert is triggered once every X occurrences the condition set is true within a given time period."; + } + + return null; // should never happen + } }
commit ef0e71c4bea6ebb2f9fb4b14eac1891007931b2e Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 23 12:15:04 2010 -0400
widen the tooltip window
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java index 86d816b..b539d0a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java @@ -158,6 +158,7 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements disableWhenFiredSelection.setDefaultValue("no"); disableWhenFiredSelection.setWrapTitle(false); disableWhenFiredSelection.setWidth(300); + disableWhenFiredSelection.setHoverWidth(300); disableWhenFiredSelection .setTooltip("Indicates if this alert will be disabled after it fires. Once disabled, the alert can be manually re-enabled or a recovery alert can be set up to automatically re-enable it. If this alert is a recovery alert itself, this setting cannot be turned on."); disableWhenFiredStatic = new StaticTextItem("disableWhenFiredStatic", "Disable When Fired"); @@ -166,6 +167,7 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements recoverAlertSelection = new SelectItem("recoveryAlert", "Recover Alert"); recoverAlertSelection.setDefaultValue("0"); recoverAlertSelection.setWrapTitle(false); + recoverAlertSelection.setHoverWidth(300); recoverAlertSelection .setTooltip("The target alert that will be recovered (i.e. re-enabled) after this alert triggers. Do not select an alert here if you are not defining a recovery alert.");
commit 4092afb4e2b2c764b5ab0e8111b37110e9af73ea Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 23 12:14:44 2010 -0400
add tooltip to explain ANY and ALL
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java index 571daed..6991b2c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java @@ -143,6 +143,9 @@ public class ConditionsAlertDefinitionForm extends LocatableVLayout implements E conditionExpression.setValueMap(condExprs); conditionExpression.setDefaultValue(BooleanExpression.ANY.name()); conditionExpression.setWrapTitle(false); + conditionExpression.setHoverWidth(300); + conditionExpression + .setTooltip("Determines if ANY or ALL of the conditions must evaluate to true in order for the entire condition set to be considered true.");
conditionExpressionStatic = new StaticTextItem("conditionExpressionStatic", "Fire alert when"); conditionExpressionStatic.setWrapTitle(false);
commit 34952d9da9c662bc241c90011e199e74c4a931cb Merge: d905826... 9a36c9d... Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Sep 23 10:58:11 2010 -0400
Merge branch 'master' into master-jay
commit d9058264c89ab9c489de7e698fd1af5de9245908 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Sep 23 10:56:56 2010 -0400
Added MANAGE_INVENTORY check for group membership subtab enablement
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 c11659e..50700f2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java @@ -18,13 +18,17 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail;
+import java.util.HashSet; import java.util.List; +import java.util.Set;
import com.google.gwt.user.client.History; +import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Side; import com.smartgwt.client.widgets.Canvas; 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.ViewPath; @@ -33,6 +37,7 @@ import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTab; import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSelectedEvent; import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSelectedHandler; import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSet; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -79,9 +84,9 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo
protected abstract List<TwoLevelTab> createTabs();
- protected abstract void loadSelectedItem(int itemId, ViewPath viewPath); + protected abstract void loadSelectedItem(int itemId, ViewPath viewPath, Set<Permission> globalPermissions);
- protected abstract void updateTabContent(T selectedItem); + protected abstract void updateTabContent(T selectedItem, Set<Permission> globalPermissions);
// ---------------------------------------------------------
@@ -136,10 +141,10 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo } }
- public void renderView(ViewPath viewPath) { + public void renderView(final ViewPath viewPath) { // e.g. #Resource/10010/Summary/Overview // ^ current path - int id = Integer.parseInt(viewPath.getCurrent().getPath()); + final int id = Integer.parseInt(viewPath.getCurrent().getPath()); viewPath.next();
if (!viewPath.isEnd()) { @@ -160,8 +165,23 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo }
if (getSelectedItemId() == null || getSelectedItemId() != id) { - // A different Resource or first load - go get data. - loadSelectedItem(id, viewPath); + GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions( + new AsyncCallback<Set<Permission>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Could not determine global permissions for user, defaulting to no global permissions.", + caught); + // A different Resource or first load - go get data. + loadSelectedItem(id, viewPath, new HashSet<Permission>()); + } + + @Override + public void onSuccess(Set<Permission> result) { + // A different Resource or first load - go get data. + loadSelectedItem(id, viewPath, result); + } + }); } else { // Same Resource - just switch tabs. selectTab(this.tabName, this.subTabName, viewPath); 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 17d901c..f273c40 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 @@ -178,7 +178,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource return tabs; }
- protected void updateTabContent(ResourceGroupComposite groupComposite) { + protected void updateTabContent(ResourceGroupComposite groupComposite, Set<Permission> globalPermissions) { + boolean enabled; boolean visible; Canvas canvas;
@@ -227,9 +228,10 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource //updateSubTab(this.inventoryTab, this.inventoryConn, // new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin), // facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), true); - // TODO: should require MANAGE_INVENTORY authz - updateSubTab(this.inventoryTab, this.inventoryMembership, new ResourceGroupMembershipView(this.inventoryTab - .extendLocatorId("MembershipView"), groupId), true, true); + enabled = globalPermissions.contains(Permission.MANAGE_INVENTORY); + canvas = (enabled) ? new ResourceGroupMembershipView(this.inventoryTab.extendLocatorId("MembershipView"), + groupId) : null; + updateSubTab(this.inventoryTab, this.inventoryMembership, canvas, true, enabled);
if (updateTab(this.operationsTab, groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.OPERATION), true)) { @@ -263,7 +265,7 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource markForRedraw(); }
- protected void loadSelectedItem(final int groupId, final ViewPath viewPath) { + protected void loadSelectedItem(final int groupId, final ViewPath viewPath, final Set<Permission> globalPermissions) { this.groupId = groupId;
ResourceGroupCriteria criteria = new ResourceGroupCriteria(); @@ -279,12 +281,13 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
public void onSuccess(PageList<ResourceGroupComposite> result) { groupComposite = result.get(0); - loadResourceType(groupComposite, viewPath); + loadResourceType(groupComposite, viewPath, globalPermissions); } }); }
- private void loadResourceType(final ResourceGroupComposite groupComposite, final ViewPath viewPath) { + private void loadResourceType(final ResourceGroupComposite groupComposite, final ViewPath viewPath, + final Set<Permission> globalPermissions) { final ResourceGroup group = this.groupComposite.getResourceGroup();
if (group.getGroupCategory() == GroupCategory.COMPATIBLE) { @@ -307,14 +310,14 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
public void onSuccess(Set<Permission> result) { ResourceGroupDetailView.this.permissions = new ResourcePermission(result); - updateTabContent(groupComposite); + updateTabContent(groupComposite, globalPermissions); selectTab(getTabName(), getSubTabName(), viewPath); } }); } }); } else { - updateTabContent(groupComposite); + updateTabContent(groupComposite, globalPermissions); selectTab(getTabName(), getSubTabName(), viewPath); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index ba88b87..7236d4b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -27,6 +27,7 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.tab.Tab;
+import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementDefinition; @@ -189,7 +190,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo return new ResourceTitleBar(extendLocatorId("TitleBar")); }
- protected void updateTabContent(ResourceComposite resourceComposite) { + protected void updateTabContent(ResourceComposite resourceComposite, Set<Permission> globalPermissions) { + boolean enabled; boolean visible; Canvas canvas;
@@ -201,7 +203,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo ((TwoLevelTab) top).getLayout().destroyViews(); }
- ResourcePermission permissions = this.resourceComposite.getResourcePermission(); + ResourcePermission resourcePermissions = this.resourceComposite.getResourcePermission(); Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets();
updateSubTab(this.summaryTab, this.summaryOverview, new OverviewView(this.summaryTab @@ -239,9 +241,10 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.inventoryTab, this.inventoryConn, canvas, visible, true); updateSubTab(this.inventoryTab, this.inventoryGroups, ResourceGroupListView.getGroupsOf(this.inventoryTab .extendLocatorId("GroupsView"), resource.getId()), true, true); - // TODO: authz check for this subtab: MANAGE_INVENTORY - updateSubTab(this.inventoryTab, this.inventoryGroupMembership, new ResourceResourceGroupsView(this.inventoryTab - .extendLocatorId("GroupMembershipView"), resourceId), true, true); + enabled = globalPermissions.contains(Permission.MANAGE_INVENTORY); + canvas = (enabled) ? new ResourceResourceGroupsView(this.inventoryTab.extendLocatorId("GroupMembershipView"), + resourceId) : null; + updateSubTab(this.inventoryTab, this.inventoryGroupMembership, canvas, true, enabled);
if (updateTab(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION), true)) { // comment out GWT-based operation history until... @@ -268,7 +271,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.alertsTab, this.alertDelete, new FullHTMLPane( "/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()), true, true);
- if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), permissions + if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), resourcePermissions .isConfigureRead())) { updateSubTab(this.configurationTab, this.configCurrent, new ResourceConfigurationEditView(this .extendLocatorId("ResourceConfigView"), resource), true, true); @@ -300,7 +303,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo return this.resourceId; }
- protected void loadSelectedItem(final int resourceId, final ViewPath viewPath) { + protected void loadSelectedItem(final int resourceId, final ViewPath viewPath, + final Set<Permission> globalPermissions) { this.resourceId = resourceId;
ResourceCriteria criteria = new ResourceCriteria(); @@ -323,13 +327,14 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo onFailure(new Exception("Resource with id [" + resourceId + "] does not exist.")); } else { final ResourceComposite resourceComposite = result.get(0); - loadResourceType(resourceComposite, viewPath); + loadResourceType(resourceComposite, viewPath, globalPermissions); } } }); }
- private void loadResourceType(final ResourceComposite resourceComposite, final ViewPath viewPath) { + private void loadResourceType(final ResourceComposite resourceComposite, final ViewPath viewPath, + final Set<Permission> globalPermissions) { final Resource resource = resourceComposite.getResource(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( resource.getResourceType().getId(), @@ -341,7 +346,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo public void onTypesLoaded(ResourceType type) { resourceComposite.getResource().setResourceType(type); ResourceDetailView.this.resourceComposite = resourceComposite; - updateTabContent(resourceComposite); + updateTabContent(resourceComposite, globalPermissions); selectTab(getTabName(), getSubTabName(), viewPath); } });
commit 964d6819a63b7a44baacbc015d72e0fc9b4c588b Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Sep 23 09:58:57 2010 -0400
Tab and SubTab work - Rearranged things a bit to avoid ID conflicts/leaked widgets. Buttons that were created but not visible (subtabs of detached tabs) were not being destroyed in a timely manner. So, now create buttons only when they are going to be visible. To help this I also encapsulated the Button into the SubTab object itself. - Added logic to not create views for subtabs that are not visible. - Work to fix initial subtab selection. - Work to avoid flash of buttons by hiding the detail view until after the tabs have been updated the first time.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java index 1d6134b..e149772 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java @@ -22,6 +22,7 @@ package org.rhq.enterprise.gui.coregui.client.components.tab; import com.smartgwt.client.widgets.Canvas;
import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableButton;
/** * Simple class to provide a SubTab a locatorId. @@ -32,11 +33,13 @@ public class SubTab implements Locatable { private String locatorId; private String title; private Canvas canvas; + private LocatableButton button;
public SubTab(String locatorId, String title, Canvas canvas) { this.locatorId = locatorId; this.title = title; this.canvas = canvas; + this.button = null; }
public String getLocatorId() { @@ -55,9 +58,17 @@ public class SubTab implements Locatable { this.canvas = canvas; }
+ public LocatableButton getButton() { + return button; + } + + public void setButton(LocatableButton button) { + this.button = button; + } + @Override public String extendLocatorId(String extension) { - return this.locatorId + "_" + extension; + return this.locatorId + "_" + extension; }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java index 0005436..ff78476 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java @@ -18,7 +18,10 @@ */ package org.rhq.enterprise.gui.coregui.client.components.tab;
-import java.util.*; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set;
import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; @@ -39,15 +42,14 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class SubTabLayout extends LocatableVLayout {
- /** maps subtab locator IDs to SubTabs */ - private Map<String, SubTab> subtabs = new LinkedHashMap<String, SubTab>(); - /** maps subtab locator IDs to subtab Buttons */ - private Map<String, Button> subTabButtons = new LinkedHashMap<String, Button>(); - /** locator IDs of subtabs that are disabled */ + /** maps subTab locator IDs to SubTabs */ + private Map<String, SubTab> subTabs = new LinkedHashMap<String, SubTab>(); + /** locator IDs of subTabs that are disabled */ private Set<String> disabledSubTabs = new HashSet<String>();
private SubTab currentlyDisplayed; private String currentlySelected; + private ToolStrip buttonBar;
public SubTabLayout(String locatorId) { super(locatorId); @@ -63,154 +65,149 @@ public class SubTabLayout extends LocatableVLayout { setMargin(0); setPadding(0);
- ToolStrip buttonBar = new ToolStrip(); + buttonBar = new ToolStrip(); buttonBar.setBackgroundColor("grey"); buttonBar.setWidth100(); buttonBar.setBorder(null); buttonBar.setMembersMargin(30);
addMember(buttonBar); - - int i = 0; - - for (final String locatorId : subtabs.keySet()) { - - SubTab subTab = subtabs.get(locatorId); - - if (currentlySelected == null) { - currentlySelected = locatorId; - } - - Button button = new LocatableButton(locatorId, subTab.getTitle()); - button.setShowRollOver(false); - button.setActionType(SelectionType.RADIO); - button.setRadioGroup("subtabs"); - button.setBorder(null); - button.setAutoFit(true); - if (disabledSubTabs.contains(locatorId)) { - button.disable(); - } else { - button.enable(); - } - - button.setBaseStyle("SubTabButton"); - - // button.setStyleName("SubTabButton"); - // button.setStylePrimaryName("SubTabButton"); - - button.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - currentlySelected = locatorId; - fireSubTabSelection(); - draw(); - } - }); - - subTabButtons.put(locatorId, button); - - buttonBar.addMember(button); - } - - // Initial settings - selectSubTabByLocatorId(currentlySelected); }
@Override protected void onDraw() { super.onDraw();
- selectSubTabByLocatorId(currentlySelected); + if (null == currentlySelected) { + SubTab initial = getDefaultSubTab(); + if (null != initial) { + currentlySelected = initial.getLocatorId(); + } + } + if (null != currentlySelected) { + selectSubTabByLocatorId(currentlySelected); + } }
- public void enableSubTab(String locatorId) { - disabledSubTabs.remove(locatorId); - if (subTabButtons.containsKey(locatorId)) { - subTabButtons.get(locatorId).enable(); - markForRedraw(); + /** + * Make subTab visible. + * + * @param subTab not null + */ + public void showSubTab(SubTab subTab) { + LocatableButton button = subTab.getButton(); + if (null == button) { + button = createSubTabButton(subTab); + buttonBar.addMember(button); + subTab.setButton(button); } + button.show(); }
- public void disableSubTab(String locatorId) { - disabledSubTabs.add(locatorId); - if (subTabButtons.containsKey(locatorId)) { - subTabButtons.get(locatorId).disable(); - markForRedraw(); + /** + * Make subTab not visible. + * + * @param subTab not null + */ + public void hideSubTab(SubTab subTab) { + Button button = subTab.getButton(); + if (null != button) { + buttonBar.removeMember(button); + button.destroy(); + subTab.setButton(null); } }
- public void updateSubTab(SubTab subTab) { + public boolean isSubTabVisible(SubTab subTab) { + return (null != subTab && null != subTab.getButton()); + }
- // Destroy old views so they don't leak - // TODO: You've already leaked because the subtab has already had its canvas replaced. -// Canvas oldCanvas = subTab.getCanvas(); -// if (oldCanvas != null) { -// oldCanvas.destroy(); -// } + private LocatableButton createSubTabButton(final SubTab subTab) { + LocatableButton button = new LocatableButton(subTab.getLocatorId(), subTab.getTitle()); + button.setShowRollOver(false); + button.setActionType(SelectionType.RADIO); + button.setRadioGroup("subTabs"); + button.setBorder(null); + button.setAutoFit(true);
- String locatorId = subTab.getLocatorId(); - this.subtabs.put(locatorId, subTab); - if (locatorId.equals(this.currentlySelected)) { - refresh(); + button.setBaseStyle("SubTabButton"); + + // button.setStyleName("SubTabButton"); + // button.setStylePrimaryName("SubTabButton"); + + button.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + SubTabLayout.this.currentlySelected = subTab.getLocatorId(); + fireSubTabSelection(); + draw(); + } + }); + + return (button); + } + + /** + * Ignored if not visible. Otherwise, enabled. + */ + public void enableSubTab(SubTab subTab) { + if (isSubTabVisible(subTab)) { + disabledSubTabs.remove(subTab.getLocatorId()); + subTab.getButton().enable(); + subTab.getButton().show(); + } + } + + /** + * Ignored if not visible. Otherwise, disabled. + */ + public void disableSubTab(SubTab subTab) { + if (isSubTabVisible(subTab)) { + disabledSubTabs.add(subTab.getLocatorId()); + subTab.getButton().disable(); + subTab.getButton().show(); } }
- public void unregisterAllSubTabs() { - destroyViews(); - subtabs.clear(); - markForRedraw(); + /** + * @return true if not visible or disabled + */ + public boolean isSubTabDisabled(SubTab subTab) { + return (!isSubTabVisible(subTab) || subTab.getButton().getDisabled()); }
public void registerSubTab(SubTab subTab) { String locatorId = subTab.getLocatorId();
- if (currentlySelected == null) { - currentlySelected = locatorId; - } - subtabs.put(locatorId, subTab); - } - - public void setVisible(SubTab subTab, boolean visible) { - Button button = this.subTabButtons.get(subTab.getLocatorId()); - if (visible) { - if (!button.isVisible()) { - button.show(); - markForRedraw(); - } - } else { - if (button.isVisible()) { - button.hide(); - markForRedraw(); - } - } + subTabs.put(locatorId, subTab); }
public SubTab getDefaultSubTab() { - // the default subtab is the first one in the set that is not disabled - for (SubTab subtab : this.subtabs.values()) { - if (!this.disabledSubTabs.contains(subtab.getLocatorId())) { - return subtab; + // the default subTab is the first one in the set that is visible and not disabled + for (SubTab subTab : this.subTabs.values()) { + if (!isSubTabDisabled(subTab)) { + return subTab; } } return null; }
- public boolean selectSubTab(SubTab subtab) { - if (subtab == null) { - throw new IllegalArgumentException("subtab is null."); + public boolean selectSubTab(SubTab subTab) { + if (subTab == null) { + throw new IllegalArgumentException("subTab is null."); } - return selectSubTabByLocatorId(subtab.getLocatorId()); + return selectSubTabByLocatorId(subTab.getLocatorId()); }
public boolean selectSubTabByLocatorId(String locatorId) { boolean foundTab = false; - for (String subtabLocatorId : this.subtabs.keySet()) { - if (subtabLocatorId.equals(locatorId)) { - if (this.disabledSubTabs.contains(subtabLocatorId)) { + for (String subTabLocatorId : this.subTabs.keySet()) { + if (subTabLocatorId.equals(locatorId)) { + if (this.disabledSubTabs.contains(subTabLocatorId)) { // Nice try - user tried to select a disabled tab, probably by going directly to a bookmark URL. - SubTab subtab = this.subtabs.get(subtabLocatorId); - CoreGUI.getErrorHandler().handleError("Cannot select disabled subtab '" + subtab.getTitle() + "'."); + SubTab subTab = this.subTabs.get(subTabLocatorId); + CoreGUI.getErrorHandler().handleError("Cannot select disabled subTab '" + subTab.getTitle() + "'."); } else { - this.currentlySelected = subtabLocatorId; + this.currentlySelected = subTabLocatorId; foundTab = true; } break; @@ -225,10 +222,10 @@ public class SubTabLayout extends LocatableVLayout { }
public SubTab getSubTabByTitle(String title) { - for (String subtabLocatorId : this.subtabs.keySet()) { - SubTab subtab = this.subtabs.get(subtabLocatorId); - if (subtab.getTitle().equals(title)) { - return subtab; + for (String subTabLocatorId : this.subTabs.keySet()) { + SubTab subTab = this.subTabs.get(subTabLocatorId); + if (subTab.getTitle().equals(title)) { + return subTab; } }
@@ -236,9 +233,9 @@ public class SubTabLayout extends LocatableVLayout { }
public SubTab getSubTabByLocatorId(String locatorId) { - for (String subtabLocatorId : this.subtabs.keySet()) { - if (subtabLocatorId.equals(locatorId)) { - return this.subtabs.get(subtabLocatorId); + for (String subTabLocatorId : this.subTabs.keySet()) { + if (subTabLocatorId.equals(locatorId)) { + return this.subTabs.get(subTabLocatorId); } }
@@ -246,23 +243,31 @@ public class SubTabLayout extends LocatableVLayout { }
public boolean selectSubTabByTitle(String title) { - SubTab subtab = getSubTabByTitle(title); - if (subtab == null) { + SubTab subTab = getSubTabByTitle(title); + if (subTab == null) { return false; } else { - if (this.disabledSubTabs.contains(subtab.getLocatorId())) { + if (this.disabledSubTabs.contains(subTab.getLocatorId())) { // Nice try - user tried to select a disabled tab, probably by going directly to a bookmark URL. - CoreGUI.getErrorHandler().handleError("Cannot select disabled subtab '" + title + "'."); + CoreGUI.getErrorHandler().handleError("Cannot select disabled subTab '" + title + "'."); return false; } - this.currentlySelected = subtab.getLocatorId(); + this.currentlySelected = subTab.getLocatorId(); refresh(); return true; } }
public SubTab getCurrentSubTab() { - return this.subtabs.get(this.currentlySelected); + if (null == currentlySelected) { + SubTab current = getDefaultSubTab(); + if (null != current) { + currentlySelected = current.getLocatorId(); + } + return current; + } + + return this.subTabs.get(this.currentlySelected); }
// ------- Event support ------- @@ -276,34 +281,34 @@ public class SubTabLayout extends LocatableVLayout {
public void fireSubTabSelection() { TwoLevelTabSelectedEvent event = new TwoLevelTabSelectedEvent("?", getCurrentSubTab().getTitle(), -1, - getCurrentCanvas()); + getCurrentCanvas()); hm.fireEvent(event); }
public Canvas getCurrentCanvas() { - return currentlyDisplayed != null ? currentlyDisplayed.getCanvas() : subtabs.get(currentlySelected).getCanvas(); + return currentlyDisplayed != null ? currentlyDisplayed.getCanvas() : subTabs.get(currentlySelected).getCanvas(); }
/** * Destroy all the currently held views so that they can be replaced with new versions */ public void destroyViews() { - for (SubTab subtab : subtabs.values()) { - if (subtab.getCanvas() != null) { - subtab.getCanvas().destroy(); - subtab.setCanvas(null); + for (SubTab subTab : subTabs.values()) { + if (subTab.getCanvas() != null) { + subTab.getCanvas().destroy(); + subTab.setCanvas(null); } } }
private void refresh() { - if (isDrawn()) { - Button button = this.subTabButtons.get(this.currentlySelected); + if (isDrawn() && null != this.currentlySelected) { + Button button = this.subTabs.get(this.currentlySelected).getButton(); button.select();
- SubTab currentSubtab = this.subtabs.get(this.currentlySelected); + SubTab currentSubTab = this.subTabs.get(this.currentlySelected);
- if (this.currentlyDisplayed != null && this.currentlyDisplayed.getCanvas() != currentSubtab.getCanvas()) { + if (this.currentlyDisplayed != null && this.currentlyDisplayed.getCanvas() != currentSubTab.getCanvas()) { try { this.currentlyDisplayed.getCanvas().hide(); } catch (Exception e) { @@ -311,7 +316,7 @@ public class SubTabLayout extends LocatableVLayout { } }
- Canvas canvas = currentSubtab.getCanvas(); + Canvas canvas = currentSubTab.getCanvas(); if (canvas != null) { if (hasMember(canvas)) { if (!canvas.isVisible()) { @@ -324,7 +329,7 @@ public class SubTabLayout extends LocatableVLayout { addMember(canvas); } markForRedraw(); - this.currentlyDisplayed = currentSubtab; + this.currentlyDisplayed = currentSubTab; } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java index cbb6370..4468d93 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java @@ -34,10 +34,6 @@ public class TwoLevelTab extends LocatableTab { layout = new SubTabLayout(locatorId); }
- public void updateSubTab(SubTab subTab) { - layout.updateSubTab(subTab); - } - public void registerSubTabs(SubTab... subTabs) { for (SubTab subTab : subTabs) { layout.registerSubTab(subTab); @@ -45,14 +41,18 @@ public class TwoLevelTab extends LocatableTab { }
public void setVisible(SubTab subTab, boolean visible) { - layout.setVisible(subTab, visible); + if (visible) { + layout.showSubTab(subTab); + } else { + layout.hideSubTab(subTab); + } }
- public void setSubTabEnabled(String locatorId, boolean enabled) { + public void setSubTabEnabled(SubTab subTab, boolean enabled) { if (enabled) { - layout.enableSubTab(locatorId); + layout.enableSubTab(subTab); } else { - layout.disableSubTab(locatorId); + layout.disableSubTab(subTab); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java index d39efb7..d8e29b2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java @@ -39,7 +39,7 @@ public class TwoLevelTabSet extends LocatableTabSet implements TabSelectedHandle
public void setTabs(TwoLevelTab... tabs) { super.setTabs(tabs); - for (TwoLevelTab tab : tabs) { + for (TwoLevelTab tab : tabs) { tab.getLayout().addTwoLevelTabSelectedHandler(this); updateTab(tab, tab.getPane()); } @@ -71,15 +71,17 @@ public class TwoLevelTabSet extends LocatableTabSet implements TabSelectedHandle
public void onTabSelected(TabSelectedEvent tabSelectedEvent) { TwoLevelTab tab = (TwoLevelTab) getSelectedTab(); - TwoLevelTabSelectedEvent event = new TwoLevelTabSelectedEvent(tab.getTitle(), - tab.getLayout().getCurrentSubTab().getTitle(), tabSelectedEvent.getTabNum(), - tab.getLayout().getCurrentCanvas()); - m.fireEvent(event); + SubTab currentSubTab = tab.getLayout().getCurrentSubTab(); + if (null != currentSubTab) { + TwoLevelTabSelectedEvent event = new TwoLevelTabSelectedEvent(tab.getTitle(), tab.getLayout() + .getCurrentSubTab().getTitle(), tabSelectedEvent.getTabNum(), tab.getLayout().getCurrentCanvas()); + m.fireEvent(event); + } }
public void onTabSelected(TwoLevelTabSelectedEvent tabSelectedEvent) { tabSelectedEvent.setTabNum(getSelectedTabNumber()); - Tab tab = getSelectedTab(); + Tab tab = getSelectedTab(); tabSelectedEvent.setId(tab.getTitle()); m.fireEvent(tabSelectedEvent); } 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 8f7452c..c11659e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java @@ -18,10 +18,13 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail;
+import java.util.List; + import com.google.gwt.user.client.History; import com.smartgwt.client.types.Side; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.layout.Layout; + import org.rhq.enterprise.gui.coregui.client.BookmarkableView; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ViewPath; @@ -32,14 +35,12 @@ import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSelectedH import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSet; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
-import java.util.List; - /** * @author Greg Hinkle * @author Ian Springer */ -public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends LocatableVLayout - implements BookmarkableView, TwoLevelTabSelectedHandler { +public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends LocatableVLayout implements + BookmarkableView, TwoLevelTabSelectedHandler { private String baseViewPath; private TwoLevelTabSet tabSet; private String tabName; @@ -81,6 +82,7 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo protected abstract void loadSelectedItem(int itemId, ViewPath viewPath);
protected abstract void updateTabContent(T selectedItem); + // ---------------------------------------------------------
protected U getTitleBar() { @@ -101,13 +103,13 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo } }
- return enabled; + return (visible && enabled); }
protected void updateSubTab(TwoLevelTab tab, SubTab subTab, Canvas canvas, boolean visible, boolean enabled) { tab.setVisible(subTab, visible); if (visible) { - tab.setSubTabEnabled(subTab.getLocatorId(), enabled); + tab.setSubTabEnabled(subTab, enabled); if (enabled) { subTab.setCanvas(canvas); } @@ -175,8 +177,7 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo */ public void selectTab(String tabTitle, String subtabTitle, ViewPath viewPath) { try { - TwoLevelTab tab = (tabTitle != null) ? this.tabSet.getTabByTitle(tabTitle) : - this.tabSet.getDefaultTab(); + TwoLevelTab tab = (tabTitle != null) ? this.tabSet.getTabByTitle(tabTitle) : this.tabSet.getDefaultTab(); if (tab == null || tab.getDisabled()) { CoreGUI.getErrorHandler().handleError("Invalid tab name: " + tabTitle); // TODO: Should we fire a history event here to redirect to a valid bookmark? @@ -221,5 +222,5 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo
public String getSubTabName() { return subTabName; - } + } } 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 05590ff..17d901c 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 @@ -24,6 +24,7 @@ import java.util.List; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.tab.Tab;
import org.rhq.core.domain.authz.Permission; @@ -98,6 +99,7 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
public ResourceGroupDetailView(String locatorId) { super(locatorId, BASE_VIEW_PATH); + this.hide(); }
@Override @@ -177,6 +179,9 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource }
protected void updateTabContent(ResourceGroupComposite groupComposite) { + boolean visible; + Canvas canvas; + this.groupComposite = groupComposite; ResourceGroup group = groupComposite.getResourceGroup(); int groupId = group.getId(); @@ -194,22 +199,24 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource // summaryTab.updateSubTab("Timeline", timelinePane); // Summary tab is always visible and enabled. updateSubTab(this.summaryTab, this.summaryOverview, new OverviewView(this.summaryTab - .extendLocatorId("Overview"), this.groupComposite), true, true); + .extendLocatorId("OverviewView"), this.groupComposite), true, true);
if (updateTab(this.monitoringTab, groupCategory == GroupCategory.COMPATIBLE, true)) { - updateSubTab(this.monitoringTab, this.monitorGraphs, new FullHTMLPane( - "/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId), hasMetricsOfType(this.groupComposite, - DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTables, new FullHTMLPane( - "/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId), hasMetricsOfType(this.groupComposite, - DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTraits, new TraitsView(this.monitoringTab - .extendLocatorId("TraitsView"), groupId), hasMetricsOfType(this.groupComposite, DataType.TRAIT), true); - updateSubTab(this.monitoringTab, this.monitorSched, new SchedulesView(this.monitoringTab - .extendLocatorId("SchedulesView"), groupId), hasMetricsOfType(this.groupComposite, null), true); - updateSubTab(this.monitoringTab, this.monitorCallTime, new FullHTMLPane( - "/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId), facets - .contains(ResourceTypeFacet.CALL_TIME), true); + visible = hasMetricsOfType(this.groupComposite, DataType.MEASUREMENT); + canvas = (visible) ? new FullHTMLPane("/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId) : null; + updateSubTab(this.monitoringTab, this.monitorGraphs, canvas, visible, true); + // visible = same test as above + canvas = (visible) ? new FullHTMLPane("/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId) : null; + updateSubTab(this.monitoringTab, this.monitorTables, canvas, visible, true); + visible = hasMetricsOfType(this.groupComposite, DataType.TRAIT); + canvas = (visible) ? new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), groupId) : null; + updateSubTab(this.monitoringTab, this.monitorTraits, canvas, visible, true); + visible = hasMetricsOfType(this.groupComposite, null); + canvas = (visible) ? new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId) : null; + updateSubTab(this.monitoringTab, this.monitorSched, canvas, visible, true); + visible = facets.contains(ResourceTypeFacet.CALL_TIME); + canvas = (visible) ? new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId) : null; + updateSubTab(this.monitoringTab, this.monitorCallTime, canvas, visible, true); // TODO (ips): Add Availability subtab. }
@@ -220,6 +227,7 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource //updateSubTab(this.inventoryTab, this.inventoryConn, // new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin), // facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), true); + // TODO: should require MANAGE_INVENTORY authz updateSubTab(this.inventoryTab, this.inventoryMembership, new ResourceGroupMembershipView(this.inventoryTab .extendLocatorId("MembershipView"), groupId), true, true);
@@ -238,8 +246,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource "/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" + groupId), true, true); }
- if (updateTab(this.configurationTab, groupCategory == GroupCategory.COMPATIBLE - && facets.contains(ResourceTypeFacet.CONFIGURATION), this.permissions.isConfigureRead())) { + 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.configHistory, new FullHTMLPane( @@ -250,6 +258,9 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource && facets.contains(ResourceTypeFacet.EVENT), true)) { updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(groupComposite), true, true); } + + this.show(); + markForRedraw(); }
protected void loadSelectedItem(final int groupId, final ViewPath viewPath) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 8e4e16f..ba88b87 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.tab.Tab;
import org.rhq.core.domain.criteria.ResourceCriteria; @@ -110,6 +111,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo
public ResourceDetailView(String locatorId) { super(locatorId, BASE_VIEW_PATH); + this.hide(); }
protected List<TwoLevelTab> createTabs() { @@ -188,6 +190,9 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo }
protected void updateTabContent(ResourceComposite resourceComposite) { + boolean visible; + Canvas canvas; + this.resourceComposite = resourceComposite; Resource resource = this.resourceComposite.getResource(); getTitleBar().setResource(resource); @@ -205,31 +210,36 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.summaryTab, this.summaryTimeline, new FullHTMLPane( "/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()), true, true);
- updateSubTab(this.monitoringTab, this.monitorGraphs, new GraphListView(this.monitoringTab - .extendLocatorId("GraphListView"), resource), - hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTables, new FullHTMLPane( - "/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId()), hasMetricsOfType(this.resourceComposite, - DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTraits, new TraitsView(this.monitoringTab - .extendLocatorId("TraitsView"), resource.getId()), - hasMetricsOfType(this.resourceComposite, DataType.TRAIT), true); + visible = hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT); + canvas = (visible) ? new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource) : null; + updateSubTab(this.monitoringTab, this.monitorGraphs, canvas, visible, true); + // visible = same test as above + canvas = (visible) ? new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId()) : null; + updateSubTab(this.monitoringTab, this.monitorTables, canvas, visible, true); + visible = hasMetricsOfType(this.resourceComposite, DataType.TRAIT); + canvas = (visible) ? new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId()) : null; + updateSubTab(this.monitoringTab, this.monitorTraits, canvas, visible, true); updateSubTab(this.monitoringTab, this.monitorAvail, new FullHTMLPane( "/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId()), true, true); updateSubTab(this.monitoringTab, this.monitorSched, new SchedulesView(monitoringTab .extendLocatorId("SchedulesView"), resource.getId()), hasMetricsOfType(this.resourceComposite, null), true); - updateSubTab(this.monitoringTab, this.monitorCallTime, new FullHTMLPane( - "/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()), facets - .contains(ResourceTypeFacet.CALL_TIME), true); + visible = facets.contains(ResourceTypeFacet.CALL_TIME); + canvas = (visible) ? new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()) + : null; + updateSubTab(this.monitoringTab, this.monitorCallTime, canvas, visible, true);
ResourceType type = this.resourceComposite.getResource().getResourceType(); - updateSubTab(this.inventoryTab, this.inventoryChildren, ResourceSearchView.getChildrenOf(this.inventoryTab - .extendLocatorId("ChildrenView"), resource.getId()), !type.getChildResourceTypes().isEmpty(), true); - updateSubTab(this.inventoryTab, this.inventoryConn, new PluginConfigurationEditView(this.inventoryTab - .extendLocatorId("PluginConfigView"), resource), facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), - true); + visible = !type.getChildResourceTypes().isEmpty(); + canvas = (visible) ? ResourceSearchView.getChildrenOf(this.inventoryTab.extendLocatorId("ChildrenView"), + resource.getId()) : null; + updateSubTab(this.inventoryTab, this.inventoryChildren, canvas, visible, true); + visible = facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION); + canvas = (visible) ? new PluginConfigurationEditView(this.inventoryTab.extendLocatorId("PluginConfigView"), + resource) : null; + updateSubTab(this.inventoryTab, this.inventoryConn, canvas, visible, true); updateSubTab(this.inventoryTab, this.inventoryGroups, ResourceGroupListView.getGroupsOf(this.inventoryTab .extendLocatorId("GroupsView"), resource.getId()), true, true); + // TODO: authz check for this subtab: MANAGE_INVENTORY updateSubTab(this.inventoryTab, this.inventoryGroupMembership, new ResourceResourceGroupsView(this.inventoryTab .extendLocatorId("GroupMembershipView"), resourceId), true, true);
@@ -241,7 +251,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo // 4) user can navigate to the group operation that spawned this resource operation history, if appropriate // note: enabled operation execution/schedules from left-nav, if it doesn't already exist updateSubTab(this.operationsTab, this.opHistory, OperationHistoryView.getResourceHistoryView(operationsTab - .extendLocatorId("History"), this.resourceComposite), true, true); + .extendLocatorId("HistoryView"), this.resourceComposite), true, true); updateSubTab(this.operationsTab, this.opSched, new FullHTMLPane( "/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" + resource.getId()), true, true); } @@ -254,16 +264,16 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.alertsTab, this.alertHistory, new FullHTMLPane( "/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" + resource.getId()), true, true); updateSubTab(this.alertsTab, this.alertDef, new ResourceAlertDefinitionsView(alertsTab - .extendLocatorId("AlertDef"), this.resourceComposite), true, true); + .extendLocatorId("AlertDefView"), this.resourceComposite), true, true); updateSubTab(this.alertsTab, this.alertDelete, new FullHTMLPane( "/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()), true, true);
if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), permissions .isConfigureRead())) { updateSubTab(this.configurationTab, this.configCurrent, new ResourceConfigurationEditView(this - .extendLocatorId("ResourceConfig"), resource), true, true); + .extendLocatorId("ResourceConfigView"), resource), true, true); updateSubTab(this.configurationTab, this.configHistory, ConfigurationHistoryView.getHistoryOf( - configurationTab.extendLocatorId("Hist"), resource.getId()), true, true); + configurationTab.extendLocatorId("HistoryView"), resource.getId()), true, true); }
if (updateTab(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT), true)) { @@ -281,6 +291,9 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.contentTab, this.contentHistory, new FullHTMLPane( "/rhq/resource/content/history-plain.xhtml?id=" + resource.getId()), true, true); } + + this.show(); + markForRedraw(); }
public Integer getSelectedItemId() {
commit c8ecb19bf05ae6685178cd2c7f129e3cfd725472 Author: John Sanda jsanda@redhat.com Date: Thu Sep 23 09:30:32 2010 -0400
Removing null placeholders
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java index 199fa13..4e5e8aa 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java @@ -459,7 +459,7 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, ResourceFactoryAgentService resourceFactoryAgentService = agentClient.getResourceFactoryAgentService(); resourceFactoryAgentService.createResource(request);
- return null; + return persistedHistory; } catch (Exception e) { log.error("Error while sending create resource request to agent service", e);
@@ -548,7 +548,7 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, ResourceFactoryAgentService resourceFactoryAgentService = agentClient.getResourceFactoryAgentService(); resourceFactoryAgentService.createResource(request);
- return null; + return persistedHistory; } catch (NoResultException nre) { return null; //eat the exception. Some of the queries return no results if no package yet exists which is fine. @@ -588,7 +588,7 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, ResourceFactoryAgentService resourceFactoryAgentService = agentClient.getResourceFactoryAgentService(); resourceFactoryAgentService.deleteResource(request);
- return null; + return persistedHistory; } catch (Exception e) { log.error("Error while sending delete resource request to agent service", e);
commit 633eea8e64f70530bfb0c80d05d5c95afd179c6f Author: John Sanda jsanda@redhat.com Date: Thu Sep 23 09:23:22 2010 -0400
Making return type of create/delete resource operations non-void
This change is primarily for remote clients like the CLI. If a remote client creates or deletes a resource, it has no way of knowing whether or not the operation succeeds since the methods in ResourceFactoryManagerRemote have a return type of void. Now they return CreateResourceHistory and DeleteResourceHistory objects so that the progress of those operations can be tracked.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/DeleteResourceHistory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/DeleteResourceHistory.java index b91622c..2812f3d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/DeleteResourceHistory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/DeleteResourceHistory.java @@ -24,6 +24,7 @@ package org.rhq.core.domain.resource;
import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.io.Serializable; import java.util.Date;
import javax.persistence.Column; @@ -59,7 +60,10 @@ import javax.persistence.Table; @NamedQuery(name = DeleteResourceHistory.QUERY_DELETE_BY_RESOURCES, query = "DELETE FROM DeleteResourceHistory drh WHERE drh.resource.id IN ( :resourceIds ) )") }) @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DELETE_RES_HIST_ID_SEQ") @Table(name = "RHQ_DELETE_RES_HIST") -public class DeleteResourceHistory { +public class DeleteResourceHistory implements Serializable { + + private static final long serialVersionUID = 1L; + // Constants --------------------------------------------
public static final String QUERY_FIND_WITH_STATUS = "DeleteResourceHistory.findWithStatus"; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java index 9a6b419..199fa13 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerBean.java @@ -431,7 +431,7 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- public void createResource(Subject user, int parentResourceId, int resourceTypeId, String resourceName, + public CreateResourceHistory createResource(Subject user, int parentResourceId, int resourceTypeId, String resourceName, Configuration pluginConfiguration, Configuration resourceConfiguration) { log.debug("Received call to create configuration backed resource under parent: " + parentResourceId + " of type: " + resourceTypeId); @@ -458,6 +458,8 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, AgentClient agentClient = agentManager.getAgentClient(agent); ResourceFactoryAgentService resourceFactoryAgentService = agentClient.getResourceFactoryAgentService(); resourceFactoryAgentService.createResource(request); + + return null; } catch (Exception e) { log.error("Error while sending create resource request to agent service", e);
@@ -471,25 +473,25 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, } }
- public void createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, + public CreateResourceHistory createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, String newResourceName,// @XmlJavaTypeAdapter(value = ConfigurationAdapter.class)// Configuration pluginConfiguration, String packageName, String packageVersionNumber, Integer architectureId,// @XmlJavaTypeAdapter(value = ConfigurationAdapter.class)// Configuration deploymentTimeConfiguration, byte[] packageBits) {
- createResource(subject, parentResourceId, newResourceTypeId, newResourceName, pluginConfiguration, packageName, + return createResource(subject, parentResourceId, newResourceTypeId, newResourceName, pluginConfiguration, packageName, packageVersionNumber, architectureId, deploymentTimeConfiguration, new ByteArrayInputStream(packageBits)); }
- public void createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, + public CreateResourceHistory createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, Configuration pluginConfiguration, String packageName, String packageVersionNumber, Integer architectureId, Configuration deploymentTimeConfiguration, InputStream packageBitStream) { - createResource(user, parentResourceId, newResourceTypeId, newResourceName, pluginConfiguration, packageName, + return createResource(user, parentResourceId, newResourceTypeId, newResourceName, pluginConfiguration, packageName, packageVersionNumber, architectureId, deploymentTimeConfiguration, packageBitStream, null); }
- public void createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, + public CreateResourceHistory createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, Configuration pluginConfiguration, String packageName, String packageVersionNumber, Integer architectureId, Configuration deploymentTimeConfiguration, InputStream packageBitStream, Map<String, String> packageUploadDetails) { @@ -545,7 +547,10 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, AgentClient agentClient = agentManager.getAgentClient(agent); ResourceFactoryAgentService resourceFactoryAgentService = agentClient.getResourceFactoryAgentService(); resourceFactoryAgentService.createResource(request); + + return null; } catch (NoResultException nre) { + return null; //eat the exception. Some of the queries return no results if no package yet exists which is fine. } catch (Exception e) { log.error("Error while sending create resource request to agent service", e); @@ -560,7 +565,7 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, } }
- public void deleteResource(Subject subject, int resourceId) { + public DeleteResourceHistory deleteResource(Subject subject, int resourceId) { log.debug("Received call to delete resource: " + resourceId);
Resource resource = entityManager.find(Resource.class, resourceId); @@ -582,6 +587,8 @@ public class ResourceFactoryManagerBean implements ResourceFactoryManagerLocal, AgentClient agentClient = agentManager.getAgentClient(agent); ResourceFactoryAgentService resourceFactoryAgentService = agentClient.getResourceFactoryAgentService(); resourceFactoryAgentService.deleteResource(request); + + return null; } catch (Exception e) { log.error("Error while sending delete resource request to agent service", e);
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerLocal.java index ea3784d..9796e0b 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerLocal.java @@ -80,11 +80,11 @@ public interface ResourceFactoryManagerLocal { * @param deploymentTimeConfiguration dictates how the package will be deployed * @param packageBitStream content of the package to create */ - void createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, + CreateResourceHistory createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, Configuration pluginConfiguration, String packageName, String packageVersion, Integer architectureId, Configuration deploymentTimeConfiguration, InputStream packageBitStream);
- void createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, + CreateResourceHistory createResource(Subject user, int parentResourceId, int newResourceTypeId, String newResourceName, Configuration pluginConfiguration, String packageName, String packageVersion, Integer architectureId, Configuration deploymentTimeConfiguration, InputStream packageBitStream, Map<String, String> packageUploadDetails); @@ -225,19 +225,19 @@ public interface ResourceFactoryManagerLocal { /** * @see {@link ResourceFactoryManagerRemote.createResource(Subject,int,int,String,Configuration,Configuration) */ - void createResource(Subject subject, int parentResourceId, int resourceTypeId, String resourceName, + CreateResourceHistory createResource(Subject subject, int parentResourceId, int resourceTypeId, String resourceName, Configuration pluginConfiguration, Configuration resourceConfiguration);
/** * @see {@link ResourceFactoryManagerRemote.createPackageBackedResource(Subject,int,int,String,Configuration,String,String,Integer,Configuration,byte[]) */ - void createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, + CreateResourceHistory createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, String newResourceName, Configuration pluginConfiguration, String packageName, String packageVersion, Integer architectureId, Configuration deploymentTimeConfiguration, byte[] packageBits);
/** * @see {@link ResourceFactoryManagerRemote.deleteResource(Subject,int) */ - void deleteResource(Subject subject, int resourceId); + DeleteResourceHistory deleteResource(Subject subject, int resourceId);
} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerRemote.java index 1c5633d..9d4f908 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceFactoryManagerRemote.java @@ -28,6 +28,8 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.resource.CreateDeletePolicy; +import org.rhq.core.domain.resource.CreateResourceHistory; +import org.rhq.core.domain.resource.DeleteResourceHistory; import org.rhq.core.domain.resource.ResourceCreationDataType; import org.rhq.enterprise.server.jaxb.adapter.ConfigurationAdapter; import org.rhq.enterprise.server.system.ServerVersion; @@ -57,7 +59,7 @@ public interface ResourceFactoryManagerRemote { * @param resourceConfiguration resource configuration for the new resource */ @WebMethod - void createResource( // + CreateResourceHistory createResource( // @WebParam(name = "subject") Subject subject, // @WebParam(name = "parentResourceId") int parentResourceId, // @WebParam(name = "resourceTypeId") int resourceTypeId, // @@ -87,7 +89,7 @@ public interface ResourceFactoryManagerRemote { * @param packageBits content of the package to create */ @WebMethod - void createPackageBackedResource(// + CreateResourceHistory createPackageBackedResource(// @WebParam(name = "subject") Subject subject, // @WebParam(name = "parentResourceId") int parentResourceId, // @WebParam(name = "newResourceTypeId") int newResourceTypeId, // @@ -112,7 +114,7 @@ public interface ResourceFactoryManagerRemote { * @param resourceId resource being deleted */ @WebMethod - void deleteResource( // + DeleteResourceHistory deleteResource( // @WebParam(name = "subject") Subject subject, // @WebParam(name = "resourceId") int resourceId); } 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 96dcdd2..0062843 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 @@ -104,6 +104,8 @@ import org.rhq.core.domain.measurement.composite.MeasurementDataNumericHighLowCo import org.rhq.core.domain.operation.GroupOperationHistory; import org.rhq.core.domain.operation.OperationDefinition; 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; @@ -782,25 +784,25 @@ public class WebservicesManagerBean implements WebservicesRemote { //REPOMANAGER: END ----------------------------------
//RESOURCEFACTORYMANAGER: BEGIN ---------------------------------- - public void createResource(Subject subject, int parentResourceId, int resourceTypeId, String resourceName, + public CreateResourceHistory createResource(Subject subject, int parentResourceId, int resourceTypeId, String resourceName, Configuration pluginConfiguration, Configuration resourceConfiguration) { - resourceFactoryManager.createResource(subject, parentResourceId, resourceTypeId, resourceName, + return resourceFactoryManager.createResource(subject, parentResourceId, resourceTypeId, resourceName, pluginConfiguration, resourceConfiguration); }
- public void createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, + public CreateResourceHistory createPackageBackedResource(Subject subject, int parentResourceId, int newResourceTypeId, String newResourceName,// @XmlJavaTypeAdapter(value = ConfigurationAdapter.class)// Configuration pluginConfiguration, String packageName, String packageVersion, Integer architectureId,// @XmlJavaTypeAdapter(value = ConfigurationAdapter.class)// Configuration deploymentTimeConfiguration, byte[] packageBits) { - resourceFactoryManager.createPackageBackedResource(subject, parentResourceId, newResourceTypeId, + return resourceFactoryManager.createPackageBackedResource(subject, parentResourceId, newResourceTypeId, newResourceName, pluginConfiguration, packageName, packageVersion, architectureId, deploymentTimeConfiguration, packageBits); }
- public void deleteResource(Subject subject, int resourceId) { - resourceFactoryManager.deleteResource(subject, resourceId); + public DeleteResourceHistory deleteResource(Subject subject, int resourceId) { + return resourceFactoryManager.deleteResource(subject, resourceId); }
//RESOURCEFACTORYMANAGER: END ----------------------------------
commit 9a36c9d68e27aead173d141e7819b2a16d6c9236 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 07:49:43 2010 -0400
simplify the process of creating Criteria objects from a DSRequest
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupDataSourceField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupDataSourceField.java new file mode 100644 index 0000000..d7deadd --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupDataSourceField.java @@ -0,0 +1,71 @@ +/* + * 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.enterprise.gui.coregui.client.inventory.groups; + +import com.smartgwt.client.widgets.grid.ListGridField; + +public enum ResourceGroupDataSourceField { + + NAME("name", "Name"), + + DESCRIPTION("description", "Description"), + + TYPE("typeName", "Type"), + + PLUGIN("pluginName", "Plugin"), + + CATEGORY("category", "Category"); + + /** + * Corresponds to a property name of Resource + */ + private String propertyName; + + /** + * The display name for the field or property + */ + private String title; + + private ResourceGroupDataSourceField(String propertyName, String title) { + this.propertyName = propertyName; + this.title = title; + } + + public String propertyName() { + return propertyName; + } + + public String title() { + return title; + } + + public ListGridField getListGridField() { + return new ListGridField(propertyName, title); + } + + public ListGridField getListGridField(int width) { + return new ListGridField(propertyName, title, width); + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java index 91bf412..2a02c99 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java @@ -18,6 +18,9 @@ */ 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; @@ -93,32 +96,13 @@ public class ResourceGroupsDataSource extends RPCDataSource<ResourceGroup> {
protected ResourceGroupCriteria getFetchCriteria(final DSRequest request) { ResourceGroupCriteria criteria = new ResourceGroupCriteria(); - criteria.setPageControl(getPageControl(request));
- if (request.getCriteria().getValues().get("name") != null) { - criteria.addFilterName((String) request.getCriteria().getValues().get("name")); - } - - if (request.getCriteria().getValues().get("category") != null) { - criteria.addFilterGroupCategory(GroupCategory.valueOf(((String) request.getCriteria().getValues().get( - "category")).toUpperCase())); - } - - if (request.getCriteria().getValues().get("downMemberCount") != null) { - criteria.addFilterDownMemberCount(Integer.parseInt((String) request.getCriteria().getValues().get( - "downMemberCount"))); - } - - if (request.getCriteria().getValues().get("explicitResourceId") != null) { - criteria.addFilterExplicitResourceIds(Integer.parseInt((String) request.getCriteria().getValues().get( - "explicitResourceId"))); - } - - if (request.getCriteria().getValues().get("groupDefinitionId") != null) { - criteria.addFilterGroupDefinitionId(Integer.parseInt((String) request.getCriteria().getValues().get( - "groupDefinitionId"))); - } + 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; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDataSourceField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDataSourceField.java index 8b81f4c..59b55e9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDataSourceField.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDataSourceField.java @@ -23,6 +23,8 @@
package org.rhq.enterprise.gui.coregui.client.inventory.resource;
+import com.smartgwt.client.widgets.grid.ListGridField; + public enum ResourceDataSourceField {
NAME("name", "Name"), @@ -60,4 +62,12 @@ public enum ResourceDataSourceField { return title; }
+ public ListGridField getListGridField() { + return new ListGridField(propertyName, title); + } + + public ListGridField getListGridField(int width) { + return new ListGridField(propertyName, title, width); + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java index 71e6eee..766df27 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java @@ -25,8 +25,6 @@ import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceD import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.PLUGIN; import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.TYPE;
-import java.util.Map; - import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@ -41,7 +39,6 @@ import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; -import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; @@ -101,75 +98,22 @@ public class ResourceDatasource extends RPCDataSource<Resource> { }); }
- @SuppressWarnings("unchecked") protected ResourceCriteria getFetchCriteria(final DSRequest request) { - ResourceCriteria criteria = new ResourceCriteria(); criteria.setPageControl(getPageControl(request)); - // TODO: This call is broken in 2.2, http://code.google.com/p/smartgwt/issues/detail?id=490 - // when using AdvancedCriteria - Map<String, Object> criteriaMap = request.getCriteria().getValues(); - - if (criteriaMap.get("parentId") != null) { - criteria.addFilterParentResourceId(Integer.parseInt((String) criteriaMap.get("parentId"))); - } - - if (criteriaMap.get("id") != null) { - criteria.addFilterId(Integer.parseInt(request.getCriteria().getAttribute("id"))); - } - - if (criteriaMap.get("resourceIds") != null) { - int[] ids = request.getCriteria().getAttributeAsIntArray("resourceIds"); - Integer[] oids = new Integer[ids.length]; - for (int i = 0; i < ids.length; i++) { - oids[i] = ids[i++]; - } - criteria.addFilterIds(oids); - } - - // Fetch member Resources of the group with the specified id. - if (criteriaMap.get("groupId") != null) { - int groupId = Integer.parseInt((String) criteriaMap.get("groupId")); - criteria.addFilterImplicitGroupIds(groupId); - } - - if (criteriaMap.get(NAME.propertyName()) != null) { - criteria.addFilterName((String) criteriaMap.get(NAME.propertyName())); - } - - if (criteriaMap.get(CATEGORY.propertyName()) != null) { - criteria.addFilterResourceCategory(ResourceCategory.valueOf(((String) criteriaMap.get(CATEGORY - .propertyName())).toUpperCase())); - } - - if (criteriaMap.get(AVAILABILITY.propertyName()) != null) { - criteria.addFilterCurrentAvailability(AvailabilityType.valueOf(((String) criteriaMap.get(AVAILABILITY - .propertyName())).toUpperCase())); - } - - if (criteriaMap.get(TYPE.propertyName()) != null) { - criteria.addFilterResourceTypeId(Integer.parseInt(((String) criteriaMap.get(TYPE.propertyName())))); - } - - if (criteriaMap.get(PLUGIN.propertyName()) != null) { - criteria.addFilterPluginName((String) criteriaMap.get(PLUGIN.propertyName())); - } - - if (criteriaMap.get("tag") != null) { - criteria.addFilterTag((Tag) criteriaMap.get("tag")); - } - - if (criteriaMap.get("tagNamespace") != null) { - criteria.addFilterTagNamespace((String) criteriaMap.get("tagNamespace")); - } - - if (criteriaMap.get("tagSemantic") != null) { - criteria.addFilterTagSemantic((String) criteriaMap.get("tagSemantic")); - } - - if (criteriaMap.get("tagName") != null) { - criteria.addFilterTagName((String) criteriaMap.get("tagName")); - } + + criteria.addFilterId(getFilter(request, "id", Integer.class)); + criteria.addFilterParentResourceId(getFilter(request, "parentId", Integer.class)); + criteria.addFilterCurrentAvailability(getFilter(request, AVAILABILITY.propertyName(), AvailabilityType.class)); + criteria.addFilterResourceCategory(getFilter(request, CATEGORY.propertyName(), ResourceCategory.class)); + criteria.addFilterIds(getArrayFilter(request, "resourceIds", Integer.class)); + criteria.addFilterImplicitGroupIds(getFilter(request, "groupId", Integer.class)); + criteria.addFilterName(getFilter(request, NAME.propertyName(), String.class)); + criteria.addFilterResourceTypeId(getFilter(request, TYPE.propertyName(), Integer.class)); + criteria.addFilterPluginName(getFilter(request, PLUGIN.propertyName(), String.class)); + criteria.addFilterTagNamespace(getFilter(request, "tagNamespace", String.class)); + criteria.addFilterTagSemantic(getFilter(request, "tagSemantic", String.class)); + criteria.addFilterTagName(getFilter(request, "tagName", String.class));
return criteria; } 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 5b3ecf7..b61458f 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 @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map;
import com.google.gwt.core.client.JavaScriptObject; +import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSource; @@ -241,4 +242,67 @@ public abstract class RPCDataSource<T> extends DataSource { JSOHelper.apply(data, newRecord.getJsObj()); return newRecord; } + + @SuppressWarnings("unchecked") + public static <S> S[] getArrayFilter(DSRequest request, String paramName, Class<S> type) { + System.out.println("Fetching array " + paramName + " (" + type + ")"); + Criteria criteria = request.getCriteria(); + Map<String, Object> criteriaMap = criteria.getValues(); + + S[] resultArray = null; + + Object value = (String) criteriaMap.get(paramName); + if (value == null) { + // nothing to do, result is already null + } else if (type == Integer.class) { + int[] intermediates = criteria.getAttributeAsIntArray(paramName); + resultArray = (S[]) new Integer[intermediates.length]; + int index = 0; + for (int next : intermediates) { + resultArray[index++] = (S) (Integer) next; + } + } else if (type == String.class) { + String[] intermediates = criteria.getAttributeAsStringArray(paramName); + resultArray = (S[]) new String[intermediates.length]; + int index = 0; + for (String next : intermediates) { + resultArray[index++] = (S) next; + } + } else { + throw new IllegalArgumentException("No support for passing array filters of type " + type); + } + + System.out.println("Result array = " + resultArray); + + return resultArray; + } + + @SuppressWarnings("unchecked") + public static <S> S getFilter(DSRequest request, String paramName, Class<S> type) { + System.out.println("Fetching " + paramName + " (" + type + ")"); + Criteria criteria = request.getCriteria(); + Map<String, Object> criteriaMap = criteria.getValues(); + + S result = null; + + Object value = criteriaMap.get(paramName); + if (value == null) { + // nothing to do, result is already null + } else { + String strValue = value.toString(); + if (type == String.class) { + result = (S) strValue; + } else if (type == Integer.class) { + result = (S) Integer.valueOf(strValue); + } else if (type.isEnum()) { + result = (S) Enum.valueOf((Class<? extends Enum>) type, strValue.toUpperCase()); + } else { + result = (S) value; // otherwise presume the object is already that type, and just cast it + } + } + + System.out.println("Result = " + result); + + return result; + } }
commit fb3843196fe9fa6c29b90f9cf8ba5e510e19fa97 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 07:48:54 2010 -0400
greater resiliance when passing null-"ish" values to addFilterXXX Criteria methods
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java index 1eae4a3..0fd3a0a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java @@ -22,7 +22,6 @@ */ package org.rhq.core.domain.criteria;
-import java.util.Arrays; import java.util.List;
import javax.xml.bind.annotation.XmlAccessType; @@ -33,6 +32,7 @@ import org.rhq.core.domain.measurement.AvailabilityType; 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.util.CriteriaUtils; import org.rhq.core.domain.util.PageOrdering;
/** @@ -213,15 +213,15 @@ public class ResourceCriteria extends TaggedCriteria { }
public void addFilterIds(Integer... filterIds) { - this.filterIds = Arrays.asList(filterIds); + this.filterIds = CriteriaUtils.getListIgnoringNulls(filterIds); }
public void addFilterExplicitGroupIds(Integer... filterExplicitGroupIds) { - this.filterExplicitGroupIds = Arrays.asList(filterExplicitGroupIds); + this.filterExplicitGroupIds = CriteriaUtils.getListIgnoringNulls(filterExplicitGroupIds); }
public void addFilterImplicitGroupIds(Integer... filterImplicitGroupIds) { - this.filterImplicitGroupIds = Arrays.asList(filterImplicitGroupIds); + this.filterImplicitGroupIds = CriteriaUtils.getListIgnoringNulls(filterImplicitGroupIds); }
public void addFilterRootResourceId(Integer filterRootResourceId) { 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 1a54f0f..6f5c259 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 @@ -22,7 +22,6 @@ */ package org.rhq.core.domain.criteria;
-import java.util.Arrays; import java.util.List;
import javax.xml.bind.annotation.XmlAccessType; @@ -31,6 +30,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.group.GroupCategory; import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.core.domain.util.CriteriaUtils; import org.rhq.core.domain.util.PageOrdering;
/** @@ -155,11 +155,11 @@ public class ResourceGroupCriteria extends TaggedCriteria { }
public void addFilterExplicitResourceIds(Integer... filterExplicitResourceIds) { - this.filterExplicitResourceIds = Arrays.asList(filterExplicitResourceIds); + this.filterExplicitResourceIds = CriteriaUtils.getListIgnoringNulls(filterExplicitResourceIds); }
public void addFilterImplicitResourceIds(Integer... filterImplicitResourceIds) { - this.filterImplicitResourceIds = Arrays.asList(filterImplicitResourceIds); + this.filterImplicitResourceIds = CriteriaUtils.getListIgnoringNulls(filterImplicitResourceIds); }
/** A somewhat special case filter that ensures that all explicit group members diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/CriteriaUtils.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/CriteriaUtils.java new file mode 100644 index 0000000..d6ca5e2 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/CriteriaUtils.java @@ -0,0 +1,58 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License, 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 java.util.ArrayList; +import java.util.List; + +/** + * A dumping ground for utility methods used by Criteria objects. We specifically don't want to put these into the + * Criteria abstract class because they would become part of the auto-completion candidate list in the interactive CLI. + * Putting them here (in core/domain versus, say, core/util) will provide the necessary utility without requiring + * further module inheritance at the coregui layer. + * + * @author Joseph Marques + */ +public class CriteriaUtils { + /* + * remove nulls from the passed items, and return the resultant list. return null if no non-null items exist. + * this is useful in criteria addFilterXXX methods which take varargs, where a single null argument should be + * interpreted as a null collection (instead of one-item collection whose first value is null). + */ + public static <T> List<T> getListIgnoringNulls(T[] items) { + if (items == null) { + return null; + } + + List<T> results = new ArrayList<T>(); + for (T next : items) { + if (next != null) { + results.add(next); + } + } + if (results.size() == 0) { + return null; + } + return results; + } +}
commit 260db28def8e9f080f3cf4bda8df8a75e3bd81be Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 07:45:41 2010 -0400
fix SearchBarPane so it searches for both resources and groups
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java index 81abe79..0d920ef 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java @@ -18,13 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.menu;
-import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.AVAILABILITY; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.CATEGORY; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.DESCRIPTION; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.PLUGIN; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.TYPE; - import com.google.gwt.user.client.History; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.TextMatchStyle; @@ -42,7 +35,9 @@ import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.grid.ListGridField;
import org.rhq.enterprise.gui.coregui.client.LinkManager; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupsDataSource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDatasource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; @@ -69,8 +64,14 @@ public class SearchBarPane extends LocatableHLayout {
final SelectItem searchType = new SelectItem("searchType", "Search"); searchType.setWidth(120); - searchType.setValueMap("Resources", "Resource Groups", "Bundles", "Packages", "Users", "Roles"); + searchType.setValueMap("Resources", "Resource Groups"/*, "Bundles", "Packages", "Users", "Roles"*/); searchType.setValue("Resources"); + searchType.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + markForRedraw(); + } + });
ComboBoxItem resourceSearch = getResourceComboBox(); resourceSearch.setShowIfCondition(new FormItemIfFunction() { @@ -79,6 +80,13 @@ public class SearchBarPane extends LocatableHLayout { } });
+ ComboBoxItem groupSearch = getGroupComboBox(); + groupSearch.setShowIfCondition(new FormItemIfFunction() { + public boolean execute(FormItem formItem, Object o, DynamicForm dynamicForm) { + return form.getValueAsString("searchType").equals("Resource Groups"); + } + }); + TextItem query = new TextItem("query"); query.setShowTitle(false);
@@ -88,7 +96,7 @@ public class SearchBarPane extends LocatableHLayout { search.setShowTitle(false); search.setIcon(Window.getImgURL("[SKIN]/actions/view.png"));
- form.setItems(searchType, resourceSearch, search, new SpacerItem()); + form.setItems(searchType, resourceSearch, groupSearch, search, new SpacerItem());
addMember(form); } @@ -103,19 +111,19 @@ public class SearchBarPane extends LocatableHLayout {
comboBox.setOptionDataSource(new ResourceDatasource());
- ListGridField nameField = new ListGridField(NAME.propertyName(), NAME.title(), 250); - ListGridField descriptionField = new ListGridField(DESCRIPTION.propertyName(), DESCRIPTION.title()); - ListGridField typeNameField = new ListGridField(TYPE.propertyName(), TYPE.title(), 130); - ListGridField pluginNameField = new ListGridField(PLUGIN.propertyName(), PLUGIN.title(), 100); - ListGridField categoryField = new ListGridField(CATEGORY.propertyName(), CATEGORY.title(), 60); - ListGridField availabilityField = new ListGridField(AVAILABILITY.propertyName(), AVAILABILITY.title(), 55); + ListGridField nameField = ResourceDataSourceField.NAME.getListGridField(250); + ListGridField descriptionField = ResourceDataSourceField.DESCRIPTION.getListGridField(); + ListGridField typeNameField = ResourceDataSourceField.TYPE.getListGridField(130); + ListGridField pluginNameField = ResourceDataSourceField.PLUGIN.getListGridField(100); + ListGridField categoryField = ResourceDataSourceField.CATEGORY.getListGridField(60); + ListGridField availabilityField = ResourceDataSourceField.AVAILABILITY.getListGridField(55); availabilityField.setAlign(Alignment.CENTER);
comboBox.setPickListFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField, availabilityField);
comboBox.setValueField("id"); - comboBox.setDisplayField("name"); + comboBox.setDisplayField(ResourceDataSourceField.NAME.propertyName()); comboBox.setPickListWidth(800); comboBox.setTextMatchStyle(TextMatchStyle.SUBSTRING); comboBox.setCompleteOnTab(true); @@ -141,19 +149,44 @@ public class SearchBarPane extends LocatableHLayout { }
private ComboBoxItem getGroupComboBox() { - ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); + final ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); comboBox.setWidth(400); comboBox.setShowTitle(false); + comboBox.setHint("group search"); + comboBox.setShowHintInField(true);
comboBox.setOptionDataSource(new ResourceGroupsDataSource()); - ListGridField nameField = new ListGridField("name"); - ListGridField descriptionField = new ListGridField("description"); - comboBox.setPickListFields(nameField, descriptionField); + + ListGridField nameField = ResourceGroupDataSourceField.NAME.getListGridField(250); + ListGridField descriptionField = ResourceGroupDataSourceField.DESCRIPTION.getListGridField(); + ListGridField typeNameField = ResourceGroupDataSourceField.TYPE.getListGridField(130); + ListGridField pluginNameField = ResourceGroupDataSourceField.PLUGIN.getListGridField(100); + ListGridField categoryField = ResourceGroupDataSourceField.CATEGORY.getListGridField(105); + + comboBox.setPickListFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField);
comboBox.setValueField("id"); - comboBox.setDisplayField("name"); - comboBox.setPickListWidth(600); + comboBox.setDisplayField(ResourceGroupDataSourceField.NAME.propertyName()); + comboBox.setPickListWidth(800); comboBox.setTextMatchStyle(TextMatchStyle.SUBSTRING); + comboBox.setCompleteOnTab(true); + + comboBox.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent changedEvent) { + try { + Integer groupId = (Integer) changedEvent.getValue(); + comboBox.setValue(""); + + String link = LinkManager.getResourceGroupLink(groupId); + if (!link.contains("#")) { + com.google.gwt.user.client.Window.Location.assign(link); + } else { + History.newItem(link.substring(1)); + } + } catch (Exception e) { + } + } + });
return comboBox; }
commit a0e563db21d42cc467bd4e8102d1ae9dd2db450f Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 07:41:39 2010 -0400
make sure to create contentCanvas and sectionStack early
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index c6d5289..01f23a2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -95,6 +95,19 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView protected void onInit() { super.onInit();
+ setWidth100(); + setHeight100(); + + contentCanvas = new Canvas(); + contentCanvas.setWidth("*"); + contentCanvas.setHeight100(); + + sectionStack = new LocatableSectionStack(getLocatorId()); + sectionStack.setShowResizeBar(true); + sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); + sectionStack.setWidth(250); + sectionStack.setHeight100(); + GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { @Override public void onFailure(Throwable caught) { @@ -111,19 +124,6 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView }
private void finishOnInit(Set<Permission> globalPermissions) { - setWidth100(); - setHeight100(); - - contentCanvas = new Canvas(); - contentCanvas.setWidth("*"); - contentCanvas.setHeight100(); - - sectionStack = new LocatableSectionStack(getLocatorId()); - sectionStack.setShowResizeBar(true); - sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); - sectionStack.setWidth(250); - sectionStack.setHeight100(); - buildResourcesSection(globalPermissions); buildGroupsSection(globalPermissions);
commit 3321fe23ca85876b6fff148737f6a58112e2c6c1 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 06:51:22 2010 -0400
never change the internal state of a Criteria object, if the filter is NULL
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java index 6ef2ce6..effbb4e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java @@ -51,6 +51,9 @@ public abstract class TaggedCriteria extends Criteria { }
public void addFilterTagNamespace(String filterTagNamespace) { + if (filterTagNamespace == null) { + return; // do nothing if the filter is empty + } if (this.filterTag == null) { this.filterTag = new Tag(); } @@ -58,6 +61,9 @@ public abstract class TaggedCriteria extends Criteria { }
public void addFilterTagSemantic(String filterTagSemantic) { + if (filterTagSemantic == null) { + return; // do nothing if the filter is empty + } if (this.filterTag == null) { this.filterTag = new Tag(); } @@ -65,6 +71,9 @@ public abstract class TaggedCriteria extends Criteria { }
public void addFilterTagName(String filterTagName) { + if (filterTagName == null) { + return; // do nothing if the filter is empty + } if (this.filterTag == null) { this.filterTag = new Tag(); }
commit 37633f6d8e7f5ceb222a415db1b9521258d46adf Author: Joseph Marques joseph@redhat.com Date: Thu Sep 23 06:45:10 2010 -0400
fix tagged view, so all tables that are tiled under it render correctly
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java index 981852e..66ff323 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java @@ -25,7 +25,6 @@ package org.rhq.enterprise.gui.coregui.client.report.tag; import java.util.ArrayList;
import com.smartgwt.client.data.Criteria; -import com.smartgwt.client.data.SortSpecifier;
import org.rhq.core.domain.tagging.Tag; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; @@ -91,10 +90,6 @@ public class TaggedView extends LocatableVLayout implements BookmarkableView { tileLayout.setTileWidth(getWidth() / 2 - 20); addMember(tileLayout);
- ResourceSearchView resourceView = new ResourceSearchView(getLocatorId(), criteria, "Tagged Resources", - new SortSpecifier[] {}, new String[] { "pluginName", "category", "currentAvailability" }); - tiles.add(resourceView); - BundlesListView bundlesView = new BundlesListView(getLocatorId(), criteria); tiles.add(bundlesView);
@@ -108,6 +103,9 @@ public class TaggedView extends LocatableVLayout implements BookmarkableView { criteria); tiles.add(bundleDestinationListView);
+ ResourceSearchView resourceView = new ResourceSearchView(getLocatorId(), criteria, "Tagged Resources"); + tiles.add(resourceView); + for (Table t : tiles) { t.setShowFooter(false); tileLayout.addTile(t);
commit 71a661acf8ce99a02f857bbd02a0c51bba5bebc3 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 22 18:29:17 2010 -0400
fix bug in restype cache that was preventing subcats from being fetched for restypes that were loaded by a previous cache request; various minor refactoring of resource tree code (better variable names, etc.)
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 8218909..a94560d 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 @@ -739,6 +739,14 @@ public class ResourceType implements Serializable, Comparable<ResourceType> { this.subCategories.add(subCategory); }
+ public Set<ProductVersion> getProductVersions() { + return productVersions; + } + + public void setProductVersions(Set<ProductVersion> productVersions) { + this.productVersions = productVersions; + } + public int compareTo(ResourceType that) { return this.name.compareTo(that.getName()); // TODO: Order by category too? 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 a8472b8..1de6dd2 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.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; @@ -232,7 +233,7 @@ public class ConfigurationEditor extends LocatableVLayout { ResourceTypeRepository.Cache.getInstance().getResourceTypes(new Integer[] { resourceTypeId }, EnumSet.of(ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + public void onTypesLoaded(Map<Integer, ResourceType> types) { System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); definition = types.get(resourceTypeId).getResourceConfigurationDefinition(); if (definition == null) { @@ -258,7 +259,7 @@ public class ConfigurationEditor extends LocatableVLayout { ResourceTypeRepository.Cache.getInstance().getResourceTypes(new Integer[] { resourceTypeId }, EnumSet.of(ResourceTypeRepository.MetadataType.pluginConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + public void onTypesLoaded(Map<Integer, ResourceType> types) { System.out.println("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); definition = types.get(resourceTypeId).getPluginConfigurationDefinition(); if (definition == null) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java index 91303ee..89583b4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java @@ -37,7 +37,8 @@ public class EnhancedTreeNode extends TreeNode { StringBuilder buffer = new StringBuilder(); String className = this.getClass().getName(); String simpleClassName = className.substring(className.lastIndexOf(".") + 1); - buffer.append(simpleClassName).append("["); + String innerClassName = simpleClassName.substring(simpleClassName.lastIndexOf("$") + 1); + buffer.append(innerClassName).append("["); String id = getID(); buffer.append("id=").append(id); String parentId = getParentID(); 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 ba57920..acaca4a 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 @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Set;
import com.google.gwt.user.client.History; @@ -69,7 +70,7 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { private ResourceGroupTreeContextMenu contextMenu;
private ResourceGroup rootResourceGroup; - private HashMap<Integer, ResourceType> typeMap; + private Map<Integer, ResourceType> typeMap; private ResourceGroup selectedGroup;
public ResourceGroupTreeView() { @@ -226,7 +227,7 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { ResourceTypeRepository.Cache.getInstance().getResourceTypes(typeIds.toArray(new Integer[typeIds.size()]), new ResourceTypeRepository.TypesLoadedCallback() { @Override - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + public void onTypesLoaded(Map<Integer, ResourceType> types) { ResourceGroupTreeView.this.typeMap = types; loadTree(root); } 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 38dc487..bad1ada 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 @@ -149,8 +149,8 @@ public class NewResourceTreeView extends LocatableVLayout { event.getNode(); event.cancel();
- if (event.getNode() instanceof ResourceTreeDatasource.TypeTreeNode) { - showContextMenu((ResourceTreeDatasource.TypeTreeNode) event.getNode()); + if (event.getNode() instanceof ResourceTreeDatasource.AutoGroupTreeNode) { + showContextMenu((ResourceTreeDatasource.AutoGroupTreeNode) event.getNode()); } else if (event.getNode() instanceof ResourceTreeDatasource.ResourceTreeNode) { showContextMenu((ResourceTreeDatasource.ResourceTreeNode) event.getNode()); } @@ -158,7 +158,7 @@ public class NewResourceTreeView extends LocatableVLayout { }); }
- private void showContextMenu(ResourceTreeDatasource.TypeTreeNode node) { + private void showContextMenu(ResourceTreeDatasource.AutoGroupTreeNode node) {
contextMenu.setItems(new MenuItem(node.getName())); contextMenu.showContextMenu(); 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 9b39e8a..ca3f8e6 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 @@ -23,6 +23,7 @@ import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; @@ -168,7 +169,9 @@ public class ResourceTreeDatasource extends DataSource {
ResourceTypeRepository.Cache.getInstance().loadResourceTypes( result, - EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, + EnumSet.of( + ResourceTypeRepository.MetadataType.operations, + ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.subCategory), new ResourceTypeRepository.ResourceTypeLoadedCallback() { public void onResourceTypeLoaded(List<Resource> result) { @@ -197,39 +200,41 @@ public class ResourceTreeDatasource extends DataSource { return introduceTypeAndCategoryNodes(nodes); }
- private static TreeNode[] introduceTypeAndCategoryNodes(ResourceTreeNode[] nodes) { + private static TreeNode[] introduceTypeAndCategoryNodes(ResourceTreeNode[] resourceNodes) { List<TreeNode> updatedNodes = new ArrayList<TreeNode>(); // Maps category node IDs to the corresponding category nodes. - Map<String, CategoryTreeNode> categories = new HashMap<String, CategoryTreeNode>(); + Map<String, SubCategoryTreeNode> subcategoryNodes = new HashMap<String, SubCategoryTreeNode>(); // Maps type node IDs to the corresponding type nodes. - Map<String, TypeTreeNode> types = new HashMap<String, TypeTreeNode>(); + Map<String, AutoGroupTreeNode> autogroupNodes = new HashMap<String, AutoGroupTreeNode>();
- for (ResourceTreeNode node : nodes) { - updatedNodes.add(node); + for (ResourceTreeNode resourceNode : resourceNodes) { + updatedNodes.add(resourceNode);
- Resource resource = node.getResource(); + Resource resource = resourceNode.getResource(); ResourceType type = resource.getResourceType(); if (type.getCategory() != ResourceCategory.PLATFORM) { - String typeNodeId = TypeTreeNode.idOf(resource); - if (!types.containsKey(typeNodeId)) { + String autogroupNodeId = AutoGroupTreeNode.idOf(resource); + if (!autogroupNodes.containsKey(autogroupNodeId)) { Resource parentResource = resource.getParentResource(); - ResourceSubCategory category = type.getSubCategory(); - if (category != null) { + ResourceSubCategory subcategory = type.getSubCategory(); + if (subcategory != null) { + System.out.println("Processing " + subcategory + "..."); do { - String categoryNodeId = CategoryTreeNode.idOf(category, parentResource); - CategoryTreeNode categoryNode = categories.get(categoryNodeId); - if (categoryNode == null) { - categoryNode = new CategoryTreeNode(category, parentResource); - categories.put(categoryNode.getID(), categoryNode); - updatedNodes.add(categoryNode); + String subcategoryNodeId = SubCategoryTreeNode.idOf(subcategory, parentResource); + if (!subcategoryNodes.containsKey(subcategoryNodeId)) { + SubCategoryTreeNode subcategoryNode = new SubCategoryTreeNode(subcategory, parentResource); + subcategoryNodes.put(subcategoryNode.getID(), subcategoryNode); + System.out.println("Adding " + subcategoryNode + " to tree..."); + updatedNodes.add(subcategoryNode); } - } while ((category = category.getParentSubCategory()) != null); + } while ((subcategory = subcategory.getParentSubCategory()) != null); }
if (!type.isSingleton()) { - TypeTreeNode typeNode = new TypeTreeNode(resource); - updatedNodes.add(typeNode); - types.put(typeNodeId, typeNode); + AutoGroupTreeNode autogroupNode = new AutoGroupTreeNode(resource); + autogroupNodes.put(autogroupNodeId, autogroupNode); + System.out.println("Adding " + autogroupNode + " to tree..."); + updatedNodes.add(autogroupNode); } } } @@ -238,15 +243,18 @@ public class ResourceTreeDatasource extends DataSource { return updatedNodes.toArray(new TreeNode[updatedNodes.size()]); }
- public static class CategoryTreeNode extends EnhancedTreeNode { - public CategoryTreeNode(ResourceSubCategory category, Resource parentResource) { + /** + * 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) ? - CategoryTreeNode.idOf(parentCategory, parentResource) : + SubCategoryTreeNode.idOf(parentCategory, parentResource) : ResourceTreeNode.idOf(parentResource); setParentID(parentId); setAttribute(Attributes.PARENT_ID, parentId); @@ -255,6 +263,8 @@ public class ResourceTreeDatasource extends DataSource { String name = category.getDisplayName(); setName(name); setAttribute(Attributes.NAME, name); + + setAttribute(Attributes.DESCRIPTION, category.getDescription()); }
public static String idOf(ResourceSubCategory category, Resource parentResource) { @@ -263,10 +273,10 @@ public class ResourceTreeDatasource extends DataSource { }
/** - * The Resource type folder node for an autogroup. + * The folder node for a Resource autogroup. */ - public static class TypeTreeNode extends EnhancedTreeNode { - private TypeTreeNode(Resource resource) { + public static class AutoGroupTreeNode extends EnhancedTreeNode { + private AutoGroupTreeNode(Resource resource) { String id = idOf(resource); setID(id); setAttribute(Attributes.ID, id); @@ -281,21 +291,23 @@ public class ResourceTreeDatasource extends DataSource { String name = StringUtility.pluralize(type.getName()); setName(name); setAttribute(Attributes.NAME, name); + + setAttribute(Attributes.DESCRIPTION, type.getDescription()); }
public static String idOf(Resource resource) { Resource parentResource = resource.getParentResource(); - return (parentResource != null) ? "type" + resource.getResourceType().getId() + "_" - + parentResource.getId() : null; + return (parentResource != null) ? + "autogroup" + resource.getResourceType().getId() + "_" + parentResource.getId() : + null; }
public static String parentIdOf(Resource resource) { ResourceType type = resource.getResourceType(); ResourceSubCategory parentCategory = type.getSubCategory(); - String parentId = (parentCategory != null) ? - CategoryTreeNode.idOf(parentCategory, resource.getParentResource()) : + return (parentCategory != null) ? + SubCategoryTreeNode.idOf(parentCategory, resource.getParentResource()) : ResourceTreeNode.idOf(resource.getParentResource()); - return parentId; } }
@@ -313,8 +325,8 @@ public class ResourceTreeDatasource extends DataSource { String parentId; if (parentResource != null) { parentId = resource.getResourceType().isSingleton() ? - TypeTreeNode.parentIdOf(resource) : - TypeTreeNode.idOf(resource); + AutoGroupTreeNode.parentIdOf(resource) : + AutoGroupTreeNode.idOf(resource); } else { parentId = null; @@ -325,17 +337,20 @@ public class ResourceTreeDatasource extends DataSource { // System.out.println(id + " / " + parentId); // setAttribute("parentKey", resource.getParentResource() == null ? 0 : (resource.getParentResource().getId() + resource.getResourceType().getName()));
- setName(resource.getName()); - setAttribute(Attributes.NAME, resource.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");
- setIsFolder((resource.getResourceType().getChildResourceTypes() != null && !resource.getResourceType() - .getChildResourceTypes().isEmpty())); + Set<ResourceType> childTypes = resource.getResourceType().getChildResourceTypes(); + setIsFolder((childTypes != null && !childTypes.isEmpty())); }
public Resource getResource() { 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 418a334..a03acaf 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 @@ -153,8 +153,8 @@ public class ResourceTreeView extends LocatableVLayout { event.getNode(); event.cancel();
- if (event.getNode() instanceof ResourceTreeDatasource.TypeTreeNode) { - showContextMenu((ResourceTreeDatasource.TypeTreeNode) event.getNode()); + if (event.getNode() instanceof ResourceTreeDatasource.AutoGroupTreeNode) { + showContextMenu((ResourceTreeDatasource.AutoGroupTreeNode) event.getNode()); } else if (event.getNode() instanceof ResourceTreeDatasource.ResourceTreeNode) { showContextMenu((ResourceTreeDatasource.ResourceTreeNode) event.getNode()); } @@ -196,18 +196,18 @@ public class ResourceTreeView extends LocatableVLayout { } }
- private void showContextMenu(ResourceTreeDatasource.TypeTreeNode node) { - + private void showContextMenu(ResourceTreeDatasource.AutoGroupTreeNode node) { contextMenu.setItems(new MenuItem(node.getName())); contextMenu.showContextMenu(); - }
private void showContextMenu(final ResourceTreeDatasource.ResourceTreeNode node) { ResourceType type = node.getResource().getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( type.getId(), - EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, + EnumSet.of( + ResourceTypeRepository.MetadataType.operations, + ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.subCategory, ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), @@ -501,8 +501,8 @@ public class ResourceTreeView extends LocatableVLayout { addMember(treeGrid);
treeGrid.fetchData(treeGrid.getCriteria(), new DSCallback() { - public void execute(DSResponse dsResponse, Object o, DSRequest dsRequest) { - System.out.println("Here!!!!!"); + public void execute(DSResponse response, Object rawData, DSRequest request) { + System.out.println("Done fetching data for tree."); updateBreadcrumbs(); } }); @@ -539,11 +539,10 @@ public class ResourceTreeView extends LocatableVLayout { ResourceTypeRepository.MetadataType.subCategory), new ResourceTypeRepository.ResourceTypeLoadedCallback() { public void onResourceTypeLoaded(List<Resource> result) { - - TreeUtility.printTree(treeGrid.getTree()); - treeGrid.getTree().linkNodes(ResourceTreeDatasource.buildNodes(result));
+ //TreeUtility.printTree(treeGrid.getTree()); + TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); if (selectedNode != null) { treeGrid.deselectAllRecords(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java index d488d14..cfa51bf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java @@ -40,6 +40,8 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTServiceAsync;
/** + * A cache for ResourceTypes and their various fields. Fields are only fetched as needed. + * * @author Greg Hinkle */ public class ResourceTypeRepository { @@ -66,7 +68,7 @@ public class ResourceTypeRepository { }
public static interface TypesLoadedCallback { - void onTypesLoaded(HashMap<Integer, ResourceType> types); + void onTypesLoaded(Map<Integer, ResourceType> types); }
public static interface ResourceTypeLoadedCallback { @@ -97,7 +99,7 @@ public class ResourceTypeRepository { types.add(res.getResourceType().getId()); } getResourceTypes(types.toArray(new Integer[types.size()]), metadataTypes, new TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + public void onTypesLoaded(Map<Integer, ResourceType> types) { for (Resource res : resources) { res.setResourceType(types.get(res.getResourceType().getId())); } @@ -130,7 +132,7 @@ public class ResourceTypeRepository { types.add(group.getResourceType().getId()); } getResourceTypes(types.toArray(new Integer[types.size()]), metadataTypes, new TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + public void onTypesLoaded(Map<Integer, ResourceType> types) { for (ResourceGroup group : groups) { group.setResourceType(types.get(group.getResourceType().getId())); } @@ -150,7 +152,7 @@ public class ResourceTypeRepository { public void getResourceTypes(final Integer resourceTypeId, final EnumSet<MetadataType> metadataTypes, final TypeLoadedCallback callback) { getResourceTypes(new Integer[] { resourceTypeId }, metadataTypes, new TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + public void onTypesLoaded(Map<Integer, ResourceType> types) { if (callback != null) { callback.onTypesLoaded(types.get(resourceTypeId)); } @@ -162,9 +164,9 @@ public class ResourceTypeRepository { final TypesLoadedCallback callback) { ResourceTypeCriteria criteria = new ResourceTypeCriteria();
- final HashMap<Integer, ResourceType> cachedTypes = new HashMap<Integer, ResourceType>(); + final Map<Integer, ResourceType> cachedTypes = new HashMap<Integer, ResourceType>();
- ArrayList<Integer> typesNeeded = new ArrayList<Integer>(); + List<Integer> typesNeeded = new ArrayList<Integer>(); if (resourceTypeIds == null) { //preload all } else { @@ -191,39 +193,41 @@ public class ResourceTypeRepository { if (metadataTypes != null) { for (MetadataType metadataType : metadataTypes) { switch (metadataType) { - case children: - criteria.fetchChildResourceTypes(true); - break; - case content: - criteria.fetchPackageTypes(true); - break; - case measurements: - criteria.fetchMetricDefinitions(true); - break; - case operations: - criteria.fetchOperationDefinitions(true); - break; - case events: - criteria.fetchEventDefinitions(true); - break; - case pluginConfigurationDefinition: - criteria.fetchPluginConfigurationDefinition(true); - break; - case resourceConfigurationDefinition: - criteria.fetchResourceConfigurationDefinition(true); - break; - case subCategory: - criteria.fetchSubCategory(true); - break; - case parentTypes: - criteria.fetchParentResourceTypes(true); - break; - case processScans: - criteria.fetchProcessScans(true); - break; - case productVersions: - criteria.fetchProductVersions(true); - break; + case children: + criteria.fetchChildResourceTypes(true); + break; + case content: + criteria.fetchPackageTypes(true); + break; + case events: + criteria.fetchEventDefinitions(true); + break; + case measurements: + criteria.fetchMetricDefinitions(true); + break; + case operations: + criteria.fetchOperationDefinitions(true); + break; + case parentTypes: + criteria.fetchParentResourceTypes(true); + break; + case pluginConfigurationDefinition: + criteria.fetchPluginConfigurationDefinition(true); + break; + case processScans: + criteria.fetchProcessScans(true); + break; + case productVersions: + criteria.fetchProductVersions(true); + break; + case resourceConfigurationDefinition: + criteria.fetchResourceConfigurationDefinition(true); + break; + case subCategory: + criteria.fetchSubCategory(true); + break; + default: + System.err.println("ERROR: metadataType " + metadataType.name() + " not incorporated into ResourceType criteria."); } } } @@ -231,7 +235,7 @@ public class ResourceTypeRepository { criteria.setPageControl(PageControl.getUnlimitedInstance());
System.out.println("Loading " + typesNeeded.size() - + ((metadataTypes != null) ? (" types: " + metadataTypes.toString()) : "")); + + ((metadataTypes != null) ? (" types: " + metadataTypes) : ""));
resourceTypeService.findResourceTypesByCriteria(criteria, new AsyncCallback<PageList<ResourceType>>() { public void onFailure(Throwable caught) { @@ -245,29 +249,43 @@ public class ResourceTypeRepository { if (metadataTypes != null) { for (MetadataType metadataType : metadataTypes) { switch (metadataType) { - case children: - cachedType.setChildResourceTypes(type.getChildResourceTypes()); - break; - case operations: - cachedType.setOperationDefinitions(type.getOperationDefinitions()); - break; - case measurements: - cachedType.setMetricDefinitions(type.getMetricDefinitions()); - break; - case content: - cachedType.setPackageTypes(type.getPackageTypes()); - break; - case events: - cachedType.setPackageTypes(type.getPackageTypes()); - break; - case pluginConfigurationDefinition: - cachedType - .setPluginConfigurationDefinition(type.getPluginConfigurationDefinition()); - break; - case resourceConfigurationDefinition: - cachedType.setResourceConfigurationDefinition(type - .getResourceConfigurationDefinition()); - break; + case children: + cachedType.setChildResourceTypes(type.getChildResourceTypes()); + break; + case content: + cachedType.setPackageTypes(type.getPackageTypes()); + break; + case events: + cachedType.setPackageTypes(type.getPackageTypes()); + break; + case measurements: + cachedType.setMetricDefinitions(type.getMetricDefinitions()); + break; + case operations: + cachedType.setOperationDefinitions(type.getOperationDefinitions()); + break; + case parentTypes: + cachedType.setParentResourceTypes(type.getParentResourceTypes()); + break; + case pluginConfigurationDefinition: + cachedType + .setPluginConfigurationDefinition(type.getPluginConfigurationDefinition()); + break; + case processScans: + cachedType.setProcessScans(type.getProcessScans()); + break; + case productVersions: + cachedType.setProductVersions(type.getProductVersions()); + break; + case resourceConfigurationDefinition: + cachedType.setResourceConfigurationDefinition(type + .getResourceConfigurationDefinition()); + break; + case subCategory: + cachedType.setSubCategory(type.getSubCategory()); + break; + default: + System.err.println("ERROR: metadataType " + metadataType.name() + " not merged into cached ResourceType."); } } } @@ -294,8 +312,8 @@ public class ResourceTypeRepository {
public void preloadAll() { getResourceTypes((Integer[]) null, EnumSet.allOf(MetadataType.class), new TypesLoadedCallback() { - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { - System.out.println("Preloaded [" + types.size() + "] resource types"); + public void onTypesLoaded(Map<Integer, ResourceType> types) { + System.out.println("Preloaded [" + types.size() + "] Resource types."); } }); } diff --git a/modules/jopr/etc/jbas5-jnp-client/client.sh b/modules/jopr/etc/jbas5-jnp-client/client.sh index 3dc0f94..240f137 100644 --- a/modules/jopr/etc/jbas5-jnp-client/client.sh +++ b/modules/jopr/etc/jbas5-jnp-client/client.sh @@ -9,7 +9,7 @@ MAIN_JAR_NAME=jbas5-jnp-client-1.0.jar MAIN_CLASS=test.RmiClient
-JBOSS_HOME=/devel/jboss-5.1.0.CR1 +JBOSS_HOME=/home/ips/Applications/jboss-6.0.0-SNAPSHOT JAVA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8788"
@@ -43,29 +43,29 @@ JAVA=$JAVA_HOME/bin/java # only include jbossall-client.jar in classpath, if # JBOSS_CLASSPATH was not yet set #if not "%JBOSS_CLASSPATH%" == "" GOTO HAVE_JB_CP -# set JBOSS_CLASSPATH=%JBOSS_HOME%/client/jbossall-client.jar +JBOSS_CLASSPATH=$JBOSS_HOME/client/jbossall-client.jar
# For the call to new InitialContext() (using org.jnp.interfaces.NamingContextFactory)... -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jnp-client.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/common/lib/jboss-security-aspects.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jbosssx-client.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-aop-client.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-common-core.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jnp-client.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/common/lib/jboss-security-aspects.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jbosssx-client.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-aop-client.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-common-core.jar # For the call to InitialContext.lookup()... -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-#oting.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-aspect-jdk50-client.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/trove.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/javassist.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-security-spi.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-javaee.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-#oting.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-aspect-jdk50-client.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/trove.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/javassist.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-security-spi.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-javaee.jar # For remote invocations on the ProfileService proxy (e.g. ProfileService.getViewManager())... -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/concurrent.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-client.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-mdr.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-integration.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/concurrent.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-client.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-mdr.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/client/jboss-integration.jar
-JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/lib/jboss-managed.jar -JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/lib/jboss-metatype.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/lib/jboss-managed.jar +#JBOSS_CLASSPATH=$JBOSS_CLASSPATH:$JBOSS_HOME/lib/jboss-metatype.jar
#:HAVE_JB_CP
diff --git a/modules/jopr/etc/jbas5-jnp-client/src/main/java/test/RmiClient.java b/modules/jopr/etc/jbas5-jnp-client/src/main/java/test/RmiClient.java index 6aa13c4..91b23ee 100644 --- a/modules/jopr/etc/jbas5-jnp-client/src/main/java/test/RmiClient.java +++ b/modules/jopr/etc/jbas5-jnp-client/src/main/java/test/RmiClient.java @@ -17,9 +17,11 @@ public class RmiClient
public static void main(String[] args) throws Exception - { + { + String jnpUrl = (args.length == 1) ? args[0] : "jnp://127.0.0.1:1099"; + Properties env = new Properties(); - env.setProperty(Context.PROVIDER_URL, "jnp://127.0.0.1:1099"); + env.setProperty(Context.PROVIDER_URL, jnpUrl); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, NAMING_CONTEXT_FACTORY); env.setProperty("jnp.disableDiscovery", "true"); env.setProperty("jnp.timeout", "120"); @@ -40,3 +42,4 @@ public class RmiClient deploymentManager.getProfiles(); } } +
commit 88e3f764331265d6557274f8b8443a7b75ea76de Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 22 17:39:25 2010 -0400
initial try of the dampening editor. still some work to make it prettier, but its functional. let's you view and edit/save dampening rules
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java index b332c3a..87eecea 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/DampeningAlertDefinitionForm.java @@ -23,7 +23,18 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.LinkedHashMap; + +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.SpinnerItem; +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 org.rhq.core.domain.alert.AlertDampening; import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.AlertDampening.Category; +import org.rhq.core.domain.alert.AlertDampening.TimeUnits; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
/** @@ -35,6 +46,27 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement
private boolean formBuilt = false;
+ private SelectItem dampeningRuleSelection; + private StaticTextItem dampeningRuleStatic; + + private SpinnerItem consecutiveOccurrencesSpinner; + private StaticTextItem consecutiveOccurrencesStatic; + + private SpinnerItem partialOccurrencesSpinner; + private StaticTextItem partialOccurrencesStatic; + + private SpinnerItem partialEvaluationsSpinner; + private StaticTextItem partialEvaluationsStatic; + + private SpinnerItem durationOccurrencesSpinner; + private StaticTextItem durationOccurrencesStatic; + + private SpinnerItem durationTimePeriodSpinner; + private StaticTextItem durationTimePeriodStatic; + + private SelectItem durationTimeUnitsSelection; + private StaticTextItem durationTimeUnitsStatic; + public DampeningAlertDefinitionForm(String locatorId) { this(locatorId, null); } @@ -69,7 +101,50 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement if (alertDef == null) { clearFormValues(); } else { - // TODO set values of the components + clearFormValues(); + + AlertDampening alertDampening = alertDef.getAlertDampening(); + if (alertDampening == null) { + alertDampening = new AlertDampening(AlertDampening.Category.NONE); + alertDefinition.setAlertDampening(alertDampening); + } + + dampeningRuleSelection.setValue(alertDampening.getCategory().name()); + dampeningRuleStatic.setValue(getCategoryTitle(alertDampening.getCategory())); + + switch (alertDampening.getCategory()) { + case NONE: { + break; + } + case CONSECUTIVE_COUNT: { + consecutiveOccurrencesSpinner.setValue(alertDampening.getValue()); + consecutiveOccurrencesStatic.setValue(alertDampening.getValue()); + break; + } + case PARTIAL_COUNT: { + partialOccurrencesSpinner.setValue(alertDampening.getValue()); + partialOccurrencesStatic.setValue(alertDampening.getValue()); + + partialEvaluationsSpinner.setValue(alertDampening.getPeriod()); + partialEvaluationsStatic.setValue(alertDampening.getPeriod()); + break; + } + case DURATION_COUNT: { + durationOccurrencesSpinner.setValue(alertDampening.getValue()); + durationOccurrencesStatic.setValue(alertDampening.getValue()); + + durationTimePeriodSpinner.setValue(alertDampening.getPeriod()); + durationTimePeriodStatic.setValue(alertDampening.getPeriod()); + + durationTimeUnitsSelection.setValue(alertDampening.getPeriodUnits().name()); + durationTimeUnitsStatic.setValue(getTimeUnitsTitle(alertDampening.getPeriodUnits())); + break; + } + default: { + throw new IllegalStateException("Invalid category - please report this as a bug: " + + alertDampening.getCategory()); // should never happen + } + } }
markForRedraw(); @@ -77,36 +152,434 @@ public class DampeningAlertDefinitionForm extends LocatableDynamicForm implement
@Override public void makeEditable() { - // TODO Auto-generated method stub + dampeningRuleSelection.show(); + dampeningRuleStatic.hide(); + + AlertDampening.Category cat = AlertDampening.Category.valueOf(dampeningRuleSelection.getValue().toString()); + switch (cat) { + case NONE: { + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.hide(); + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.hide(); + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.hide(); + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.hide(); + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.hide(); + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.hide(); + break; + } + case CONSECUTIVE_COUNT: { + consecutiveOccurrencesSpinner.show(); + consecutiveOccurrencesStatic.hide(); + + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.hide(); + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.hide(); + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.hide(); + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.hide(); + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.hide(); + + break; + } + case PARTIAL_COUNT: { + partialOccurrencesSpinner.show(); + partialOccurrencesStatic.hide(); + + partialEvaluationsSpinner.show(); + partialEvaluationsStatic.hide(); + + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.hide(); + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.hide(); + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.hide(); + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.hide(); + break; + } + case DURATION_COUNT: { + durationOccurrencesSpinner.show(); + durationOccurrencesStatic.hide(); + + durationTimePeriodSpinner.show(); + durationTimePeriodStatic.hide(); + + durationTimeUnitsSelection.show(); + durationTimeUnitsStatic.hide(); + + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.hide(); + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.hide(); + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.hide(); + break; + } + default: { + throw new IllegalStateException("Bad dampening category - please report this bug: " + cat); // should never happen + } + }
markForRedraw(); }
@Override public void makeViewOnly() { - // TODO Auto-generated method stub + dampeningRuleSelection.hide(); + dampeningRuleStatic.show(); + + AlertDampening.Category cat = AlertDampening.Category.valueOf(dampeningRuleSelection.getValue().toString()); + switch (cat) { + case NONE: { + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.hide(); + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.hide(); + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.hide(); + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.hide(); + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.hide(); + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.hide(); + break; + } + case CONSECUTIVE_COUNT: { + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.show(); + + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.hide(); + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.hide(); + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.hide(); + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.hide(); + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.hide(); + break; + } + case PARTIAL_COUNT: { + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.show(); + + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.show(); + + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.hide(); + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.hide(); + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.hide(); + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.hide(); + break; + } + case DURATION_COUNT: { + durationOccurrencesSpinner.hide(); + durationOccurrencesStatic.show(); + + durationTimePeriodSpinner.hide(); + durationTimePeriodStatic.show(); + + durationTimeUnitsSelection.hide(); + durationTimeUnitsStatic.show(); + + consecutiveOccurrencesSpinner.hide(); + consecutiveOccurrencesStatic.hide(); + partialOccurrencesSpinner.hide(); + partialOccurrencesStatic.hide(); + partialEvaluationsSpinner.hide(); + partialEvaluationsStatic.hide(); + break; + } + default: { + throw new IllegalStateException("Bad dampening category - please report this bug: " + cat); // should never happen + } + }
markForRedraw(); }
@Override public void saveAlertDefinition() { - // TODO Auto-generated method stub + AlertDampening.Category cat = AlertDampening.Category.valueOf(dampeningRuleSelection.getValue().toString()); + AlertDampening alertDampening = new AlertDampening(cat); + switch (cat) { + case NONE: { + // each time condition set is true + alertDampening.setValue(0); + alertDampening.setValueUnits(null); + alertDampening.setPeriod(0); + alertDampening.setPeriodUnits(null); + break; + } + case CONSECUTIVE_COUNT: { + // once every N times condition set is true consecutively + alertDampening.setValue(Integer.valueOf(consecutiveOccurrencesSpinner.getValue().toString())); + alertDampening.setValueUnits(null); + alertDampening.setPeriod(0); + alertDampening.setPeriodUnits(null); + break; + } + case PARTIAL_COUNT: { + // once every N times condition set is true during the last M evaluations + alertDampening.setValue(Integer.valueOf(partialOccurrencesSpinner.getValue().toString())); + alertDampening.setValueUnits(null); + alertDampening.setPeriod(Integer.valueOf(partialEvaluationsSpinner.getValue().toString())); + alertDampening.setPeriodUnits(null); + break; + } + case DURATION_COUNT: { + // once every N times condition set is true within a time period of M {mins, hours, days, weeks} + alertDampening.setValue(Integer.valueOf(durationOccurrencesSpinner.getValue().toString())); + alertDampening.setValueUnits(null); + alertDampening.setPeriod(Integer.valueOf(durationTimePeriodSpinner.getValue().toString())); + alertDampening.setPeriodUnits(TimeUnits.valueOf(durationTimeUnitsSelection.getValue().toString())); + break; + } + default: { + throw new IllegalStateException("Bad dampening category - please report this bug: " + cat); // should never happen + } + } + alertDefinition.setAlertDampening(alertDampening); }
@Override public void clearFormValues() { - // TODO component.clearValue(); + dampeningRuleSelection.clearValue(); + consecutiveOccurrencesSpinner.clearValue(); + partialOccurrencesSpinner.clearValue(); + partialEvaluationsSpinner.clearValue(); + durationOccurrencesSpinner.clearValue(); + durationTimePeriodSpinner.clearValue(); + durationTimeUnitsSelection.clearValue(); + + dampeningRuleStatic.clearValue(); + consecutiveOccurrencesStatic.clearValue(); + partialOccurrencesStatic.clearValue(); + partialEvaluationsStatic.clearValue(); + durationOccurrencesStatic.clearValue(); + durationTimePeriodStatic.clearValue(); + durationTimeUnitsStatic.clearValue();
markForRedraw(); }
private void buildForm() { if (!formBuilt) { - // TODO buildNodes components - // TODO setFields(components); + setNumCols(3); + + dampeningRuleSelection = new SelectItem("dampeningRule", "Dampening Rule"); + LinkedHashMap<String, String> rules = new LinkedHashMap<String, String>(4); + rules.put(AlertDampening.Category.NONE.name(), getCategoryTitle(AlertDampening.Category.NONE)); + rules.put(AlertDampening.Category.CONSECUTIVE_COUNT.name(), + getCategoryTitle(AlertDampening.Category.CONSECUTIVE_COUNT)); + rules.put(AlertDampening.Category.PARTIAL_COUNT.name(), + getCategoryTitle(AlertDampening.Category.PARTIAL_COUNT)); + rules.put(AlertDampening.Category.DURATION_COUNT.name(), + getCategoryTitle(AlertDampening.Category.DURATION_COUNT)); + dampeningRuleSelection.setValueMap(rules); + dampeningRuleSelection.setDefaultValue(AlertDampening.Category.NONE.name()); + dampeningRuleSelection.setWrapTitle(false); + dampeningRuleSelection.setRedrawOnChange(true); + dampeningRuleSelection.setColSpan(2); + dampeningRuleStatic = new StaticTextItem("dampeningRuleStatic", "Dampening Rule"); + dampeningRuleStatic.setColSpan(2); + dampeningRuleStatic.setWrapTitle(false); + + // NONE + // nothing to do - the none category has no ui components to render + + // CONSECUTIVE_COUNT + consecutiveOccurrencesSpinner = new SpinnerItem("consecutiveOccurrencesSpinner", "Occurrences"); + consecutiveOccurrencesSpinner.setColSpan(2); + consecutiveOccurrencesSpinner.setWrapTitle(false); + consecutiveOccurrencesSpinner.setMin(1); + consecutiveOccurrencesSpinner.setMax(999999); + consecutiveOccurrencesSpinner.setStep(1); + consecutiveOccurrencesSpinner.setDefaultValue(1); + consecutiveOccurrencesSpinner + .setTooltip("The number of times the condition set must be consecutively true before the alert is triggered."); + consecutiveOccurrencesStatic = new StaticTextItem("consecutiveOccurrencesStatic", "Occurrences"); + consecutiveOccurrencesStatic.setColSpan(2); + consecutiveOccurrencesStatic.setWrapTitle(false); + + // PARTIAL_COUNT + partialOccurrencesSpinner = new SpinnerItem("partialOccurrencesSpinner", "Occurrences"); + partialOccurrencesSpinner.setColSpan(2); + partialOccurrencesSpinner.setWrapTitle(false); + partialOccurrencesSpinner.setMin(1); + partialOccurrencesSpinner.setMax(999999); + partialOccurrencesSpinner.setStep(1); + partialOccurrencesSpinner.setDefaultValue(1); + partialOccurrencesSpinner + .setTooltip("The number of times the condition set must be true during the last N evaluations before the alert is triggered."); + partialOccurrencesStatic = new StaticTextItem("partialOccurrencesStatic", "Occurrences"); + partialOccurrencesStatic.setColSpan(2); + partialOccurrencesStatic.setWrapTitle(false); + + partialEvaluationsSpinner = new SpinnerItem("partialEvaluationsSpinner", "Evaluations"); + partialEvaluationsSpinner.setColSpan(2); + partialEvaluationsSpinner.setWrapTitle(false); + partialEvaluationsSpinner.setMin(1); + partialEvaluationsSpinner.setMax(999999); + partialEvaluationsSpinner.setStep(1); + partialEvaluationsSpinner.setDefaultValue(1); + partialEvaluationsStatic = new StaticTextItem("partialEvaluationStatic", "Evaluations"); + partialEvaluationsStatic.setColSpan(2); + partialEvaluationsStatic.setWrapTitle(false); + + // DURATION_COUNT + durationOccurrencesSpinner = new SpinnerItem("durationOccurrencesSpinner", "Occurrences"); + durationOccurrencesSpinner.setColSpan(2); + durationOccurrencesSpinner.setWrapTitle(false); + durationOccurrencesSpinner.setMin(1); + durationOccurrencesSpinner.setMax(999999); + durationOccurrencesSpinner.setStep(1); + durationOccurrencesSpinner.setDefaultValue(1); + durationOccurrencesSpinner + .setTooltip("The number of times the condition set must be true during the given time period before the alert is triggered."); + durationOccurrencesStatic = new StaticTextItem("durationOccurrencesStatic", "Occurrences"); + durationOccurrencesStatic.setColSpan(2); + durationOccurrencesStatic.setWrapTitle(false); + + durationTimePeriodSpinner = new SpinnerItem("durationTimePeriodSpinner", "Time Period"); + durationTimePeriodSpinner.setEndRow(false); + durationTimePeriodSpinner.setWrapTitle(false); + durationTimePeriodSpinner.setMin(1); + durationTimePeriodSpinner.setMax(999999); + durationTimePeriodSpinner.setStep(1); + durationTimePeriodSpinner.setDefaultValue(1); + durationTimePeriodStatic = new StaticTextItem("durationTimePeriodStatic", "Time Period"); + durationTimePeriodStatic.setEndRow(false); + durationTimePeriodStatic.setWrapTitle(false); + + durationTimeUnitsSelection = new SelectItem("durationTimeUnits"); + LinkedHashMap<String, String> units = new LinkedHashMap<String, String>(4); + units.put(AlertDampening.TimeUnits.MINUTES.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.MINUTES)); + units.put(AlertDampening.TimeUnits.HOURS.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.HOURS)); + units.put(AlertDampening.TimeUnits.DAYS.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.DAYS)); + units.put(AlertDampening.TimeUnits.WEEKS.name(), getTimeUnitsTitle(AlertDampening.TimeUnits.WEEKS)); + durationTimeUnitsSelection.setValueMap(units); + durationTimeUnitsSelection.setDefaultValue(AlertDampening.TimeUnits.MINUTES.name()); + durationTimeUnitsSelection.setStartRow(false); + durationTimeUnitsSelection.setEndRow(true); + durationTimeUnitsSelection.setShowTitle(false); + durationTimeUnitsStatic = new StaticTextItem("durationTimeUnitsStatic"); + durationTimeUnitsStatic.setStartRow(false); + durationTimeUnitsStatic.setEndRow(true); + durationTimeUnitsStatic.setShowTitle(false); + + dampeningRuleSelection.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + Category cat = AlertDampening.Category.valueOf(event.getValue().toString()); + switch (cat) { + case NONE: { + consecutiveOccurrencesSpinner.hide(); + partialOccurrencesSpinner.hide(); + partialEvaluationsSpinner.hide(); + durationOccurrencesSpinner.hide(); + durationTimePeriodSpinner.hide(); + durationTimeUnitsSelection.hide(); + break; + } + case CONSECUTIVE_COUNT: { + consecutiveOccurrencesSpinner.show(); + partialOccurrencesSpinner.hide(); + partialEvaluationsSpinner.hide(); + durationOccurrencesSpinner.hide(); + durationTimePeriodSpinner.hide(); + durationTimeUnitsSelection.hide(); + break; + } + case PARTIAL_COUNT: { + consecutiveOccurrencesSpinner.hide(); + partialOccurrencesSpinner.show(); + partialEvaluationsSpinner.show(); + durationOccurrencesSpinner.hide(); + durationTimePeriodSpinner.hide(); + durationTimeUnitsSelection.hide(); + break; + } + case DURATION_COUNT: { + consecutiveOccurrencesSpinner.hide(); + partialOccurrencesSpinner.hide(); + partialEvaluationsSpinner.hide(); + durationOccurrencesSpinner.show(); + durationTimePeriodSpinner.show(); + durationTimeUnitsSelection.show(); + break; + } + default: { + throw new IllegalStateException("Invalid category - please report this as a bug: " + cat); // should never happen + } + } + markForRedraw(); + } + }); + + // put all the fields in the form now + setFields(dampeningRuleSelection, dampeningRuleStatic, consecutiveOccurrencesSpinner, + consecutiveOccurrencesStatic, partialOccurrencesSpinner, partialOccurrencesStatic, + partialEvaluationsSpinner, partialEvaluationsStatic, durationOccurrencesSpinner, + durationOccurrencesStatic, durationTimePeriodSpinner, durationTimePeriodStatic, + durationTimeUnitsSelection, durationTimeUnitsStatic);
formBuilt = true; } } + + private String getCategoryTitle(AlertDampening.Category category) { + switch (category) { + case NONE: { + return "None"; + } + case CONSECUTIVE_COUNT: { + return "Consecutive"; + } + case PARTIAL_COUNT: { + return "Last N Evaluations"; + } + case DURATION_COUNT: { + return "Time Period"; + } + default: { + throw new IllegalStateException("Invalid category - please report this as a bug: " + category); // should never happen + } + } + } + + private String getTimeUnitsTitle(AlertDampening.TimeUnits units) { + switch (units) { + case MINUTES: { + return "minutes"; + } + case HOURS: { + return "hours"; + } + case DAYS: { + return "days"; + } + case WEEKS: { + return "weeks"; + } + default: { + throw new IllegalStateException("Invalid time units - please report this as a bug: " + units); // should never happen + } + } + } }
commit 6689f8e0e7057c2e183879a7a3bbbbb05f36d34b Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 14:35:10 2010 -0400
only read from viewPath if the user is allowed to access this view
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index bcdb9ca..ef55f63 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -333,10 +333,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm }
@Override - public void renderView(ViewPath viewPath) { - groupDefinitionId = viewPath.getCurrentAsInt(); - viewId = viewPath.getCurrent(); - basePath = viewPath.getPathToCurrent(); + public void renderView(final ViewPath viewPath) { GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { @Override public void onFailure(Throwable caught) { @@ -355,6 +352,9 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm if (result.contains(Permission.MANAGE_INVENTORY) == false) { handleAuthorizationFailure(); } else { + groupDefinitionId = viewPath.getCurrentAsInt(); + viewId = viewPath.getCurrent(); + basePath = viewPath.getPathToCurrent(); lookupDetails(groupDefinitionId); } }
commit d93ec8d394b4e25a5f4ca3c0bc20f715976957d0 Merge: eda3ff1... e5215ae... Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 22 14:28:05 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit e5215ae78bdb6ce50c560e5d957022489c161907 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 14:18:06 2010 -0400
authz: disable links in nav panel for InventoryView according to perms
* hide "Discovery Manager" behind MANAGE_INVENTORY * hide "DynaGroup Manager" behind MANAGE_INVENTORY
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index ed442b2..c6d5289 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -18,10 +18,13 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource;
+import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set;
import com.google.gwt.user.client.History; +import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.Canvas; @@ -33,12 +36,14 @@ import com.smartgwt.client.widgets.tree.Tree; import com.smartgwt.client.widgets.tree.TreeGrid; import com.smartgwt.client.widgets.tree.TreeNode;
+import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; 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.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupListView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions.GroupDefinitionListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.discovery.ResourceAutodiscoveryView; @@ -90,6 +95,22 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView protected void onInit() { super.onInit();
+ GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Could not determine user's global permissions, assuming none", + caught); + finishOnInit(EnumSet.noneOf(Permission.class)); + } + + @Override + public void onSuccess(Set<Permission> result) { + finishOnInit(result); + } + }); + } + + private void finishOnInit(Set<Permission> globalPermissions) { setWidth100(); setHeight100();
@@ -103,8 +124,8 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView sectionStack.setWidth(250); sectionStack.setHeight100();
- buildResourcesSection(); - buildGroupsSection(); + buildResourcesSection(globalPermissions); + buildGroupsSection(globalPermissions);
for (final String sectionName : treeGrids.keySet()) { TreeGrid grid = treeGrids.get(sectionName); @@ -133,12 +154,13 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView addMember(contentCanvas); }
- private SectionStackSection buildResourcesSection() { + private SectionStackSection buildResourcesSection(Set<Permission> globalPermissions) {
final SectionStackSection section = new SectionStackSection(SECTION_RESOURCES); section.setExpanded(true);
final TreeNode discoveryQueue = new TreeNode(PAGE_ADQ); + discoveryQueue.setEnabled(globalPermissions.contains(Permission.MANAGE_INVENTORY)); discoveryQueue.setIcon("global/Recent_16.png");
final TreeNode onlyPlatforms = new TreeNode(PAGE_PLATFORMS); @@ -171,11 +193,12 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView return section; }
- private SectionStackSection buildGroupsSection() { + private SectionStackSection buildGroupsSection(Set<Permission> globalPermissions) { final SectionStackSection section = new SectionStackSection(SECTION_GROUPS); section.setExpanded(true);
final TreeNode groupGroupDefinitions = new TreeNode(PAGE_GROUP_DEFINITIONS); + groupGroupDefinitions.setEnabled(globalPermissions.contains(Permission.MANAGE_INVENTORY)); groupGroupDefinitions.setIcon("types/GroupDefinition_16.png");
final TreeNode onlyCompatible = new TreeNode(PAGE_COMPATIBLE_GROUPS);
commit a97483270b9bb2be2ef07413d9a4bc81e1558a20 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 14:16:40 2010 -0400
authz: disallow users w/o MANAGE_INVENTORY from viewing list of group defs
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index c8293c7..a4fac9f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -18,13 +18,18 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions;
+import java.util.Set; + +import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
+import org.rhq.core.domain.authz.Permission; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; @@ -144,4 +149,30 @@ public class GroupDefinitionListView extends TableSection { .extendLocatorId("Details")); return singleGroupDefinitionView; } + + @Override + public void renderView(final ViewPath viewPath) { + GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Could not determine whether user had MANAGE_INVENTORY permission", caught); + handleAuthorizationFailure(); + } + + private void handleAuthorizationFailure() { + CoreGUI.getErrorHandler().handleError("You do not have permission to view group definitions"); + History.back(); + } + + @Override + public void onSuccess(Set<Permission> result) { + if (result.contains(Permission.MANAGE_INVENTORY) == false) { + handleAuthorizationFailure(); + } else { + GroupDefinitionListView.super.renderView(viewPath); + } + } + }); + } } \ No newline at end of file
commit b5a275a90b1249c52153d734c180d0174660255d Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 14:15:55 2010 -0400
authz: disallow users w/o MANAGE_INVENTORY from viewing group def details
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index dde421c..bcdb9ca 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -36,7 +36,6 @@ import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.form.fields.CheckboxItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.SpinnerItem; -import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -78,14 +77,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm private TextAreaItem expression; private SpinnerItem recalculationInterval;
- // read-only form - private StaticTextItem idStatic; - private StaticTextItem nameStatic; - private StaticTextItem descriptionStatic; - private StaticTextItem recursiveStatic; - private StaticTextItem expressionStatic; - private StaticTextItem recalculationIntervalStatic; - public SingleGroupDefinitionView(String locatorId) { super(locatorId);
@@ -101,26 +92,14 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
// form setup id.setValue(groupDefinition.getId()); - idStatic.setValue(groupDefinition.getId()); - name.setValue(groupDefinition.getName()); - nameStatic.setValue(groupDefinition.getName()); - recursive.setValue(groupDefinition.isRecursive()); - recursiveStatic.setValue(groupDefinition.isRecursive()); - description.setValue(groupDefinition.getDescription()); - descriptionStatic.setValue(groupDefinition.getDescription()); - recalculationInterval.setValue(groupDefinition.getRecalculationInterval()); - recalculationIntervalStatic.setValue(groupDefinition.getRecalculationInterval()); - expression.setValue(groupDefinition.getExpression()); - expressionStatic.setValue(groupDefinition.getExpression());
final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("GroupDefinitionForm")); - form.setFields(id, idStatic, name, nameStatic, description, descriptionStatic, expression, expressionStatic, - recursive, recursiveStatic, recalculationInterval, recalculationIntervalStatic); + form.setFields(id, name, description, expression, recursive, recalculationInterval); form.setDataSource(GroupDefinitionDataSource.getInstance()); form.setHiliteRequiredFields(true); form.setRequiredTitleSuffix(" <span style="color: red;">* </span>:"); @@ -229,71 +208,40 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm expression.show(); recalculationInterval.show();
- nameStatic.hide(); - descriptionStatic.hide(); - recursiveStatic.hide(); - expressionStatic.hide(); - recalculationIntervalStatic.hide(); - if (groupDefinitionId == 0) { viewId.getBreadcrumbs().get(0).setDisplayName("New Group Definition"); } else { - viewId.getBreadcrumbs().get(0).setDisplayName("Editing '" + nameStatic.getValue().toString() + "'"); + viewId.getBreadcrumbs().get(0).setDisplayName("Editing '" + name.getValue().toString() + "'"); } CoreGUI.refreshBreadCrumbTrail();
markForRedraw(); }
- public void switchToViewMode() { - name.hide(); - description.hide(); - recursive.hide(); - expression.hide(); - recalculationInterval.hide(); - - nameStatic.show(); - descriptionStatic.show(); - recursiveStatic.show(); - expressionStatic.show(); - recalculationIntervalStatic.show(); - - viewId.getBreadcrumbs().get(0).setDisplayName("Viewing '" + nameStatic.getValue().toString() + "'"); - - markForRedraw(); - } - private void buildForm() { id = new TextItem("id", "ID"); id.setVisible(false); - idStatic = new StaticTextItem("idStatic", "ID"); - idStatic.setVisible(false);
name = new TextItem("name", "Name"); name.setWidth(400); name.setDefaultValue(""); - nameStatic = new StaticTextItem("nameStatic", "Name");
description = new TextAreaItem("description", "Description"); description.setWidth(400); description.setHeight(50); description.setDefaultValue(""); - descriptionStatic = new StaticTextItem("descriptionStatic", "Description");
recursive = new CheckboxItem("recursive", "Recursive"); - recursiveStatic = new StaticTextItem("recursiveStatic", "Recursive");
expression = new TextAreaItem("expression", "Expression"); expression.setWidth(400); expression.setHeight(150); expression.setDefaultValue(""); - expressionStatic = new StaticTextItem("expressionStatic", "Expression");
recalculationInterval = new SpinnerItem("recalculationInterval", "Recalculation Interval"); recalculationInterval.setWrapTitle(false); recalculationInterval.setMin(0); recalculationInterval.setDefaultValue(0); - recalculationIntervalStatic = new StaticTextItem("recalculationIntervalStatic", "Recalculation Interval");
templateSelector = new SelectItem(); templateSelector.setValueMap(getTemplates()); @@ -352,18 +300,14 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm return results.toString(); }
- private void lookupDetails(final int groupDefinitionId, final boolean hasEditPermission) { + private void lookupDetails(final int groupDefinitionId) { ResourceGroupDefinitionCriteria criteria = new ResourceGroupDefinitionCriteria(); criteria.addFilterId(groupDefinitionId);
if (groupDefinitionId == 0) { GroupDefinition newGroupDefinition = new GroupDefinition(); setGroupDefinition(newGroupDefinition); - if (hasEditPermission) { - switchToEditMode(); - } else { - switchToViewMode(); - } + switchToEditMode(); } else { GWTServiceLookup.getResourceGroupService().findGroupDefinitionsByCriteria(criteria, new AsyncCallback<PageList<GroupDefinition>>() { @@ -381,11 +325,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm } else { GroupDefinition existingGroupDefinition = result.get(0); setGroupDefinition(existingGroupDefinition); - if (hasEditPermission) { - switchToEditMode(); - } else { - switchToViewMode(); - } + switchToEditMode(); } } }); @@ -401,14 +341,22 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm @Override public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( - "Could not determine whether user had MANAGE_INVENTORY permission, defaulting to view-only mode", - caught); - lookupDetails(groupDefinitionId, false); + "Could not determine whether user had MANAGE_INVENTORY permission", caught); + handleAuthorizationFailure(); + } + + private void handleAuthorizationFailure() { + CoreGUI.getErrorHandler().handleError("You do not have permission to view group definitions"); + History.back(); }
@Override public void onSuccess(Set<Permission> result) { - lookupDetails(groupDefinitionId, result.contains(Permission.MANAGE_INVENTORY)); + if (result.contains(Permission.MANAGE_INVENTORY) == false) { + handleAuthorizationFailure(); + } else { + lookupDetails(groupDefinitionId); + } } });
commit 9fa4e9c1a1444e4716cfd32a12499295ab2d5a35 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 13:10:12 2010 -0400
refactoring for maintainability; fix alignment of elements
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java index 6878764..2aa22ce 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java @@ -22,11 +22,13 @@ import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.Hyperlink; +import com.smartgwt.client.types.Alignment; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.Img; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.HLayout; -import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.enterprise.gui.coregui.client.components.AboutModalWindow; @@ -36,16 +38,13 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** * @author Greg Hinkle + * @author Joseph Marques */ public class MenuBarView extends LocatableVLayout {
- private AboutModalWindow aboutModalWindow; - public static final String[] SECTIONS = { "Dashboard", "Inventory", "Reports", "Bundles", "Administration" };
- private String selected = "Dashboard"; - - private HTMLFlow linksPane; + private String currentlySelectedSection = "Dashboard";
public MenuBarView(String locatorId) { super(locatorId); @@ -54,97 +53,62 @@ public class MenuBarView extends LocatableVLayout { protected void onDraw() { super.onDraw();
- History.addValueChangeHandler(new ValueChangeHandler<String>() { - public void onValueChange(ValueChangeEvent<String> stringValueChangeEvent) { - String first = stringValueChangeEvent.getValue().split("/")[0]; - - if ("Resource".equals(first)) { - first = "Inventory"; - } - - selected = first; - linksPane.setContents(setupLinks()); - linksPane.markForRedraw(); - } - }); - ToolStrip topStrip = new ToolStrip(); topStrip.setHeight(34); topStrip.setWidth100(); topStrip.setBackgroundImage("header/header_bg.png"); topStrip.setMembersMargin(20);
- this.aboutModalWindow = new AboutModalWindow(); + topStrip.addMember(getLogoSection()); + topStrip.addMember(getLinksSection()); + topStrip.addMember(getActionsSection()); + + addMember(topStrip); + addMember(new SearchBarPane(this.extendLocatorId("Search"))); + + markForRedraw(); + } + + private Canvas getLogoSection() { + final AboutModalWindow aboutModalWindow = new AboutModalWindow(); Img logo = new Img("header/rhq_logo_28px.png", 80, 28); - logo.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { - public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) { - MenuBarView.this.aboutModalWindow.show(); + logo.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent event) { + aboutModalWindow.show(); } }); - topStrip.addMember(logo); + return logo; + }
- linksPane = new HTMLFlow(); + private Canvas getLinksSection() { + final HTMLFlow linksPane = new HTMLFlow(); linksPane.setContents(setupLinks());
- topStrip.addMember(linksPane); - - topStrip.addMember(new LayoutSpacer()); - - //HLayout helpLayout = new HLayout(); - // Label loggedInAs = new Label("Logged in as " + CoreGUI.getSessionSubject().getName()); - // loggedInAs.setWrap(false); - // loggedInAs.setValign(VerticalAlignment.CENTER); - // helpLayout.addMember(loggedInAs); - - topStrip.addMember(getHelpLinkSection()); - topStrip.addMember(SeleniumUtility.setHtmlId(new Hyperlink("Log Out", "LogOut"))); - // helpLayout.setLayoutAlign(VerticalAlignment.CENTER); - // topStrip.addMember(helpLayout); - - /* DynamicForm links = new DynamicForm(); - links.setNumCols(SECTIONS.length * 2); - links.setHeight100(); - - int i = 0; - FormItem[] linkItems = new FormItem[SECTIONS.length]; - for (String section : SECTIONS) { - LinkItem sectionLink = new LinkItem(); - sectionLink.setTitle(section); - sectionLink.setValue("#" + section); - sectionLink.setShowTitle(false); - - if (section.equals("Demo")) { - sectionLink.setCellStyle("TopSectionLinkSelected"); - // sectionLink.("header/header_bg_selected.png"); - } else { - sectionLink.setCellStyle("TopSectionLink"); - // widgetCanvas.setStyleName("TopSectionLink"); - } - linkItems[i++] = sectionLink; - } - links.setItems(linkItems); + History.addValueChangeHandler(new ValueChangeHandler<String>() { + public void onValueChange(ValueChangeEvent<String> stringValueChangeEvent) { + String first = stringValueChangeEvent.getValue().split("/")[0];
- topStrip.addMember(links); - */ - addMember(topStrip); - addMember(new SearchBarPane(this.extendLocatorId("Search"))); + if ("Resource".equals(first)) { + first = "Inventory"; + }
- markForRedraw(); + currentlySelectedSection = first; + linksPane.setContents(setupLinks()); + linksPane.markForRedraw(); + } + }); + return linksPane; }
private String setupLinks() { StringBuilder headerString = new StringBuilder( "<table style="height: 34px;" cellpadding="0" cellspacing="0"><tr>");
- boolean first = true; + headerString.append("<td style="width: 1px;"><img src="images/header/header_bg_line.png"/></td>"); for (String section : SECTIONS) { - if (first) { - headerString.append("<td style="width: 1px;"><img src="images/header/header_bg_line.png"/></td>"); - } - first = false;
String styleClass = "TopSectionLink"; - if (section.equals(selected)) { + if (section.equals(currentlySelectedSection)) { styleClass += "Selected"; }
@@ -162,13 +126,19 @@ public class MenuBarView extends LocatableVLayout { return headerString.toString(); }
- private Canvas getHelpLinkSection() { - HLayout helpLayout = new HLayout(); + private Canvas getActionsSection() { + HLayout layout = new HLayout(); + layout.setMargin(10); + layout.setAlign(Alignment.RIGHT); + LocatableImg helpImage = new LocatableImg("HelpImage", "[SKIN]/actions/help.png", 16, 16); Hyperlink helpLink = SeleniumUtility.setHtmlId(new Hyperlink("Help", "Help")); - helpLayout.addMember(helpImage); - helpLayout.addMember(helpLink); - return helpLayout; - } + Hyperlink logoutLink = SeleniumUtility.setHtmlId(new Hyperlink("Log Out", "LogOut"));
+ layout.addMember(helpImage); + layout.addMember(helpLink); + layout.addMember(logoutLink); + + return layout; + } }
commit bfbd77a21072e829969cdbf7a054997be06b74fe Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 11:29:28 2010 -0400
add icon next to help link in menu bar
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java index cd1b7d9..6878764 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java @@ -22,12 +22,15 @@ import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.Hyperlink; +import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.Img; +import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.enterprise.gui.coregui.client.components.AboutModalWindow; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableImg; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
@@ -92,7 +95,8 @@ public class MenuBarView extends LocatableVLayout { // loggedInAs.setWrap(false); // loggedInAs.setValign(VerticalAlignment.CENTER); // helpLayout.addMember(loggedInAs); - topStrip.addMember(SeleniumUtility.setHtmlId(new Hyperlink("Help", "Help"))); + + topStrip.addMember(getHelpLinkSection()); topStrip.addMember(SeleniumUtility.setHtmlId(new Hyperlink("Log Out", "LogOut"))); // helpLayout.setLayoutAlign(VerticalAlignment.CENTER); // topStrip.addMember(helpLayout); @@ -158,4 +162,13 @@ public class MenuBarView extends LocatableVLayout { return headerString.toString(); }
+ private Canvas getHelpLinkSection() { + HLayout helpLayout = new HLayout(); + LocatableImg helpImage = new LocatableImg("HelpImage", "[SKIN]/actions/help.png", 16, 16); + Hyperlink helpLink = SeleniumUtility.setHtmlId(new Hyperlink("Help", "Help")); + helpLayout.addMember(helpImage); + helpLayout.addMember(helpLink); + return helpLayout; + } + }
commit 1bb5479e42ed753091337fdf2a81ffe089a1a937 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 10:56:27 2010 -0400
cosmetic, reformatting
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 403456c..00a27f0 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 @@ -447,21 +447,24 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { * This is a nasty hack; but it's extremely reliable when running with other * js libraries on the same page at the same time as gwt. */ - public static native boolean detectIe6() /*-{ - if (typeof $doc.body.style.maxHeight != "undefined") - return(false); - else - return(true); - }-*/; - - public static native void forceIe6Hacks() /*-{ - $wnd.XMLHttpRequestBackup = $wnd.XMLHttpRequest; - $wnd.XMLHttpRequest = null; - }-*/; - - public static native void unforceIe6Hacks() /*-{ - $wnd.XMLHttpRequest = $wnd.XMLHttpRequestBackup; - $wnd.XMLHttpRequestBackup = null; - }-*/; + public static native boolean detectIe6() + /*-{ + if (typeof $doc.body.style.maxHeight != "undefined") + return(false); + else + return(true); + }-*/; + + public static native void forceIe6Hacks() + /*-{ + $wnd.XMLHttpRequestBackup = $wnd.XMLHttpRequest; + $wnd.XMLHttpRequest = null; + }-*/; + + public static native void unforceIe6Hacks() + /*-{ + $wnd.XMLHttpRequest = $wnd.XMLHttpRequestBackup; + $wnd.XMLHttpRequestBackup = null; + }-*/;
}
commit 6905ddc17545a6cb9e06230d476a81a2c379f8ca Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 00:35:24 2010 -0400
remove debugging statements from GroupDefinitionDataSource
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java index 32692b1..f4da478 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java @@ -109,7 +109,6 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
@Override protected void executeAdd(final DSRequest request, final DSResponse response) { - System.out.println("executeAdd"); JavaScriptObject data = request.getData(); final ListGridRecord record = new ListGridRecord(data); final GroupDefinition newGroupDefinition = copyValues(record); @@ -137,7 +136,6 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
@Override protected void executeUpdate(final DSRequest request, final DSResponse response) { - System.out.println("executeUpdate"); final ListGridRecord record = getEditedRecord(request); final GroupDefinition updatedGroupDefinition = copyValues(record); final String name = updatedGroupDefinition.getName(); @@ -161,10 +159,6 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { @Override public GroupDefinition copyValues(ListGridRecord from) { GroupDefinition groupDefinition = new GroupDefinition(); - String[] attributes = from.getAttributes(); - for (String nextAttribute : attributes) { - System.out.println("ListGridRecord attribute: " + nextAttribute); - } groupDefinition.setId(from.getAttributeAsInt("id")); groupDefinition.setName(from.getAttributeAsString("name")); groupDefinition.setDescription(from.getAttributeAsString("description"));
commit eda3ff13594fff0133daf8a61bc7afa40f2aa2f4 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 22 14:10:08 2010 -0400
resource tree bug fixes: 1) do not add autogroup nodes for singleton resource types, 2) key the Map that stores created autogroup nodes off the node IDs rather than the ResourceTypes
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java index c0752a1..91303ee 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tree/EnhancedTreeNode.java @@ -24,15 +24,12 @@ import com.smartgwt.client.widgets.tree.TreeNode; * @author Ian Springer */ public class EnhancedTreeNode extends TreeNode { - private static final String ID_FIELD = "id"; - private static final String PARENT_ID_FIELD = "parentId"; - public String getID() { - return getAttribute(ID_FIELD); + return getAttribute(Attributes.ID); }
public String getParentID() { - return getAttribute(PARENT_ID_FIELD); + return getAttribute(Attributes.PARENT_ID); }
@Override @@ -50,4 +47,14 @@ public class EnhancedTreeNode extends TreeNode { buffer.append("]"); return buffer.toString(); } + + public class Attributes { + public static final String ID = "id"; + public static final String PARENT_ID = "parentId"; + public static final String NAME = "name"; + public static final String DESCRIPTION = "description"; + + private Attributes() { + } + } } 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 bc9c956..9b39e8a 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 @@ -201,8 +201,8 @@ public class ResourceTreeDatasource extends DataSource { List<TreeNode> updatedNodes = new ArrayList<TreeNode>(); // Maps category node IDs to the corresponding category nodes. Map<String, CategoryTreeNode> categories = new HashMap<String, CategoryTreeNode>(); - // Maps Resource types to the corresponding type nodes. - Map<ResourceType, TypeTreeNode> types = new HashMap<ResourceType, TypeTreeNode>(); + // Maps type node IDs to the corresponding type nodes. + Map<String, TypeTreeNode> types = new HashMap<String, TypeTreeNode>();
for (ResourceTreeNode node : nodes) { updatedNodes.add(node); @@ -210,7 +210,8 @@ public class ResourceTreeDatasource extends DataSource { Resource resource = node.getResource(); ResourceType type = resource.getResourceType(); if (type.getCategory() != ResourceCategory.PLATFORM) { - if (!types.containsKey(type)) { + String typeNodeId = TypeTreeNode.idOf(resource); + if (!types.containsKey(typeNodeId)) { Resource parentResource = resource.getParentResource(); ResourceSubCategory category = type.getSubCategory(); if (category != null) { @@ -225,9 +226,11 @@ public class ResourceTreeDatasource extends DataSource { } while ((category = category.getParentSubCategory()) != null); }
- TypeTreeNode typeNode = new TypeTreeNode(resource); - updatedNodes.add(typeNode); - types.put(type, typeNode); + if (!type.isSingleton()) { + TypeTreeNode typeNode = new TypeTreeNode(resource); + updatedNodes.add(typeNode); + types.put(typeNodeId, typeNode); + } } } } @@ -239,19 +242,19 @@ public class ResourceTreeDatasource extends DataSource { public CategoryTreeNode(ResourceSubCategory category, Resource parentResource) { String id = idOf(category, parentResource); setID(id); - setAttribute("id", id); + setAttribute(Attributes.ID, id);
ResourceSubCategory parentCategory = category.getParentSubCategory(); String parentId = (parentCategory != null) ? CategoryTreeNode.idOf(parentCategory, parentResource) : ResourceTreeNode.idOf(parentResource); setParentID(parentId); - setAttribute("parentId", parentId); + setAttribute(Attributes.PARENT_ID, parentId);
// Note, subcategory names are typically already plural, so there's no need to pluralize them. String name = category.getDisplayName(); setName(name); - setAttribute("name", name); + setAttribute(Attributes.NAME, name); }
public static String idOf(ResourceSubCategory category, Resource parentResource) { @@ -266,18 +269,18 @@ public class ResourceTreeDatasource extends DataSource { private TypeTreeNode(Resource resource) { String id = idOf(resource); setID(id); - setAttribute("id", id); + setAttribute(Attributes.ID, id);
String parentId = parentIdOf(resource); setParentID(parentId); - setAttribute("parentId", parentId); + setAttribute(Attributes.PARENT_ID, parentId);
// setAttribute("parentKey", parentId);
ResourceType type = resource.getResourceType(); String name = StringUtility.pluralize(type.getName()); setName(name); - setAttribute("name", name); + setAttribute(Attributes.NAME, name); }
public static String idOf(Resource resource) { @@ -304,7 +307,7 @@ public class ResourceTreeDatasource extends DataSource {
String id = idOf(resource); setID(id); - setAttribute("id", id); + setAttribute(Attributes.ID, id);
Resource parentResource = resource.getParentResource(); String parentId; @@ -317,14 +320,14 @@ public class ResourceTreeDatasource extends DataSource { parentId = null; } setParentID(parentId); - setAttribute("parentId", parentId); + setAttribute(Attributes.PARENT_ID, parentId);
// System.out.println(id + " / " + parentId); // setAttribute("parentKey", resource.getParentResource() == null ? 0 : (resource.getParentResource().getId() + resource.getResourceType().getName()));
setName(resource.getName()); - setAttribute("name", resource.getName()); - setAttribute("description", resource.getDescription()); + setAttribute(Attributes.NAME, resource.getName()); + setAttribute(Attributes.DESCRIPTION, resource.getDescription()); ResourceAvailability currentAvail = resource.getCurrentAvailability(); setAttribute( "currentAvailability",
commit bd4c18a4954c6a8c5351d025dc97c97c8f025c64 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 22 12:30:21 2010 -0400
trivial l&f changes
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java index e6b6cad..86d816b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java @@ -157,21 +157,22 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements disableWhenFiredSelection.setValueMap(yesNo); disableWhenFiredSelection.setDefaultValue("no"); disableWhenFiredSelection.setWrapTitle(false); + disableWhenFiredSelection.setWidth(300); disableWhenFiredSelection - .setTooltip("If this setting is turned on, then this alert will be disabled after it fires. When this occurs, the only way for the alert to be able to fire again is if a user manually re-enables the alert, or if a recovery alert triggers and automatically re-enables this alert. If this alert is a recovery alert itself, it cannot be disabled after it fires so it can always recover its target alert."); + .setTooltip("Indicates if this alert will be disabled after it fires. Once disabled, the alert can be manually re-enabled or a recovery alert can be set up to automatically re-enable it. If this alert is a recovery alert itself, this setting cannot be turned on."); disableWhenFiredStatic = new StaticTextItem("disableWhenFiredStatic", "Disable When Fired"); disableWhenFiredStatic.setWrapTitle(false);
recoverAlertSelection = new SelectItem("recoveryAlert", "Recover Alert"); recoverAlertSelection.setDefaultValue("0"); recoverAlertSelection.setWrapTitle(false); - recoverAlertSelection.setRedrawOnChange(true); recoverAlertSelection - .setTooltip("If this alert is a recovery alert, this option lets you select the target alert that will be re-enabled after this alert triggers. If this is not a recovery alert, do not select an alert here."); + .setTooltip("The target alert that will be recovered (i.e. re-enabled) after this alert triggers. Do not select an alert here if you are not defining a recovery alert.");
recoverAlertStatic = new StaticTextItem("recoveryAlertStatic", "Recover Alert"); recoverAlertStatic.setDefaultValue(getNoRecoveryMenuItemTitle()); recoverAlertStatic.setWrapTitle(false); + recoverAlertStatic.setWidth(300);
// if a recovery alert is set, then this alert definition must not disable itself when fired // because it will be needed to recover its recovery alert the next time it fires. disabling is only @@ -255,7 +256,7 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements } }
- recoverAlertSelection.redraw(); + markForRedraw(); }
private void refreshDisableWhenFiredSelection(String recoveryAlertDefId) { @@ -265,7 +266,8 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements disableWhenFiredSelection.setValue("no"); disableWhenFiredSelection.setDisabled(true); } - disableWhenFiredSelection.redraw(); + + markForRedraw(); }
private String getNoRecoveryMenuItemTitle() {
commit ca19ca4e70a06d02fd701e2aa57a4c7090f4e2f8 Author: Simeon Pinder spinder@redhat.com Date: Wed Sep 22 12:24:02 2010 -0400
initial rss portet badge work.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java index 457b75d..caffe54 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java @@ -27,6 +27,7 @@ import com.smartgwt.client.types.HeaderControls; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HeaderControl; +import com.smartgwt.client.widgets.HeaderControl.HeaderIcon; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.events.CloseClickHandler; @@ -46,6 +47,7 @@ public class PortletWindow extends LocatableWindow {
private DashboardView dashboardView; private DashboardPortlet dashboardPortlet; + private static String RSS = "Rss";
private Portlet view;
@@ -58,6 +60,8 @@ public class PortletWindow extends LocatableWindow {
private ClickHandler helpHandlerDelegate = NO_OP_HANDLER;
+ private ClickHandler rssHandlerDelegate = NO_OP_HANDLER; + private ClickHandler settingsHandler = new ClickHandler() { public void onClick(ClickEvent clickEvent) { settingsHandlerDelegate.onClick(clickEvent); @@ -70,6 +74,12 @@ public class PortletWindow extends LocatableWindow { } };
+ private ClickHandler rssHandler = new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + rssHandlerDelegate.onClick(clickEvent); + } + }; + private ClickHandler refreshHandler = new ClickHandler() { public void onClick(ClickEvent clickEvent) { if (PortletWindow.this.view instanceof Table) { @@ -91,6 +101,11 @@ public class PortletWindow extends LocatableWindow { // setShowHeader(false); // setShowEdges(false);
+ //configure HeaderControls with toolTips + LocatableHeaderControl RssHeader = new LocatableHeaderControl(extendLocatorId(RSS), new HeaderIcon( + "[SKIN]/headerIcons/clipboard.png"), rssHandler); + RssHeader.setTooltip(RSS); + // customize the appearance and order of the controls in the window header setHeaderControls(HeaderControls.MINIMIZE_BUTTON, HeaderControls.HEADER_LABEL, new LocatableHeaderControl( extendLocatorId("Refresh"), HeaderControl.REFRESH, refreshHandler), new LocatableHeaderControl(
commit 9ad4b66bb53ddcab3c3b084ce02620e8eb99b027 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 22 09:46:51 2010 -0400
trivial change to label when no recover alert set
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java index 0e9fe8c..e6b6cad 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java @@ -271,7 +271,7 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements private String getNoRecoveryMenuItemTitle() { StringBuilder str = new StringBuilder(); str.append("-- "); - str.append("No Recovery"); + str.append("None"); str.append(" --"); return str.toString(); }
commit ff9f820ba31283c57228c6a3357bc31f3f69b6d2 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 22 08:15:43 2010 -0400
add tooltip help
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java index a929a84..0e9fe8c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java @@ -157,6 +157,8 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements disableWhenFiredSelection.setValueMap(yesNo); disableWhenFiredSelection.setDefaultValue("no"); disableWhenFiredSelection.setWrapTitle(false); + disableWhenFiredSelection + .setTooltip("If this setting is turned on, then this alert will be disabled after it fires. When this occurs, the only way for the alert to be able to fire again is if a user manually re-enables the alert, or if a recovery alert triggers and automatically re-enables this alert. If this alert is a recovery alert itself, it cannot be disabled after it fires so it can always recover its target alert."); disableWhenFiredStatic = new StaticTextItem("disableWhenFiredStatic", "Disable When Fired"); disableWhenFiredStatic.setWrapTitle(false);
@@ -164,6 +166,8 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements recoverAlertSelection.setDefaultValue("0"); recoverAlertSelection.setWrapTitle(false); recoverAlertSelection.setRedrawOnChange(true); + recoverAlertSelection + .setTooltip("If this alert is a recovery alert, this option lets you select the target alert that will be re-enabled after this alert triggers. If this is not a recovery alert, do not select an alert here.");
recoverAlertStatic = new StaticTextItem("recoveryAlertStatic", "Recover Alert"); recoverAlertStatic.setDefaultValue(getNoRecoveryMenuItemTitle());
commit c40e42e59d96772ea2b953a47754db8f865d0cb9 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 22 00:36:38 2010 -0400
fix bug in usage of resource tree node IDs
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 1b7e5b5..bc9c956 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 @@ -49,6 +49,7 @@ import org.rhq.enterprise.gui.coregui.client.components.tree.EnhancedTreeNode; 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.StringUtility;
/** * This doesn't extend RPCDataSource because it is tree-oriented and behaves differently than normal list data sources @@ -127,13 +128,13 @@ public class ResourceTreeDatasource extends DataSource { public void executeFetch(final String requestId, final DSRequest request, final DSResponse response) { final long start = System.currentTimeMillis();
- String p = request.getCriteria().getAttribute("parentId"); + String parentResourceId = request.getCriteria().getAttribute("parentId"); // System.out.println("All attributes: " + Arrays.toString(request.getCriteria().getAttributes()));
ResourceCriteria criteria = new ResourceCriteria();
- if (p == null) { - System.out.println("DataSourceTree: Loading initial data"); + if (parentResourceId == null) { + System.out.println("ResourceTreeDatasource: Loading initial data...");
// criteria.addFilterId(rootId);
@@ -142,9 +143,9 @@ public class ResourceTreeDatasource extends DataSource { return;
} else { - System.out.println("DataSourceTree: Loading " + p); + System.out.println("ResourceTreeDatasource: Loading Resource [" + parentResourceId + "]...");
- criteria.addFilterParentResourceId(Integer.parseInt(p)); + criteria.addFilterParentResourceId(Integer.parseInt(parentResourceId)); }
// The server is already eager fetch resource type @@ -186,14 +187,14 @@ public class ResourceTreeDatasource extends DataSource { * @return */ public static TreeNode[] buildNodes(List<Resource> resources) { - ResourceTreeNode[] records = new ResourceTreeNode[resources.size()]; - for (int x = 0; x < resources.size(); x++) { - Resource resource = resources.get(x); - ResourceTreeNode record = new ResourceTreeNode(resource); - records[x] = record; + ResourceTreeNode[] nodes = new ResourceTreeNode[resources.size()]; + for (int i = 0; i < resources.size(); i++) { + Resource resource = resources.get(i); + ResourceTreeNode node = new ResourceTreeNode(resource); + nodes[i] = node; }
- return introduceTypeAndCategoryNodes(records); + return introduceTypeAndCategoryNodes(nodes); }
private static TreeNode[] introduceTypeAndCategoryNodes(ResourceTreeNode[] nodes) { @@ -274,7 +275,7 @@ public class ResourceTreeDatasource extends DataSource { // setAttribute("parentKey", parentId);
ResourceType type = resource.getResourceType(); - String name = pluralize(type.getName()); + String name = StringUtility.pluralize(type.getName()); setName(name); setAttribute("name", name); } @@ -335,7 +336,7 @@ public class ResourceTreeDatasource extends DataSource { }
public Resource getResource() { - return resource; + return this.resource; }
public static String idOf(Resource resource) { @@ -343,19 +344,7 @@ public class ResourceTreeDatasource extends DataSource { }
public static String idOf(int resourceId) { - return "resource" + resourceId; + return String.valueOf(resourceId); } } - - private static String pluralize(String singularNoun) { - // TODO: Make this smarter. - String pluralNoun; - if (singularNoun.endsWith("y") && !singularNoun.endsWith("ay") && !singularNoun.endsWith("ey") && - !singularNoun.endsWith("oy")) { - pluralNoun = singularNoun.substring(0, singularNoun.length() - 1) + "ies"; - } else { - pluralNoun = singularNoun + "s"; - } - return pluralNoun; - } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java new file mode 100644 index 0000000..00a2cf1 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/StringUtility.java @@ -0,0 +1,41 @@ +/* + * 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.util; + +/** + * A collection of utility methods for working with Strings. + * + * @author Ian Springer + */ +public class StringUtility { + public static String pluralize(String singularNoun) { + String pluralNoun; + if (singularNoun.endsWith("y") && !singularNoun.endsWith("ay") && !singularNoun.endsWith("ey") && + !singularNoun.endsWith("oy")) { + pluralNoun = singularNoun.substring(0, singularNoun.length() - 1) + "ies"; + } else { + pluralNoun = singularNoun + "s"; + } + return pluralNoun; + } + + private StringUtility() { + } +}
commit 2791d339c9959921882881afe23764961e0d8135 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 22 00:33:39 2010 -0400
enforce consistency of GroupDefinitions by controlling the merge explicitly
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/definition/GroupDefinitionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/definition/GroupDefinitionManagerBean.java index 905688b..ca04351 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/definition/GroupDefinitionManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/definition/GroupDefinitionManagerBean.java @@ -210,11 +210,15 @@ public class GroupDefinitionManagerBean implements GroupDefinitionManagerLocal { } }
- try { - return entityManager.merge(groupDefinition); - } catch (Exception e) { - throw new GroupDefinitionUpdateException(e); - } + // do not call entityManager.merge, it could overwrite managed fields + // merge fields explicitly to control precisely which fields get updated + attachedGroupDefinition.setName(groupDefinition.getName()); + attachedGroupDefinition.setDescription(groupDefinition.getDescription()); + attachedGroupDefinition.setRecursive(groupDefinition.isRecursive()); + attachedGroupDefinition.setExpression(groupDefinition.getExpression()); + attachedGroupDefinition.setRecalculationInterval(groupDefinition.getRecalculationInterval()); + + return attachedGroupDefinition; }
// return boolean indicating whether the name of this group definition is changing
commit ba09ae501b545b2a6452290584e7d5a9ea81b6ff Author: Joseph Marques joseph@redhat.com Date: Tue Sep 21 23:31:14 2010 -0400
fix master/details impl to allow detailsView navigation from /0 to /<id>
basically, since the detailsView is already showing when navigating from /0 to /<id>, the animationHide event was being suppressed, which meant that the subsequent callback wasn't invoked. this left the original detailsView canvas attached to the detailsHolder, instead of refreshing the holder with the latest view returned from the renderView method.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java index 0e3a899..c8ab12b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java @@ -187,7 +187,6 @@ public abstract class TableSection extends Table implements BookmarkableView {
@Override public void renderView(ViewPath viewPath) { - basePath = viewPath.getPathToCurrent();
if (!viewPath.isEnd()) { @@ -224,20 +223,42 @@ public abstract class TableSection extends Table implements BookmarkableView { protected void switchToDetailsView() { Canvas contents = getTableContents(); if (contents != null) { - contents.animateHide(AnimationEffect.WIPE, new AnimationCallback() { - @Override - public void execute(boolean b) { - detailsView.setWidth100(); - detailsView.setHeight100(); - - detailsHolder.addMember(new BackButton(extendLocatorId("BackButton"), "Back to List", basePath)); - detailsHolder.addMember(detailsView); - detailsHolder.animateShow(AnimationEffect.WIPE); + if (contents.isVisible()) { + contents.animateHide(AnimationEffect.WIPE, new AnimationCallback() { + @Override + public void execute(boolean b) { + buildDetailsView(); + } + }); + } else { + /* + * if the programmer chooses to go directly from the detailView in create-mode to the + * detailsView in edit-mode, the content canvas will already be hidden, which means the + * animateHide would be a no-op (the event won't fire). this causes the detailsHolder + * to keep a reference to the previous detailsView (the one in create-mode) instead of the + * newly returned reference from getDetailsView(int) that was called when the renderView + * methods were called hierarchically down to render the new detailsView in edit-mode. + * therefore, we need to explicitly destroy what's already there (presumably the detailsView + * in create-mode), and then rebuild it (presumably the detailsView in edit-mode). + */ + for (Canvas child : detailsHolder.getMembers()) { + child.destroy(); } - }); + + buildDetailsView(); + } } }
+ private void buildDetailsView() { + detailsView.setWidth100(); + detailsView.setHeight100(); + + detailsHolder.addMember(new BackButton(extendLocatorId("BackButton"), "Back to List", basePath)); + detailsHolder.addMember(detailsView); + detailsHolder.animateShow(AnimationEffect.WIPE); + } + /** * Switches to viewing the table, hiding the details canvas. */
commit 2b9ec8f1ab6be2fb2a9437b51f89eb19219c849e Author: Joseph Marques joseph@redhat.com Date: Tue Sep 21 23:27:03 2010 -0400
remove debugging statements
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index 9b17abf..c8293c7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -141,8 +141,7 @@ public class GroupDefinitionListView extends TableSection { @Override public Canvas getDetailsView(int id) { final SingleGroupDefinitionView singleGroupDefinitionView = new SingleGroupDefinitionView(this - .extendLocatorId("Empty")); + .extendLocatorId("Details")); return singleGroupDefinitionView; } - } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index d6ac260..dde421c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -31,6 +31,8 @@ import com.smartgwt.client.data.Record; import com.smartgwt.client.types.DSOperationType; 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.form.fields.CheckboxItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.SpinnerItem; @@ -65,7 +67,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm private int groupDefinitionId; private GroupDefinition groupDefinition; private String basePath; - private ViewId viewId;
// editable form @@ -85,29 +86,18 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm private StaticTextItem expressionStatic; private StaticTextItem recalculationIntervalStatic;
- private GroupDefinitionDataSource dataSource; - public SingleGroupDefinitionView(String locatorId) { - this(locatorId, null); - } - - public SingleGroupDefinitionView(String locatorId, GroupDefinition groupDefinition) { super(locatorId);
- this.dataSource = GroupDefinitionDataSource.getInstance(); - setPadding(10); setOverflow(Overflow.VISIBLE); setWidth(5);
buildForm(); - - this.groupDefinition = groupDefinition; }
public void setGroupDefinition(final GroupDefinition groupDefinition) { this.groupDefinition = groupDefinition; - System.out.println("setGroupDefinition(" + groupDefinition + ")");
// form setup id.setValue(groupDefinition.getId()); @@ -131,50 +121,39 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("GroupDefinitionForm")); form.setFields(id, idStatic, name, nameStatic, description, descriptionStatic, expression, expressionStatic, recursive, recursiveStatic, recalculationInterval, recalculationIntervalStatic); - form.setDataSource(dataSource); + form.setDataSource(GroupDefinitionDataSource.getInstance()); form.setHiliteRequiredFields(true); form.setRequiredTitleSuffix(" <span style="color: red;">* </span>:"); - final DSOperationType operationType; if (groupDefinition.getId() == 0) { - System.out.println("setting form operation: ADD"); form.setSaveOperationType(DSOperationType.ADD); - operationType = DSOperationType.ADD; } else { - System.out.println("setting form operation: UPDATE"); form.setSaveOperationType(DSOperationType.UPDATE); - operationType = DSOperationType.UPDATE; } - System.out.println("form operation default is " + form.getSaveOperationType());
final DynaGroupChildrenView dynaGroupChildrenView = new DynaGroupChildrenView(extendLocatorId("DynaGroups"), groupDefinitionId);
// button setup IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); - saveButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { - public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { - System.out.println("cached operaton type is " + operationType); - form.setSaveOperationType(operationType); - System.out.println("form operation before validation is " + form.getSaveOperationType()); + //saveButton.addClickHandler(new SaveOrUpdateClickHandler(form, operationType, dynaGroupChildrenView)); + saveButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { if (form.validate()) { - System.out.println("form operation after validation is " + form.getSaveOperationType()); form.saveData(new DSCallback() { @Override public void execute(DSResponse response, Object rawData, DSRequest request) { - if (groupDefinition.getId() == 0) { - System.out.println("just created new group def"); + if (form.isNewRecord()) { Record[] results = response.getData(); if (results.length != 1) { CoreGUI.getErrorHandler().handleError( "Error: " + results.length + " created instead of one"); } else { Record newRecord = results[0]; - GroupDefinition newGroupDefinition = dataSource + GroupDefinition newGroupDefinition = GroupDefinitionDataSource.getInstance() .copyValues((ListGridRecord) newRecord); History.newItem(basePath + "/" + newGroupDefinition.getId()); } } else { - System.out.println("just edited existing group def"); dynaGroupChildrenView.refresh(); } } @@ -185,8 +164,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
IButton recalculateButton = new LocatableIButton(this.extendLocatorId("Recalculate"), "Save & Recalculate"); recalculateButton.setWidth(150); - recalculateButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { - public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { + recalculateButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { if (form.validate()) { form.saveData(new DSCallback() { @Override @@ -214,8 +193,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm });
IButton resetButton = new LocatableIButton(this.extendLocatorId("Reset"), "Reset"); - resetButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { - public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { + resetButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { form.reset(); } }); @@ -239,6 +218,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm super(locatorId, "DynaGroup Children", new Criteria("groupDefinitionId", String.valueOf(groupDefinition .getId()))); setDataSource(ResourceGroupsDataSource.getInstance()); + setMinHeight(250); } }
@@ -285,7 +265,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
private void buildForm() { id = new TextItem("id", "ID"); - //id.setVisible(false); + id.setVisible(false); idStatic = new StaticTextItem("idStatic", "ID"); idStatic.setVisible(false);
commit be2e9d2f22804f857e660692c138337f14bfef66 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 21 20:40:44 2010 -0400
fix so subcategory nodes for subcategories that have parent subcategories and rendered as child nodes of the parent subcategory nodes
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 5edd16d..38dc487 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 @@ -166,8 +166,9 @@ public class NewResourceTreeView extends LocatableVLayout { }
private void showContextMenu(final ResourceTreeDatasource.ResourceTreeNode node) { + ResourceType type = node.getResource().getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( - node.getResourceType().getId(), + type.getId(), EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.subCategory, ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, 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 2516ac5..1b7e5b5 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 @@ -188,8 +188,8 @@ public class ResourceTreeDatasource extends DataSource { public static TreeNode[] buildNodes(List<Resource> resources) { ResourceTreeNode[] records = new ResourceTreeNode[resources.size()]; for (int x = 0; x < resources.size(); x++) { - Resource res = resources.get(x); - ResourceTreeNode record = new ResourceTreeNode(res); + Resource resource = resources.get(x); + ResourceTreeNode record = new ResourceTreeNode(resource); records[x] = record; }
@@ -198,42 +198,33 @@ public class ResourceTreeDatasource extends DataSource {
private static TreeNode[] introduceTypeAndCategoryNodes(ResourceTreeNode[] nodes) { List<TreeNode> updatedNodes = new ArrayList<TreeNode>(); - Map<Integer, CategoryTreeNode> categories = new HashMap<Integer, CategoryTreeNode>(); + // Maps category node IDs to the corresponding category nodes. + Map<String, CategoryTreeNode> categories = new HashMap<String, CategoryTreeNode>(); + // Maps Resource types to the corresponding type nodes. Map<ResourceType, TypeTreeNode> types = new HashMap<ResourceType, TypeTreeNode>();
for (ResourceTreeNode node : nodes) { updatedNodes.add(node);
- ResourceType type = node.getResourceType(); + Resource resource = node.getResource(); + ResourceType type = resource.getResourceType(); if (type.getCategory() != ResourceCategory.PLATFORM) { if (!types.containsKey(type)) { - - String parentResourceId = String.valueOf(node.getResource().getParentResource().getId()); - - CategoryTreeNode categoryNode = null; - if (type.getSubCategory() != null) { - ResourceSubCategory category = type.getSubCategory(); - if (category.getName() != null) { - categoryNode = categories.get(category.getId()); + Resource parentResource = resource.getParentResource(); + ResourceSubCategory category = type.getSubCategory(); + if (category != null) { + do { + String categoryNodeId = CategoryTreeNode.idOf(category, parentResource); + CategoryTreeNode categoryNode = categories.get(categoryNodeId); if (categoryNode == null) { - // TODO (ips): Handle connecting child subcat nodes to their parent subcats. - /*ResourceSubCategory parentCategory = category.getParentSubCategory(); - while (parentCategory != null) { - Resource parentType = parentCategory.findParentResourceType(); - if (parentCategory.findTaggedResourceTypes().isEmpty()) { - CategoryTreeNode parentCategoryNode = - new CategoryTreeNode(parentResourceId, parentCategory); - } - }*/ - categoryNode = new CategoryTreeNode(parentResourceId, category); - categories.put(category.getId(), categoryNode); + categoryNode = new CategoryTreeNode(category, parentResource); + categories.put(categoryNode.getID(), categoryNode); updatedNodes.add(categoryNode); } - } + } while ((category = category.getParentSubCategory()) != null); }
- String parentId = (categoryNode != null) ? categoryNode.getID() : parentResourceId; - TypeTreeNode typeNode = new TypeTreeNode(parentId, parentResourceId, type); + TypeTreeNode typeNode = new TypeTreeNode(resource); updatedNodes.add(typeNode); types.put(type, typeNode); } @@ -243,78 +234,65 @@ public class ResourceTreeDatasource extends DataSource { return updatedNodes.toArray(new TreeNode[updatedNodes.size()]); }
- private static boolean sameTypes(ResourceTreeNode[] nodes) { - ResourceType first = nodes[0].getResourceType(); - for (ResourceTreeNode node : nodes) { - if (!first.equals(node)) { - return false; - } - } - return true; - } - public static class CategoryTreeNode extends EnhancedTreeNode { - public CategoryTreeNode(String parentResourceId, ResourceSubCategory category) { - String id = parentResourceId + "__" + fixId(category.getName()); + public CategoryTreeNode(ResourceSubCategory category, Resource parentResource) { + String id = idOf(category, parentResource); setID(id); setAttribute("id", id);
- setParentID(parentResourceId); - setAttribute("parentId", parentResourceId); + ResourceSubCategory parentCategory = category.getParentSubCategory(); + String parentId = (parentCategory != null) ? + CategoryTreeNode.idOf(parentCategory, parentResource) : + ResourceTreeNode.idOf(parentResource); + setParentID(parentId); + setAttribute("parentId", parentId);
// Note, subcategory names are typically already plural, so there's no need to pluralize them. String name = category.getDisplayName(); setName(name); setAttribute("name", name); } + + public static String idOf(ResourceSubCategory category, Resource parentResource) { + return "subcat" + category.getId() + "_" + parentResource.getId(); + } }
+ /** + * The Resource type folder node for an autogroup. + */ public static class TypeTreeNode extends EnhancedTreeNode { - private TypeTreeNode(String parentId, String parentResourceId, ResourceType type) { - String id = parentResourceId + "_" + type.getId(); + private TypeTreeNode(Resource resource) { + String id = idOf(resource); setID(id); setAttribute("id", id);
- if (parentId == null) { - try { - throw new IllegalStateException("**************** WARNING: parent ID is null for type " + type); - } catch (IllegalStateException e) { - e.printStackTrace(); - } - } + String parentId = parentIdOf(resource); setParentID(parentId); setAttribute("parentId", parentId);
// setAttribute("parentKey", parentId);
+ ResourceType type = resource.getResourceType(); String name = pluralize(type.getName()); setName(name); setAttribute("name", name); }
- @Override - public void setParentID(String parentID) { - if (parentID == null) { - try { - throw new IllegalStateException("**************** WARNING: setting parent ID to null for type " + getName()); - } catch (IllegalStateException e) { - e.printStackTrace(); - } - } - super.setParentID(parentID); + public static String idOf(Resource resource) { + Resource parentResource = resource.getParentResource(); + return (parentResource != null) ? "type" + resource.getResourceType().getId() + "_" + + parentResource.getId() : null; }
- @Override - public void setAttribute(String property, String value) { - if (property.equals("parentId") && value == null) { - try { - throw new IllegalStateException("**************** WARNING: setting parent ID to null for type " + getName()); - } catch (IllegalStateException e) { - e.printStackTrace(); - } - } - super.setAttribute(property, value); - } + public static String parentIdOf(Resource resource) { + ResourceType type = resource.getResourceType(); + ResourceSubCategory parentCategory = type.getSubCategory(); + String parentId = (parentCategory != null) ? + CategoryTreeNode.idOf(parentCategory, resource.getParentResource()) : + ResourceTreeNode.idOf(resource.getParentResource()); + return parentId; + } }
public static class ResourceTreeNode extends EnhancedTreeNode { @@ -323,12 +301,20 @@ public class ResourceTreeDatasource extends DataSource { private ResourceTreeNode(Resource resource) { this.resource = resource;
- String id = String.valueOf(resource.getId()); + String id = idOf(resource); setID(id); setAttribute("id", id);
- String parentId = (resource.getParentResource() != null) ? - (resource.getParentResource().getId() + "_" + resource.getResourceType().getId()) : null; + Resource parentResource = resource.getParentResource(); + String parentId; + if (parentResource != null) { + parentId = resource.getResourceType().isSingleton() ? + TypeTreeNode.parentIdOf(resource) : + TypeTreeNode.idOf(resource); + } + else { + parentId = null; + } setParentID(parentId); setAttribute("parentId", parentId);
@@ -352,13 +338,13 @@ public class ResourceTreeDatasource extends DataSource { return resource; }
- public ResourceType getResourceType() { - return resource.getResourceType(); + public static String idOf(Resource resource) { + return idOf(resource.getId()); } - }
- private static String fixId(String id) { - return id.replace(' ', '_'); + public static String idOf(int resourceId) { + return "resource" + resourceId; + } }
private static String pluralize(String singularNoun) { 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 02afc80..418a334 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 @@ -172,7 +172,7 @@ public class ResourceTreeView extends LocatableVLayout {
private void updateBreadcrumbs() { - TreeNode selectedNode = treeGrid.getTree().findById(String.valueOf(selectedResourceId)); + TreeNode selectedNode = treeGrid.getTree().findById(ResourceTreeDatasource.ResourceTreeNode.idOf(selectedResourceId)); // System.out.println("Trying to preopen: " + selectedNode); if (selectedNode != null) { TreeNode[] parents = treeGrid.getTree().getParents(selectedNode); @@ -204,8 +204,9 @@ public class ResourceTreeView extends LocatableVLayout { }
private void showContextMenu(final ResourceTreeDatasource.ResourceTreeNode node) { + ResourceType type = node.getResource().getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( - node.getResourceType().getId(), + type.getId(), EnumSet.of(ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.subCategory, ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, @@ -433,7 +434,7 @@ public class ResourceTreeView extends LocatableVLayout { Resource getResource(int resourceId) { if (this.treeGrid != null && this.treeGrid.getTree() != null) { ResourceTreeDatasource.ResourceTreeNode treeNode = (ResourceTreeDatasource.ResourceTreeNode) this.treeGrid - .getTree().findById(String.valueOf(resourceId)); + .getTree().findById(ResourceTreeDatasource.ResourceTreeNode.idOf(resourceId)); if (treeNode != null) { return treeNode.getResource(); } @@ -449,8 +450,9 @@ public class ResourceTreeView extends LocatableVLayout { this.selectedResourceId = selectedResourceId;
TreeNode node; + final String resourceNodeId = ResourceTreeDatasource.ResourceTreeNode.idOf(selectedResourceId); if (treeGrid != null && treeGrid.getTree() != null - && (node = treeGrid.getTree().findById(String.valueOf(selectedResourceId))) != null) { + && (node = treeGrid.getTree().findById(resourceNodeId)) != null) {
// This is the case where the tree was previously loaded and we get fired to look at a different // node in the same tree and just have to switch the selection @@ -459,7 +461,7 @@ public class ResourceTreeView extends LocatableVLayout { treeGrid.getTree().openFolders(parents); treeGrid.getTree().openFolder(node);
- if (!treeGrid.getSelectedRecord().equals(node)) { + if (!node.equals(treeGrid.getSelectedRecord())) { treeGrid.deselectAllRecords(); treeGrid.selectRecord(node); } @@ -507,7 +509,8 @@ public class ResourceTreeView extends LocatableVLayout {
TreeUtility.printTree(treeGrid.getTree());
- TreeNode selectedNode = treeGrid.getTree().findById(String.valueOf(selectedResourceId)); + TreeNode selectedNode = + treeGrid.getTree().findById(resourceNodeId); // System.out.println("Trying to preopen: " + selectedNode); if (selectedNode != null) { // System.out.println("Preopen node!!!"); @@ -541,8 +544,7 @@ public class ResourceTreeView extends LocatableVLayout {
treeGrid.getTree().linkNodes(ResourceTreeDatasource.buildNodes(result));
- TreeNode selectedNode = treeGrid.getTree().findById( - String.valueOf(selectedResourceId)); + TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); if (selectedNode != null) { treeGrid.deselectAllRecords(); treeGrid.selectRecord(selectedNode); @@ -564,7 +566,7 @@ public class ResourceTreeView extends LocatableVLayout {
} else { CoreGUI.getMessageCenter().notify( - new Message("Failed to select resource [" + selectedResourceId + new Message("Failed to select Resource [" + selectedResourceId + "] in tree.", Message.Severity.Warning)); }
@@ -573,7 +575,7 @@ public class ResourceTreeView extends LocatableVLayout {
}
- TreeNode selectedNode = treeGrid.getTree().findById(String.valueOf(selectedResourceId)); + TreeNode selectedNode = treeGrid.getTree().findById(resourceNodeId); // System.out.println("Trying to preopen: " + selectedNode); if (selectedNode != null) { TreeNode[] parents = treeGrid.getTree().getParents(selectedNode);
commit 43ce65db4af85551e98c636db80f113cb7be2d98 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 21 18:30:53 2010 -0400
Allow Resource.explicitGroups to be passed from server to CoreGUI.
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 25b19b0..66a25be 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 @@ -86,7 +86,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re // "resourceConfigurationUpdates \n" + // "pluginConfigurationUpdates \n" + // "implicitGroups \n" + - // "explicitGroups \n" + + "explicitGroups", // "contentServiceRequests \n" + // "createChildResourceRequests \n" + // "deleteResourceRequests \n" +
commit ef9231d7fcda51f9ca9e64bf91086e2237d63ccd Merge: 2f19995... ed4c35f... Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 18:04:25 2010 -0400
Merge branch 'master' of ssh://spinder@git.fedorahosted.org/git/rhq/rhq into track-master
commit ed4c35f7a4e2f68ebc52eac47912ef7c4f8ebca0 Author: Joseph Marques joseph@redhat.com Date: Tue Sep 21 17:08:29 2010 -0400
add some debugging statements
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index 01dceca..d6ac260 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -105,7 +105,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm this.groupDefinition = groupDefinition; }
- public void setGroupDefinition(GroupDefinition groupDefinition) { + public void setGroupDefinition(final GroupDefinition groupDefinition) { this.groupDefinition = groupDefinition; System.out.println("setGroupDefinition(" + groupDefinition + ")");
@@ -134,6 +134,17 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm form.setDataSource(dataSource); form.setHiliteRequiredFields(true); form.setRequiredTitleSuffix(" <span style="color: red;">* </span>:"); + final DSOperationType operationType; + if (groupDefinition.getId() == 0) { + System.out.println("setting form operation: ADD"); + form.setSaveOperationType(DSOperationType.ADD); + operationType = DSOperationType.ADD; + } else { + System.out.println("setting form operation: UPDATE"); + form.setSaveOperationType(DSOperationType.UPDATE); + operationType = DSOperationType.UPDATE; + } + System.out.println("form operation default is " + form.getSaveOperationType());
final DynaGroupChildrenView dynaGroupChildrenView = new DynaGroupChildrenView(extendLocatorId("DynaGroups"), groupDefinitionId); @@ -142,19 +153,16 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); saveButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { + System.out.println("cached operaton type is " + operationType); + form.setSaveOperationType(operationType); + System.out.println("form operation before validation is " + form.getSaveOperationType()); if (form.validate()) { - if (groupDefinitionId == 0) { - System.out.println("setting form operation: ADD"); - form.setSaveOperationType(DSOperationType.ADD); - } else { - System.out.println("setting form operation: UPDATE"); - form.setSaveOperationType(DSOperationType.UPDATE); - } - System.out.println("form operation type is " + form.getSaveOperationType()); + System.out.println("form operation after validation is " + form.getSaveOperationType()); form.saveData(new DSCallback() { @Override public void execute(DSResponse response, Object rawData, DSRequest request) { - if (SingleGroupDefinitionView.this.groupDefinitionId == 0) { + if (groupDefinition.getId() == 0) { + System.out.println("just created new group def"); Record[] results = response.getData(); if (results.length != 1) { CoreGUI.getErrorHandler().handleError( @@ -166,6 +174,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm History.newItem(basePath + "/" + newGroupDefinition.getId()); } } else { + System.out.println("just edited existing group def"); dynaGroupChildrenView.refresh(); } }
commit 944ccfa1d927d00b9ca253a3f47dbdf792684592 Author: John Mazzitelli mazz@redhat.com Date: Tue Sep 21 16:54:00 2010 -0400
finished the "recovery editor" portion of the alert definition editor. you can now set recovery alerts and disable-on-fire flag
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java index 8f8c5c3..bf38e6b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsDataSource.java @@ -136,4 +136,10 @@ public abstract class AbstractAlertDefinitionsDataSource extends RPCDataSource<A }
protected abstract AlertDefinitionCriteria getCriteria(DSRequest request); + + /** + * Returns a criteria that will query for all alerts, but only for the ID and name fields. + * @return criteria for an inexpensive query to obtain all alert defs + */ + protected abstract AlertDefinitionCriteria getSimpleCriteriaForAll(); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GeneralPropertiesAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GeneralPropertiesAlertDefinitionForm.java index fe1e2e2..12e27d9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GeneralPropertiesAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GeneralPropertiesAlertDefinitionForm.java @@ -99,10 +99,10 @@ public class GeneralPropertiesAlertDefinitionForm extends LocatableDynamicForm i prioritySelection.setValue(alertDef.getPriority().name()); priorityStatic.setValue(alertDef.getPriority().name());
- enabledSelection.setValue(alertDef.getEnabled() ? "Yes" : "No"); + enabledSelection.setValue(alertDef.getEnabled() ? "yes" : "no"); enabledStatic.setValue(alertDef.getEnabled() ? "Yes" : "No");
- readOnlySelection.setValue(alertDef.isReadOnly() ? "Yes" : "No"); + readOnlySelection.setValue(alertDef.isReadOnly() ? "yes" : "no"); readOnlyStatic.setValue(alertDef.isReadOnly() ? "Yes" : "No"); }
@@ -181,8 +181,8 @@ public class GeneralPropertiesAlertDefinitionForm extends LocatableDynamicForm i String prioritySelected = prioritySelection.getValue().toString(); alertDefinition.setPriority(AlertPriority.valueOf(prioritySelected));
- alertDefinition.setEnabled("Yes".equals(enabledSelection.getValue())); - alertDefinition.setReadOnly("Yes".equals(readOnlySelection.getValue())); + alertDefinition.setEnabled("yes".equals(enabledSelection.getValue())); + alertDefinition.setReadOnly("yes".equals(readOnlySelection.getValue())); }
@Override @@ -230,13 +230,19 @@ public class GeneralPropertiesAlertDefinitionForm extends LocatableDynamicForm i priorityStatic.setValueIcons(priorityIcons);
enabledSelection = new RadioGroupItem("enabled", "Enabled"); - enabledSelection.setValueMap("Yes", "No"); - enabledSelection.setDefaultValue("Yes"); + LinkedHashMap<String, String> enabledYesNo = new LinkedHashMap<String, String>(2); + enabledYesNo.put("yes", "Yes"); + enabledYesNo.put("no", "No"); + enabledSelection.setValueMap(enabledYesNo); + enabledSelection.setDefaultValue("yes"); enabledStatic = new StaticTextItem("enabledStatic", "Enabled");
readOnlySelection = new RadioGroupItem("readOnly", "Protected"); - readOnlySelection.setValueMap("Yes", "No"); - readOnlySelection.setDefaultValue("Yes"); + LinkedHashMap<String, String> readOnlyYesNo = new LinkedHashMap<String, String>(2); + readOnlyYesNo.put("yes", "Yes"); + readOnlyYesNo.put("no", "No"); + readOnlySelection.setValueMap(readOnlyYesNo); + readOnlySelection.setDefaultValue("yes"); readOnlySelection .setPrompt("If true, this definition is protected from being changed by the parent definition. In other words, the parent definition settings will not override this definition."); readOnlyStatic = new StaticTextItem("readOnlyStatic", "Protected"); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsDataSource.java index 90f9490..bb2cc71 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsDataSource.java @@ -29,12 +29,21 @@ import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSRequest;
import org.rhq.core.domain.criteria.AlertDefinitionCriteria; +import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.core.domain.util.PageControl;
/** * @author John Mazzitelli */ public class GroupAlertDefinitionsDataSource extends AbstractAlertDefinitionsDataSource {
+ private ResourceGroup resourceGroup; + + public GroupAlertDefinitionsDataSource(ResourceGroup group) { + super(); + this.resourceGroup = group; + } + @Override protected AlertDefinitionCriteria getCriteria(DSRequest request) { AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); @@ -54,4 +63,12 @@ public class GroupAlertDefinitionsDataSource extends AbstractAlertDefinitionsDat criteria.setPageControl(getPageControl(request)); return criteria; } + + @Override + protected AlertDefinitionCriteria getSimpleCriteriaForAll() { + AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); + criteria.addFilterResourceGroupIds(Integer.valueOf(this.resourceGroup.getId())); + criteria.setPageControl(PageControl.getUnlimitedInstance()); + return criteria; + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java index 4775ee4..183faec 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java @@ -82,7 +82,7 @@ public class GroupAlertDefinitionsView extends AbstractAlertDefinitionsView {
@Override protected AbstractAlertDefinitionsDataSource getAlertDefinitionDataSource() { - return new GroupAlertDefinitionsDataSource(); + return new GroupAlertDefinitionsDataSource(group); }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java index ab64324..a929a84 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/RecoveryAlertDefinitionForm.java @@ -23,10 +23,21 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.ArrayList; +import java.util.LinkedHashMap; + +import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.form.fields.RadioGroupItem; 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 org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.criteria.AlertDefinitionCriteria; +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.util.selenium.LocatableDynamicForm;
/** @@ -35,18 +46,25 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements EditAlertDefinitionForm {
private AlertDefinition alertDefinition; + private AbstractAlertDefinitionsDataSource alertDataSource; + private ArrayList<AlertDefinition> allAlertDefinitions;
private SelectItem recoverAlertSelection; + private StaticTextItem recoverAlertStatic; + private RadioGroupItem disableWhenFiredSelection; + private StaticTextItem disableWhenFiredStatic;
private boolean formBuilt = false;
- public RecoveryAlertDefinitionForm(String locatorId) { - this(locatorId, null); + public RecoveryAlertDefinitionForm(String locatorId, AbstractAlertDefinitionsDataSource dataSource) { + this(locatorId, dataSource, null); }
- public RecoveryAlertDefinitionForm(String locatorId, AlertDefinition alertDefinition) { + public RecoveryAlertDefinitionForm(String locatorId, AbstractAlertDefinitionsDataSource dataSource, + AlertDefinition alertDefinition) { super(locatorId); + this.alertDataSource = dataSource; this.alertDefinition = alertDefinition; }
@@ -55,7 +73,6 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements super.onInit();
if (!formBuilt) { - buildForm(); setAlertDefinition(alertDefinition); makeViewOnly(); } @@ -75,7 +92,10 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements if (alertDef == null) { clearFormValues(); } else { - disableWhenFiredSelection.setValue(alertDef.getWillRecover() ? "Yes" : "No"); + refreshWidgets(allAlertDefinitions); + + disableWhenFiredSelection.setValue(alertDef.getWillRecover() ? "yes" : "no"); + disableWhenFiredStatic.setValue(alertDef.getWillRecover() ? "Yes" : "No"); }
markForRedraw(); @@ -83,21 +103,38 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements
@Override public void makeEditable() { - // TODO Auto-generated method stub + recoverAlertSelection.show(); + disableWhenFiredSelection.show(); + + recoverAlertStatic.hide(); + disableWhenFiredStatic.hide();
markForRedraw(); }
@Override public void makeViewOnly() { - // TODO Auto-generated method stub + recoverAlertSelection.hide(); + disableWhenFiredSelection.hide(); + + recoverAlertStatic.show(); + disableWhenFiredStatic.show();
markForRedraw(); }
@Override public void saveAlertDefinition() { - // TODO Auto-generated method stub + // this silliness is to workaround the validation that AlertDefinition setters try to do + alertDefinition.setRecoveryId(0); + alertDefinition.setWillRecover(false); + + alertDefinition.setRecoveryId(Integer.valueOf(recoverAlertSelection.getValue().toString())); + if (alertDefinition.getRecoveryId() != 0) { + alertDefinition.setWillRecover(false); + } else { + alertDefinition.setWillRecover("yes".equals(disableWhenFiredSelection.getValue())); + } }
@Override @@ -105,23 +142,133 @@ public class RecoveryAlertDefinitionForm extends LocatableDynamicForm implements recoverAlertSelection.clearValue(); disableWhenFiredSelection.clearValue();
+ recoverAlertStatic.clearValue(); + disableWhenFiredStatic.clearValue(); + markForRedraw(); }
private void buildForm() { if (!formBuilt) { + disableWhenFiredSelection = new RadioGroupItem("disableWhenFired", "Disable When Fired"); + LinkedHashMap<String, String> yesNo = new LinkedHashMap<String, String>(2); + yesNo.put("yes", "Yes"); + yesNo.put("no", "No"); + disableWhenFiredSelection.setValueMap(yesNo); + disableWhenFiredSelection.setDefaultValue("no"); + disableWhenFiredSelection.setWrapTitle(false); + disableWhenFiredStatic = new StaticTextItem("disableWhenFiredStatic", "Disable When Fired"); + disableWhenFiredStatic.setWrapTitle(false); + recoverAlertSelection = new SelectItem("recoveryAlert", "Recover Alert"); - recoverAlertSelection.setValueMap("Select..."); - recoverAlertSelection.setDefaultValue("Select..."); - // TODO: call into server and get the menu list of all alerts that we can recover + recoverAlertSelection.setDefaultValue("0"); + recoverAlertSelection.setWrapTitle(false); + recoverAlertSelection.setRedrawOnChange(true);
- disableWhenFiredSelection = new RadioGroupItem("disableWhenFired", "Disable When Fired"); - disableWhenFiredSelection.setValueMap("Yes", "No"); - disableWhenFiredSelection.setDefaultValue("Yes"); + recoverAlertStatic = new StaticTextItem("recoveryAlertStatic", "Recover Alert"); + recoverAlertStatic.setDefaultValue(getNoRecoveryMenuItemTitle()); + recoverAlertStatic.setWrapTitle(false); + + // if a recovery alert is set, then this alert definition must not disable itself when fired + // because it will be needed to recover its recovery alert the next time it fires. disabling is only + // for non-recoverable alerts or for alerts that will themselves be recovered. + // therefore, force the disableWhenFired selection to go to no and do not allow it to be changed when appropriate + recoverAlertSelection.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + String recoveryAlertDefId = event.getItem().getValue().toString(); + refreshDisableWhenFiredSelection(recoveryAlertDefId); + } + }); + + refreshWidgets(null); // for it to at least show the initial "no-op" entry + loadAllAlertDefinitionsAndRefreshRecoverAlertSelection(); // this gets the real entries asynchronously
- setFields(recoverAlertSelection, disableWhenFiredSelection); + setFields(recoverAlertSelection, recoverAlertStatic, disableWhenFiredSelection, disableWhenFiredStatic);
formBuilt = true; } } + + private AlertDefinition lookupAlertDefinition(Integer id) { + if (id != null && id.intValue() != 0) { + if (this.allAlertDefinitions != null) { + for (AlertDefinition def : this.allAlertDefinitions) { + if (def.getId() == id.intValue()) { + return def; + } + } + } + } + + return null; + } + + private void loadAllAlertDefinitionsAndRefreshRecoverAlertSelection() { + if (allAlertDefinitions == null) { + AlertDefinitionCriteria criteria = alertDataSource.getSimpleCriteriaForAll(); + GWTServiceLookup.getAlertService().findAlertDefinitionsByCriteria(criteria, + new AsyncCallback<PageList<AlertDefinition>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Cannot build recovery menu", caught); + } + + public void onSuccess(PageList<AlertDefinition> result) { + allAlertDefinitions = result; + refreshWidgets(allAlertDefinitions); + } + }); + } else { + // we already got the values before, just refresh the menu (in case this.alertDef changed) + refreshWidgets(allAlertDefinitions); + } + } + + private void refreshWidgets(ArrayList<AlertDefinition> allDefs) { + int allDefsSize = (allDefs != null) ? allDefs.size() : 0; + LinkedHashMap<String, String> alertMap = new LinkedHashMap<String, String>(allDefsSize + 1); + alertMap.put("0", getNoRecoveryMenuItemTitle()); + if (allDefs != null) { + for (AlertDefinition def : allDefs) { + if (alertDefinition == null || alertDefinition.getId() != def.getId()) { + alertMap.put(String.valueOf(def.getId()), def.getName()); + } + } + } + recoverAlertSelection.setValueMap(alertMap); + + if (alertDefinition != null) { + AlertDefinition recoveryAlert = lookupAlertDefinition(alertDefinition.getRecoveryId()); + if (recoveryAlert != null) { + String recoveryIdStr = String.valueOf(recoveryAlert.getId()); + recoverAlertSelection.setValue(recoveryIdStr); + recoverAlertStatic.setValue(recoveryAlert.getName()); + refreshDisableWhenFiredSelection(recoveryIdStr); + } else { + recoverAlertSelection.setValue("0"); + recoverAlertStatic.setValue(getNoRecoveryMenuItemTitle()); + refreshDisableWhenFiredSelection("0"); + } + } + + recoverAlertSelection.redraw(); + } + + private void refreshDisableWhenFiredSelection(String recoveryAlertDefId) { + if ("0".equals(recoveryAlertDefId)) { + disableWhenFiredSelection.setDisabled(false); + } else { + disableWhenFiredSelection.setValue("no"); + disableWhenFiredSelection.setDisabled(true); + } + disableWhenFiredSelection.redraw(); + } + + private String getNoRecoveryMenuItemTitle() { + StringBuilder str = new StringBuilder(); + str.append("-- "); + str.append("No Recovery"); + str.append(" --"); + return str.toString(); + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsDataSource.java index dc04a1e..3bc7a3f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsDataSource.java @@ -34,6 +34,7 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.criteria.AlertDefinitionCriteria; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.util.PageControl;
/** * @author John Mazzitelli @@ -115,4 +116,12 @@ public class ResourceAlertDefinitionsDataSource extends AbstractAlertDefinitions criteria.setPageControl(getPageControl(request)); return criteria; } + + @Override + protected AlertDefinitionCriteria getSimpleCriteriaForAll() { + AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); + criteria.addFilterResourceIds(Integer.valueOf(this.resource.getId())); + criteria.setPageControl(PageControl.getUnlimitedInstance()); + return criteria; + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SingleAlertDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SingleAlertDefinitionView.java index bc7a8b0..2e3caf0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SingleAlertDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SingleAlertDefinitionView.java @@ -79,7 +79,8 @@ public class SingleAlertDefinitionView extends LocatableVLayout { notificationsTab.setPane(notifications);
Tab recoveryTab = new LocatableTab(tabSet.extendLocatorId("Recovery"), "Recovery"); - recovery = new RecoveryAlertDefinitionForm(this.getLocatorId(), alertDefinition); + recovery = new RecoveryAlertDefinitionForm(this.getLocatorId(), alertDefView.getAlertDefinitionDataSource(), + alertDefinition); recoveryTab.setPane(recovery);
Tab dampeningTab = new LocatableTab(tabSet.extendLocatorId("Dampening"), "Dampening"); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsDataSource.java index 9a96db8..15163f0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsDataSource.java @@ -29,12 +29,21 @@ import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSRequest;
import org.rhq.core.domain.criteria.AlertDefinitionCriteria; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.util.PageControl;
/** * @author John Mazzitelli */ public class TemplateAlertDefinitionsDataSource extends AbstractAlertDefinitionsDataSource {
+ private ResourceType resourceType; + + public TemplateAlertDefinitionsDataSource(ResourceType rt) { + super(); + this.resourceType = rt; + } + @Override protected AlertDefinitionCriteria getCriteria(DSRequest request) { AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); @@ -54,4 +63,12 @@ public class TemplateAlertDefinitionsDataSource extends AbstractAlertDefinitions criteria.setPageControl(getPageControl(request)); return criteria; } + + @Override + protected AlertDefinitionCriteria getSimpleCriteriaForAll() { + AlertDefinitionCriteria criteria = new AlertDefinitionCriteria(); + criteria.addFilterAlertTemplateResourceTypeId(Integer.valueOf(this.resourceType.getId())); + criteria.setPageControl(PageControl.getUnlimitedInstance()); + return criteria; + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java index 4366291..c26a8f9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java @@ -83,7 +83,7 @@ public class TemplateAlertDefinitionsView extends AbstractAlertDefinitionsView {
@Override protected AbstractAlertDefinitionsDataSource getAlertDefinitionDataSource() { - return new TemplateAlertDefinitionsDataSource(); + return new TemplateAlertDefinitionsDataSource(resourceType); }
@Override
commit 2f1999541edf590c3af79484071c28ef6dffeee6 Merge: 09d836b... a67696b... Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 16:37:00 2010 -0400
Merge branch 'master' of ssh://spinder@git.fedorahosted.org/git/rhq/rhq into track-master
commit a67696bb08a8ab5c338a6be99de8c7e01ddd2866 Author: Joseph Marques joseph@redhat.com Date: Tue Sep 21 16:26:02 2010 -0400
go to edit mode after finished creating new group definition
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java index 49ea417..32692b1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java @@ -109,6 +109,7 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
@Override protected void executeAdd(final DSRequest request, final DSResponse response) { + System.out.println("executeAdd"); JavaScriptObject data = request.getData(); final ListGridRecord record = new ListGridRecord(data); final GroupDefinition newGroupDefinition = copyValues(record); @@ -136,6 +137,7 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
@Override protected void executeUpdate(final DSRequest request, final DSResponse response) { + System.out.println("executeUpdate"); final ListGridRecord record = getEditedRecord(request); final GroupDefinition updatedGroupDefinition = copyValues(record); final String name = updatedGroupDefinition.getName(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index f4ca2cf..01dceca 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -27,6 +27,7 @@ import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.data.Record; import com.smartgwt.client.types.DSOperationType; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.IButton; @@ -36,6 +37,7 @@ import com.smartgwt.client.widgets.form.fields.SpinnerItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.TextItem; +import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.layout.HLayout;
import org.rhq.core.domain.authz.Permission; @@ -62,6 +64,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
private int groupDefinitionId; private GroupDefinition groupDefinition; + private String basePath;
private ViewId viewId;
@@ -104,6 +107,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
public void setGroupDefinition(GroupDefinition groupDefinition) { this.groupDefinition = groupDefinition; + System.out.println("setGroupDefinition(" + groupDefinition + ")");
// form setup id.setValue(groupDefinition.getId()); @@ -130,11 +134,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm form.setDataSource(dataSource); form.setHiliteRequiredFields(true); form.setRequiredTitleSuffix(" <span style="color: red;">* </span>:"); - if (groupDefinition.getId() == 0) { - form.setSaveOperationType(DSOperationType.ADD); - } else { - form.setSaveOperationType(DSOperationType.UPDATE); - }
final DynaGroupChildrenView dynaGroupChildrenView = new DynaGroupChildrenView(extendLocatorId("DynaGroups"), groupDefinitionId); @@ -144,10 +143,31 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm saveButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { if (form.validate()) { + if (groupDefinitionId == 0) { + System.out.println("setting form operation: ADD"); + form.setSaveOperationType(DSOperationType.ADD); + } else { + System.out.println("setting form operation: UPDATE"); + form.setSaveOperationType(DSOperationType.UPDATE); + } + System.out.println("form operation type is " + form.getSaveOperationType()); form.saveData(new DSCallback() { @Override public void execute(DSResponse response, Object rawData, DSRequest request) { - dynaGroupChildrenView.refresh(); + if (SingleGroupDefinitionView.this.groupDefinitionId == 0) { + Record[] results = response.getData(); + if (results.length != 1) { + CoreGUI.getErrorHandler().handleError( + "Error: " + results.length + " created instead of one"); + } else { + Record newRecord = results[0]; + GroupDefinition newGroupDefinition = dataSource + .copyValues((ListGridRecord) newRecord); + History.newItem(basePath + "/" + newGroupDefinition.getId()); + } + } else { + dynaGroupChildrenView.refresh(); + } } }); } @@ -256,7 +276,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
private void buildForm() { id = new TextItem("id", "ID"); - id.setVisible(false); + //id.setVisible(false); idStatic = new StaticTextItem("idStatic", "ID"); idStatic.setVisible(false);
@@ -387,6 +407,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm public void renderView(ViewPath viewPath) { groupDefinitionId = viewPath.getCurrentAsInt(); viewId = viewPath.getCurrent(); + basePath = viewPath.getPathToCurrent(); GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { @Override public void onFailure(Throwable caught) {
commit 44f77ff7a5df1f2054180290285831b44fa87292 Merge: c1f4166... c073bce... Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 21 15:26:36 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 09d836bba1d73eef4d48cc6dcf83931b042572fd Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 14:52:29 2010 -0400
commit to bind WS namespace to the build versioning.
diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index 04d3557..4c4e9a5 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -406,7 +406,16 @@ <build> <finalName>${project.artifactId}</finalName>
+ <!-- point to new source code directory that has been filtered. --> + <sourceDirectory>target/filtered-sources/java</sourceDirectory> + <resources> + <!-- Redefine which directories to treat like resources(which are filtered). --> + <resource> + <directory>src/main/java</directory> + <filtering>true</filtering> + <targetPath>../filtered-sources/java</targetPath> + </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/ServerVersion.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/ServerVersion.java index e8114aa..275a5c6 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/ServerVersion.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/ServerVersion.java @@ -42,10 +42,8 @@ public class ServerVersion implements Serializable { private String version; private String build;
- //This value must be set by build system just before Build Time. - public static final String namespace = "http://www.rhq-project.org/2.4/2010/7/Webservices.xsd"; - - // private final String namespace = "@ws-namespace@"; + //This value must be set by build system just before Build/Compile Time. + public static final String namespace = "http://www.rhq-project.org/$%7Bpom.version%7D/Webservices.xsd";
public ServerVersion(String version, String build) { this.version = version;
commit 2fa80f50dfdbf1ba8820f1300066b669e2328eb1 Merge: 9075e22... c073bce... Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 14:36:28 2010 -0400
Merge branch 'master' of ssh://spinder@git.fedorahosted.org/git/rhq/rhq into track-master
commit c073bceb346b0ecc93e238cf58646624fefde13c Merge: 4d44fd5... fe4cc40... Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 21 14:26:49 2010 -0400
Merge branch 'master' into master-jay
Conflicts: modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerLocal.java
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index 60a3783,f88f949..f318cf4 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@@ -65,3 -563,95 +563,96 @@@ public class RecentAlertsPortlet extend } } } + + class CustomizedResourceSelector extends ResourceSelector { - public CustomizedResourceSelector(String id) { - super(id); ++ public CustomizedResourceSelector(String locatorId) { ++ super(locatorId); ++ } ++ ++ public CustomizedResourceSelector(String locatorId, ResourceType rtFilter, boolean forceRtFilter) { ++ super(locatorId, rtFilter, forceRtFilter); + } + + public void addAvailableGridSelectionsToAssignedGrid() { + assignedGrid.transferSelectedData(availableGrid); + select(assignedGrid.getSelection()); + updateButtons(); + } + } + + class AlertResourceSelectorRegion extends GroupMembersStep { + // private ResourceSelector selector = null; + private CustomizedResourceSelector selector = null; - private ResourceType requireType = null; + private Integer[] currentlyAssignedIds; + + public Integer[] getCurrentlyAssignedIds() { + return currentlyAssignedIds; + } + + public Integer[] getListGridValues() { + Integer[] listGridValues = new Integer[0]; + if ((null != selector) && (null != selector.getAssignedGrid())) { + RecordList allRecords = selector.getAssignedGrid().getDataAsRecordList(); + if (allRecords.getLength() > 0) { + listGridValues = new Integer[allRecords.getLength()]; + for (int i = 0; i < allRecords.getLength(); i++) { + Record record = allRecords.get(i); + listGridValues[i] = record.getAttributeAsInt(RecentAlertsPortlet.ID); + } + } + } + return listGridValues; + } + + public AlertResourceSelectorRegion(Integer[] assigned) { + super(null); + this.currentlyAssignedIds = assigned; + } + + public Canvas getCanvas() { - ResourceType rt = ResourceType.ANY_PLATFORM_TYPE; - if ((selector == null) || (rt != requireType)) { ++ if (selector == null) { + // selector = new ResourceSelector(getName()); - selector = new CustomizedResourceSelector(getName()); ++ selector = new CustomizedResourceSelector(getName(), ResourceType.ANY_PLATFORM_TYPE, true); + selector.setWidth100(); + selector.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH); - selector.setRequireType(rt); + //widget ui updates + selector.getAvailableGrid().setTitle("Available Resources"); + selector.getAvailableGrid().setEmptyMessage("Loading data..."); + selector.getAssignedGrid().setTitle("Selected Resources"); + + //populate fields for grid. + ListGridField nameField = new ListGridField("name", "Name"); + ListGridField iconField = new ListGridField("icon", "icon", 50); + iconField.setImageURLPrefix("types/"); + iconField.setType(ListGridFieldType.ICON); + selector.getAssignedGrid().setFields(iconField, nameField); + + //add listener to AvailableGrid, to act after successfully populated. + selector.getAvailableGrid().addDataArrivedHandler(new DataArrivedHandler() { + @Override + public void onDataArrived(DataArrivedEvent event) { + if ((getCurrentlyAssignedIds() != null) && (getCurrentlyAssignedIds().length > 0)) { + //retrieve the loaded data and add to the table itself + RecordList recordList = selector.getAvailableGrid().getDataAsRecordList(); + for (int ci : getCurrentlyAssignedIds()) { + int located = recordList.findIndex("id", ci); + if (located > -1) { + selector.getAvailableGrid().selectRecord(located); + } + } + selector.addAvailableGridSelectionsToAssignedGrid(); + selector.getAssignedGrid().invalidateCache(); + selector.getAssignedGrid().markForRedraw(); + } else {//no selected resources found + selector.getAvailableGrid().setEmptyMessage("No items to show"); + } + } + }); + } + return selector; + } + + public void setCurrentlyAssignedIds(Integer[] currentlyAssignedIds) { + this.currentlyAssignedIds = currentlyAssignedIds; + } + } diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java index 0951851,d475aa8..d968e19 --- 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 @@@ -48,10 -49,10 +49,12 @@@ public interface ResourceGroupGWTServic
PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria);
- void recalculateGroupDefinitions(int[] groupDefinitionIds); + void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType); + + void setAssignedResources(int groupId, int[] resourceIds, boolean setType);
- void setMembership(int groupId, int[] resourceIds, boolean setType); ++ void recalculateGroupDefinitions(int[] groupDefinitionIds); + void updateGroupDefinition(GroupDefinition groupDefinition);
void updateResourceGroup(ResourceGroup group); diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java index 20786a0,f0fe978..91bf412 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java @@@ -115,11 -110,11 +110,16 @@@ public class ResourceGroupsDataSource e "downMemberCount"))); }
+ if (request.getCriteria().getValues().get("explicitResourceId") != null) { + criteria.addFilterExplicitResourceIds(Integer.parseInt((String) request.getCriteria().getValues().get( + "explicitResourceId"))); + } + + if (request.getCriteria().getValues().get("groupDefinitionId") != null) { + criteria.addFilterGroupDefinitionId(Integer.parseInt((String) request.getCriteria().getValues().get( + "groupDefinitionId"))); + } + return criteria; }
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java index 6603a00,f085e9b..05590ff --- 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 @@@ -187,74 -192,68 +192,64 @@@ public class ResourceGroupDetailView ex // FullHTMLPane timelinePane = new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()); // summaryTab.updateSubTab("Overview", new DashboardView(resource)); // summaryTab.updateSubTab("Timeline", timelinePane); - this.summaryOverview.setCanvas(new OverviewView(this.summaryTab.extendLocatorId("Overview"), - this.groupComposite)); - - int groupId = this.groupComposite.getResourceGroup().getId(); - - this.monitorGraphs.setCanvas(new FullHTMLPane("/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId)); - this.monitorTables.setCanvas(new FullHTMLPane("/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId)); - this.monitorTraits.setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), groupId)); - this.monitorSched.setCanvas(new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId)); - this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId)); + // Summary tab is always visible and enabled. - updateSubTab(this.summaryTab, this.summaryOverview, - new OverviewView(this.summaryTab.extendLocatorId("Overview"), this.groupComposite), true, true); - - if (updateTab(this.monitoringTab, groupCategory == GroupCategory.COMPATIBLE, true)) { - updateSubTab(this.monitoringTab, this.monitorGraphs, - new FullHTMLPane("/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId), - hasMetricsOfType(this.groupComposite, DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTables, - new FullHTMLPane("/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId), - hasMetricsOfType(this.groupComposite, DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTraits, - new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), groupId), - hasMetricsOfType(this.groupComposite, DataType.TRAIT), true); - updateSubTab(this.monitoringTab, this.monitorSched, - new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId), - hasMetricsOfType(this.groupComposite, null), true); - updateSubTab(this.monitoringTab, this.monitorCallTime, - new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId), - facets.contains(ResourceTypeFacet.CALL_TIME), true); ++ updateSubTab(this.summaryTab, this.summaryOverview, new OverviewView(this.summaryTab ++ .extendLocatorId("Overview"), this.groupComposite), true, true); ++ ++ if (updateTab(this.monitoringTab, groupCategory == GroupCategory.COMPATIBLE, true)) { ++ updateSubTab(this.monitoringTab, this.monitorGraphs, new FullHTMLPane( ++ "/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId), hasMetricsOfType(this.groupComposite, ++ DataType.MEASUREMENT), true); ++ updateSubTab(this.monitoringTab, this.monitorTables, new FullHTMLPane( ++ "/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId), hasMetricsOfType(this.groupComposite, ++ DataType.MEASUREMENT), true); ++ updateSubTab(this.monitoringTab, this.monitorTraits, new TraitsView(this.monitoringTab ++ .extendLocatorId("TraitsView"), groupId), hasMetricsOfType(this.groupComposite, DataType.TRAIT), true); ++ updateSubTab(this.monitoringTab, this.monitorSched, new SchedulesView(this.monitoringTab ++ .extendLocatorId("SchedulesView"), groupId), hasMetricsOfType(this.groupComposite, null), true); ++ updateSubTab(this.monitoringTab, this.monitorCallTime, new FullHTMLPane( ++ "/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId), facets ++ .contains(ResourceTypeFacet.CALL_TIME), true); + // TODO (ips): Add Availability subtab. + }
- this.inventoryMembers.setCanvas(ResourceSearchView.getMembersOf(this.inventoryTab - .extendLocatorId("MembersView"), groupId)); + // Inventory tab is always visible and enabled. - updateSubTab(this.inventoryTab, this.inventoryMembers, - ResourceSearchView.getMembersOf(this.inventoryMembers.extendLocatorId("View"), groupId), true, true); ++ updateSubTab(this.inventoryTab, this.inventoryMembers, ResourceSearchView.getMembersOf(this.inventoryTab ++ .extendLocatorId("MembersView"), groupId), true, true); // TODO: Uncomment this once the group config component is done. - //this.inventoryConn.setCanvas(new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin)); - this.inventoryMembership.setCanvas(new ResourceGroupMembershipView(this.inventoryTab - .extendLocatorId("MembershipView"), groupId)); - - this.opHistory.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" - + groupId)); - this.opSched.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationSchedules-plain.xhtml?groupId=" - + groupId)); - - this.alertHistory.setCanvas(new FullHTMLPane("/rhq/group/alert/listGroupAlertHistory-plain.xhtml?groupId=" - + groupId)); - this.alertDef.setCanvas(new FullHTMLPane("/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" - + groupId)); - - this.configCurrent.setCanvas(new FullHTMLPane("/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" - + groupId)); - this.configHistory - .setCanvas(new FullHTMLPane("/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId)); - - this.eventHistory.setCanvas(EventCompositeHistoryView.get(groupComposite)); - - updateTabEnablement(); - } - - private void updateTabEnablement() { - GroupCategory groupCategory = groupComposite.getResourceGroup().getGroupCategory(); - Set<ResourceTypeFacet> facets = groupComposite.getResourceFacets().getFacets(); - - // Summary and Inventory tabs are always enabled. - - // Only enable "Call Time" and "Traits" subtabs for groups that implement them. - this.monitoringTab.setSubTabEnabled(this.monitorTraits.getLocatorId(), hasTraits(this.groupComposite)); - this.monitoringTab.setSubTabEnabled(this.monitorCallTime.getLocatorId(), facets - .contains(ResourceTypeFacet.CALL_TIME)); - - // Inventory>Connection Settings subtab is only enabled for compat groups that define conn props. - this.inventoryTab.setSubTabEnabled(this.inventoryConn.getLocatorId(), groupCategory == GroupCategory.COMPATIBLE - && facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); - - // Monitoring and Alerts tabs are always enabled for compatible groups and always disabled for mixed groups. - // TODO (ips): Break out mixed groups into a separate view. - getTabSet().setTabEnabled(this.monitoringTab, groupCategory == GroupCategory.COMPATIBLE); - getTabSet().setTabEnabled(this.alertsTab, groupCategory == GroupCategory.COMPATIBLE); + //updateSubTab(this.inventoryTab, this.inventoryConn, + // new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin), + // facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), true); - updateSubTab(this.inventoryTab, this.inventoryMembership, - new ResourceGroupMembershipView(this.inventoryTab.extendLocatorId("MembershipView"), groupId), true, true); - - if (updateTab(this.operationsTab, - groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.OPERATION), true)) { - updateSubTab(this.operationsTab, this.opHistory, - new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" + groupId), true, true); - updateSubTab(this.operationsTab, this.opSched, - new FullHTMLPane("/rhq/group/operation/groupOperationSchedules-plain.xhtml?groupId=" + groupId), true, true); ++ updateSubTab(this.inventoryTab, this.inventoryMembership, new ResourceGroupMembershipView(this.inventoryTab ++ .extendLocatorId("MembershipView"), groupId), true, true); ++ ++ if (updateTab(this.operationsTab, groupCategory == GroupCategory.COMPATIBLE ++ && facets.contains(ResourceTypeFacet.OPERATION), true)) { ++ updateSubTab(this.operationsTab, this.opHistory, new FullHTMLPane( ++ "/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" + groupId), true, true); ++ updateSubTab(this.operationsTab, this.opSched, new FullHTMLPane( ++ "/rhq/group/operation/groupOperationSchedules-plain.xhtml?groupId=" + groupId), true, true); + }
- // Operations tab is only enabled for compatible groups of a type that supports the Operations facet. - getTabSet().setTabEnabled(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION)); + if (updateTab(this.operationsTab, groupCategory == GroupCategory.COMPATIBLE, true)) { - updateSubTab(this.alertsTab, this.alertHistory, - new FullHTMLPane("/rhq/group/alert/listGroupAlertHistory-plain.xhtml?groupId=" + groupId), true, true); - updateSubTab(this.alertsTab, this.alertDef, - new FullHTMLPane("/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" + groupId), true, true); ++ updateSubTab(this.alertsTab, this.alertHistory, new FullHTMLPane( ++ "/rhq/group/alert/listGroupAlertHistory-plain.xhtml?groupId=" + groupId), true, true); ++ updateSubTab(this.alertsTab, this.alertDef, new FullHTMLPane( ++ "/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" + groupId), true, true); + }
- // Configuration tab is only enabled for compatible groups of a type that supports the Configuration facet - // and when the current user has the CONFIGURE_READ permission. - getTabSet().setTabEnabled(this.configurationTab, - facets.contains(ResourceTypeFacet.CONFIGURATION) && this.permissions.isConfigureRead()); - if (updateTab(this.configurationTab, - groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.CONFIGURATION), - this.permissions.isConfigureRead())) { - updateSubTab(this.configurationTab, this.configCurrent, - new FullHTMLPane("/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" + groupId), true, true); - updateSubTab(this.configurationTab, this.configHistory, - new FullHTMLPane("/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId), true, true); ++ if (updateTab(this.configurationTab, groupCategory == GroupCategory.COMPATIBLE ++ && facets.contains(ResourceTypeFacet.CONFIGURATION), this.permissions.isConfigureRead())) { ++ updateSubTab(this.configurationTab, this.configCurrent, new FullHTMLPane( ++ "/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" + groupId), true, true); ++ updateSubTab(this.configurationTab, this.configHistory, new FullHTMLPane( ++ "/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId), true, true); + }
- // Events tab is only enabled for compatible groups of a type that supports the Events facet. - getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); - if (updateTab(this.eventsTab, - groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.EVENT), true)) { - updateSubTab(this.eventsTab, this.eventHistory, - EventCompositeHistoryView.get(groupComposite), true, true); ++ if (updateTab(this.eventsTab, groupCategory == GroupCategory.COMPATIBLE ++ && facets.contains(ResourceTypeFacet.EVENT), true)) { ++ updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(groupComposite), true, true); + } }
protected void loadSelectedItem(final int groupId, final ViewPath viewPath) { diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java index 2e3e9c7,2e3e9c7..d87e26b --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java @@@ -43,7 -43,7 +43,7 @@@ public class GroupMembersStep extends A
public Canvas getCanvas() { if (selector == null) { -- selector = new ResourceSelector(getName()); ++ selector = new ResourceSelector("GroupMembers"); } return selector; } diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 8e73379,88dd2f9..8e4e16f --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@@ -197,92 -189,92 +196,91 @@@ public class ResourceDetailView extend ((TwoLevelTab) top).getLayout().destroyViews(); }
- this.summaryOverview.setCanvas(new OverviewView(this.summaryTab.extendLocatorId("OverviewView"), - this.resourceComposite)); - this.summaryDashboard.setCanvas(new DashboardView(this.resourceComposite)); - this.summaryTimeline.setCanvas(new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" - + resource.getId())); - - this.monitorGraphs.setCanvas(new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource)); - this.monitorTables.setCanvas(new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId())); - this.monitorTraits - .setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId())); - this.monitorAvail.setCanvas(new FullHTMLPane("/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" - + resource.getId())); - this.monitorSched - .setCanvas(new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId())); - this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" - + resource.getId())); - - this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(this.inventoryTab - .extendLocatorId("ChildrenView"), resource.getId())); - this.inventoryConn.setCanvas(new PluginConfigurationEditView(this.inventoryTab - .extendLocatorId("PluginConfigView"), resource)); - this.inventoryGroups.setCanvas(ResourceGroupListView.getGroupsOf(this.inventoryTab - .extendLocatorId("GroupsView"), resource.getId())); - this.inventoryGroupMembership.setCanvas(new ResourceResourceGroupsView(this.inventoryTab - .extendLocatorId("GroupMembershipView"), resourceId)); - - // comment out GWT-based operation history until... - // 1) user can delete history if they possess the appropriate permissions - // 2) user can see both operation arguments and results in the history details pop-up - // 3) operation arguments/results become read-only configuration data in the history details pop-up - // 4) user can navigate to the group operation that spawned this resource operation history, if appropriate - // note: enabled operation execution/schedules from left-nav, if it doesn't already exist - this.opHistory.setCanvas(OperationHistoryView.getResourceHistoryView(operationsTab.extendLocatorId("History"), - resourceComposite)); - this.opSched.setCanvas(new FullHTMLPane("/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" - + resource.getId())); + ResourcePermission permissions = this.resourceComposite.getResourcePermission(); + Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets(); + - updateSubTab(this.summaryTab, this.summaryOverview, - new OverviewView(this.summaryOverview.getLocatorId(), this.resourceComposite), true, true); - updateSubTab(this.summaryTab, this.summaryDashboard, - new DashboardView(this.resourceComposite), true, true); - updateSubTab(this.summaryTab, this.summaryTimeline, - new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.summaryTab, this.summaryOverview, new OverviewView(this.summaryTab ++ .extendLocatorId("OverviewView"), this.resourceComposite), true, true); ++ updateSubTab(this.summaryTab, this.summaryDashboard, new DashboardView(this.resourceComposite), true, true); ++ updateSubTab(this.summaryTab, this.summaryTimeline, new FullHTMLPane( ++ "/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()), true, true); + - updateSubTab(this.monitoringTab, this.monitorGraphs, - new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource), ++ updateSubTab(this.monitoringTab, this.monitorGraphs, new GraphListView(this.monitoringTab ++ .extendLocatorId("GraphListView"), resource), + hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTables, - new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId()), - hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT), true); - updateSubTab(this.monitoringTab, this.monitorTraits, - new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId()), ++ updateSubTab(this.monitoringTab, this.monitorTables, new FullHTMLPane( ++ "/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId()), hasMetricsOfType(this.resourceComposite, ++ DataType.MEASUREMENT), true); ++ updateSubTab(this.monitoringTab, this.monitorTraits, new TraitsView(this.monitoringTab ++ .extendLocatorId("TraitsView"), resource.getId()), + hasMetricsOfType(this.resourceComposite, DataType.TRAIT), true); - updateSubTab(this.monitoringTab, this.monitorAvail, - new FullHTMLPane("/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId()), true, - true); - updateSubTab(this.monitoringTab, this.monitorSched, - new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId()), - hasMetricsOfType(this.resourceComposite, null), true); - updateSubTab(this.monitoringTab, this.monitorCallTime, - new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()), - facets.contains(ResourceTypeFacet.CALL_TIME), true); ++ updateSubTab(this.monitoringTab, this.monitorAvail, new FullHTMLPane( ++ "/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.monitoringTab, this.monitorSched, new SchedulesView(monitoringTab ++ .extendLocatorId("SchedulesView"), resource.getId()), hasMetricsOfType(this.resourceComposite, null), true); ++ updateSubTab(this.monitoringTab, this.monitorCallTime, new FullHTMLPane( ++ "/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()), facets ++ .contains(ResourceTypeFacet.CALL_TIME), true); + + ResourceType type = this.resourceComposite.getResource().getResourceType(); - updateSubTab(this.inventoryTab, this.inventoryChildren, - ResourceSearchView.getChildrenOf(this.extendLocatorId("Children"), resource.getId()), - !type.getChildResourceTypes().isEmpty(), true); - updateSubTab(this.inventoryTab, this.inventoryConn, - new PluginConfigurationEditView(this.extendLocatorId("PluginConfig"), resource), - facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), true); ++ updateSubTab(this.inventoryTab, this.inventoryChildren, ResourceSearchView.getChildrenOf(this.inventoryTab ++ .extendLocatorId("ChildrenView"), resource.getId()), !type.getChildResourceTypes().isEmpty(), true); ++ updateSubTab(this.inventoryTab, this.inventoryConn, new PluginConfigurationEditView(this.inventoryTab ++ .extendLocatorId("PluginConfigView"), resource), facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), ++ true); ++ updateSubTab(this.inventoryTab, this.inventoryGroups, ResourceGroupListView.getGroupsOf(this.inventoryTab ++ .extendLocatorId("GroupsView"), resource.getId()), true, true); ++ updateSubTab(this.inventoryTab, this.inventoryGroupMembership, new ResourceResourceGroupsView(this.inventoryTab ++ .extendLocatorId("GroupMembershipView"), resourceId), true, true); + + if (updateTab(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION), true)) { + // comment out GWT-based operation history until... + // 1) user can delete history if they possess the appropriate permissions + // 2) user can see both operation arguments and results in the history details pop-up + // 3) operation arguments/results become read-only configuration data in the history details pop-up + // 4) user can navigate to the group operation that spawned this resource operation history, if appropriate + // note: enabled operation execution/schedules from left-nav, if it doesn't already exist - updateSubTab(this.operationsTab, this.opHistory, - OperationHistoryView.getResourceHistoryView(operationsTab.extendLocatorId("History"), this.resourceComposite), - true, true); - updateSubTab(this.operationsTab, this.opSched, - new FullHTMLPane("/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" + resource.getId()), - true, true); ++ updateSubTab(this.operationsTab, this.opHistory, OperationHistoryView.getResourceHistoryView(operationsTab ++ .extendLocatorId("History"), this.resourceComposite), true, true); ++ updateSubTab(this.operationsTab, this.opSched, new FullHTMLPane( ++ "/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" + resource.getId()), true, true); + }
// comment out GWT-based alert definitions/history views until... // 1) new workflow is implement for alert definition creation, with particular attention to interaction model for alert notifications // 2) user can delete/ack/purgeAll alerts if they possess the appropriate permissions // 3) user can enable/disable/delete alert definitions if they possess the appropriate permissions // 4) user can search alert history by: date alert was fired, alert priority, or alert definition - this.alertHistory.setCanvas(new FullHTMLPane("/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" - + resource.getId())); - this.alertDef.setCanvas(new ResourceAlertDefinitionsView(alertsTab.extendLocatorId("AlertDef"), - resourceComposite)); - this.alertDelete.setCanvas(new FullHTMLPane("/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" - + resource.getId())); - - this.configCurrent - .setCanvas(new ResourceConfigurationEditView(this.extendLocatorId("ResourceConfig"), resource)); - this.configHistory.setCanvas(ConfigurationHistoryView.getHistoryOf(configurationTab.extendLocatorId("Hist"), - resource.getId())); - - this.eventHistory.setCanvas(EventCompositeHistoryView.get(resourceComposite)); - - this.contentDeployed - .setCanvas(new FullHTMLPane("/rhq/resource/content/view-plain.xhtml?id=" + resource.getId())); - this.contentNew.setCanvas(new FullHTMLPane("/rhq/resource/content/deploy-plain.xhtml?id=" + resource.getId())); - this.contentSubscrip.setCanvas(new FullHTMLPane("/rhq/resource/content/subscription-plain.xhtml?id=" - + resource.getId())); - this.contentHistory.setCanvas(new FullHTMLPane("/rhq/resource/content/history-plain.xhtml?id=" - + resource.getId())); - - updateTabEnablement(); - } - - private void updateTabEnablement() { - ResourcePermission permissions = this.resourceComposite.getResourcePermission(); - Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets(); - - // Summary, Monitoring, Inventory, and Alerts tabs are always enabled. - - monitoringTab.setSubTabEnabled(monitorTraits.getLocatorId(), hasTraits(this.resourceComposite)); - monitoringTab.setSubTabEnabled(monitorCallTime.getLocatorId(), facets.contains(ResourceTypeFacet.CALL_TIME)); - updateSubTab(this.alertsTab, this.alertHistory, - new FullHTMLPane("/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" + resource.getId()), true, true); - updateSubTab(this.alertsTab, this.alertDef, - new ResourceAlertDefinitionsView(alertsTab.extendLocatorId("AlertDef"), this.resourceComposite), true, true); - updateSubTab(this.alertsTab, this.alertDelete, - new FullHTMLPane("/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.alertsTab, this.alertHistory, new FullHTMLPane( ++ "/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.alertsTab, this.alertDef, new ResourceAlertDefinitionsView(alertsTab ++ .extendLocatorId("AlertDef"), this.resourceComposite), true, true); ++ updateSubTab(this.alertsTab, this.alertDelete, new FullHTMLPane( ++ "/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()), true, true); + - if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), permissions.isConfigureRead())) { - updateSubTab(this.configurationTab, this.configCurrent, - new ResourceConfigurationEditView(this.extendLocatorId("ResourceConfig"), resource), true, true); - updateSubTab(this.configurationTab, this.configHistory, - ConfigurationHistoryView.getHistoryOf(configurationTab.extendLocatorId("Hist"), resource.getId()), true, true); ++ if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), permissions ++ .isConfigureRead())) { ++ updateSubTab(this.configurationTab, this.configCurrent, new ResourceConfigurationEditView(this ++ .extendLocatorId("ResourceConfig"), resource), true, true); ++ updateSubTab(this.configurationTab, this.configHistory, ConfigurationHistoryView.getHistoryOf( ++ configurationTab.extendLocatorId("Hist"), resource.getId()), true, true); + }
- inventoryTab.setSubTabEnabled(inventoryConn.getLocatorId(), facets - .contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); - ResourceType type = this.resourceComposite.getResource().getResourceType(); - inventoryTab.setSubTabEnabled(inventoryChildren.getLocatorId(), !type.getChildResourceTypes().isEmpty()); + if (updateTab(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT), true)) { - updateSubTab(this.eventsTab, this.eventHistory, - EventCompositeHistoryView.get(resourceComposite), true, true); ++ updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(resourceComposite), true, ++ true); + }
- getTabSet().setTabEnabled(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION)); - getTabSet().setTabEnabled(this.configurationTab, - facets.contains(ResourceTypeFacet.CONFIGURATION) && permissions.isConfigureRead()); - getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); - getTabSet().setTabEnabled(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT)); + if (updateTab(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT), true)) { - updateSubTab(this.contentTab, this.contentDeployed, - new FullHTMLPane("/rhq/resource/content/view-plain.xhtml?id=" + resource.getId()), true, true); - updateSubTab(this.contentTab, this.contentNew, - new FullHTMLPane("/rhq/resource/content/deploy-plain.xhtml?id=" + resource.getId()), true, true); - updateSubTab(this.contentTab, this.contentSubscrip, - new FullHTMLPane("/rhq/resource/content/subscription-plain.xhtml?id=" + resource.getId()), true, true); - updateSubTab(this.contentTab, this.contentHistory, - new FullHTMLPane("/rhq/resource/content/history-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.contentTab, this.contentDeployed, new FullHTMLPane( ++ "/rhq/resource/content/view-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.contentTab, this.contentNew, new FullHTMLPane( ++ "/rhq/resource/content/deploy-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.contentTab, this.contentSubscrip, new FullHTMLPane( ++ "/rhq/resource/content/subscription-plain.xhtml?id=" + resource.getId()), true, true); ++ updateSubTab(this.contentTab, this.contentHistory, new FullHTMLPane( ++ "/rhq/resource/content/history-plain.xhtml?id=" + resource.getId()), true, true); + } }
public Integer getSelectedItemId() { diff --cc modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java index b210e31,4aaf7ca..b81400d --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java @@@ -138,8 -138,8 +138,8 @@@ public class ClusterManagerBean impleme try { // You are allowed to cause the creation of an auto cluster backing group as long as you can // view the parent group. (That check was done above) - resourceGroupManager.setAssignedResources(subjectManager.getOverlord(), autoClusterBackingGroup.getId(), - resourceIds, false); - resourceGroupManager.setMembership(subjectManager.getOverlord(), autoClusterBackingGroup.getId(), - resourceIds, false); ++ resourceGroupManager.setAssignedResources(subjectManager.getOverlord(), ++ autoClusterBackingGroup.getId(), resourceIds, false); } catch (Exception e) { log.error("Could not add resources to group:" + e); } diff --cc modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java index 3acae10,28ae218..0e7500f --- 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 @@@ -1319,40 -1319,6 +1319,39 @@@ public class ResourceGroupManagerBean i } }
+ public void setAssignedResourceGroupsForResource(Subject subject, int resourceId, int[] resourceGroupIds, + boolean setType) throws ResourceGroupDeleteException { + + Resource resource = entityManager.find(Resource.class, resourceId); + Set<ResourceGroup> currentGroups = resource.getExplicitGroups(); + List<Integer> currentGroupIds = new ArrayList<Integer>(currentGroups.size()); + for (ResourceGroup currentGroup : currentGroups) { + currentGroupIds.add(currentGroup.getId()); + } + + int[] resourceIdArr = new int[] { resourceId }; + + List<Integer> addedGroupIds = ArrayUtils.wrapInList(resourceGroupIds); + addedGroupIds.removeAll(currentGroupIds); + for (Integer addedGroupId : addedGroupIds) { + addResourcesToGroup(subject, addedGroupId, resourceIdArr); + // As a result of the membership change ensure that the group type is set correctly. + if (setType) { + setResourceType(addedGroupId); + } + } + + List<Integer> removedGroupIds = new ArrayList<Integer>(currentGroupIds); // groups needing removal + removedGroupIds.removeAll(ArrayUtils.wrapInList(resourceGroupIds)); + for (Integer removedGroupId : removedGroupIds) { + removeResourcesFromGroup(subject, removedGroupId, resourceIdArr); + // As a result of the membership change ensure that the group type is set correctly. + if (setType) { + setResourceType(removedGroupId); + } + } - + } + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Remote interface impl // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
commit c1f4166199695ed25b031074f10cb9a012bacd47 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 21 13:01:56 2010 -0400
don't pluralize subcat names since they're typically already pluralized as defined in the plugin descriptors
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 0862d3a..2516ac5 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 @@ -262,7 +262,8 @@ public class ResourceTreeDatasource extends DataSource { setParentID(parentResourceId); setAttribute("parentId", parentResourceId);
- String name = pluralize(category.getDisplayName()); + // Note, subcategory names are typically already plural, so there's no need to pluralize them. + String name = category.getDisplayName(); setName(name); setAttribute("name", name); } @@ -360,8 +361,15 @@ public class ResourceTreeDatasource extends DataSource { return id.replace(' ', '_'); }
- private static String pluralize(String s) { + private static String pluralize(String singularNoun) { // TODO: Make this smarter. - return s + "s"; + String pluralNoun; + if (singularNoun.endsWith("y") && !singularNoun.endsWith("ay") && !singularNoun.endsWith("ey") && + !singularNoun.endsWith("oy")) { + pluralNoun = singularNoun.substring(0, singularNoun.length() - 1) + "ies"; + } else { + pluralNoun = singularNoun + "s"; + } + return pluralNoun; } }
commit 4d44fd501554dbb58b30b7f561f110953b525dba Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 21 12:41:16 2010 -0400
Group CRUD - initially restrict group membership to group type for compat groups - renamed some new "setAssigned*" SLSB methods for understanding and consistency. (may need to consider these for remote API later) - added new resource inventory subtabs for group view/assignment
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java index 9ea9467..6c86265 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java @@ -160,7 +160,7 @@ public class UserEditView extends LocatableVLayout implements BookmarkableView { roleIds[i++] = id; }
- GWTServiceLookup.getRoleService().setAssignedSubjectRoles(subjectId, roleIds, + GWTServiceLookup.getRoleService().setAssignedRolesForSubject(subjectId, roleIds, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to save user role assignments.", caught); 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 333427f..0951851 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 @@ -48,7 +48,9 @@ public interface ResourceGroupGWTService extends RemoteService {
PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria);
- void setMembership(int groupId, int[] resourceIds, boolean setType); + void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType); + + void setAssignedResources(int groupId, int[] resourceIds, boolean setType);
void updateGroupDefinition(GroupDefinition groupDefinition);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RoleGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RoleGWTService.java index 932ceb8..41d7204 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RoleGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RoleGWTService.java @@ -18,13 +18,12 @@ */ package org.rhq.enterprise.gui.coregui.client.gwt;
-import org.rhq.core.domain.auth.Subject; +import com.google.gwt.user.client.rpc.RemoteService; + import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.criteria.RoleCriteria; import org.rhq.core.domain.util.PageList;
-import com.google.gwt.user.client.rpc.RemoteService; - /** * @author Greg Hinkle */ @@ -42,5 +41,5 @@ public interface RoleGWTService extends RemoteService {
void setAssignedSubjects(int roleId, int[] subjectIds);
- void setAssignedSubjectRoles(int subjectId, int[] roleIds); + void setAssignedRolesForSubject(int subjectId, int[] roleIds); } 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 38d409f..7053f7c 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 @@ -123,4 +123,11 @@ public class ResourceGroupListView extends Table { }); }
+ // -------- Static Utility loaders ------------ + + public static ResourceGroupListView getGroupsOf(String locatorId, int explicitResourceId) { + return new ResourceGroupListView(locatorId, new Criteria("explicitResourceId", String + .valueOf(explicitResourceId)), "Resource Groups"); + } + } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java index 00e9389..20786a0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java @@ -115,6 +115,11 @@ public class ResourceGroupsDataSource extends RPCDataSource<ResourceGroup> { "downMemberCount"))); }
+ if (request.getCriteria().getValues().get("explicitResourceId") != null) { + criteria.addFilterExplicitResourceIds(Integer.parseInt((String) request.getCriteria().getValues().get( + "explicitResourceId"))); + } + return criteria; }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java index e08b57d..48d0859 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java @@ -22,7 +22,6 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.inventory; import java.util.HashSet;
import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; @@ -30,6 +29,7 @@ import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.core.domain.criteria.ResourceGroupCriteria; +import org.rhq.core.domain.resource.group.GroupCategory; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -79,6 +79,7 @@ public class ResourceGroupMembershipView extends LocatableVLayout { ResourceGroupCriteria c = new ResourceGroupCriteria(); c.addFilterId(this.resourceGroupId); c.fetchExplicitResources(true); + c.fetchResourceType(true); GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(c, new AsyncCallback<PageList<ResourceGroup>>() { public void onFailure(Throwable caught) { @@ -86,11 +87,14 @@ public class ResourceGroupMembershipView extends LocatableVLayout { }
public void onSuccess(PageList<ResourceGroup> result) { - ResourceGroupMembershipView.this.resourceGroup = result.get(0); + ResourceGroup group = result.get(0); + ResourceGroupMembershipView.this.resourceGroup = group; ResourceGroupMembershipView.this.selector = new ResourceGroupResourceSelector( - ResourceGroupMembershipView.this.getLocatorId(), ResourceGroupMembershipView.this.resourceGroup - .getExplicitResources()); - ResourceGroupMembershipView.this.selector.setOverflow(Overflow.AUTO); + ResourceGroupMembershipView.this.getLocatorId(), + group.getExplicitResources(), + (GroupCategory.COMPATIBLE == ResourceGroupMembershipView.this.resourceGroup.getGroupCategory()) ? group + .getResourceType() + : null, false);
addMember(ResourceGroupMembershipView.this.selector); } @@ -100,7 +104,7 @@ public class ResourceGroupMembershipView extends LocatableVLayout { private void save() { int[] resourceIds = getSelectedResourceIds();
- GWTServiceLookup.getResourceGroupService().setMembership(this.resourceGroup.getId(), resourceIds, true, + GWTServiceLookup.getResourceGroupService().setAssignedResources(this.resourceGroup.getId(), resourceIds, true, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to update configuration", caught); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java index 6bc96fb..587a8ca 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java @@ -24,9 +24,11 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.inventory;
import java.util.Collection;
+import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDatasource; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector;
@@ -35,11 +37,16 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.Resour */ public class ResourceGroupResourceSelector extends ResourceSelector {
- public ResourceGroupResourceSelector(String locatorId, Collection<Resource> resources) { - super(locatorId); + public ResourceGroupResourceSelector(String locatorId, Collection<Resource> resources, + ResourceType resourceTypeFilter, boolean forceResourceTypeFilter) { + + super(locatorId, resourceTypeFilter, forceResourceTypeFilter); + if (null != resources) { ListGridRecord[] data = (new ResourceDatasource()).buildRecords(resources); setAssigned(data); } + + this.setOverflow(Overflow.AUTO); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index e80be32..8e73379 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -44,11 +44,13 @@ 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.ResourceGroupListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.InventoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration.ConfigurationHistoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration.ResourceConfigurationEditView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory.PluginConfigurationEditView; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory.ResourceResourceGroupsView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.GraphListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.schedules.SchedulesView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.traits.TraitsView; @@ -91,6 +93,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo private SubTab monitorCallTime; private SubTab inventoryChildren; private SubTab inventoryConn; + private SubTab inventoryGroups; + private SubTab inventoryGroupMembership; private SubTab opHistory; private SubTab opSched; private SubTab alertHistory; @@ -135,7 +139,10 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo "/images/icons/Inventory_grey_16.png"); inventoryChildren = new SubTab(inventoryTab.extendLocatorId("Children"), "Children", null); inventoryConn = new SubTab(inventoryTab.extendLocatorId("ConnectionSettings"), "Connection Settings", null); - inventoryTab.registerSubTabs(this.inventoryChildren, this.inventoryConn); + inventoryGroups = new SubTab(inventoryTab.extendLocatorId("Groups"), "Groups", null); + inventoryGroupMembership = new SubTab(inventoryTab.extendLocatorId("GroupMembership"), "Group Membership", null); + inventoryTab.registerSubTabs(this.inventoryChildren, this.inventoryConn, this.inventoryGroups, + this.inventoryGroupMembership); tabs.add(inventoryTab);
operationsTab = new TwoLevelTab(getTabSet().extendLocatorId("Operations"), "Operations", @@ -207,9 +214,14 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()));
- this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(this.extendLocatorId("Children"), resource - .getId())); - this.inventoryConn.setCanvas(new PluginConfigurationEditView(this.extendLocatorId("PluginConfig"), resource)); + this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(this.inventoryTab + .extendLocatorId("ChildrenView"), resource.getId())); + this.inventoryConn.setCanvas(new PluginConfigurationEditView(this.inventoryTab + .extendLocatorId("PluginConfigView"), resource)); + this.inventoryGroups.setCanvas(ResourceGroupListView.getGroupsOf(this.inventoryTab + .extendLocatorId("GroupsView"), resource.getId())); + this.inventoryGroupMembership.setCanvas(new ResourceResourceGroupsView(this.inventoryTab + .extendLocatorId("GroupMembershipView"), resourceId));
// comment out GWT-based operation history until... // 1) user can delete history if they possess the appropriate permissions diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupSelector.java new file mode 100644 index 0000000..6a178ea --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupSelector.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, 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.inventory.resource.detail.inventory; + +import java.util.Collection; + +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupsDataSource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceGroupSelector; + +/** + * @author Jay Shaughnessy + */ +public class ResourceResourceGroupSelector extends ResourceGroupSelector { + + public ResourceResourceGroupSelector(String locatorId, Collection<ResourceGroup> resourceGroups) { + + super(locatorId); + + if (null != resourceGroups) { + ListGridRecord[] data = (new ResourceGroupsDataSource()).buildRecords(resourceGroups); + setAssigned(data); + } + + this.setOverflow(Overflow.AUTO); + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupsView.java new file mode 100644 index 0000000..8669142 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceGroupsView.java @@ -0,0 +1,125 @@ +/* + * 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.inventory; + +import java.util.HashSet; + +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 com.smartgwt.client.widgets.layout.LayoutSpacer; +import com.smartgwt.client.widgets.toolbar.ToolStrip; + +import org.rhq.core.domain.criteria.ResourceCriteria; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * @author Jay Shaughnessy + */ +public class ResourceResourceGroupsView extends LocatableVLayout { + + private int resourceId; + private Resource resource; + private ResourceResourceGroupSelector selector; + + public ResourceResourceGroupsView(String locatorId, int resourceId) { + super(locatorId); + + this.resourceId = resourceId; + } + + @Override + protected void onDraw() { + super.onDraw(); + + build(); + } + + public void build() { + ToolStrip toolStrip = new ToolStrip(); + toolStrip.setWidth100(); + + toolStrip.addMember(new LayoutSpacer()); + + IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + saveButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + save(); + } + }); + + toolStrip.addMember(saveButton); + this.addMember(toolStrip); + + ResourceCriteria c = new ResourceCriteria(); + c.addFilterId(this.resourceId); + c.fetchExplicitGroups(true); + GWTServiceLookup.getResourceService().findResourcesByCriteria(c, new AsyncCallback<PageList<Resource>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch Resource's Groups", caught); + } + + public void onSuccess(PageList<Resource> result) { + resource = result.get(0); + ResourceResourceGroupsView.this.selector = new ResourceResourceGroupSelector( + ResourceResourceGroupsView.this.getLocatorId(), resource.getExplicitGroups()); + + addMember(ResourceResourceGroupsView.this.selector); + } + }); + } + + private void save() { + int[] resourceGroupIds = getSelectedResourceGroupIds(); + + GWTServiceLookup.getResourceGroupService().setAssignedResourceGroupsForResource(this.resource.getId(), + resourceGroupIds, true, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to update configuration", caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Group membership updated for [" + + ResourceResourceGroupsView.this.resource.getName() + "]", Message.Severity.Info)); + CoreGUI.refresh(); + } + }); + } + + private int[] getSelectedResourceGroupIds() { + int[] selection = new int[this.selector.getSelection().size()]; + HashSet<Integer> selectedIds = this.selector.getSelection(); + int i = 0; + for (Integer id : selectedIds) { + selection[i++] = id; + } + + return selection; + } + +} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java index b1ad07f..0047b1f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java @@ -47,28 +47,29 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; */ public class ResourceSelector extends AbstractSelector<Resource> {
- private ResourceType requireType; + private ResourceType resourceTypeFilter; + private boolean forceResourceTypeFilter; + private IPickTreeItem typeSelectItem;
public ResourceSelector(String locatorId) { - super(locatorId); - } - - public ResourceType getRequireType() { - return requireType; + this(locatorId, null, false); }
- public void setRequireType(ResourceType requireType) { - this.requireType = requireType; - markForRedraw(); + public ResourceSelector(String locatorId, ResourceType resourceTypeFilter, boolean forceResourceTypeFilter) { + super(locatorId); + this.resourceTypeFilter = resourceTypeFilter; + this.forceResourceTypeFilter = forceResourceTypeFilter; }
protected DynamicForm getAvailableFilterForm() { if (null == availableFilterForm) { availableFilterForm = new LocatableDynamicForm("ResSelectAvailFilterForm"); availableFilterForm.setNumCols(6); + availableFilterForm.setWidth("75%"); final TextItem search = new TextItem("search", "Search"); + final SelectItem categorySelect;
- IPickTreeItem typeSelectItem = new IPickTreeItem("type", "Type"); + typeSelectItem = new IPickTreeItem("type", "Type"); typeSelectItem.setDataSource(new ResourceTypePluginTreeDataSource()); typeSelectItem.setValueField("id"); typeSelectItem.setCanSelectParentItems(true); @@ -76,22 +77,15 @@ public class ResourceSelector extends AbstractSelector<Resource> { typeSelectItem.setEmptyMenuMessage("Loading..."); typeSelectItem.setShowIcons(true);
- if (requireType != null) { - // TODO: Currently ignore the typeSelectItem widget because we already know the type. - // Alternatively, we could display it disabled but we'd want the type name to be displayed as the - // value. To get this to display the type name I think we need to pre-fetch the type tree here. We could - // potentially optimize typeSelectItem.setValue(requireType.getId()) to buildNodes a tree that includes only - // this single type. - //typeSelectItem.setValue(requireType.getId()); - //typeSelectItem.setDisabled(true); - availableFilterForm.setItems(search); - } else { - SelectItem categorySelect = new SelectItem("category", "Category"); - categorySelect.setValueMap("Platform", "Server", "Service"); - categorySelect.setAllowEmptyValue(true); - - availableFilterForm.setItems(search, typeSelectItem, categorySelect); + if (this.forceResourceTypeFilter) { + typeSelectItem.setDisabled(true); } + + categorySelect = new SelectItem("category", "Category"); + categorySelect.setValueMap("Platform", "Server", "Service"); + categorySelect.setAllowEmptyValue(true); + + availableFilterForm.setItems(search, categorySelect, typeSelectItem); }
return availableFilterForm; @@ -173,13 +167,15 @@ public class ResourceSelector extends AbstractSelector<Resource> {
@Override protected ResourceCriteria getFetchCriteria(final DSRequest request) { - ResourceCriteria result = super.getFetchCriteria(request); - - // additional filters - if (null != requireType) { - result.addFilterResourceTypeId(requireType.getId()); + // if specified seed with an initial type filter + if (null != ResourceSelector.this.resourceTypeFilter) { + ResourceSelector.this.typeSelectItem.setValue(resourceTypeFilter.getId()); + request.getCriteria().addCriteria(TYPE.propertyName(), String.valueOf(resourceTypeFilter.getId())); + ResourceSelector.this.resourceTypeFilter = null; }
+ ResourceCriteria result = super.getFetchCriteria(request); + // additional return data result.fetchResourceType(true);
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 b9642d6..8655bd8 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 @@ -71,9 +71,17 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void setMembership(int groupId, int[] resourceIds, boolean setType) { + public void setAssignedResources(int groupId, int[] resourceIds, boolean setType) { try { - groupManager.setMembership(getSessionSubject(), groupId, resourceIds, setType); + groupManager.setAssignedResources(getSessionSubject(), groupId, resourceIds, setType); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } + } + + public void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType) { + try { + groupManager.setAssignedResources(getSessionSubject(), resourceId, resourceGroupIds, setType); } catch (Throwable t) { throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } @@ -83,7 +91,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen try { Subject user = getSessionSubject(); group = groupManager.createResourceGroup(user, group); - groupManager.setMembership(user, group.getId(), resourceIds, true); + groupManager.setAssignedResources(user, group.getId(), resourceIds, true); return SerialUtility.prepare(group, "ResourceGroupService.createResourceGroup"); } catch (Throwable t) { throw new RuntimeException(ThrowableUtil.getAllMessages(t)); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java index 87d9132..7b278e1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java @@ -18,7 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
-import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.criteria.RoleCriteria; import org.rhq.core.domain.util.PageList; @@ -34,20 +33,17 @@ public class RoleGWTServiceImpl extends AbstractGWTServiceImpl implements RoleGW
private RoleManagerLocal roleManager = LookupUtil.getRoleManager();
- public PageList<Role> findRolesByCriteria(RoleCriteria criteria) { return SerialUtility.prepare(roleManager.findRolesByCriteria(getSessionSubject(), criteria), - "RoleService.findRolesByCriteria"); + "RoleService.findRolesByCriteria"); }
public Role createRole(Role role) { - return SerialUtility.prepare(roleManager.createRole(getSessionSubject(), role), - "RoleService.createRole"); + return SerialUtility.prepare(roleManager.createRole(getSessionSubject(), role), "RoleService.createRole"); }
public Role updateRole(Role role) { - return SerialUtility.prepare(roleManager.updateRole(getSessionSubject(), role), - "RoleService.updateRole"); + return SerialUtility.prepare(roleManager.updateRole(getSessionSubject(), role), "RoleService.updateRole"); }
public void removeRoles(Integer[] roleIds) { @@ -62,8 +58,7 @@ public class RoleGWTServiceImpl extends AbstractGWTServiceImpl implements RoleGW roleManager.setAssignedSubjects(getSessionSubject(), roleId, subjectIds); }
- - public void setAssignedSubjectRoles(int subjectId, int[] roleIds) { + public void setAssignedRolesForSubject(int subjectId, int[] roleIds) { roleManager.setAssignedSubjectRoles(getSessionSubject(), subjectId, roleIds); } } \ 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 ce68440..c9b4420 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 @@ -721,7 +721,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage // This ensures Hibernate actually fetches the parent Resource. grandchildResource.getParentResource().getId(); } - } + } }
return result; @@ -2126,7 +2126,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage @SuppressWarnings("unchecked") public PageList<Resource> findResourcesByCriteria(Subject subject, ResourceCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ; + if (authorizationManager.isInventoryManager(subject) == false) { if (criteria.isInventoryManagerRequired()) { throw new PermissionException("Subject [" + subject.getName() @@ -2138,8 +2138,8 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage }
CriteriaQueryRunner<Resource> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); - - return queryRunner.execute(); + PageList<Resource> results = queryRunner.execute(); + return results; }
public Resource getPlaformOfResource(Subject subject, int resourceId) { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java index 4aaf7ca..b210e31 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java @@ -138,7 +138,7 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe try { // You are allowed to cause the creation of an auto cluster backing group as long as you can // view the parent group. (That check was done above) - resourceGroupManager.setMembership(subjectManager.getOverlord(), autoClusterBackingGroup.getId(), + resourceGroupManager.setAssignedResources(subjectManager.getOverlord(), autoClusterBackingGroup.getId(), resourceIds, false); } catch (Exception e) { log.error("Could not add resources to group:" + e); 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 28ae218..3acae10 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 @@ -1296,9 +1296,9 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso return groupIds; }
- public void setMembership(Subject subject, int groupId, int[] resourceIds, boolean setType) + public void setAssignedResources(Subject subject, int groupId, int[] resourceIds, boolean setType) throws ResourceGroupDeleteException { - //throws ResourceGroupUpdateException { + List<Integer> currentMembers = resourceManager.findExplicitResourceIdsByResourceGroup(groupId);
List<Integer> newMembers = ArrayUtils.wrapInList(resourceIds); // members needing addition @@ -1319,6 +1319,40 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso } }
+ public void setAssignedResourceGroupsForResource(Subject subject, int resourceId, int[] resourceGroupIds, + boolean setType) throws ResourceGroupDeleteException { + + Resource resource = entityManager.find(Resource.class, resourceId); + Set<ResourceGroup> currentGroups = resource.getExplicitGroups(); + List<Integer> currentGroupIds = new ArrayList<Integer>(currentGroups.size()); + for (ResourceGroup currentGroup : currentGroups) { + currentGroupIds.add(currentGroup.getId()); + } + + int[] resourceIdArr = new int[] { resourceId }; + + List<Integer> addedGroupIds = ArrayUtils.wrapInList(resourceGroupIds); + addedGroupIds.removeAll(currentGroupIds); + for (Integer addedGroupId : addedGroupIds) { + addResourcesToGroup(subject, addedGroupId, resourceIdArr); + // As a result of the membership change ensure that the group type is set correctly. + if (setType) { + setResourceType(addedGroupId); + } + } + + List<Integer> removedGroupIds = new ArrayList<Integer>(currentGroupIds); // groups needing removal + removedGroupIds.removeAll(ArrayUtils.wrapInList(resourceGroupIds)); + for (Integer removedGroupId : removedGroupIds) { + removeResourcesFromGroup(subject, removedGroupId, resourceIdArr); + // As a result of the membership change ensure that the group type is set correctly. + if (setType) { + setResourceType(removedGroupId); + } + } + + } + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Remote interface impl // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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 45f7cc4..de96dbf 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 @@ -118,7 +118,23 @@ public interface ResourceGroupManagerLocal { * @throws ResourceGroupUpdateException * @throws ResourceGroupDeleteException */ - void setMembership(Subject subject, int groupId, int[] resourceIds, boolean setType) + void setAssignedResources(Subject subject, int groupId, int[] resourceIds, boolean setType) + throws ResourceGroupUpdateException, ResourceGroupDeleteException; + + /** + * This method ensures that the resource will have exactly the specified set of explicit group + * membership. Make sure you pass the correct value for the <setType> parameter. + * + * @param subject + * @param resourceId + * @param resourceGroupIds + * @param setType Set to false if addition or removal of the specified resourceId will not alter the group + * type for the specified resource groups (compatible or mixed). Set true to have the group type + * (re)set automatically, based on the new group membership. + * @throws ResourceGroupUpdateException + * @throws ResourceGroupDeleteException + */ + void setAssignedResourceGroupsForResource(Subject subject, int groupId, int[] resourceIds, boolean setType) throws ResourceGroupUpdateException, ResourceGroupDeleteException;
void uninventoryMembers(Subject subject, int groupId);
commit fe4cc406e8b82ba6b8d78d9e0d22440ebbaa432b Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 21 11:15:06 2010 -0400
tabs/subtabs that are not applicable to a Resource or group's type are no longer shown; tabs/subtabs that are not available due to lack of authz permissions are grayed out / disabled
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java index 1739a35..1d6134b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTab.java @@ -21,12 +21,14 @@ package org.rhq.enterprise.gui.coregui.client.components.tab;
import com.smartgwt.client.widgets.Canvas;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable; + /** * Simple class to provide a SubTab a locatorId. * * @author Jay Shaughnessy */ -public class SubTab { +public class SubTab implements Locatable { private String locatorId; private String title; private Canvas canvas; @@ -54,6 +56,11 @@ public class SubTab { }
@Override + public String extendLocatorId(String extension) { + return this.locatorId + "_" + extension; + } + + @Override public String toString() { return "SubTab[title=" + this.title + ", locatorId=" + this.locatorId + "]"; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java index 741d931..0005436 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java @@ -155,7 +155,9 @@ public class SubTabLayout extends LocatableVLayout { }
public void unregisterAllSubTabs() { + destroyViews(); subtabs.clear(); + markForRedraw(); }
public void registerSubTab(SubTab subTab) { @@ -167,6 +169,21 @@ public class SubTabLayout extends LocatableVLayout { subtabs.put(locatorId, subTab); }
+ public void setVisible(SubTab subTab, boolean visible) { + Button button = this.subTabButtons.get(subTab.getLocatorId()); + if (visible) { + if (!button.isVisible()) { + button.show(); + markForRedraw(); + } + } else { + if (button.isVisible()) { + button.hide(); + markForRedraw(); + } + } + } + public SubTab getDefaultSubTab() { // the default subtab is the first one in the set that is not disabled for (SubTab subtab : this.subtabs.values()) { @@ -218,6 +235,16 @@ public class SubTabLayout extends LocatableVLayout { return null; }
+ public SubTab getSubTabByLocatorId(String locatorId) { + for (String subtabLocatorId : this.subtabs.keySet()) { + if (subtabLocatorId.equals(locatorId)) { + return this.subtabs.get(subtabLocatorId); + } + } + + return null; + } + public boolean selectSubTabByTitle(String title) { SubTab subtab = getSubTabByTitle(title); if (subtab == null) { @@ -264,6 +291,7 @@ public class SubTabLayout extends LocatableVLayout { for (SubTab subtab : subtabs.values()) { if (subtab.getCanvas() != null) { subtab.getCanvas().destroy(); + subtab.setCanvas(null); } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java index 6258e9e..cbb6370 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTab.java @@ -44,6 +44,10 @@ public class TwoLevelTab extends LocatableTab { } }
+ public void setVisible(SubTab subTab, boolean visible) { + layout.setVisible(subTab, visible); + } + public void setSubTabEnabled(String locatorId, boolean enabled) { if (enabled) { layout.enableSubTab(locatorId); @@ -56,6 +60,10 @@ public class TwoLevelTab extends LocatableTab { return this.layout.getSubTabByTitle(title); }
+ public SubTab getSubTabByLocatorId(String locatorId) { + return this.layout.getSubTabByLocatorId(locatorId); + } + public SubTab getDefaultSubTab() { return this.layout.getDefaultSubTab(); } 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 bdd1981..8f7452c 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 @@ -87,6 +87,33 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo return this.titleBar; }
+ protected boolean updateTab(TwoLevelTab tab, boolean visible, boolean enabled) { + TwoLevelTab attachedTab = getTabSet().getTabByLocatorId(tab.getLocatorId()); + if (visible) { + if (attachedTab == null) { + getTabSet().addTab(tab); + attachedTab = getTabSet().getTabByLocatorId(tab.getLocatorId()); + } + getTabSet().setTabEnabled(attachedTab, enabled); + } else { + if (attachedTab != null) { + getTabSet().removeTab(attachedTab); + } + } + + return enabled; + } + + protected void updateSubTab(TwoLevelTab tab, SubTab subTab, Canvas canvas, boolean visible, boolean enabled) { + tab.setVisible(subTab, visible); + if (visible) { + tab.setSubTabEnabled(subTab.getLocatorId(), enabled); + if (enabled) { + subTab.setCanvas(canvas); + } + } + } + public void onTabSelected(TwoLevelTabSelectedEvent tabSelectedEvent) { //CoreGUI.printWidgetTree();
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 6603a00..f085e9b 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 @@ -56,6 +56,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTyp * Be able to view members as a resource list, or edit members via selector. * * @author Jay Shaughnessy + * @author Ian Springer */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { private static final String BASE_VIEW_PATH = "ResourceGroup"; @@ -177,84 +178,82 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
protected void updateTabContent(ResourceGroupComposite groupComposite) { this.groupComposite = groupComposite; - - getTitleBar().setGroup(groupComposite.getResourceGroup()); + ResourceGroup group = groupComposite.getResourceGroup(); + int groupId = group.getId(); + getTitleBar().setGroup(group);
for (Tab top : this.getTabSet().getTabs()) { ((TwoLevelTab) top).getLayout().destroyViews(); }
+ GroupCategory groupCategory = groupComposite.getResourceGroup().getGroupCategory(); + Set<ResourceTypeFacet> facets = groupComposite.getResourceFacets().getFacets(); + // FullHTMLPane timelinePane = new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()); // summaryTab.updateSubTab("Overview", new DashboardView(resource)); // summaryTab.updateSubTab("Timeline", timelinePane); - this.summaryOverview.setCanvas(new OverviewView(this.summaryTab.extendLocatorId("Overview"), - this.groupComposite)); - - int groupId = this.groupComposite.getResourceGroup().getId(); - - this.monitorGraphs.setCanvas(new FullHTMLPane("/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId)); - this.monitorTables.setCanvas(new FullHTMLPane("/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId)); - this.monitorTraits.setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), groupId)); - this.monitorSched.setCanvas(new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId)); - this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId)); + // Summary tab is always visible and enabled. + updateSubTab(this.summaryTab, this.summaryOverview, + new OverviewView(this.summaryTab.extendLocatorId("Overview"), this.groupComposite), true, true); + + if (updateTab(this.monitoringTab, groupCategory == GroupCategory.COMPATIBLE, true)) { + updateSubTab(this.monitoringTab, this.monitorGraphs, + new FullHTMLPane("/rhq/group/monitor/graphs-plain.xhtml?groupId=" + groupId), + hasMetricsOfType(this.groupComposite, DataType.MEASUREMENT), true); + updateSubTab(this.monitoringTab, this.monitorTables, + new FullHTMLPane("/rhq/group/monitor/tables-plain.xhtml?groupId=" + groupId), + hasMetricsOfType(this.groupComposite, DataType.MEASUREMENT), true); + updateSubTab(this.monitoringTab, this.monitorTraits, + new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), groupId), + hasMetricsOfType(this.groupComposite, DataType.TRAIT), true); + updateSubTab(this.monitoringTab, this.monitorSched, + new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId), + hasMetricsOfType(this.groupComposite, null), true); + updateSubTab(this.monitoringTab, this.monitorCallTime, + new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId), + facets.contains(ResourceTypeFacet.CALL_TIME), true); + // TODO (ips): Add Availability subtab. + }
- this.inventoryMembers.setCanvas(ResourceSearchView.getMembersOf(this.inventoryTab - .extendLocatorId("MembersView"), groupId)); + // Inventory tab is always visible and enabled. + updateSubTab(this.inventoryTab, this.inventoryMembers, + ResourceSearchView.getMembersOf(this.inventoryMembers.extendLocatorId("View"), groupId), true, true); // TODO: Uncomment this once the group config component is done. - //this.inventoryConn.setCanvas(new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin)); - this.inventoryMembership.setCanvas(new ResourceGroupMembershipView(this.inventoryTab - .extendLocatorId("MembershipView"), groupId)); - - this.opHistory.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" - + groupId)); - this.opSched.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationSchedules-plain.xhtml?groupId=" - + groupId)); - - this.alertHistory.setCanvas(new FullHTMLPane("/rhq/group/alert/listGroupAlertHistory-plain.xhtml?groupId=" - + groupId)); - this.alertDef.setCanvas(new FullHTMLPane("/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" - + groupId)); - - this.configCurrent.setCanvas(new FullHTMLPane("/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" - + groupId)); - this.configHistory - .setCanvas(new FullHTMLPane("/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId)); - - this.eventHistory.setCanvas(EventCompositeHistoryView.get(groupComposite)); - - updateTabEnablement(); - } - - private void updateTabEnablement() { - GroupCategory groupCategory = groupComposite.getResourceGroup().getGroupCategory(); - Set<ResourceTypeFacet> facets = groupComposite.getResourceFacets().getFacets(); - - // Summary and Inventory tabs are always enabled. - - // Only enable "Call Time" and "Traits" subtabs for groups that implement them. - this.monitoringTab.setSubTabEnabled(this.monitorTraits.getLocatorId(), hasTraits(this.groupComposite)); - this.monitoringTab.setSubTabEnabled(this.monitorCallTime.getLocatorId(), facets - .contains(ResourceTypeFacet.CALL_TIME)); - - // Inventory>Connection Settings subtab is only enabled for compat groups that define conn props. - this.inventoryTab.setSubTabEnabled(this.inventoryConn.getLocatorId(), groupCategory == GroupCategory.COMPATIBLE - && facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); - - // Monitoring and Alerts tabs are always enabled for compatible groups and always disabled for mixed groups. - // TODO (ips): Break out mixed groups into a separate view. - getTabSet().setTabEnabled(this.monitoringTab, groupCategory == GroupCategory.COMPATIBLE); - getTabSet().setTabEnabled(this.alertsTab, groupCategory == GroupCategory.COMPATIBLE); + //updateSubTab(this.inventoryTab, this.inventoryConn, + // new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin), + // facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), true); + updateSubTab(this.inventoryTab, this.inventoryMembership, + new ResourceGroupMembershipView(this.inventoryTab.extendLocatorId("MembershipView"), groupId), true, true); + + if (updateTab(this.operationsTab, + groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.OPERATION), true)) { + updateSubTab(this.operationsTab, this.opHistory, + new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" + groupId), true, true); + updateSubTab(this.operationsTab, this.opSched, + new FullHTMLPane("/rhq/group/operation/groupOperationSchedules-plain.xhtml?groupId=" + groupId), true, true); + }
- // Operations tab is only enabled for compatible groups of a type that supports the Operations facet. - getTabSet().setTabEnabled(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION)); + if (updateTab(this.operationsTab, groupCategory == GroupCategory.COMPATIBLE, true)) { + updateSubTab(this.alertsTab, this.alertHistory, + new FullHTMLPane("/rhq/group/alert/listGroupAlertHistory-plain.xhtml?groupId=" + groupId), true, true); + updateSubTab(this.alertsTab, this.alertDef, + new FullHTMLPane("/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" + groupId), true, true); + }
- // Configuration tab is only enabled for compatible groups of a type that supports the Configuration facet - // and when the current user has the CONFIGURE_READ permission. - getTabSet().setTabEnabled(this.configurationTab, - facets.contains(ResourceTypeFacet.CONFIGURATION) && this.permissions.isConfigureRead()); + if (updateTab(this.configurationTab, + groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.CONFIGURATION), + this.permissions.isConfigureRead())) { + updateSubTab(this.configurationTab, this.configCurrent, + new FullHTMLPane("/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" + groupId), true, true); + updateSubTab(this.configurationTab, this.configHistory, + new FullHTMLPane("/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId), true, true); + }
- // Events tab is only enabled for compatible groups of a type that supports the Events facet. - getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); + if (updateTab(this.eventsTab, + groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.EVENT), true)) { + updateSubTab(this.eventsTab, this.eventHistory, + EventCompositeHistoryView.get(groupComposite), true, true); + } }
protected void loadSelectedItem(final int groupId, final ViewPath viewPath) { @@ -313,12 +312,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource } }
- private static boolean hasTraits(ResourceGroupComposite groupComposite) { + private static boolean hasMetricsOfType(ResourceGroupComposite groupComposite, DataType dataType) { ResourceType type = groupComposite.getResourceGroup().getResourceType(); if (type != null) { Set<MeasurementDefinition> metricDefs = type.getMetricDefinitions(); for (MeasurementDefinition metricDef : metricDefs) { - if (metricDef.getDataType() == DataType.TRAIT) { + if (dataType == null || metricDef.getDataType() == dataType) { return true; } } @@ -332,5 +331,4 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource currentSubTab = subtabTitle; super.selectTab(tabTitle, subtabTitle, viewPath); } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index e80be32..88dd2f9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -182,95 +182,99 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo
protected void updateTabContent(ResourceComposite resourceComposite) { this.resourceComposite = resourceComposite; - - final Resource resource = this.resourceComposite.getResource(); + Resource resource = this.resourceComposite.getResource(); getTitleBar().setResource(resource);
for (Tab top : this.getTabSet().getTabs()) { ((TwoLevelTab) top).getLayout().destroyViews(); }
- this.summaryOverview.setCanvas(new OverviewView(this.summaryTab.extendLocatorId("OverviewView"), - this.resourceComposite)); - this.summaryDashboard.setCanvas(new DashboardView(this.resourceComposite)); - this.summaryTimeline.setCanvas(new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" - + resource.getId())); - - this.monitorGraphs.setCanvas(new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource)); - this.monitorTables.setCanvas(new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId())); - this.monitorTraits - .setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId())); - this.monitorAvail.setCanvas(new FullHTMLPane("/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" - + resource.getId())); - this.monitorSched - .setCanvas(new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId())); - this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" - + resource.getId())); - - this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(this.extendLocatorId("Children"), resource - .getId())); - this.inventoryConn.setCanvas(new PluginConfigurationEditView(this.extendLocatorId("PluginConfig"), resource)); - - // comment out GWT-based operation history until... - // 1) user can delete history if they possess the appropriate permissions - // 2) user can see both operation arguments and results in the history details pop-up - // 3) operation arguments/results become read-only configuration data in the history details pop-up - // 4) user can navigate to the group operation that spawned this resource operation history, if appropriate - // note: enabled operation execution/schedules from left-nav, if it doesn't already exist - this.opHistory.setCanvas(OperationHistoryView.getResourceHistoryView(operationsTab.extendLocatorId("History"), - resourceComposite)); - this.opSched.setCanvas(new FullHTMLPane("/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" - + resource.getId())); + ResourcePermission permissions = this.resourceComposite.getResourcePermission(); + Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets(); + + updateSubTab(this.summaryTab, this.summaryOverview, + new OverviewView(this.summaryOverview.getLocatorId(), this.resourceComposite), true, true); + updateSubTab(this.summaryTab, this.summaryDashboard, + new DashboardView(this.resourceComposite), true, true); + updateSubTab(this.summaryTab, this.summaryTimeline, + new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()), true, true); + + updateSubTab(this.monitoringTab, this.monitorGraphs, + new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource), + hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT), true); + updateSubTab(this.monitoringTab, this.monitorTables, + new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId()), + hasMetricsOfType(this.resourceComposite, DataType.MEASUREMENT), true); + updateSubTab(this.monitoringTab, this.monitorTraits, + new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId()), + hasMetricsOfType(this.resourceComposite, DataType.TRAIT), true); + updateSubTab(this.monitoringTab, this.monitorAvail, + new FullHTMLPane("/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId()), true, + true); + updateSubTab(this.monitoringTab, this.monitorSched, + new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId()), + hasMetricsOfType(this.resourceComposite, null), true); + updateSubTab(this.monitoringTab, this.monitorCallTime, + new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()), + facets.contains(ResourceTypeFacet.CALL_TIME), true); + + ResourceType type = this.resourceComposite.getResource().getResourceType(); + updateSubTab(this.inventoryTab, this.inventoryChildren, + ResourceSearchView.getChildrenOf(this.extendLocatorId("Children"), resource.getId()), + !type.getChildResourceTypes().isEmpty(), true); + updateSubTab(this.inventoryTab, this.inventoryConn, + new PluginConfigurationEditView(this.extendLocatorId("PluginConfig"), resource), + facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION), true); + + if (updateTab(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION), true)) { + // comment out GWT-based operation history until... + // 1) user can delete history if they possess the appropriate permissions + // 2) user can see both operation arguments and results in the history details pop-up + // 3) operation arguments/results become read-only configuration data in the history details pop-up + // 4) user can navigate to the group operation that spawned this resource operation history, if appropriate + // note: enabled operation execution/schedules from left-nav, if it doesn't already exist + updateSubTab(this.operationsTab, this.opHistory, + OperationHistoryView.getResourceHistoryView(operationsTab.extendLocatorId("History"), this.resourceComposite), + true, true); + updateSubTab(this.operationsTab, this.opSched, + new FullHTMLPane("/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" + resource.getId()), + true, true); + }
// comment out GWT-based alert definitions/history views until... // 1) new workflow is implement for alert definition creation, with particular attention to interaction model for alert notifications // 2) user can delete/ack/purgeAll alerts if they possess the appropriate permissions // 3) user can enable/disable/delete alert definitions if they possess the appropriate permissions // 4) user can search alert history by: date alert was fired, alert priority, or alert definition - this.alertHistory.setCanvas(new FullHTMLPane("/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" - + resource.getId())); - this.alertDef.setCanvas(new ResourceAlertDefinitionsView(alertsTab.extendLocatorId("AlertDef"), - resourceComposite)); - this.alertDelete.setCanvas(new FullHTMLPane("/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" - + resource.getId())); - - this.configCurrent - .setCanvas(new ResourceConfigurationEditView(this.extendLocatorId("ResourceConfig"), resource)); - this.configHistory.setCanvas(ConfigurationHistoryView.getHistoryOf(configurationTab.extendLocatorId("Hist"), - resource.getId())); - - this.eventHistory.setCanvas(EventCompositeHistoryView.get(resourceComposite)); - - this.contentDeployed - .setCanvas(new FullHTMLPane("/rhq/resource/content/view-plain.xhtml?id=" + resource.getId())); - this.contentNew.setCanvas(new FullHTMLPane("/rhq/resource/content/deploy-plain.xhtml?id=" + resource.getId())); - this.contentSubscrip.setCanvas(new FullHTMLPane("/rhq/resource/content/subscription-plain.xhtml?id=" - + resource.getId())); - this.contentHistory.setCanvas(new FullHTMLPane("/rhq/resource/content/history-plain.xhtml?id=" - + resource.getId())); - - updateTabEnablement(); - } - - private void updateTabEnablement() { - ResourcePermission permissions = this.resourceComposite.getResourcePermission(); - Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets(); - - // Summary, Monitoring, Inventory, and Alerts tabs are always enabled. - - monitoringTab.setSubTabEnabled(monitorTraits.getLocatorId(), hasTraits(this.resourceComposite)); - monitoringTab.setSubTabEnabled(monitorCallTime.getLocatorId(), facets.contains(ResourceTypeFacet.CALL_TIME)); + updateSubTab(this.alertsTab, this.alertHistory, + new FullHTMLPane("/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" + resource.getId()), true, true); + updateSubTab(this.alertsTab, this.alertDef, + new ResourceAlertDefinitionsView(alertsTab.extendLocatorId("AlertDef"), this.resourceComposite), true, true); + updateSubTab(this.alertsTab, this.alertDelete, + new FullHTMLPane("/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()), true, true); + + if (updateTab(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION), permissions.isConfigureRead())) { + updateSubTab(this.configurationTab, this.configCurrent, + new ResourceConfigurationEditView(this.extendLocatorId("ResourceConfig"), resource), true, true); + updateSubTab(this.configurationTab, this.configHistory, + ConfigurationHistoryView.getHistoryOf(configurationTab.extendLocatorId("Hist"), resource.getId()), true, true); + }
- inventoryTab.setSubTabEnabled(inventoryConn.getLocatorId(), facets - .contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); - ResourceType type = this.resourceComposite.getResource().getResourceType(); - inventoryTab.setSubTabEnabled(inventoryChildren.getLocatorId(), !type.getChildResourceTypes().isEmpty()); + if (updateTab(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT), true)) { + updateSubTab(this.eventsTab, this.eventHistory, + EventCompositeHistoryView.get(resourceComposite), true, true); + }
- getTabSet().setTabEnabled(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION)); - getTabSet().setTabEnabled(this.configurationTab, - facets.contains(ResourceTypeFacet.CONFIGURATION) && permissions.isConfigureRead()); - getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); - getTabSet().setTabEnabled(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT)); + if (updateTab(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT), true)) { + updateSubTab(this.contentTab, this.contentDeployed, + new FullHTMLPane("/rhq/resource/content/view-plain.xhtml?id=" + resource.getId()), true, true); + updateSubTab(this.contentTab, this.contentNew, + new FullHTMLPane("/rhq/resource/content/deploy-plain.xhtml?id=" + resource.getId()), true, true); + updateSubTab(this.contentTab, this.contentSubscrip, + new FullHTMLPane("/rhq/resource/content/subscription-plain.xhtml?id=" + resource.getId()), true, true); + updateSubTab(this.contentTab, this.contentHistory, + new FullHTMLPane("/rhq/resource/content/history-plain.xhtml?id=" + resource.getId()), true, true); + } }
public Integer getSelectedItemId() { @@ -324,11 +328,11 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo }); }
- private static boolean hasTraits(ResourceComposite resourceComposite) { + private static boolean hasMetricsOfType(ResourceComposite resourceComposite, DataType dataType) { ResourceType type = resourceComposite.getResource().getResourceType(); Set<MeasurementDefinition> metricDefs = type.getMetricDefinitions(); for (MeasurementDefinition metricDef : metricDefs) { - if (metricDef.getDataType() == DataType.TRAIT) { + if (dataType == null || metricDef.getDataType() == dataType) { return true; } }
commit 31a27cb1807ea2e0ae258d996ce968ec0f730135 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 21 11:10:38 2010 -0400
comment out some code that was causing the following unit test failure:
Tests run: 3, Failures: 1, Errors: 0, Skipped: 2, Time elapsed: 863.162 sec <<< FAILURE! beforeClass(org.rhq.core.pc.inventory.ResourceContainerTest) Time elapsed: 0 sec <<< FAILURE! java.lang.RuntimeException: Cannot initialize the plugin container at org.rhq.core.pc.plugin.PluginManager.initialize(PluginManager.java:173) at org.rhq.core.pc.PluginContainer.startContainerService(PluginContainer.java:391) at org.rhq.core.pc.PluginContainer.initialize(PluginContainer.java:252) at org.rhq.core.pc.inventory.ResourceContainerTest.beforeClass(ResourceContainerTest.java:48) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.testng.internal.MethodHelper.invokeMethod(MethodHelper.java:607) at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:417) at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:154) at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:88) at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:167) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:104) at org.testng.TestRunner.runWorkers(TestRunner.java:759) at org.testng.TestRunner.privateRun(TestRunner.java:592) at org.testng.TestRunner.run(TestRunner.java:486) at org.testng.SuiteRunner.runTest(SuiteRunner.java:332) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:327) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:299) at org.testng.SuiteRunner.run(SuiteRunner.java:204) at org.testng.TestNG.createAndRunSuiteRunners(TestNG.java:877) at org.testng.TestNG.runSuitesLocally(TestNG.java:842) at org.testng.TestNG.run(TestNG.java:751) at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:62) at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:141) at org.apache.maven.surefire.Surefire.run(Surefire.java:180) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350) at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021) Caused by: org.rhq.core.clientapi.agent.PluginContainerException: A valid plugin JAR URL must be supplied. at org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.loadPluginDescriptorFromUrl(AgentPluginDescriptorUtil.java:296) at org.rhq.core.pc.plugin.PluginDescriptorLoader.loadPluginDescriptor(PluginDescriptorLoader.java:67) at org.rhq.core.pc.plugin.PluginManager.loadPlugin(PluginManager.java:316) at org.rhq.core.pc.plugin.PluginManager.initialize(PluginManager.java:168) ... 32 more
Results :
Failed tests: beforeClass(org.rhq.core.pc.inventory.ResourceContainerTest)
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginManager.java index 2c64ff1..d9976cb 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginManager.java @@ -163,9 +163,11 @@ public class PluginManager implements ContainerService { }
} else { + // TODO (ips, 10/21/10): I don't think this block of code is needed any longer. I am commenting it for + // now, but it should eventually be deleted. // Loading a null plugin loads the plugin using the current classloader (for unit test testing) - log.info("Loading the null plugin which uses non-isolated classloader"); - loadPlugin(null, thisClassLoader); + //log.info("Loading the null plugin which uses non-isolated classloader"); + //loadPlugin(null, thisClassLoader); } } catch (Exception e) { shutdown(); // have to clean up the environments (e.g. unpacked jars) we might have already created @@ -379,7 +381,6 @@ public class PluginManager implements ContainerService { * * @param pluginName the name of the plugin to obtain dependency URLs for * @param pluginNamesUrls map of all known plugin names and their plugin jar URLs - * @param graph the dependency graph * @param allUrls where the results will be stored * * TODO: Use it or lose it - this used to be needed, keeping this around just in case it needs to be resurrected
commit f742f93aabcfe099c727c4eb6b3fbde55f8baf53 Author: Ian Springer ian.springer@redhat.com Date: Mon Sep 20 23:43:29 2010 -0400
pluralize autogroup and subcategory names in the Resource tree (https://bugzilla.redhat.com/show_bug.cgi?id=587631)
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 9d7f395..0862d3a 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 @@ -262,8 +262,9 @@ public class ResourceTreeDatasource extends DataSource { setParentID(parentResourceId); setAttribute("parentId", parentResourceId);
- setName(category.getDisplayName()); - setAttribute("name", category.getDisplayName()); + String name = pluralize(category.getDisplayName()); + setName(name); + setAttribute("name", name); } }
@@ -285,7 +286,7 @@ public class ResourceTreeDatasource extends DataSource {
// setAttribute("parentKey", parentId);
- String name = type.getName(); + String name = pluralize(type.getName()); setName(name); setAttribute("name", name); } @@ -358,4 +359,9 @@ public class ResourceTreeDatasource extends DataSource { private static String fixId(String id) { return id.replace(' ', '_'); } + + private static String pluralize(String s) { + // TODO: Make this smarter. + return s + "s"; + } }
commit 981dad09ee03eb74c3752900a036f03c93aac522 Merge: c443dbc... 73c0d37... Author: Heiko W. Rupp hwr@redhat.com Date: Tue Sep 21 16:29:50 2010 +0200
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit c443dbcd87339ccbb859c7ee4fef8576929c82f0 Author: Heiko W. Rupp hwr@redhat.com Date: Tue Sep 21 15:41:27 2010 +0200
Disable here, as it is broken and development goes on in the perftest branch for now.
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 a289960..fdd5f6a 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 @@ -44,7 +44,7 @@ import org.testng.annotations.Test; * * @author Heiko W. Rupp */ -@Test(groups = "PERF") +@Test(groups = "PERF", enabled = false) public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest {
private final Log log = LogFactory.getLog(AvailabilityInsertPurgeTest.class);
commit 9075e226eaac9f7476d7b51f8582749eea54d50d Merge: aba004b... 73c0d37... Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 09:10:35 2010 -0400
Merge branch 'master' of ssh://spinder@git.fedorahosted.org/git/rhq/rhq into track-master
commit 73c0d3779b57b45b62ae592a77024dd476b8c645 Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 08:40:46 2010 -0400
RecentAlerts config changes and some modifications to super classes for reuse.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java index a639fca..d21ab76 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java @@ -7,10 +7,15 @@ import com.smartgwt.client.rpc.RPCResponse;
import org.rhq.core.domain.alert.Alert; import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.configuration.Property; +import org.rhq.core.domain.configuration.PropertyList; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.AlertCriteria; +import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts.RecentAlertsPortlet;
public class AlertPortletDataSource extends AlertDataSource { //configuration attributes @@ -19,12 +24,50 @@ public class AlertPortletDataSource extends AlertDataSource { private long alertTimeRange = -1; private String alertResourcesToUse = "all"; private Integer[] alertFilterResourceIds = {}; + private DashboardPortlet portlet = null; + + public AlertPortletDataSource() { + super(); + } + + public AlertPortletDataSource(DashboardPortlet recentAlertsPortlet) { + super(); + this.portlet = recentAlertsPortlet; + }
/** Override the executeFetch for AlertPortlet to allow specifying smaller than total * result displays. */ protected void executeFetch(final DSRequest request, final DSResponse response) { final long start = System.currentTimeMillis(); + //retrieve previous settings from portlet config + if ((portlet != null) && (this.portlet instanceof DashboardPortlet)) { + //must check for whether portlet config + PropertySimple property = portlet.getConfiguration().getSimple( + RecentAlertsPortlet.ALERT_RANGE_RESOURCES_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + if (retrieved.trim().equalsIgnoreCase(RecentAlertsPortlet.RESOURCES_SELECTED)) { + setAlertResourcesToUse(RecentAlertsPortlet.RESOURCES_SELECTED); + } else { + setAlertResourcesToUse(RecentAlertsPortlet.RESOURCES_ALL); + } + //if 'selected' then check for previously set resource ids to filter on + if (getAlertResourcesToUse().equals(RecentAlertsPortlet.RESOURCES_SELECTED)) { + Integer[] alertResourceFilterIds = null; + alertResourceFilterIds = extractFilterResourceIds(portlet, alertResourceFilterIds); + if (alertFilterResourceIds != null) { + setAlertFilterResourceId(alertFilterResourceIds); + } + } + } else {//create setting + portlet.getConfiguration().put( + new PropertySimple(RecentAlertsPortlet.ALERT_RANGE_RESOURCES_VALUE, + RecentAlertsPortlet.defaultResourceValue)); + setAlertResourcesToUse(RecentAlertsPortlet.RESOURCES_ALL); + } + }
AlertCriteria criteria = new AlertCriteria(); criteria.fetchAlertDefinition(true); @@ -34,7 +77,8 @@ public class AlertPortletDataSource extends AlertDataSource { PageControl pc = new PageControl(0, getAlertRangeCompleted()); criteria.setPageControl(pc);//display per page criteria.addFilterStartTime(getAlertTimeRange());//alert age - if (getAlertResourcesToUse().equalsIgnoreCase("selected")) { + if ((getAlertResourcesToUse().equalsIgnoreCase(RecentAlertsPortlet.RESOURCES_SELECTED)) + && (getAlertFilterResourceIds().length > 0)) { //add resource ids to filter on criteria.addFilterResourceIds(getAlertFilterResourceIds()); } @@ -99,4 +143,25 @@ public class AlertPortletDataSource extends AlertDataSource { public void setAlertFilterResourceId(Integer[] alertFilterResourceId) { this.alertFilterResourceIds = alertFilterResourceId; } + + public Integer[] extractFilterResourceIds(DashboardPortlet storedPortlet, Integer[] filterResourceIds) { + PropertyList propertyList = storedPortlet.getConfiguration().getList( + RecentAlertsPortlet.ALERT_RANGE_RESOURCE_IDS); + if ((propertyList != null) && (propertyList.getList() != null) && (!propertyList.getList().isEmpty()) + && (propertyList.getList().get(0) != null)) { + Property container = propertyList.getList().get(0); + if (container instanceof PropertyList) { + PropertyList anotherList = (PropertyList) container; + if (anotherList.getList() != null) { + filterResourceIds = new Integer[anotherList.getList().size()]; + int index = 0; + for (Property p : anotherList.getList()) { + filterResourceIds[index++] = ((PropertySimple) p).getIntegerValue(); + } + } + } + } + return filterResourceIds; + } + } 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 1c8774f..e5a9d1f 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 @@ -182,6 +182,7 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { updateButtons(); } }); + removeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { deselect(assignedGrid.getSelection()); @@ -265,6 +266,16 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { addMember(hlayout); }
+ protected ClickHandler getAddButtonClickHandler() { + return new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + assignedGrid.transferSelectedData(availableGrid); + select(assignedGrid.getSelection()); + updateButtons(); + } + }; + } + @Override protected void onDestroy() { super.onDestroy(); @@ -310,4 +321,16 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { } availableGrid.markForRedraw(); } + + public LocatableListGrid getAvailableGrid() { + return availableGrid; + } + + public LocatableListGrid getAssignedGrid() { + return assignedGrid; + } + + // public TransferImgButton getAddButton() { + // return addButton; + // } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java index 9e0ee74..c3dea19 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java @@ -223,13 +223,13 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView DashboardPortlet discoveryQueue = new DashboardPortlet("Discovery Queue", AutodiscoveryPortlet.KEY, 250); dashboard.addPortlet(discoveryQueue, 1, 2);
- DashboardPortlet recentAlerts = new DashboardPortlet("Recent Alerts", RecentAlertsPortlet.KEY, 250); + DashboardPortlet recentAlerts = new DashboardPortlet(RecentAlertsPortlet.KEY, RecentAlertsPortlet.KEY, 250); dashboard.addPortlet(recentAlerts, 1, 3);
DashboardPortlet recentlyAdded = new DashboardPortlet("Recently Added Resources", RecentlyAddedView.KEY, 250); dashboard.addPortlet(recentlyAdded, 1, 4);
- DashboardPortlet operations = new DashboardPortlet("Operations", OperationsPortlet.KEY, 250); + DashboardPortlet operations = new DashboardPortlet("Operations", OperationsPortlet.KEY, 500); dashboard.addPortlet(operations, 1, 5);
DashboardPortlet problemResources = new DashboardPortlet("Has Alerts or Currently Unavailable", diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index c1a4ef9..f88f949 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@ -19,6 +19,9 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts;
import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.data.Record; +import com.smartgwt.client.data.RecordList; +import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -27,24 +30,34 @@ import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; +import com.smartgwt.client.widgets.grid.ListGridField; +import com.smartgwt.client.widgets.grid.events.DataArrivedEvent; +import com.smartgwt.client.widgets.grid.events.DataArrivedHandler; +import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.configuration.PropertyList; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.alert.AlertPortletDataSource; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.wizard.GroupMembersStep; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector; import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel;
/** + * @author Simeon Pinder * @author Greg Hinkle */ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPortlet { @@ -52,10 +65,11 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor public static final String KEY = "Recent Alerts"; public static final String TITLE = KEY; //widget keys also used in form population - private static final String ALERT_RANGE_DISPLAY_AMOUNT_VALUE = "alert-range-display-amount-value"; - private static final String ALERT_RANGE_PRIORITY_VALUE = "alert-range-priority-value"; - private static final String ALERT_RANGE_TIME_VALUE = "alert-range-time-value"; - private static final String ALERT_RANGE_RESOURCES_VALUE = "alert-range-resource-value"; + public static final String ALERT_RANGE_DISPLAY_AMOUNT_VALUE = "alert-range-display-amount-value"; + public static final String ALERT_RANGE_PRIORITY_VALUE = "alert-range-priority-value"; + public static final String ALERT_RANGE_TIME_VALUE = "alert-range-time-value"; + public static final String ALERT_RANGE_RESOURCES_VALUE = "alert-range-resource-value"; + public static final String ALERT_RANGE_RESOURCE_IDS = "alert-range-resource-ids"; //configuration default information private static final String defaultAlertCountValue = "5"; private static final String PRIORITY_ALL = "ALL"; @@ -70,16 +84,24 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor private static final String TIME_WEEK = "week"; private static final String TIME_MONTH = "month"; private static final String defaultTimeValue = TIME_DAY; - private static final String RESOURCES_ALL = "all resources"; - private static final String RESOURCES_SELECTED = "selected resources"; - private static final String defaultResourceValue = RESOURCES_ALL; + public static final String RESOURCES_ALL = "all resources"; + public static final String RESOURCES_SELECTED = "selected resources"; + public static final String defaultResourceValue = RESOURCES_ALL; private static final String unlimited = "unlimited"; - //configuration container element + //alert resource labels + public static final String ALERT_LABEL_SELECTED_RESOURCES = "Selected Resources"; + public static final String ALERT_LABEL_AVAILABLE_RESOURCES = "Available Resources"; + public static final String ALERT_LABEL_RESOURCE_INVENTORY = "Resource Inventory"; + public static final int ALERT_RESOURCE_SELECTION_WIDTH = 800; + public static final String ID = "id"; + //shared private UI elements + private AlertResourceSelectorRegion resourceSelector; private DashboardPortlet storedPortlet = null; private AlertPortletDataSource dataSource; + private Canvas containerCanvas; + private HLayout resourceSelectionLabelRow;
public RecentAlertsPortlet(String locatorId) { - // super(locatorId); this(locatorId, null, null);
setShowHeader(false); @@ -106,7 +128,6 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor //retrieve and translate to int String retrieved = property.getStringValue(); int translatedAlertRangeSelection = translatedAlertRangeSelection(retrieved); - // getDataSource().setAlertRangeCompleted(Integer.parseInt(retrieved)); getDataSource().setAlertRangeCompleted(translatedAlertRangeSelection); } else {//create setting storedPortlet.getConfiguration().put( @@ -143,13 +164,35 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor //retrieve and translate to int String retrieved = property.getStringValue(); if (retrieved.trim().equalsIgnoreCase(RESOURCES_SELECTED)) { - getDataSource().setAlertResourcesToUse("selected"); + getDataSource().setAlertResourcesToUse(RESOURCES_SELECTED); } else { - getDataSource().setAlertResourcesToUse("all"); + getDataSource().setAlertResourcesToUse(RESOURCES_ALL); } } else {//create setting storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_RESOURCES_VALUE, defaultResourceValue)); - getDataSource().setAlertResourcesToUse("all"); + getDataSource().setAlertResourcesToUse(RESOURCES_ALL); + } + + //resource ids to be conditionally included in the query + Integer[] filterResourceIds = null; + filterResourceIds = getDataSource().extractFilterResourceIds(storedPortlet, filterResourceIds); + //no defaults + + if (filterResourceIds != null) { + getDataSource().setAlertFilterResourceId(filterResourceIds); + } + + //conditionally display the selected resources ui + if (containerCanvas != null) { + //empty out earlier canvas + for (Canvas c : containerCanvas.getChildren()) { + c.destroy(); + } + if ((resourceSelector != null) && getDataSource().getAlertResourcesToUse().equals(RESOURCES_SELECTED)) { + containerCanvas.addChild(resourceSelector.getCanvas()); + } else { + containerCanvas.addChild(new Canvas()); + } } }
@@ -222,8 +265,11 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor
//root dynamic form instance final DynamicForm form = new DynamicForm(); - form.setWidth(200); + form.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH + 40);//largest widget display + 40 for buttons + form.setHeight(450); + form.setMargin(5);
+ //vertical container VLayout column = new VLayout();
//label @@ -348,12 +394,29 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor alertResourcesComboBox.setType("selection"); String[] acceptableResourceDisplayValues = { RESOURCES_ALL, RESOURCES_SELECTED }; alertResourcesComboBox.setValueMap(acceptableResourceDisplayValues); - alertResourcesComboBox.setWidth(100); + alertResourcesComboBox.setWidth(150); alertResourcesComboBox.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { String selectedItem = "" + event.getValue(); //stuff into the master form for retrieval form.setValue(ALERT_RANGE_RESOURCES_VALUE, selectedItem); + //empty out earlier canvas + for (Canvas c : containerCanvas.getChildren()) { + c.destroy(); + } + if (selectedItem.equals(RESOURCES_SELECTED)) { + containerCanvas.addChild(resourceSelector.getCanvas()); + resourceSelectionLabelRow.setVisible(true); + for (Canvas c : resourceSelectionLabelRow.getMembers()) { + c.setVisible(true); + } + } else { + containerCanvas.addChild(new Canvas()); + resourceSelectionLabelRow.setVisible(false); + for (Canvas c : resourceSelectionLabelRow.getMembers()) { + c.setVisible(false); + } + } } });
@@ -379,8 +442,62 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor row2.addMember(alertRangeSpanLabel); row2.addMember(timeSelectionWrapper); row2.addMember(resourceSelectionWrapper); + + //Row 3 of labels for the alert selected resources area + resourceSelectionLabelRow = new HLayout(); + resourceSelectionLabelRow.setHeight(30); + resourceSelectionLabelRow.setMembersMargin(5); + resourceSelectionLabelRow.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH);//ui size + fixed button widths + Label availableResourcesLabel = new Label("<b>" + ALERT_LABEL_AVAILABLE_RESOURCES + "</b>"); + availableResourcesLabel.setHeight(20); + availableResourcesLabel.setWrap(false); + resourceSelectionLabelRow.addMember(availableResourcesLabel); + Label spacer = new Label(""); + spacer.setWidth(400); + Label selectedResourcesLabel = new Label("<b>" + ALERT_LABEL_SELECTED_RESOURCES + "</b>"); + selectedResourcesLabel.setHeight(20); + selectedResourcesLabel.setWrap(false); + resourceSelectionLabelRow.addMember(spacer); + resourceSelectionLabelRow.addMember(selectedResourcesLabel); + + //##### if portlet config setting exist, then retrieve############# + Integer[] alertFilterResourceIds = null; + alertFilterResourceIds = getDataSource().extractFilterResourceIds(storedPortlet, alertFilterResourceIds); + if (alertFilterResourceIds != null) { + getDataSource().setAlertFilterResourceId(alertFilterResourceIds); + } + + HLayout row4 = new HLayout(); + row4.setID("row4"); + // resourceSelector = new MemberSelect(); + resourceSelector = new AlertResourceSelectorRegion(alertFilterResourceIds); + row4.setWidth100(); + containerCanvas = new Canvas(); + String retProp = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE).getStringValue(); + + //reload the ResourceSelectionRegion if user has chosen to focus on specific resources with alerts + if (retProp.equals(RESOURCES_SELECTED)) { + containerCanvas.addChild(resourceSelector.getCanvas()); + } else { + containerCanvas.addChild(new Canvas()); + //iterate over children of row3 and make invisible + for (Canvas c : resourceSelectionLabelRow.getMembers()) { + c.setVisible(false); + } + } + //add contain resource selection region. + row4.addMember(containerCanvas); + + //finish construction of the layout column.addMember(row); column.addMember(row2); + SpacerItem verticalSpace = new SpacerItem(); + verticalSpace.setHeight(20); + DynamicForm spacerWrapper = new DynamicForm(); + spacerWrapper.setItems(verticalSpace); + column.addMember(spacerWrapper); + column.addMember(resourceSelectionLabelRow); + column.addMember(row4); form.addChild(column);
//submit handler @@ -390,12 +507,30 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor //no need to insert validation here as user not allowed to enter values parseFormAndPopulateConfiguration(form, storedPortlet, ALERT_RANGE_DISPLAY_AMOUNT_VALUE, ALERT_RANGE_PRIORITY_VALUE, ALERT_RANGE_RESOURCES_VALUE, ALERT_RANGE_TIME_VALUE); + + //retrieve alert-resource-selection property + PropertySimple prop = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE); + + //check to see if "Selected Resources" or "All Resources" + if (prop.getStringValue().equals(RESOURCES_SELECTED)) { + //retrieve currentlyAssignedIds + Integer[] valuesToPersist = resourceSelector.getListGridValues(); + resourceSelector.setCurrentlyAssignedIds(valuesToPersist); + + //build property list of ids to persist + PropertyList list = new PropertyList(ALERT_RANGE_RESOURCE_IDS); + for (int rid : resourceSelector.getCurrentlyAssignedIds()) { + list.add(new PropertySimple(ALERT_RANGE_RESOURCE_IDS, rid)); + } + storedPortlet.getConfiguration().put(new PropertyList(ALERT_RANGE_RESOURCE_IDS, list)); + getDataSource().setAlertFilterResourceId(resourceSelector.getCurrentlyAssignedIds()); + } refresh();// + markForRedraw(); } });
return form; - }
/**Iterates over DynamicForm instance to check for properties passed in and if they have been set @@ -428,3 +563,95 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor } } } + +class CustomizedResourceSelector extends ResourceSelector { + public CustomizedResourceSelector(String id) { + super(id); + } + + public void addAvailableGridSelectionsToAssignedGrid() { + assignedGrid.transferSelectedData(availableGrid); + select(assignedGrid.getSelection()); + updateButtons(); + } +} + +class AlertResourceSelectorRegion extends GroupMembersStep { + // private ResourceSelector selector = null; + private CustomizedResourceSelector selector = null; + private ResourceType requireType = null; + private Integer[] currentlyAssignedIds; + + public Integer[] getCurrentlyAssignedIds() { + return currentlyAssignedIds; + } + + public Integer[] getListGridValues() { + Integer[] listGridValues = new Integer[0]; + if ((null != selector) && (null != selector.getAssignedGrid())) { + RecordList allRecords = selector.getAssignedGrid().getDataAsRecordList(); + if (allRecords.getLength() > 0) { + listGridValues = new Integer[allRecords.getLength()]; + for (int i = 0; i < allRecords.getLength(); i++) { + Record record = allRecords.get(i); + listGridValues[i] = record.getAttributeAsInt(RecentAlertsPortlet.ID); + } + } + } + return listGridValues; + } + + public AlertResourceSelectorRegion(Integer[] assigned) { + super(null); + this.currentlyAssignedIds = assigned; + } + + public Canvas getCanvas() { + ResourceType rt = ResourceType.ANY_PLATFORM_TYPE; + if ((selector == null) || (rt != requireType)) { + // selector = new ResourceSelector(getName()); + selector = new CustomizedResourceSelector(getName()); + selector.setWidth100(); + selector.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH); + selector.setRequireType(rt); + //widget ui updates + selector.getAvailableGrid().setTitle("Available Resources"); + selector.getAvailableGrid().setEmptyMessage("Loading data..."); + selector.getAssignedGrid().setTitle("Selected Resources"); + + //populate fields for grid. + ListGridField nameField = new ListGridField("name", "Name"); + ListGridField iconField = new ListGridField("icon", "icon", 50); + iconField.setImageURLPrefix("types/"); + iconField.setType(ListGridFieldType.ICON); + selector.getAssignedGrid().setFields(iconField, nameField); + + //add listener to AvailableGrid, to act after successfully populated. + selector.getAvailableGrid().addDataArrivedHandler(new DataArrivedHandler() { + @Override + public void onDataArrived(DataArrivedEvent event) { + if ((getCurrentlyAssignedIds() != null) && (getCurrentlyAssignedIds().length > 0)) { + //retrieve the loaded data and add to the table itself + RecordList recordList = selector.getAvailableGrid().getDataAsRecordList(); + for (int ci : getCurrentlyAssignedIds()) { + int located = recordList.findIndex("id", ci); + if (located > -1) { + selector.getAvailableGrid().selectRecord(located); + } + } + selector.addAvailableGridSelectionsToAssignedGrid(); + selector.getAssignedGrid().invalidateCache(); + selector.getAssignedGrid().markForRedraw(); + } else {//no selected resources found + selector.getAvailableGrid().setEmptyMessage("No items to show"); + } + } + }); + } + return selector; + } + + public void setCurrentlyAssignedIds(Integer[] currentlyAssignedIds) { + this.currentlyAssignedIds = currentlyAssignedIds; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java index 8a55ed7..71e6eee 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java @@ -85,7 +85,6 @@ public class ResourceDatasource extends RPCDataSource<Resource> { }
public void executeFetch(final DSRequest request, final DSResponse response) { - ResourceCriteria criteria = getFetchCriteria(request);
resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { @@ -208,4 +207,8 @@ public class ResourceDatasource extends RPCDataSource<Resource> {
return record; } + + public ResourceGWTServiceAsync getResourceService() { + return resourceService; + } }
commit a1bc4dae4211c6eadd0335dd362a582bcaa03240 Author: Simeon Pinder spinder@redhat.com Date: Thu Sep 16 16:13:46 2010 -0400
enable recent alerts config(minus resource selection) and table footer
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java index 33d32b3..61b58b7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java @@ -144,6 +144,7 @@ public class AlertDataSource extends RPCDataSource<Alert> { AlertCriteria criteria = getCriteria(request);
this.alertService.findAlertsByCriteria(criteria, new AsyncCallback<PageList<Alert>>() { + public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to fetch alerts data", caught); response.setStatus(RPCResponse.STATUS_FAILURE); @@ -153,7 +154,6 @@ public class AlertDataSource extends RPCDataSource<Alert> { public void onSuccess(PageList<Alert> result) { long fetchTime = System.currentTimeMillis() - start; System.out.println(result.size() + " alerts fetched in: " + fetchTime + "ms"); - response.setData(buildRecords(result)); // For paging to work, we have to specify size of full result set. response.setTotalRows(result.getTotalSize()); @@ -296,4 +296,8 @@ public class AlertDataSource extends RPCDataSource<Alert> { } }); } + + public AlertGWTServiceAsync getAlertService() { + return alertService; + } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java new file mode 100644 index 0000000..a639fca --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java @@ -0,0 +1,102 @@ +package org.rhq.enterprise.gui.coregui.client.alert; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.rpc.RPCResponse; + +import org.rhq.core.domain.alert.Alert; +import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.criteria.AlertCriteria; +import org.rhq.core.domain.util.PageControl; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; + +public class AlertPortletDataSource extends AlertDataSource { + //configuration attributes + private int alertRangeCompleted = -1; + private int alertPriorityIndex = -1; + private long alertTimeRange = -1; + private String alertResourcesToUse = "all"; + private Integer[] alertFilterResourceIds = {}; + + /** Override the executeFetch for AlertPortlet to allow specifying smaller than total + * result displays. + */ + protected void executeFetch(final DSRequest request, final DSResponse response) { + final long start = System.currentTimeMillis(); + + AlertCriteria criteria = new AlertCriteria(); + criteria.fetchAlertDefinition(true); + criteria.fetchRecoveryAlertDefinition(true); + // TODO: Uncomment the below once the bad performance of it has been fixed. + //criteria.fetchConditionLogs(true); + PageControl pc = new PageControl(0, getAlertRangeCompleted()); + criteria.setPageControl(pc);//display per page + criteria.addFilterStartTime(getAlertTimeRange());//alert age + if (getAlertResourcesToUse().equalsIgnoreCase("selected")) { + //add resource ids to filter on + criteria.addFilterResourceIds(getAlertFilterResourceIds()); + } + if (getAlertPriorityIndex() > 0) {//add priority selection + criteria.addFilterPriority(AlertPriority.getByLegacyIndex(getAlertPriorityIndex())); + } + + getAlertService().findAlertsByCriteria(criteria, new AsyncCallback<PageList<Alert>>() { + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch alerts data", caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + + public void onSuccess(PageList<Alert> result) { + long fetchTime = System.currentTimeMillis() - start; + System.out.println(result.size() + " alerts fetched in: " + fetchTime + "ms"); + response.setData(buildRecords(result)); + response.setTotalRows(result.size()); + processResponse(request.getRequestId(), response); + } + }); + } + + public int getAlertRangeCompleted() { + return alertRangeCompleted; + } + + public void setAlertRangeCompleted(int alertRangeCompleted) { + this.alertRangeCompleted = alertRangeCompleted; + } + + public int getAlertPriorityIndex() { + return alertPriorityIndex; + } + + public void setAlertPriorityIndex(int alertPriorityIndex) { + this.alertPriorityIndex = alertPriorityIndex; + } + + public long getAlertTimeRange() { + return alertTimeRange; + } + + public void setAlertTimeRange(long alertTimeRange) { + this.alertTimeRange = alertTimeRange; + } + + public String getAlertResourcesToUse() { + return alertResourcesToUse; + } + + public void setAlertResourcesToUse(String resourcesToUse) { + this.alertResourcesToUse = resourcesToUse; + } + + public Integer[] getAlertFilterResourceIds() { + return alertFilterResourceIds; + } + + public void setAlertFilterResourceId(Integer[] alertFilterResourceId) { + this.alertFilterResourceIds = alertFilterResourceId; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index 60a3783..c1a4ef9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@ -18,35 +18,200 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts;
+import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; +import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; +import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; +import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; +import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.alert.AlertPortletDataSource; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; +import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; +import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel;
/** * @author Greg Hinkle */ -public class RecentAlertsPortlet extends AlertsView implements Portlet { +public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPortlet {
public static final String KEY = "Recent Alerts"; + public static final String TITLE = KEY; + //widget keys also used in form population + private static final String ALERT_RANGE_DISPLAY_AMOUNT_VALUE = "alert-range-display-amount-value"; + private static final String ALERT_RANGE_PRIORITY_VALUE = "alert-range-priority-value"; + private static final String ALERT_RANGE_TIME_VALUE = "alert-range-time-value"; + private static final String ALERT_RANGE_RESOURCES_VALUE = "alert-range-resource-value"; + //configuration default information + private static final String defaultAlertCountValue = "5"; + private static final String PRIORITY_ALL = "ALL"; + private static final String PRIORITY_HIGH = AlertPriority.HIGH.getDisplayName(); + private static final String PRIORITY_MEDIUM = AlertPriority.MEDIUM.getDisplayName(); + private static final String PRIORITY_LOW = AlertPriority.LOW.getDisplayName(); + private static final String defaultPriorityValue = PRIORITY_ALL; + private static final String TIME_30_MINS = "30 minutes"; + private static final String TIME_HOUR = "hour"; + private static final String TIME_12_HRS = "12 hours"; + private static final String TIME_DAY = "day"; + private static final String TIME_WEEK = "week"; + private static final String TIME_MONTH = "month"; + private static final String defaultTimeValue = TIME_DAY; + private static final String RESOURCES_ALL = "all resources"; + private static final String RESOURCES_SELECTED = "selected resources"; + private static final String defaultResourceValue = RESOURCES_ALL; + private static final String unlimited = "unlimited"; + //configuration container element + private DashboardPortlet storedPortlet = null; + private AlertPortletDataSource dataSource;
public RecentAlertsPortlet(String locatorId) { - super(locatorId); + // super(locatorId); + this(locatorId, null, null);
setShowHeader(false); - setShowFooter(false); + setShowFooter(true); + //disable footer refresh + setShowFooterRefresh(false);
setOverflow(Overflow.HIDDEN); }
+ public RecentAlertsPortlet(String locatorId, Criteria criteria, String[] excludedFieldNames) { + super(locatorId, criteria, excludedFieldNames); + + //override the shared datasource + this.dataSource = new AlertPortletDataSource(); + setDataSource(this.dataSource); + } + public void configure(PortletWindow portletWindow, DashboardPortlet storedPortlet) { - // TODO: Implement this method. + this.storedPortlet = storedPortlet; + //Operation range property - retrieve existing value + PropertySimple property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + int translatedAlertRangeSelection = translatedAlertRangeSelection(retrieved); + // getDataSource().setAlertRangeCompleted(Integer.parseInt(retrieved)); + getDataSource().setAlertRangeCompleted(translatedAlertRangeSelection); + } else {//create setting + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE, defaultAlertCountValue)); + getDataSource().setAlertRangeCompleted(Integer.parseInt(defaultAlertCountValue)); + } + //Operation priority property setting + property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_PRIORITY_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + int translatedPriorityIndex = translatedPriorityToValidIndex(retrieved); + getDataSource().setAlertPriorityIndex(translatedPriorityIndex); + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_PRIORITY_VALUE, defaultPriorityValue)); + getDataSource().setAlertPriorityIndex(translatedPriorityToValidIndex(PRIORITY_ALL)); + } + + //Range to time that alerts will be shown for + property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_TIME_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + long translatedRange = translateTimeToValidRange(retrieved); + getDataSource().setAlertTimeRange(translatedRange); + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_TIME_VALUE, defaultTimeValue)); + getDataSource().setAlertTimeRange(translateTimeToValidRange(defaultTimeValue)); + } + + //Range of resources to be included in the query + property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + if (retrieved.trim().equalsIgnoreCase(RESOURCES_SELECTED)) { + getDataSource().setAlertResourcesToUse("selected"); + } else { + getDataSource().setAlertResourcesToUse("all"); + } + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_RESOURCES_VALUE, defaultResourceValue)); + getDataSource().setAlertResourcesToUse("all"); + } + } + + private int translatedAlertRangeSelection(String retrieved) { + int translated = -1; + if ((retrieved != null) && (!retrieved.trim().isEmpty())) { + if (retrieved.equalsIgnoreCase(unlimited)) { + translated = -1; + } else { + translated = Integer.parseInt(retrieved);//default to all + } + } else {//default to defaultValue + if (defaultAlertCountValue.equalsIgnoreCase(unlimited)) { + translated = -1; + } else { + translated = Integer.parseInt(defaultAlertCountValue); + } + } + return translated; + } + + private int translatedPriorityToValidIndex(String retrieved) { + int translatedPriority = 0;//default to all + if ((retrieved != null) && (!retrieved.trim().isEmpty())) { + if (retrieved.equalsIgnoreCase(PRIORITY_HIGH)) { + translatedPriority = 3; + } else if (retrieved.equalsIgnoreCase(PRIORITY_MEDIUM)) { + translatedPriority = 2; + } else if (retrieved.equalsIgnoreCase(PRIORITY_LOW)) { + translatedPriority = 1; + } else { + translatedPriority = 0;//default to all + } + } + return translatedPriority; + } + + /**Translates the UI selection options into time values for alert query. + * + * @param retrieved + * @return long value mapping to string passed in. + */ + private long translateTimeToValidRange(String retrieved) { + long translated = 0;//default to ALL + if ((retrieved != null) && (!retrieved.trim().isEmpty())) { + if (retrieved.equalsIgnoreCase(TIME_30_MINS)) { + translated = MeasurementUtility.MINUTES * 30; + } else if (retrieved.equalsIgnoreCase(TIME_HOUR)) { + translated = MeasurementUtility.HOURS; + } else if (retrieved.equalsIgnoreCase(TIME_12_HRS)) { + translated = MeasurementUtility.HOURS * 12; + } else if (retrieved.equalsIgnoreCase(TIME_DAY)) { + translated = MeasurementUtility.DAYS; + } else if (retrieved.equalsIgnoreCase(TIME_WEEK)) { + translated = MeasurementUtility.WEEKS; + } else if (retrieved.equalsIgnoreCase(TIME_MONTH)) { + translated = MeasurementUtility.DAYS * 28;//replicated from old struts def. + } else { + translated = MeasurementUtility.DAYS;//default to day otherwise. + } + } + return translated; }
public Canvas getHelpCanvas() { @@ -54,7 +219,205 @@ public class RecentAlertsPortlet extends AlertsView implements Portlet { }
public DynamicForm getCustomSettingsForm() { - return null; // TODO: Implement this method. + + //root dynamic form instance + final DynamicForm form = new DynamicForm(); + form.setWidth(200); + + VLayout column = new VLayout(); + + //label + LocatableLabel alertRangeLabel = new LocatableLabel("DynamicForm_Label_Alert_Range", "<b>Alert Range</b>"); + + //horizontal layout + LocatableHLayout row = new LocatableHLayout("alert-range-settings-row-1"); + row.setMembersMargin(10); + + //-------------combobox for number of completed scheduled ops to display on the dashboard + final SelectItem alertRangeLastComboBox = new SelectItem(ALERT_RANGE_DISPLAY_AMOUNT_VALUE); + alertRangeLastComboBox.setTitle("Last"); + alertRangeLastComboBox.setType("selection"); + //define acceptable values for display amount + String[] acceptableDisplayValues = { "5", "10", "unlimited" }; + alertRangeLastComboBox.setValueMap(acceptableDisplayValues); + //set width of dropdown display region + alertRangeLastComboBox.setWidth(100); + alertRangeLastComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_DISPLAY_AMOUNT_VALUE, selectedItem); + } + }); + + //default selected value to 'unlimited'(live lists) and check both combobox settings here. + String selectedValue = defaultAlertCountValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE) + .getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE, defaultAlertCountValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertRangeLastComboBox.setDefaultValue(selectedValue); + + //-------------combobox for number of completed scheduled ops to display on the dashboard + final SelectItem alertRangePriorityComboBox = new SelectItem(ALERT_RANGE_PRIORITY_VALUE); + alertRangePriorityComboBox.setTitle(""); + alertRangePriorityComboBox.setHint("<nobr> <b> priority Alerts,</b></nobr>"); + alertRangePriorityComboBox.setType("selection"); + //define acceptable values for display amount + String[] acceptablePriorityDisplayValues = { PRIORITY_ALL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW }; + alertRangePriorityComboBox.setValueMap(acceptablePriorityDisplayValues); + //set width of dropdown display region + alertRangePriorityComboBox.setWidth(100); + alertRangePriorityComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_PRIORITY_VALUE, selectedItem); + } + }); + + //default selected value to 'unlimited'(live lists) and check both combobox settings here. + selectedValue = defaultPriorityValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_PRIORITY_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_PRIORITY_VALUE).getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_PRIORITY_VALUE, defaultPriorityValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertRangePriorityComboBox.setDefaultValue(selectedValue); + row.addMember(alertRangeLabel); + DynamicForm wrappedRange = new DynamicForm(); + wrappedRange.setFields(alertRangeLastComboBox); + row.addMember(wrappedRange); + + DynamicForm wrappedPriority = new DynamicForm(); + wrappedPriority.setFields(alertRangePriorityComboBox); + row.addMember(wrappedPriority); + + //horizontal layout + LocatableHLayout row2 = new LocatableHLayout("alert-range-settings-row-2"); + + Label alertRangeSpanLabel = new Label("<b>within the past<b>"); + //------------- Build second combobox for timeframe for problem resources search. + final SelectItem alertRangeTimeComboBox = new SelectItem(ALERT_RANGE_TIME_VALUE); + alertRangeTimeComboBox.setTitle(""); + alertRangeTimeComboBox.setHint(""); + alertRangeTimeComboBox.setType("selection"); + String[] acceptableTimeDisplayValues = { TIME_30_MINS, TIME_HOUR, TIME_12_HRS, TIME_DAY, TIME_WEEK, TIME_MONTH }; + alertRangeTimeComboBox.setValueMap(acceptableTimeDisplayValues); + alertRangeTimeComboBox.setWidth(100); + alertRangeTimeComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_TIME_VALUE, selectedItem); + } + }); + + //set to default + selectedValue = defaultTimeValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_TIME_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_TIME_VALUE).getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_TIME_VALUE, defaultTimeValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertRangeTimeComboBox.setDefaultValue(selectedValue); + DynamicForm timeSelectionWrapper = new DynamicForm(); + timeSelectionWrapper.setFields(alertRangeTimeComboBox); + + // build resource selection drop down + //------------- Build second combobox for timeframe for problem resources search. + final SelectItem alertResourcesComboBox = new SelectItem(ALERT_RANGE_RESOURCES_VALUE); + alertResourcesComboBox.setTitle("for"); + alertResourcesComboBox.setHint(""); + alertResourcesComboBox.setType("selection"); + String[] acceptableResourceDisplayValues = { RESOURCES_ALL, RESOURCES_SELECTED }; + alertResourcesComboBox.setValueMap(acceptableResourceDisplayValues); + alertResourcesComboBox.setWidth(100); + alertResourcesComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_RESOURCES_VALUE, selectedItem); + } + }); + + //set to default + selectedValue = defaultResourceValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE) + .getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_RESOURCES_VALUE, defaultResourceValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertResourcesComboBox.setDefaultValue(selectedValue); + DynamicForm resourceSelectionWrapper = new DynamicForm(); + resourceSelectionWrapper.setFields(alertResourcesComboBox); + + alertRangeSpanLabel.setWrap(false); + alertRangeSpanLabel.setWidth(150); + row2.addMember(alertRangeSpanLabel); + row2.addMember(timeSelectionWrapper); + row2.addMember(resourceSelectionWrapper); + column.addMember(row); + column.addMember(row2); + form.addChild(column); + + //submit handler + form.addSubmitValuesHandler(new SubmitValuesHandler() { + @Override + public void onSubmitValues(SubmitValuesEvent event) { + //no need to insert validation here as user not allowed to enter values + parseFormAndPopulateConfiguration(form, storedPortlet, ALERT_RANGE_DISPLAY_AMOUNT_VALUE, + ALERT_RANGE_PRIORITY_VALUE, ALERT_RANGE_RESOURCES_VALUE, ALERT_RANGE_TIME_VALUE); + refresh();// + } + }); + + return form; + + } + + /**Iterates over DynamicForm instance to check for properties passed in and if they have been set + * to put that property into the DashboardPortlet configuration. + * + * @param form Dynamic form storing user selections + * @param portlet Container for configuration changes + * @param properties Variable list of keys used to verify or populate properties. + */ + private void parseFormAndPopulateConfiguration(final DynamicForm form, DashboardPortlet portlet, + String... properties) { + if ((form != null) && (portlet != null)) { + for (String property : properties) { + if (form.getValue(property) != null) {//if new value supplied + storedPortlet.getConfiguration().put(new PropertySimple(property, form.getValue(property))); + } + } + } + } + + public AlertPortletDataSource getDataSource() { + return dataSource; }
public static final class Factory implements PortletViewFactory {
commit aba004b202fd48d2d869908b96052cae9d9a5aca Author: Simeon Pinder spinder@redhat.com Date: Tue Sep 21 08:40:46 2010 -0400
RecentAlerts config changes and some modifications to super classes for reuse.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java index a639fca..d21ab76 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java @@ -7,10 +7,15 @@ import com.smartgwt.client.rpc.RPCResponse;
import org.rhq.core.domain.alert.Alert; import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.configuration.Property; +import org.rhq.core.domain.configuration.PropertyList; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.AlertCriteria; +import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts.RecentAlertsPortlet;
public class AlertPortletDataSource extends AlertDataSource { //configuration attributes @@ -19,12 +24,50 @@ public class AlertPortletDataSource extends AlertDataSource { private long alertTimeRange = -1; private String alertResourcesToUse = "all"; private Integer[] alertFilterResourceIds = {}; + private DashboardPortlet portlet = null; + + public AlertPortletDataSource() { + super(); + } + + public AlertPortletDataSource(DashboardPortlet recentAlertsPortlet) { + super(); + this.portlet = recentAlertsPortlet; + }
/** Override the executeFetch for AlertPortlet to allow specifying smaller than total * result displays. */ protected void executeFetch(final DSRequest request, final DSResponse response) { final long start = System.currentTimeMillis(); + //retrieve previous settings from portlet config + if ((portlet != null) && (this.portlet instanceof DashboardPortlet)) { + //must check for whether portlet config + PropertySimple property = portlet.getConfiguration().getSimple( + RecentAlertsPortlet.ALERT_RANGE_RESOURCES_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + if (retrieved.trim().equalsIgnoreCase(RecentAlertsPortlet.RESOURCES_SELECTED)) { + setAlertResourcesToUse(RecentAlertsPortlet.RESOURCES_SELECTED); + } else { + setAlertResourcesToUse(RecentAlertsPortlet.RESOURCES_ALL); + } + //if 'selected' then check for previously set resource ids to filter on + if (getAlertResourcesToUse().equals(RecentAlertsPortlet.RESOURCES_SELECTED)) { + Integer[] alertResourceFilterIds = null; + alertResourceFilterIds = extractFilterResourceIds(portlet, alertResourceFilterIds); + if (alertFilterResourceIds != null) { + setAlertFilterResourceId(alertFilterResourceIds); + } + } + } else {//create setting + portlet.getConfiguration().put( + new PropertySimple(RecentAlertsPortlet.ALERT_RANGE_RESOURCES_VALUE, + RecentAlertsPortlet.defaultResourceValue)); + setAlertResourcesToUse(RecentAlertsPortlet.RESOURCES_ALL); + } + }
AlertCriteria criteria = new AlertCriteria(); criteria.fetchAlertDefinition(true); @@ -34,7 +77,8 @@ public class AlertPortletDataSource extends AlertDataSource { PageControl pc = new PageControl(0, getAlertRangeCompleted()); criteria.setPageControl(pc);//display per page criteria.addFilterStartTime(getAlertTimeRange());//alert age - if (getAlertResourcesToUse().equalsIgnoreCase("selected")) { + if ((getAlertResourcesToUse().equalsIgnoreCase(RecentAlertsPortlet.RESOURCES_SELECTED)) + && (getAlertFilterResourceIds().length > 0)) { //add resource ids to filter on criteria.addFilterResourceIds(getAlertFilterResourceIds()); } @@ -99,4 +143,25 @@ public class AlertPortletDataSource extends AlertDataSource { public void setAlertFilterResourceId(Integer[] alertFilterResourceId) { this.alertFilterResourceIds = alertFilterResourceId; } + + public Integer[] extractFilterResourceIds(DashboardPortlet storedPortlet, Integer[] filterResourceIds) { + PropertyList propertyList = storedPortlet.getConfiguration().getList( + RecentAlertsPortlet.ALERT_RANGE_RESOURCE_IDS); + if ((propertyList != null) && (propertyList.getList() != null) && (!propertyList.getList().isEmpty()) + && (propertyList.getList().get(0) != null)) { + Property container = propertyList.getList().get(0); + if (container instanceof PropertyList) { + PropertyList anotherList = (PropertyList) container; + if (anotherList.getList() != null) { + filterResourceIds = new Integer[anotherList.getList().size()]; + int index = 0; + for (Property p : anotherList.getList()) { + filterResourceIds[index++] = ((PropertySimple) p).getIntegerValue(); + } + } + } + } + return filterResourceIds; + } + } 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 1c8774f..e5a9d1f 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 @@ -182,6 +182,7 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { updateButtons(); } }); + removeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { deselect(assignedGrid.getSelection()); @@ -265,6 +266,16 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { addMember(hlayout); }
+ protected ClickHandler getAddButtonClickHandler() { + return new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + assignedGrid.transferSelectedData(availableGrid); + select(assignedGrid.getSelection()); + updateButtons(); + } + }; + } + @Override protected void onDestroy() { super.onDestroy(); @@ -310,4 +321,16 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { } availableGrid.markForRedraw(); } + + public LocatableListGrid getAvailableGrid() { + return availableGrid; + } + + public LocatableListGrid getAssignedGrid() { + return assignedGrid; + } + + // public TransferImgButton getAddButton() { + // return addButton; + // } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java index 9e0ee74..c3dea19 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java @@ -223,13 +223,13 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView DashboardPortlet discoveryQueue = new DashboardPortlet("Discovery Queue", AutodiscoveryPortlet.KEY, 250); dashboard.addPortlet(discoveryQueue, 1, 2);
- DashboardPortlet recentAlerts = new DashboardPortlet("Recent Alerts", RecentAlertsPortlet.KEY, 250); + DashboardPortlet recentAlerts = new DashboardPortlet(RecentAlertsPortlet.KEY, RecentAlertsPortlet.KEY, 250); dashboard.addPortlet(recentAlerts, 1, 3);
DashboardPortlet recentlyAdded = new DashboardPortlet("Recently Added Resources", RecentlyAddedView.KEY, 250); dashboard.addPortlet(recentlyAdded, 1, 4);
- DashboardPortlet operations = new DashboardPortlet("Operations", OperationsPortlet.KEY, 250); + DashboardPortlet operations = new DashboardPortlet("Operations", OperationsPortlet.KEY, 500); dashboard.addPortlet(operations, 1, 5);
DashboardPortlet problemResources = new DashboardPortlet("Has Alerts or Currently Unavailable", diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index c1a4ef9..f88f949 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@ -19,6 +19,9 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts;
import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.data.Record; +import com.smartgwt.client.data.RecordList; +import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -27,24 +30,34 @@ import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; +import com.smartgwt.client.widgets.grid.ListGridField; +import com.smartgwt.client.widgets.grid.events.DataArrivedEvent; +import com.smartgwt.client.widgets.grid.events.DataArrivedHandler; +import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.configuration.PropertyList; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.alert.AlertPortletDataSource; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.wizard.GroupMembersStep; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector; import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel;
/** + * @author Simeon Pinder * @author Greg Hinkle */ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPortlet { @@ -52,10 +65,11 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor public static final String KEY = "Recent Alerts"; public static final String TITLE = KEY; //widget keys also used in form population - private static final String ALERT_RANGE_DISPLAY_AMOUNT_VALUE = "alert-range-display-amount-value"; - private static final String ALERT_RANGE_PRIORITY_VALUE = "alert-range-priority-value"; - private static final String ALERT_RANGE_TIME_VALUE = "alert-range-time-value"; - private static final String ALERT_RANGE_RESOURCES_VALUE = "alert-range-resource-value"; + public static final String ALERT_RANGE_DISPLAY_AMOUNT_VALUE = "alert-range-display-amount-value"; + public static final String ALERT_RANGE_PRIORITY_VALUE = "alert-range-priority-value"; + public static final String ALERT_RANGE_TIME_VALUE = "alert-range-time-value"; + public static final String ALERT_RANGE_RESOURCES_VALUE = "alert-range-resource-value"; + public static final String ALERT_RANGE_RESOURCE_IDS = "alert-range-resource-ids"; //configuration default information private static final String defaultAlertCountValue = "5"; private static final String PRIORITY_ALL = "ALL"; @@ -70,16 +84,24 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor private static final String TIME_WEEK = "week"; private static final String TIME_MONTH = "month"; private static final String defaultTimeValue = TIME_DAY; - private static final String RESOURCES_ALL = "all resources"; - private static final String RESOURCES_SELECTED = "selected resources"; - private static final String defaultResourceValue = RESOURCES_ALL; + public static final String RESOURCES_ALL = "all resources"; + public static final String RESOURCES_SELECTED = "selected resources"; + public static final String defaultResourceValue = RESOURCES_ALL; private static final String unlimited = "unlimited"; - //configuration container element + //alert resource labels + public static final String ALERT_LABEL_SELECTED_RESOURCES = "Selected Resources"; + public static final String ALERT_LABEL_AVAILABLE_RESOURCES = "Available Resources"; + public static final String ALERT_LABEL_RESOURCE_INVENTORY = "Resource Inventory"; + public static final int ALERT_RESOURCE_SELECTION_WIDTH = 800; + public static final String ID = "id"; + //shared private UI elements + private AlertResourceSelectorRegion resourceSelector; private DashboardPortlet storedPortlet = null; private AlertPortletDataSource dataSource; + private Canvas containerCanvas; + private HLayout resourceSelectionLabelRow;
public RecentAlertsPortlet(String locatorId) { - // super(locatorId); this(locatorId, null, null);
setShowHeader(false); @@ -106,7 +128,6 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor //retrieve and translate to int String retrieved = property.getStringValue(); int translatedAlertRangeSelection = translatedAlertRangeSelection(retrieved); - // getDataSource().setAlertRangeCompleted(Integer.parseInt(retrieved)); getDataSource().setAlertRangeCompleted(translatedAlertRangeSelection); } else {//create setting storedPortlet.getConfiguration().put( @@ -143,13 +164,35 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor //retrieve and translate to int String retrieved = property.getStringValue(); if (retrieved.trim().equalsIgnoreCase(RESOURCES_SELECTED)) { - getDataSource().setAlertResourcesToUse("selected"); + getDataSource().setAlertResourcesToUse(RESOURCES_SELECTED); } else { - getDataSource().setAlertResourcesToUse("all"); + getDataSource().setAlertResourcesToUse(RESOURCES_ALL); } } else {//create setting storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_RESOURCES_VALUE, defaultResourceValue)); - getDataSource().setAlertResourcesToUse("all"); + getDataSource().setAlertResourcesToUse(RESOURCES_ALL); + } + + //resource ids to be conditionally included in the query + Integer[] filterResourceIds = null; + filterResourceIds = getDataSource().extractFilterResourceIds(storedPortlet, filterResourceIds); + //no defaults + + if (filterResourceIds != null) { + getDataSource().setAlertFilterResourceId(filterResourceIds); + } + + //conditionally display the selected resources ui + if (containerCanvas != null) { + //empty out earlier canvas + for (Canvas c : containerCanvas.getChildren()) { + c.destroy(); + } + if ((resourceSelector != null) && getDataSource().getAlertResourcesToUse().equals(RESOURCES_SELECTED)) { + containerCanvas.addChild(resourceSelector.getCanvas()); + } else { + containerCanvas.addChild(new Canvas()); + } } }
@@ -222,8 +265,11 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor
//root dynamic form instance final DynamicForm form = new DynamicForm(); - form.setWidth(200); + form.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH + 40);//largest widget display + 40 for buttons + form.setHeight(450); + form.setMargin(5);
+ //vertical container VLayout column = new VLayout();
//label @@ -348,12 +394,29 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor alertResourcesComboBox.setType("selection"); String[] acceptableResourceDisplayValues = { RESOURCES_ALL, RESOURCES_SELECTED }; alertResourcesComboBox.setValueMap(acceptableResourceDisplayValues); - alertResourcesComboBox.setWidth(100); + alertResourcesComboBox.setWidth(150); alertResourcesComboBox.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { String selectedItem = "" + event.getValue(); //stuff into the master form for retrieval form.setValue(ALERT_RANGE_RESOURCES_VALUE, selectedItem); + //empty out earlier canvas + for (Canvas c : containerCanvas.getChildren()) { + c.destroy(); + } + if (selectedItem.equals(RESOURCES_SELECTED)) { + containerCanvas.addChild(resourceSelector.getCanvas()); + resourceSelectionLabelRow.setVisible(true); + for (Canvas c : resourceSelectionLabelRow.getMembers()) { + c.setVisible(true); + } + } else { + containerCanvas.addChild(new Canvas()); + resourceSelectionLabelRow.setVisible(false); + for (Canvas c : resourceSelectionLabelRow.getMembers()) { + c.setVisible(false); + } + } } });
@@ -379,8 +442,62 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor row2.addMember(alertRangeSpanLabel); row2.addMember(timeSelectionWrapper); row2.addMember(resourceSelectionWrapper); + + //Row 3 of labels for the alert selected resources area + resourceSelectionLabelRow = new HLayout(); + resourceSelectionLabelRow.setHeight(30); + resourceSelectionLabelRow.setMembersMargin(5); + resourceSelectionLabelRow.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH);//ui size + fixed button widths + Label availableResourcesLabel = new Label("<b>" + ALERT_LABEL_AVAILABLE_RESOURCES + "</b>"); + availableResourcesLabel.setHeight(20); + availableResourcesLabel.setWrap(false); + resourceSelectionLabelRow.addMember(availableResourcesLabel); + Label spacer = new Label(""); + spacer.setWidth(400); + Label selectedResourcesLabel = new Label("<b>" + ALERT_LABEL_SELECTED_RESOURCES + "</b>"); + selectedResourcesLabel.setHeight(20); + selectedResourcesLabel.setWrap(false); + resourceSelectionLabelRow.addMember(spacer); + resourceSelectionLabelRow.addMember(selectedResourcesLabel); + + //##### if portlet config setting exist, then retrieve############# + Integer[] alertFilterResourceIds = null; + alertFilterResourceIds = getDataSource().extractFilterResourceIds(storedPortlet, alertFilterResourceIds); + if (alertFilterResourceIds != null) { + getDataSource().setAlertFilterResourceId(alertFilterResourceIds); + } + + HLayout row4 = new HLayout(); + row4.setID("row4"); + // resourceSelector = new MemberSelect(); + resourceSelector = new AlertResourceSelectorRegion(alertFilterResourceIds); + row4.setWidth100(); + containerCanvas = new Canvas(); + String retProp = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE).getStringValue(); + + //reload the ResourceSelectionRegion if user has chosen to focus on specific resources with alerts + if (retProp.equals(RESOURCES_SELECTED)) { + containerCanvas.addChild(resourceSelector.getCanvas()); + } else { + containerCanvas.addChild(new Canvas()); + //iterate over children of row3 and make invisible + for (Canvas c : resourceSelectionLabelRow.getMembers()) { + c.setVisible(false); + } + } + //add contain resource selection region. + row4.addMember(containerCanvas); + + //finish construction of the layout column.addMember(row); column.addMember(row2); + SpacerItem verticalSpace = new SpacerItem(); + verticalSpace.setHeight(20); + DynamicForm spacerWrapper = new DynamicForm(); + spacerWrapper.setItems(verticalSpace); + column.addMember(spacerWrapper); + column.addMember(resourceSelectionLabelRow); + column.addMember(row4); form.addChild(column);
//submit handler @@ -390,12 +507,30 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor //no need to insert validation here as user not allowed to enter values parseFormAndPopulateConfiguration(form, storedPortlet, ALERT_RANGE_DISPLAY_AMOUNT_VALUE, ALERT_RANGE_PRIORITY_VALUE, ALERT_RANGE_RESOURCES_VALUE, ALERT_RANGE_TIME_VALUE); + + //retrieve alert-resource-selection property + PropertySimple prop = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE); + + //check to see if "Selected Resources" or "All Resources" + if (prop.getStringValue().equals(RESOURCES_SELECTED)) { + //retrieve currentlyAssignedIds + Integer[] valuesToPersist = resourceSelector.getListGridValues(); + resourceSelector.setCurrentlyAssignedIds(valuesToPersist); + + //build property list of ids to persist + PropertyList list = new PropertyList(ALERT_RANGE_RESOURCE_IDS); + for (int rid : resourceSelector.getCurrentlyAssignedIds()) { + list.add(new PropertySimple(ALERT_RANGE_RESOURCE_IDS, rid)); + } + storedPortlet.getConfiguration().put(new PropertyList(ALERT_RANGE_RESOURCE_IDS, list)); + getDataSource().setAlertFilterResourceId(resourceSelector.getCurrentlyAssignedIds()); + } refresh();// + markForRedraw(); } });
return form; - }
/**Iterates over DynamicForm instance to check for properties passed in and if they have been set @@ -428,3 +563,95 @@ public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPor } } } + +class CustomizedResourceSelector extends ResourceSelector { + public CustomizedResourceSelector(String id) { + super(id); + } + + public void addAvailableGridSelectionsToAssignedGrid() { + assignedGrid.transferSelectedData(availableGrid); + select(assignedGrid.getSelection()); + updateButtons(); + } +} + +class AlertResourceSelectorRegion extends GroupMembersStep { + // private ResourceSelector selector = null; + private CustomizedResourceSelector selector = null; + private ResourceType requireType = null; + private Integer[] currentlyAssignedIds; + + public Integer[] getCurrentlyAssignedIds() { + return currentlyAssignedIds; + } + + public Integer[] getListGridValues() { + Integer[] listGridValues = new Integer[0]; + if ((null != selector) && (null != selector.getAssignedGrid())) { + RecordList allRecords = selector.getAssignedGrid().getDataAsRecordList(); + if (allRecords.getLength() > 0) { + listGridValues = new Integer[allRecords.getLength()]; + for (int i = 0; i < allRecords.getLength(); i++) { + Record record = allRecords.get(i); + listGridValues[i] = record.getAttributeAsInt(RecentAlertsPortlet.ID); + } + } + } + return listGridValues; + } + + public AlertResourceSelectorRegion(Integer[] assigned) { + super(null); + this.currentlyAssignedIds = assigned; + } + + public Canvas getCanvas() { + ResourceType rt = ResourceType.ANY_PLATFORM_TYPE; + if ((selector == null) || (rt != requireType)) { + // selector = new ResourceSelector(getName()); + selector = new CustomizedResourceSelector(getName()); + selector.setWidth100(); + selector.setWidth(RecentAlertsPortlet.ALERT_RESOURCE_SELECTION_WIDTH); + selector.setRequireType(rt); + //widget ui updates + selector.getAvailableGrid().setTitle("Available Resources"); + selector.getAvailableGrid().setEmptyMessage("Loading data..."); + selector.getAssignedGrid().setTitle("Selected Resources"); + + //populate fields for grid. + ListGridField nameField = new ListGridField("name", "Name"); + ListGridField iconField = new ListGridField("icon", "icon", 50); + iconField.setImageURLPrefix("types/"); + iconField.setType(ListGridFieldType.ICON); + selector.getAssignedGrid().setFields(iconField, nameField); + + //add listener to AvailableGrid, to act after successfully populated. + selector.getAvailableGrid().addDataArrivedHandler(new DataArrivedHandler() { + @Override + public void onDataArrived(DataArrivedEvent event) { + if ((getCurrentlyAssignedIds() != null) && (getCurrentlyAssignedIds().length > 0)) { + //retrieve the loaded data and add to the table itself + RecordList recordList = selector.getAvailableGrid().getDataAsRecordList(); + for (int ci : getCurrentlyAssignedIds()) { + int located = recordList.findIndex("id", ci); + if (located > -1) { + selector.getAvailableGrid().selectRecord(located); + } + } + selector.addAvailableGridSelectionsToAssignedGrid(); + selector.getAssignedGrid().invalidateCache(); + selector.getAssignedGrid().markForRedraw(); + } else {//no selected resources found + selector.getAvailableGrid().setEmptyMessage("No items to show"); + } + } + }); + } + return selector; + } + + public void setCurrentlyAssignedIds(Integer[] currentlyAssignedIds) { + this.currentlyAssignedIds = currentlyAssignedIds; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java index 8a55ed7..71e6eee 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java @@ -85,7 +85,6 @@ public class ResourceDatasource extends RPCDataSource<Resource> { }
public void executeFetch(final DSRequest request, final DSResponse response) { - ResourceCriteria criteria = getFetchCriteria(request);
resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { @@ -208,4 +207,8 @@ public class ResourceDatasource extends RPCDataSource<Resource> {
return record; } + + public ResourceGWTServiceAsync getResourceService() { + return resourceService; + } }
commit 4b53c0811d1e0d6d876806ac368a440ce50663c1 Author: Simeon Pinder spinder@redhat.com Date: Thu Sep 16 16:13:46 2010 -0400
enable recent alerts config(minus resource selection) and table footer
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java index 33d32b3..61b58b7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDataSource.java @@ -144,6 +144,7 @@ public class AlertDataSource extends RPCDataSource<Alert> { AlertCriteria criteria = getCriteria(request);
this.alertService.findAlertsByCriteria(criteria, new AsyncCallback<PageList<Alert>>() { + public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to fetch alerts data", caught); response.setStatus(RPCResponse.STATUS_FAILURE); @@ -153,7 +154,6 @@ public class AlertDataSource extends RPCDataSource<Alert> { public void onSuccess(PageList<Alert> result) { long fetchTime = System.currentTimeMillis() - start; System.out.println(result.size() + " alerts fetched in: " + fetchTime + "ms"); - response.setData(buildRecords(result)); // For paging to work, we have to specify size of full result set. response.setTotalRows(result.getTotalSize()); @@ -296,4 +296,8 @@ public class AlertDataSource extends RPCDataSource<Alert> { } }); } + + public AlertGWTServiceAsync getAlertService() { + return alertService; + } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java new file mode 100644 index 0000000..a639fca --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertPortletDataSource.java @@ -0,0 +1,102 @@ +package org.rhq.enterprise.gui.coregui.client.alert; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.rpc.RPCResponse; + +import org.rhq.core.domain.alert.Alert; +import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.criteria.AlertCriteria; +import org.rhq.core.domain.util.PageControl; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; + +public class AlertPortletDataSource extends AlertDataSource { + //configuration attributes + private int alertRangeCompleted = -1; + private int alertPriorityIndex = -1; + private long alertTimeRange = -1; + private String alertResourcesToUse = "all"; + private Integer[] alertFilterResourceIds = {}; + + /** Override the executeFetch for AlertPortlet to allow specifying smaller than total + * result displays. + */ + protected void executeFetch(final DSRequest request, final DSResponse response) { + final long start = System.currentTimeMillis(); + + AlertCriteria criteria = new AlertCriteria(); + criteria.fetchAlertDefinition(true); + criteria.fetchRecoveryAlertDefinition(true); + // TODO: Uncomment the below once the bad performance of it has been fixed. + //criteria.fetchConditionLogs(true); + PageControl pc = new PageControl(0, getAlertRangeCompleted()); + criteria.setPageControl(pc);//display per page + criteria.addFilterStartTime(getAlertTimeRange());//alert age + if (getAlertResourcesToUse().equalsIgnoreCase("selected")) { + //add resource ids to filter on + criteria.addFilterResourceIds(getAlertFilterResourceIds()); + } + if (getAlertPriorityIndex() > 0) {//add priority selection + criteria.addFilterPriority(AlertPriority.getByLegacyIndex(getAlertPriorityIndex())); + } + + getAlertService().findAlertsByCriteria(criteria, new AsyncCallback<PageList<Alert>>() { + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch alerts data", caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + + public void onSuccess(PageList<Alert> result) { + long fetchTime = System.currentTimeMillis() - start; + System.out.println(result.size() + " alerts fetched in: " + fetchTime + "ms"); + response.setData(buildRecords(result)); + response.setTotalRows(result.size()); + processResponse(request.getRequestId(), response); + } + }); + } + + public int getAlertRangeCompleted() { + return alertRangeCompleted; + } + + public void setAlertRangeCompleted(int alertRangeCompleted) { + this.alertRangeCompleted = alertRangeCompleted; + } + + public int getAlertPriorityIndex() { + return alertPriorityIndex; + } + + public void setAlertPriorityIndex(int alertPriorityIndex) { + this.alertPriorityIndex = alertPriorityIndex; + } + + public long getAlertTimeRange() { + return alertTimeRange; + } + + public void setAlertTimeRange(long alertTimeRange) { + this.alertTimeRange = alertTimeRange; + } + + public String getAlertResourcesToUse() { + return alertResourcesToUse; + } + + public void setAlertResourcesToUse(String resourcesToUse) { + this.alertResourcesToUse = resourcesToUse; + } + + public Integer[] getAlertFilterResourceIds() { + return alertFilterResourceIds; + } + + public void setAlertFilterResourceId(Integer[] alertFilterResourceId) { + this.alertFilterResourceIds = alertFilterResourceId; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index 60a3783..c1a4ef9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@ -18,35 +18,200 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts;
+import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; +import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; +import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; +import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; +import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.alert.AlertPriority; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.alert.AlertPortletDataSource; import org.rhq.enterprise.gui.coregui.client.alert.AlertsView; +import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletWindow; +import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel;
/** * @author Greg Hinkle */ -public class RecentAlertsPortlet extends AlertsView implements Portlet { +public class RecentAlertsPortlet extends AlertsView implements CustomSettingsPortlet {
public static final String KEY = "Recent Alerts"; + public static final String TITLE = KEY; + //widget keys also used in form population + private static final String ALERT_RANGE_DISPLAY_AMOUNT_VALUE = "alert-range-display-amount-value"; + private static final String ALERT_RANGE_PRIORITY_VALUE = "alert-range-priority-value"; + private static final String ALERT_RANGE_TIME_VALUE = "alert-range-time-value"; + private static final String ALERT_RANGE_RESOURCES_VALUE = "alert-range-resource-value"; + //configuration default information + private static final String defaultAlertCountValue = "5"; + private static final String PRIORITY_ALL = "ALL"; + private static final String PRIORITY_HIGH = AlertPriority.HIGH.getDisplayName(); + private static final String PRIORITY_MEDIUM = AlertPriority.MEDIUM.getDisplayName(); + private static final String PRIORITY_LOW = AlertPriority.LOW.getDisplayName(); + private static final String defaultPriorityValue = PRIORITY_ALL; + private static final String TIME_30_MINS = "30 minutes"; + private static final String TIME_HOUR = "hour"; + private static final String TIME_12_HRS = "12 hours"; + private static final String TIME_DAY = "day"; + private static final String TIME_WEEK = "week"; + private static final String TIME_MONTH = "month"; + private static final String defaultTimeValue = TIME_DAY; + private static final String RESOURCES_ALL = "all resources"; + private static final String RESOURCES_SELECTED = "selected resources"; + private static final String defaultResourceValue = RESOURCES_ALL; + private static final String unlimited = "unlimited"; + //configuration container element + private DashboardPortlet storedPortlet = null; + private AlertPortletDataSource dataSource;
public RecentAlertsPortlet(String locatorId) { - super(locatorId); + // super(locatorId); + this(locatorId, null, null);
setShowHeader(false); - setShowFooter(false); + setShowFooter(true); + //disable footer refresh + setShowFooterRefresh(false);
setOverflow(Overflow.HIDDEN); }
+ public RecentAlertsPortlet(String locatorId, Criteria criteria, String[] excludedFieldNames) { + super(locatorId, criteria, excludedFieldNames); + + //override the shared datasource + this.dataSource = new AlertPortletDataSource(); + setDataSource(this.dataSource); + } + public void configure(PortletWindow portletWindow, DashboardPortlet storedPortlet) { - // TODO: Implement this method. + this.storedPortlet = storedPortlet; + //Operation range property - retrieve existing value + PropertySimple property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + int translatedAlertRangeSelection = translatedAlertRangeSelection(retrieved); + // getDataSource().setAlertRangeCompleted(Integer.parseInt(retrieved)); + getDataSource().setAlertRangeCompleted(translatedAlertRangeSelection); + } else {//create setting + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE, defaultAlertCountValue)); + getDataSource().setAlertRangeCompleted(Integer.parseInt(defaultAlertCountValue)); + } + //Operation priority property setting + property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_PRIORITY_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + int translatedPriorityIndex = translatedPriorityToValidIndex(retrieved); + getDataSource().setAlertPriorityIndex(translatedPriorityIndex); + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_PRIORITY_VALUE, defaultPriorityValue)); + getDataSource().setAlertPriorityIndex(translatedPriorityToValidIndex(PRIORITY_ALL)); + } + + //Range to time that alerts will be shown for + property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_TIME_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + long translatedRange = translateTimeToValidRange(retrieved); + getDataSource().setAlertTimeRange(translatedRange); + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_TIME_VALUE, defaultTimeValue)); + getDataSource().setAlertTimeRange(translateTimeToValidRange(defaultTimeValue)); + } + + //Range of resources to be included in the query + property = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE); + if ((property != null) && (property.getStringValue() != null)) { + //retrieve and translate to int + String retrieved = property.getStringValue(); + if (retrieved.trim().equalsIgnoreCase(RESOURCES_SELECTED)) { + getDataSource().setAlertResourcesToUse("selected"); + } else { + getDataSource().setAlertResourcesToUse("all"); + } + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_RESOURCES_VALUE, defaultResourceValue)); + getDataSource().setAlertResourcesToUse("all"); + } + } + + private int translatedAlertRangeSelection(String retrieved) { + int translated = -1; + if ((retrieved != null) && (!retrieved.trim().isEmpty())) { + if (retrieved.equalsIgnoreCase(unlimited)) { + translated = -1; + } else { + translated = Integer.parseInt(retrieved);//default to all + } + } else {//default to defaultValue + if (defaultAlertCountValue.equalsIgnoreCase(unlimited)) { + translated = -1; + } else { + translated = Integer.parseInt(defaultAlertCountValue); + } + } + return translated; + } + + private int translatedPriorityToValidIndex(String retrieved) { + int translatedPriority = 0;//default to all + if ((retrieved != null) && (!retrieved.trim().isEmpty())) { + if (retrieved.equalsIgnoreCase(PRIORITY_HIGH)) { + translatedPriority = 3; + } else if (retrieved.equalsIgnoreCase(PRIORITY_MEDIUM)) { + translatedPriority = 2; + } else if (retrieved.equalsIgnoreCase(PRIORITY_LOW)) { + translatedPriority = 1; + } else { + translatedPriority = 0;//default to all + } + } + return translatedPriority; + } + + /**Translates the UI selection options into time values for alert query. + * + * @param retrieved + * @return long value mapping to string passed in. + */ + private long translateTimeToValidRange(String retrieved) { + long translated = 0;//default to ALL + if ((retrieved != null) && (!retrieved.trim().isEmpty())) { + if (retrieved.equalsIgnoreCase(TIME_30_MINS)) { + translated = MeasurementUtility.MINUTES * 30; + } else if (retrieved.equalsIgnoreCase(TIME_HOUR)) { + translated = MeasurementUtility.HOURS; + } else if (retrieved.equalsIgnoreCase(TIME_12_HRS)) { + translated = MeasurementUtility.HOURS * 12; + } else if (retrieved.equalsIgnoreCase(TIME_DAY)) { + translated = MeasurementUtility.DAYS; + } else if (retrieved.equalsIgnoreCase(TIME_WEEK)) { + translated = MeasurementUtility.WEEKS; + } else if (retrieved.equalsIgnoreCase(TIME_MONTH)) { + translated = MeasurementUtility.DAYS * 28;//replicated from old struts def. + } else { + translated = MeasurementUtility.DAYS;//default to day otherwise. + } + } + return translated; }
public Canvas getHelpCanvas() { @@ -54,7 +219,205 @@ public class RecentAlertsPortlet extends AlertsView implements Portlet { }
public DynamicForm getCustomSettingsForm() { - return null; // TODO: Implement this method. + + //root dynamic form instance + final DynamicForm form = new DynamicForm(); + form.setWidth(200); + + VLayout column = new VLayout(); + + //label + LocatableLabel alertRangeLabel = new LocatableLabel("DynamicForm_Label_Alert_Range", "<b>Alert Range</b>"); + + //horizontal layout + LocatableHLayout row = new LocatableHLayout("alert-range-settings-row-1"); + row.setMembersMargin(10); + + //-------------combobox for number of completed scheduled ops to display on the dashboard + final SelectItem alertRangeLastComboBox = new SelectItem(ALERT_RANGE_DISPLAY_AMOUNT_VALUE); + alertRangeLastComboBox.setTitle("Last"); + alertRangeLastComboBox.setType("selection"); + //define acceptable values for display amount + String[] acceptableDisplayValues = { "5", "10", "unlimited" }; + alertRangeLastComboBox.setValueMap(acceptableDisplayValues); + //set width of dropdown display region + alertRangeLastComboBox.setWidth(100); + alertRangeLastComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_DISPLAY_AMOUNT_VALUE, selectedItem); + } + }); + + //default selected value to 'unlimited'(live lists) and check both combobox settings here. + String selectedValue = defaultAlertCountValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE) + .getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_DISPLAY_AMOUNT_VALUE, defaultAlertCountValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertRangeLastComboBox.setDefaultValue(selectedValue); + + //-------------combobox for number of completed scheduled ops to display on the dashboard + final SelectItem alertRangePriorityComboBox = new SelectItem(ALERT_RANGE_PRIORITY_VALUE); + alertRangePriorityComboBox.setTitle(""); + alertRangePriorityComboBox.setHint("<nobr> <b> priority Alerts,</b></nobr>"); + alertRangePriorityComboBox.setType("selection"); + //define acceptable values for display amount + String[] acceptablePriorityDisplayValues = { PRIORITY_ALL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW }; + alertRangePriorityComboBox.setValueMap(acceptablePriorityDisplayValues); + //set width of dropdown display region + alertRangePriorityComboBox.setWidth(100); + alertRangePriorityComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_PRIORITY_VALUE, selectedItem); + } + }); + + //default selected value to 'unlimited'(live lists) and check both combobox settings here. + selectedValue = defaultPriorityValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_PRIORITY_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_PRIORITY_VALUE).getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_PRIORITY_VALUE, defaultPriorityValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertRangePriorityComboBox.setDefaultValue(selectedValue); + row.addMember(alertRangeLabel); + DynamicForm wrappedRange = new DynamicForm(); + wrappedRange.setFields(alertRangeLastComboBox); + row.addMember(wrappedRange); + + DynamicForm wrappedPriority = new DynamicForm(); + wrappedPriority.setFields(alertRangePriorityComboBox); + row.addMember(wrappedPriority); + + //horizontal layout + LocatableHLayout row2 = new LocatableHLayout("alert-range-settings-row-2"); + + Label alertRangeSpanLabel = new Label("<b>within the past<b>"); + //------------- Build second combobox for timeframe for problem resources search. + final SelectItem alertRangeTimeComboBox = new SelectItem(ALERT_RANGE_TIME_VALUE); + alertRangeTimeComboBox.setTitle(""); + alertRangeTimeComboBox.setHint(""); + alertRangeTimeComboBox.setType("selection"); + String[] acceptableTimeDisplayValues = { TIME_30_MINS, TIME_HOUR, TIME_12_HRS, TIME_DAY, TIME_WEEK, TIME_MONTH }; + alertRangeTimeComboBox.setValueMap(acceptableTimeDisplayValues); + alertRangeTimeComboBox.setWidth(100); + alertRangeTimeComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_TIME_VALUE, selectedItem); + } + }); + + //set to default + selectedValue = defaultTimeValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_TIME_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_TIME_VALUE).getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put(new PropertySimple(ALERT_RANGE_TIME_VALUE, defaultTimeValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertRangeTimeComboBox.setDefaultValue(selectedValue); + DynamicForm timeSelectionWrapper = new DynamicForm(); + timeSelectionWrapper.setFields(alertRangeTimeComboBox); + + // build resource selection drop down + //------------- Build second combobox for timeframe for problem resources search. + final SelectItem alertResourcesComboBox = new SelectItem(ALERT_RANGE_RESOURCES_VALUE); + alertResourcesComboBox.setTitle("for"); + alertResourcesComboBox.setHint(""); + alertResourcesComboBox.setType("selection"); + String[] acceptableResourceDisplayValues = { RESOURCES_ALL, RESOURCES_SELECTED }; + alertResourcesComboBox.setValueMap(acceptableResourceDisplayValues); + alertResourcesComboBox.setWidth(100); + alertResourcesComboBox.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent event) { + String selectedItem = "" + event.getValue(); + //stuff into the master form for retrieval + form.setValue(ALERT_RANGE_RESOURCES_VALUE, selectedItem); + } + }); + + //set to default + selectedValue = defaultResourceValue; + if (storedPortlet != null) { + //if property exists retrieve it + if (storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE) != null) { + selectedValue = storedPortlet.getConfiguration().getSimple(ALERT_RANGE_RESOURCES_VALUE) + .getStringValue(); + } else {//insert default value + storedPortlet.getConfiguration().put( + new PropertySimple(ALERT_RANGE_RESOURCES_VALUE, defaultResourceValue)); + } + } + //prepopulate the combobox with the previously stored selection + alertResourcesComboBox.setDefaultValue(selectedValue); + DynamicForm resourceSelectionWrapper = new DynamicForm(); + resourceSelectionWrapper.setFields(alertResourcesComboBox); + + alertRangeSpanLabel.setWrap(false); + alertRangeSpanLabel.setWidth(150); + row2.addMember(alertRangeSpanLabel); + row2.addMember(timeSelectionWrapper); + row2.addMember(resourceSelectionWrapper); + column.addMember(row); + column.addMember(row2); + form.addChild(column); + + //submit handler + form.addSubmitValuesHandler(new SubmitValuesHandler() { + @Override + public void onSubmitValues(SubmitValuesEvent event) { + //no need to insert validation here as user not allowed to enter values + parseFormAndPopulateConfiguration(form, storedPortlet, ALERT_RANGE_DISPLAY_AMOUNT_VALUE, + ALERT_RANGE_PRIORITY_VALUE, ALERT_RANGE_RESOURCES_VALUE, ALERT_RANGE_TIME_VALUE); + refresh();// + } + }); + + return form; + + } + + /**Iterates over DynamicForm instance to check for properties passed in and if they have been set + * to put that property into the DashboardPortlet configuration. + * + * @param form Dynamic form storing user selections + * @param portlet Container for configuration changes + * @param properties Variable list of keys used to verify or populate properties. + */ + private void parseFormAndPopulateConfiguration(final DynamicForm form, DashboardPortlet portlet, + String... properties) { + if ((form != null) && (portlet != null)) { + for (String property : properties) { + if (form.getValue(property) != null) {//if new value supplied + storedPortlet.getConfiguration().put(new PropertySimple(property, form.getValue(property))); + } + } + } + } + + public AlertPortletDataSource getDataSource() { + return dataSource; }
public static final class Factory implements PortletViewFactory {
commit b38fbd992d4a236fdf71ea5001db32b3af889ee8 Merge: 2b0a1c3... a03a5f6... Author: Heiko W. Rupp hwr@redhat.com Date: Tue Sep 21 14:31:49 2010 +0200
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 2b0a1c3b350e74bb07943063a2df6b73f3de783c Author: Heiko W. Rupp hwr@redhat.com Date: Tue Sep 21 14:30:38 2010 +0200
Bump target version to follow the recent change to the upgrade script.
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 1f4adef..11ba639 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.94</db.schema.version> + <db.schema.version>2.95</db.schema.version> </properties>
<dependencies>
commit a03a5f6757ac252cfd91f5578129e46a5ed54866 Author: Joseph Marques joseph@redhat.com Date: Tue Sep 21 01:37:40 2010 -0400
more dynagroup CRUD work:
* add list of dynagroup children to details view * add ability to recalculate the current group def from details view * fix column widths and cell formatting for list view * add ability to recalculate selected group definitions from list view
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java index 00e8819..f0fe978 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java @@ -110,6 +110,11 @@ public class ResourceGroupsDataSource extends RPCDataSource<ResourceGroup> { "downMemberCount"))); }
+ if (request.getCriteria().getValues().get("groupDefinitionId") != null) { + criteria.addFilterGroupDefinitionId(Integer.parseInt((String) request.getCriteria().getValues().get( + "groupDefinitionId"))); + } + return criteria; }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java index a95e0e6..49ea417 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java @@ -30,7 +30,6 @@ import com.smartgwt.client.data.Record; import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.rpc.RPCResponse; -import com.smartgwt.client.types.FieldType; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; @@ -70,23 +69,21 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
DataSourceTextField descriptionField = new DataSourceTextField("description", "Description");
- DataSourceTextField expressionField = new DataSourceTextField("expression", "Expression"); + DataSourceTextField expressionField = new DataSourceTextField("expression", "Expression Set"); expressionField.setRequired(true);
- DataSourceTextField recursiveField = new DataSourceTextField("recursive", "Recursive"); - recursiveField.setType(FieldType.BOOLEAN); - - /* - DataSourceTextField recalculationIntervalField = new DataSourceTextField("recalculationInterval", + DataSourceIntegerField lastCalculationTimeIntervalField = new DataSourceIntegerField("lastCalculationTime", "Recalculation Interval"); - */
- DataSourceTextField nextCalculationTimeField = new DataSourceTextField("nextCalculationTime", + DataSourceIntegerField nextCalculationTimeField = new DataSourceIntegerField("nextCalculationTime", "Next Calculation Time");
- setFields(idField, nameField, descriptionField, expressionField, recursiveField, /*recalculationIntervalField,*/ - nextCalculationTimeField); - + addField(idField); + addField(nameField); + addField(descriptionField); + addField(expressionField); + addField(lastCalculationTimeIntervalField); + addField(nextCalculationTimeField); }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index d6d78e5..9b17abf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -21,13 +21,14 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.CellFormatter; -import com.smartgwt.client.widgets.grid.ListGrid; +import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; +import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; 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.TableUtility; @@ -50,25 +51,71 @@ public class GroupDefinitionListView extends TableSection {
@Override protected void configureTable() { - super.configureTable();
- ListGrid grid = getListGrid(); + ListGridField idField = new ListGridField("id", "ID", 50); + ListGridField nameField = new ListGridField("name", "Name", 150); + ListGridField descriptionField = new ListGridField("description", "Description"); + ListGridField expressionField = new ListGridField("expression", "Expression Set", 250); + expressionField.setCellFormatter(new CellFormatter() { + public String format(Object value, ListGridRecord record, int rowNum, int colNum) { + return value.toString().replaceAll("\n", "<br/>"); + } + }); + + ListGridField lastCalculationTimeField = new ListGridField("lastCalculationTime", "Last Calculation Time", 175); + //lastCalculationTimeField.setAlign(Alignment.CENTER); + lastCalculationTimeField.setCellFormatter(new TimestampCellFormatter() { + public String format(Object value, ListGridRecord record, int rowNum, int colNum) { + if (value == null) { + return "Never"; + } + return super.format(value, record, rowNum, colNum); + } + });
- grid.getField("nextCalculationTime").setCellFormatter(new CellFormatter() { + ListGridField nextCalculationTimeField = new ListGridField("nextCalculationTime", "Next Calculation Time", 175); + //nextCalculationTimeField.setAlign(Alignment.CENTER); + nextCalculationTimeField.setCellFormatter(new TimestampCellFormatter() { public String format(Object value, ListGridRecord record, int rowNum, int colNum) { - if ("0".equals(value.toString())) { + if (value == null || "0".equals(value.toString())) { return "N/A"; } - return value.toString(); + return super.format(value, record, rowNum, colNum); } });
+ getListGrid().setFields(idField, nameField, descriptionField, expressionField, lastCalculationTimeField, + nextCalculationTimeField); + addTableAction(extendLocatorId("New"), "New", Table.SelectionEnablement.ALWAYS, null, new TableAction() { public void executeAction(ListGridRecord[] selection) { newDetails(); } });
+ addTableAction(extendLocatorId("Recalculate"), "Recalculate", Table.SelectionEnablement.ANY, null, + new TableAction() { + public void executeAction(ListGridRecord[] selection) { + final int[] groupDefinitionIds = TableUtility.getIds(selection); + ResourceGroupGWTServiceAsync resourceGroupManager = GWTServiceLookup.getResourceGroupService(); + + resourceGroupManager.recalculateGroupDefinitions(groupDefinitionIds, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to recalculate selected group definitions", + caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Successfully recalculated " + groupDefinitionIds.length + + " group definitions", Severity.Info)); + + GroupDefinitionListView.this.refresh(); + } + }); + } + }); + addTableAction(extendLocatorId("Delete"), "Delete", Table.SelectionEnablement.ANY, null, new TableAction() { public void executeAction(ListGridRecord[] selection) { final int[] groupDefinitionIds = TableUtility.getIds(selection); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index 1639a92..f4ca2cf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -23,6 +23,7 @@ import java.util.Set;
import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@ -45,7 +46,11 @@ import org.rhq.enterprise.gui.coregui.client.BookmarkableView; 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.components.table.Table; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupsDataSource; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; @@ -131,16 +136,48 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm form.setSaveOperationType(DSOperationType.UPDATE); }
+ final DynaGroupChildrenView dynaGroupChildrenView = new DynaGroupChildrenView(extendLocatorId("DynaGroups"), + groupDefinitionId); + // button setup IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); saveButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { if (form.validate()) { - //createOrUpdate(); form.saveData(new DSCallback() { @Override public void execute(DSResponse response, Object rawData, DSRequest request) { - History.back(); + dynaGroupChildrenView.refresh(); + } + }); + } + } + }); + + IButton recalculateButton = new LocatableIButton(this.extendLocatorId("Recalculate"), "Save & Recalculate"); + recalculateButton.setWidth(150); + recalculateButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { + if (form.validate()) { + form.saveData(new DSCallback() { + @Override + public void execute(DSResponse response, Object rawData, DSRequest request) { + GWTServiceLookup.getResourceGroupService().recalculateGroupDefinitions( + new int[] { groupDefinitionId }, new AsyncCallback<Void>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failed to recalculate this group definition", caught); + } + + @Override + public void onSuccess(Void result) { + dynaGroupChildrenView.refresh(); + CoreGUI.getMessageCenter().notify( + new Message("Successfully recalculated this group definition", + Severity.Info)); + } + }); } }); } @@ -157,15 +194,25 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm HLayout buttonLayout = new HLayout(10); // margin between members buttonLayout.setMargin(10); // margin around layout widget buttonLayout.addMember(saveButton); + buttonLayout.addMember(recalculateButton); buttonLayout.addMember(resetButton);
// canvas setup addMember(form); addMember(buttonLayout); + addMember(dynaGroupChildrenView);
markForRedraw(); }
+ class DynaGroupChildrenView extends Table { + public DynaGroupChildrenView(String locatorId, int groupDefinitionId) { + super(locatorId, "DynaGroup Children", new Criteria("groupDefinitionId", String.valueOf(groupDefinition + .getId()))); + setDataSource(ResourceGroupsDataSource.getInstance()); + } + } + public void switchToEditMode() { name.show(); description.show(); 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 71f1996..e1bed72 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 @@ -106,7 +106,6 @@ public class ResourceSearchView extends Table { protected void configureTable() {
getListGrid().setSelectionType(SelectionStyle.SIMPLE); - getListGrid().setResizeFieldsInRealTime(true);
ListGridField idField = new ListGridField("id", "Id", 55); idField.setType(ListGridFieldType.INTEGER);
commit c97a7a3d47cadd9405d9becdfda5beb3da783e8a Author: Joseph Marques joseph@redhat.com Date: Tue Sep 21 01:29:37 2010 -0400
add recalculation method to the ResourceGroup GWT service
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 333427f..d475aa8 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 @@ -30,6 +30,7 @@ import org.rhq.core.domain.util.PageList;
/** * @author Greg Hinkle + * @author Joseph Marques */ @RemoteServiceRelativePath("ResourceGroupGWTService") public interface ResourceGroupGWTService extends RemoteService { @@ -48,6 +49,8 @@ public interface ResourceGroupGWTService extends RemoteService {
PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria);
+ void recalculateGroupDefinitions(int[] groupDefinitionIds); + void setMembership(int groupId, int[] resourceIds, boolean setType);
void updateGroupDefinition(GroupDefinition groupDefinition); @@ -55,5 +58,4 @@ public interface ResourceGroupGWTService extends RemoteService { void updateResourceGroup(ResourceGroup group);
void updateResourceGroup(ResourceGroup group, boolean updateMembership); - } \ No newline at end of file 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 b9642d6..07b9168 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 @@ -132,6 +132,16 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
+ public void recalculateGroupDefinitions(int[] groupDefinitionIds) { + try { + for (int nextGroupDefinitionId : groupDefinitionIds) { + definitionManager.calculateGroupMembership(getSessionSubject(), nextGroupDefinitionId); + } + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } + } + public void deleteGroupDefinitions(int[] groupDefinitionIds) { try { for (int nextGroupDefinitionId : groupDefinitionIds) {
commit a8203c775172bf83d9aa611433f7c051fa253f7d Author: Joseph Marques joseph@redhat.com Date: Mon Sep 20 22:14:15 2010 -0400
remove redundant data caching methods from ResourceGroupsDatasource
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java index 00e9389..00e8819 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java @@ -54,10 +54,7 @@ public class ResourceGroupsDataSource extends RPCDataSource<ResourceGroup> { }
public ResourceGroupsDataSource() { - - // TODO until http://code.google.com/p/smartgwt/issues/detail?id=490 is fixed always go to the server for data - this.setAutoCacheAllData(false); - this.setCacheAllData(false); + super();
DataSourceField idDataField = new DataSourceIntegerField("id", "ID", 20); idDataField.setPrimaryKey(true); @@ -77,8 +74,6 @@ public class ResourceGroupsDataSource extends RPCDataSource<ResourceGroup> { }
public void executeFetch(final DSRequest request, final DSResponse response) { - final long start = System.currentTimeMillis(); - ResourceGroupCriteria criteria = getFetchCriteria(request);
groupService.findResourceGroupsByCriteria(criteria, new AsyncCallback<PageList<ResourceGroup>>() {
commit a5b3075fb496babadb208e2be2b1d4c5f2e92a1e Author: Joseph Marques joseph@redhat.com Date: Mon Sep 20 22:05:17 2010 -0400
remove redundant data caching methods from ResourceDatasource
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java index 280cb89..8a55ed7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java @@ -58,10 +58,6 @@ public class ResourceDatasource extends RPCDataSource<Resource> { public ResourceDatasource() { super();
- // TODO until http://code.google.com/p/smartgwt/issues/detail?id=490 is fixed always go to the server for data - this.setAutoCacheAllData(false); - this.setCacheAllData(false); - DataSourceField idDataField = new DataSourceIntegerField("id", "ID", 20); idDataField.setPrimaryKey(true);
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 dd5e77b..5b3ecf7 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 @@ -58,6 +58,7 @@ public abstract class RPCDataSource<T> extends DataSource { System.out.println("Trying to build DS: " + name); setID(name); } + // TODO until http://code.google.com/p/smartgwt/issues/detail?id=490 is fixed always go to the server for data setClientOnly(false); setAutoCacheAllData(false); setCacheAllData(false);
commit f4d2f1663b3beffe728af06df3aa7a12737fc201 Author: Joseph Marques joseph@redhat.com Date: Mon Sep 20 13:13:58 2010 -0400
remove unnecessary set for number of columns
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index 7b5ea42..1639a92 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -122,7 +122,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("GroupDefinitionForm")); form.setFields(id, idStatic, name, nameStatic, description, descriptionStatic, expression, expressionStatic, recursive, recursiveStatic, recalculationInterval, recalculationIntervalStatic); - form.setNumCols(2); form.setDataSource(dataSource); form.setHiliteRequiredFields(true); form.setRequiredTitleSuffix(" <span style="color: red;">* </span>:");
commit 1140690afe36709b2c53722c9ad447fb7a0ec8c1 Author: Ian Springer ian.springer@redhat.com Date: Mon Sep 20 14:58:44 2010 -0400
only ask discovery components for additional classpath URLs (i.e. client jars) if per-resource classloaders are enabled in the plugin container config
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/ClassLoaderManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/ClassLoaderManager.java index aec2353..ffaae5e 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/ClassLoaderManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/ClassLoaderManager.java @@ -463,6 +463,21 @@ public class ClassLoaderManager { return new HashMap<CanonicalResourceKey, ClassLoader>(this.resourceClassLoaders); }
+ /** + * Returns <code>true</code> if this manager will create instances of classloaders for those + * individual Resources that require it, or <code>false</code> if this manager will never create + * individual classloaders for Resources (i.e. {@link #obtainResourceClassLoader(Resource, ResourceContainer, List)} + * will always just return plugin classloaders). + * + * @return <code>true</code> if this manager will create instances of classloaders for those + * individual Resources that require it, or <code>false</code> if this manager will never create + * individual classloaders for Resources (i.e. {@link #obtainResourceClassLoader(Resource, ResourceContainer, List)} + * will always just return plugin classloaders) + */ + public boolean isCreateResourceClassLoaders() { + return this.createResourceClassLoaders; + } + private Set<ClassLoader> getUniquePluginClassLoaders() { HashSet<ClassLoader> uniqueClassLoaders = new HashSet<ClassLoader>(this.pluginClassLoaders.values()); return uniqueClassLoaders; 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..ca8eef6 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 @@ -23,6 +23,7 @@ package org.rhq.core.pc.plugin;
import java.net.URL; +import java.util.Collections; import java.util.List;
import org.apache.commons.logging.Log; @@ -174,14 +175,16 @@ public class PluginComponentFactory implements ContainerService { + parentResource); } } else if (resource.equals(inventoryMgr.getPlatform())) { - // the given resource is our top platform resource, just use its plugin classloader + // the given resource is our top platform resource - just use its plugin classloader return classLoaderMgr.obtainPluginClassLoader(resourceType.getPlugin()); } else { throw new PluginContainerException("Missing parent resource for resource=" + resource); }
// get the classloader the resource should use - List<URL> additionalJars = askDiscoveryComponentForAdditionalClasspathUrls(resource, parentContainer); + List<URL> additionalJars = (classLoaderMgr.isCreateResourceClassLoaders()) ? + askDiscoveryComponentForAdditionalClasspathUrls(resource, parentContainer) : + Collections.<URL>emptyList(); ClassLoader cl = classLoaderMgr.obtainResourceClassLoader(resource, parentContainer, additionalJars); return cl; } catch (Throwable t) {
commit a63b4bcd0ea05090acac14797f9e06d31e00c6b7 Author: John Mazzitelli mazz@redhat.com Date: Mon Sep 20 14:16:36 2010 -0400
use WIPE animation - seems to work faster than the FADE
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java index a1303a1..0e3a899 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection.java @@ -224,7 +224,7 @@ public abstract class TableSection extends Table implements BookmarkableView { protected void switchToDetailsView() { Canvas contents = getTableContents(); if (contents != null) { - contents.animateHide(AnimationEffect.FADE, new AnimationCallback() { + contents.animateHide(AnimationEffect.WIPE, new AnimationCallback() { @Override public void execute(boolean b) { detailsView.setWidth100(); @@ -232,7 +232,7 @@ public abstract class TableSection extends Table implements BookmarkableView {
detailsHolder.addMember(new BackButton(extendLocatorId("BackButton"), "Back to List", basePath)); detailsHolder.addMember(detailsView); - detailsHolder.animateShow(AnimationEffect.FADE); + detailsHolder.animateShow(AnimationEffect.WIPE); } }); } @@ -246,18 +246,18 @@ public abstract class TableSection extends Table implements BookmarkableView { if (contents != null) {
if (detailsHolder != null && detailsHolder.isVisible()) { - detailsHolder.animateHide(AnimationEffect.FADE, new AnimationCallback() { + detailsHolder.animateHide(AnimationEffect.WIPE, new AnimationCallback() { @Override public void execute(boolean b) { for (Canvas child : detailsHolder.getMembers()) { child.destroy(); }
- contents.animateShow(AnimationEffect.FADE); + contents.animateShow(AnimationEffect.WIPE); } }); } else { - contents.animateShow(AnimationEffect.FADE); + contents.animateShow(AnimationEffect.WIPE); } } }
commit 665349f2a221a7aed276f67197ca9289fba322b2 Author: John Mazzitelli mazz@redhat.com Date: Mon Sep 20 13:05:03 2010 -0400
bz 535756 add the ability to create calltime conditions to an alert definition
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java index 098e92a..14cb2c2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java @@ -54,17 +54,40 @@ public class AlertFormatUtility { break; } case THRESHOLD: { - str.append("Metric Value Exceeds Threshold"); - str.append(" ["); - str.append(condition.getName()); - str.append(" "); - str.append(condition.getComparator()); - str.append(" "); double value = condition.getThreshold(); MeasurementUnits units = condition.getMeasurementDefinition().getUnits(); String formatted = MeasurementConverterClient.format(value, units, true); - str.append(formatted); - str.append("]"); + + if (condition.getOption() == null) { + str.append("Metric Value Exceeds Threshold"); + str.append(" ["); + str.append(condition.getName()); + str.append(" "); + str.append(condition.getComparator()); + str.append(" "); + str.append(formatted); + str.append("]"); + } else { + // this is a calltime threshold condition + // the name of the metric is only obtainable by querying for the name from the meas def ID + // but since most times (all the time?) there is only one calltime metric per resource, + // not showing the metric name probably isn't detrimental + str.append("Calltime Value Exceeds Threshold"); + str.append(" ["); + str.append(condition.getOption()); // MIN, MAX, AVG (never null) + str.append(" "); + str.append(condition.getComparator()); // <, >, = + str.append(" "); + str.append(condition.getThreshold()); + str.append("]"); + if (condition.getName() != null && condition.getName().length() > 0) { + str.append(" "); + str.append("with call destination matching"); + str.append(" '"); + str.append(condition.getName()); + str.append("'"); + } + } break; } case BASELINE: { @@ -86,10 +109,39 @@ public class AlertFormatUtility { break; } case CHANGE: { - str.append("Metric Value Change"); - str.append(" ["); - str.append(condition.getName()); - str.append("]"); + if (condition.getOption() == null) { + str.append("Metric Value Change"); + str.append(" ["); + str.append(condition.getName()); + str.append("]"); + } else { + // this is a calltime change condition + // the name of the metric is only obtainable by querying for the name from the meas def ID + // but since most times (all the time?) there is only one calltime metric per resource, + // not showing the metric name probably isn't detrimental + str.append("Calltime Value Changes"); + str.append(" ["); + str.append(condition.getOption()); // MIN, MAX, AVG (never null) + str.append(" "); + str.append(getCalltimeChangeComparator(condition.getComparator())); // LO, HI, CH + str.append(" "); + str.append("by at least"); + str.append(" "); + + double value = condition.getThreshold(); + MeasurementUnits units = MeasurementUnits.PERCENTAGE; + String formatted = MeasurementConverterClient.format(value, units, true); + str.append(formatted); + + str.append("]"); + if (condition.getName() != null && condition.getName().length() > 0) { + str.append(" "); + str.append("with call destination matching"); + str.append(" '"); + str.append(condition.getName()); + str.append("'"); + } + } break; } case TRAIT: { @@ -122,9 +174,9 @@ public class AlertFormatUtility { if (condition.getOption() != null && condition.getOption().length() > 0) { str.append(" "); str.append("matching"); - str.append(" ["); + str.append(" '"); str.append(condition.getOption()); - str.append("]"); + str.append("'"); } break; } @@ -136,6 +188,16 @@ public class AlertFormatUtility { return str.toString(); }
+ private static String getCalltimeChangeComparator(String comparator) { + if ("HI".equals(comparator)) { + return "Grows"; + } else if ("LO".equals(comparator)) { + return "Shrinks"; + } else { // CH + return "Changes"; + } + } + public static String getAlertRecoveryInfo(Alert alert) { String recoveryInfo; AlertDefinition recoveryAlertDefinition = alert.getRecoveryAlertDefinition(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java index 7e81a0e..3fcc64e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java @@ -58,6 +58,11 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; */ public class NewConditionEditor extends LocatableDynamicForm {
+ // these aren't "real" calltime condition categories (not real AlertConditionCategory enums) + // but we need these values for the drop down menu selections + private static final String ALERT_CONDITION_CATEGORY_CALLTIME_CHANGE = "calltime-change"; + private static final String ALERT_CONDITION_CATEGORY_CALLTIME_THRESHOLD = "calltime-threshold"; + private static final String AVAILABILITY_ITEMNAME = "availability"; private static final String THRESHOLD_METRIC_ITEMNAME = "thresholdMetric"; private static final String THRESHOLD_COMPARATOR_ITEMNAME = "thresholdComparator"; @@ -67,6 +72,16 @@ public class NewConditionEditor extends LocatableDynamicForm { private static final String BASELINE_PERCENTAGE_ITEMNAME = "baselinePercentage"; private static final String BASELINE_SELECTION_ITEMNAME = "baselineSelection"; private static final String CHANGE_METRIC_ITEMNAME = "changeMetric"; + private static final String CALLTIME_THRESHOLD_METRIC_ITEMNAME = "calltimeThresholdMetric"; + private static final String CALLTIME_THRESHOLD_MINMAXAVG_ITEMNAME = "calltimeThresholdMinMaxAvgSelection"; + private static final String CALLTIME_THRESHOLD_COMPARATOR_ITEMNAME = "calltimeThresholdComparator"; + private static final String CALLTIME_THRESHOLD_ABSVALUE_ITEMNAME = "calltimeThresholdAbsoluteValue"; + private static final String CALLTIME_THRESHOLD_REGEX_ITEMNAME = "calltimeThresholdRegex"; + private static final String CALLTIME_CHANGE_METRIC_ITEMNAME = "calltimeChangeMetric"; + private static final String CALLTIME_CHANGE_MINMAXAVG_ITEMNAME = "calltimeChangeMinMaxAvgSelection"; + private static final String CALLTIME_CHANGE_COMPARATOR_ITEMNAME = "calltimeChangeComparator"; + private static final String CALLTIME_CHANGE_PERCENTAGE_ITEMNAME = "calltimeChangePercentageValue"; + private static final String CALLTIME_CHANGE_REGEX_ITEMNAME = "calltimeChangeRegex"; private static final String TRAIT_METRIC_ITEMNAME = "trait"; private static final String OPERATION_NAME_ITEMNAME = "operation"; private static final String OPERATION_RESULTS_ITEMNAME = "operationResults"; @@ -76,6 +91,7 @@ public class NewConditionEditor extends LocatableDynamicForm { private SelectItem conditionTypeSelectItem; private HashSet<AlertCondition> conditions; // the new condition we create goes into this set private boolean supportsMetrics = false; + private boolean supportsCalltimeMetrics = false; private boolean supportsTraits = false; private boolean supportsOperations = false; private boolean supportsEvents = false; @@ -101,6 +117,10 @@ public class NewConditionEditor extends LocatableDynamicForm { this.supportsMetrics = true; break; } + case CALLTIME: { + this.supportsCalltimeMetrics = true; + break; + } case TRAIT: { this.supportsTraits = true; break; @@ -132,6 +152,10 @@ public class NewConditionEditor extends LocatableDynamicForm { condTypes.put(AlertConditionCategory.BASELINE.name(), "Measurement Baseline Threshold"); condTypes.put(AlertConditionCategory.CHANGE.name(), "Measurement Value Change"); } + if (supportsCalltimeMetrics) { + condTypes.put(ALERT_CONDITION_CATEGORY_CALLTIME_THRESHOLD, "Calltime Value Threshold"); + condTypes.put(ALERT_CONDITION_CATEGORY_CALLTIME_CHANGE, "Calltime Value Change"); + } if (supportsTraits) { condTypes.put(AlertConditionCategory.TRAIT.name(), "Trait Value Change"); } @@ -176,6 +200,10 @@ public class NewConditionEditor extends LocatableDynamicForm { formItems.addAll(buildMetricBaselineFormItems()); formItems.addAll(buildMetricChangeFormItems()); } + if (supportsCalltimeMetrics) { + formItems.addAll(buildCalltimeThresholdFormItems()); + formItems.addAll(buildCalltimeChangeFormItems()); + } if (supportsTraits) { formItems.addAll(buildTraitChangeFormItems()); } @@ -194,8 +222,20 @@ public class NewConditionEditor extends LocatableDynamicForm { };
private void saveNewCondition() { - AlertConditionCategory category; - category = AlertConditionCategory.valueOf(conditionTypeSelectItem.getValue().toString()); + final boolean calltimeCategory; + final AlertConditionCategory category; + + String selectedCategory = conditionTypeSelectItem.getValue().toString(); + if (selectedCategory.equals(ALERT_CONDITION_CATEGORY_CALLTIME_THRESHOLD)) { + calltimeCategory = true; + category = AlertConditionCategory.THRESHOLD; + } else if (selectedCategory.equals(ALERT_CONDITION_CATEGORY_CALLTIME_CHANGE)) { + calltimeCategory = true; + category = AlertConditionCategory.CHANGE; + } else { + calltimeCategory = false; + category = AlertConditionCategory.valueOf(selectedCategory); + }
AlertCondition newCondition = new AlertCondition(); newCondition.setCategory(category); @@ -211,12 +251,21 @@ public class NewConditionEditor extends LocatableDynamicForm { }
case THRESHOLD: { - MeasurementDefinition measDef = getMeasurementDefinition(getValueAsString(THRESHOLD_METRIC_ITEMNAME)); - newCondition.setName(measDef.getDisplayName()); // TODO should not use display name - newCondition.setThreshold(Double.valueOf(getValueAsString(THRESHOLD_ABSVALUE_ITEMNAME))); - newCondition.setComparator(getValueAsString(THRESHOLD_COMPARATOR_ITEMNAME)); - newCondition.setOption(null); - newCondition.setMeasurementDefinition(measDef); + if (!calltimeCategory) { + MeasurementDefinition measDef = getMeasurementDefinition(getValueAsString(THRESHOLD_METRIC_ITEMNAME)); + newCondition.setName(measDef.getDisplayName()); // TODO should not use display name + newCondition.setThreshold(Double.valueOf(getValueAsString(THRESHOLD_ABSVALUE_ITEMNAME))); + newCondition.setComparator(getValueAsString(THRESHOLD_COMPARATOR_ITEMNAME)); + newCondition.setOption(null); + newCondition.setMeasurementDefinition(measDef); + } else { + MeasurementDefinition measDef = getMeasurementDefinition(getValueAsString(CALLTIME_THRESHOLD_METRIC_ITEMNAME)); + newCondition.setName(getValueAsString(CALLTIME_THRESHOLD_REGEX_ITEMNAME)); + newCondition.setThreshold(Double.valueOf(getValueAsString(CALLTIME_THRESHOLD_ABSVALUE_ITEMNAME))); + newCondition.setComparator(getValueAsString(CALLTIME_THRESHOLD_COMPARATOR_ITEMNAME)); + newCondition.setOption(getValueAsString(CALLTIME_THRESHOLD_MINMAXAVG_ITEMNAME)); + newCondition.setMeasurementDefinition(measDef); + } break; }
@@ -231,12 +280,22 @@ public class NewConditionEditor extends LocatableDynamicForm { }
case CHANGE: { - MeasurementDefinition measDef = getMeasurementDefinition(getValueAsString(CHANGE_METRIC_ITEMNAME)); - newCondition.setName(measDef.getDisplayName()); // TODO should not use display name - newCondition.setComparator(null); - newCondition.setThreshold(null); - newCondition.setOption(null); - newCondition.setMeasurementDefinition(measDef); + if (!calltimeCategory) { + MeasurementDefinition measDef = getMeasurementDefinition(getValueAsString(CHANGE_METRIC_ITEMNAME)); + newCondition.setName(measDef.getDisplayName()); // TODO should not use display name + newCondition.setComparator(null); + newCondition.setThreshold(null); + newCondition.setOption(null); + newCondition.setMeasurementDefinition(measDef); + } else { + MeasurementDefinition measDef = getMeasurementDefinition(getValueAsString(CALLTIME_CHANGE_METRIC_ITEMNAME)); + newCondition.setName(getValueAsString(CALLTIME_CHANGE_REGEX_ITEMNAME)); + newCondition + .setThreshold(Double.valueOf(getValueAsString(CALLTIME_CHANGE_PERCENTAGE_ITEMNAME)) / 100.0); + newCondition.setComparator(getValueAsString(CALLTIME_CHANGE_COMPARATOR_ITEMNAME)); + newCondition.setOption(getValueAsString(CALLTIME_CHANGE_MINMAXAVG_ITEMNAME)); + newCondition.setMeasurementDefinition(measDef); + } break; }
@@ -360,6 +419,97 @@ public class NewConditionEditor extends LocatableDynamicForm { return formItems; }
+ private ArrayList<FormItem> buildCalltimeThresholdFormItems() { + ArrayList<FormItem> formItems = new ArrayList<FormItem>(); + + ShowIfCategoryFunction ifFunc = new ShowIfCategoryFunction(ALERT_CONDITION_CATEGORY_CALLTIME_THRESHOLD); + + String helpStr = "Specify the calltime threshold value that, when violated, triggers the condition. The value you specify is an absolute value with an optional units specifier. You also must specify which calltime limit to compare the value with (minimum, maximum or average calltime value)."; + StaticTextItem helpItem = buildHelpTextItem("calltimeThresholdHelp", helpStr, ifFunc); + formItems.add(helpItem); + + formItems.add(buildCalltimeMetricDropDownMenu(CALLTIME_THRESHOLD_METRIC_ITEMNAME, ifFunc)); + + SelectItem minMaxAvgSelection = new SelectItem(CALLTIME_THRESHOLD_MINMAXAVG_ITEMNAME, "Calltime Limit"); + LinkedHashMap<String, String> limits = new LinkedHashMap<String, String>(3); + limits.put("MIN", "Minimum"); + limits.put("AVG", "Average"); + limits.put("MAX", "Maximum"); + minMaxAvgSelection.setTooltip("The calltime limit value that is to be compared with the given value"); + minMaxAvgSelection.setValueMap(limits); + minMaxAvgSelection.setDefaultValue("AVG"); + minMaxAvgSelection.setWrapTitle(false); + minMaxAvgSelection.setWidth("*"); + minMaxAvgSelection.setRedrawOnChange(true); + minMaxAvgSelection.setShowIfCondition(ifFunc); + formItems.add(minMaxAvgSelection); + + formItems.add(buildComparatorDropDownMenu(CALLTIME_THRESHOLD_COMPARATOR_ITEMNAME, ifFunc)); + TextItem absoluteValue = new TextItem(CALLTIME_THRESHOLD_ABSVALUE_ITEMNAME, "Calltime Value"); + absoluteValue.setWrapTitle(false); + absoluteValue.setRequired(true); + absoluteValue + .setTooltip("The threshold value of the metric that will trigger the condition when compared using the selected comparator."); + absoluteValue.setShowIfCondition(ifFunc); + formItems.add(absoluteValue); + + TextItem regex = new TextItem(CALLTIME_THRESHOLD_REGEX_ITEMNAME, "Regular Expression"); + regex.setRequired(false); + regex + .setTooltip("If specified, this is a regular expression that must match a call destination in order to trigger the condition."); + regex.setWrapTitle(false); + regex.setShowIfCondition(ifFunc); + formItems.add(regex); + + return formItems; + } + + private ArrayList<FormItem> buildCalltimeChangeFormItems() { + ArrayList<FormItem> formItems = new ArrayList<FormItem>(); + + ShowIfCategoryFunction ifFunc = new ShowIfCategoryFunction(ALERT_CONDITION_CATEGORY_CALLTIME_CHANGE); + + String helpStr = "Specify the calltime value that, when changed at least a specified amount, triggers the condition. You must specify which calltime limit to check (minimum, maximum or average calltime value) and the percentage of change that must occur."; + StaticTextItem helpItem = buildHelpTextItem("calltimeChangeHelp", helpStr, ifFunc); + formItems.add(helpItem); + + formItems.add(buildCalltimeMetricDropDownMenu(CALLTIME_CHANGE_METRIC_ITEMNAME, ifFunc)); + + SelectItem minMaxAvgSelection = new SelectItem(CALLTIME_CHANGE_MINMAXAVG_ITEMNAME, "Calltime Limit"); + LinkedHashMap<String, String> limits = new LinkedHashMap<String, String>(3); + limits.put("MIN", "Minimum"); + limits.put("AVG", "Average"); + limits.put("MAX", "Maximum"); + minMaxAvgSelection.setTooltip("The calltime limit value that is to be checked for change"); + minMaxAvgSelection.setValueMap(limits); + minMaxAvgSelection.setDefaultValue("AVG"); + minMaxAvgSelection.setWrapTitle(false); + minMaxAvgSelection.setWidth("*"); + minMaxAvgSelection.setRedrawOnChange(true); + minMaxAvgSelection.setShowIfCondition(ifFunc); + formItems.add(minMaxAvgSelection); + + formItems.add(buildCalltimeComparatorDropDownMenu(CALLTIME_CHANGE_COMPARATOR_ITEMNAME, ifFunc)); + + TextItem percentage = new TextItem(CALLTIME_CHANGE_PERCENTAGE_ITEMNAME, "Percentage Change"); + percentage.setWrapTitle(false); + percentage.setRequired(true); + percentage + .setTooltip("A collected calltime value will trigger this condition when it differs by at least this percentage of the selected calltime limit value"); + percentage.setShowIfCondition(ifFunc); + formItems.add(percentage); + + TextItem regex = new TextItem(CALLTIME_CHANGE_REGEX_ITEMNAME, "Regular Expression"); + regex.setRequired(false); + regex + .setTooltip("If specified, this is a regular expression that must match a call destination in order to trigger the condition."); + regex.setWrapTitle(false); + regex.setShowIfCondition(ifFunc); + formItems.add(regex); + + return formItems; + } + private ArrayList<FormItem> buildTraitChangeFormItems() { ArrayList<FormItem> formItems = new ArrayList<FormItem>();
@@ -510,9 +660,27 @@ public class NewConditionEditor extends LocatableDynamicForm { return metricSelection; }
+ private SelectItem buildCalltimeMetricDropDownMenu(String itemName, FormItemIfFunction ifFunc) { + + LinkedHashMap<String, String> metricsMap = new LinkedHashMap<String, String>(); + for (MeasurementDefinition def : this.resourceType.getMetricDefinitions()) { + if (def.getDataType() == DataType.CALLTIME) { + metricsMap.put(def.getName(), def.getDisplayName()); + } + } + + SelectItem metricSelection = new SelectItem(itemName, "Metric"); + metricSelection.setValueMap(metricsMap); + metricSelection.setDefaultValue(metricsMap.keySet().iterator().next()); // just use the first one + metricSelection.setWidth("*"); + metricSelection.setRedrawOnChange(true); + metricSelection.setShowIfCondition(ifFunc); + return metricSelection; + } + private SelectItem buildComparatorDropDownMenu(String itemName, FormItemIfFunction ifFunc) {
- LinkedHashMap<String, String> comparators = new LinkedHashMap<String, String>(); + LinkedHashMap<String, String> comparators = new LinkedHashMap<String, String>(3); comparators.put("<", "< (Less than)"); comparators.put("=", "= (Equal to)"); comparators.put(">", "> (Greater than)"); @@ -525,6 +693,21 @@ public class NewConditionEditor extends LocatableDynamicForm { return comparatorSelection; }
+ private SelectItem buildCalltimeComparatorDropDownMenu(String itemName, FormItemIfFunction ifFunc) { + + LinkedHashMap<String, String> comparators = new LinkedHashMap<String, String>(3); + comparators.put("LO", "Shrinks"); + comparators.put("CH", "Changes"); + comparators.put("HI", "Grows"); + + SelectItem comparatorSelection = new SelectItem(itemName, "Comparator"); + comparatorSelection.setValueMap(comparators); + comparatorSelection.setDefaultValue("CH"); + comparatorSelection.setTooltip("How a collected calltime value should be compared to the given calltime limit"); + comparatorSelection.setShowIfCondition(ifFunc); + return comparatorSelection; + } + private StaticTextItem buildHelpTextItem(String itemName, String helpText, FormItemIfFunction ifFunc) { StaticTextItem help = new StaticTextItem(itemName); help.setShowTitle(false); @@ -548,13 +731,25 @@ public class NewConditionEditor extends LocatableDynamicForm {
private class ShowIfCategoryFunction implements FormItemIfFunction { private final AlertConditionCategory category; + private final String calltimeCategory;
public ShowIfCategoryFunction(AlertConditionCategory category) { this.category = category; + this.calltimeCategory = null; + } + + public ShowIfCategoryFunction(String calltimeCategory) { + this.category = null; + this.calltimeCategory = calltimeCategory; }
public boolean execute(FormItem item, Object value, DynamicForm form) { - return category.name().equals(form.getValue("conditionType").toString()); + String conditionTypeString = form.getValue("conditionType").toString(); + if (category != null) { + return category.name().equals(conditionTypeString); + } else { + return calltimeCategory.equals(conditionTypeString); + } } } }
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 d4a02cc3c2fb7e999fede59f3813357e6b0e79ec Author: John Mazzitelli mazz@redhat.com Date: Mon Sep 20 09:19:34 2010 -0400
add more javadocs to explain what the fields are for calltime alert conditions
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertCondition.java b/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertCondition.java index 3218d9d..640648b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertCondition.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertCondition.java @@ -390,6 +390,8 @@ public class AlertCondition implements Serializable { * THRESHOLD: the name of the metric (TODO: today its the display name, very bad for i18n purposes) * BASELINE: the name of the metric (TODO: today its the display name, very bad for i18n purposes) * CHANGE: the name of the metric (TODO: today its the display name, very bad for i18n purposes) + * OR (for calltime alert conditions only) this will be the optional regular expression condition + * (which may be null) * TRAIT: the name of the trait (TODO: today its the display name, very bad for i18n purposes) * CONTROL: the name of the operation (not its display name) * EVENT: the level of event to compare with (DEBUG, INFO, WARN, ERROR, FATAL) @@ -405,11 +407,14 @@ public class AlertCondition implements Serializable { }
/** - * One of these comparators: "<", ">" or "=". - * This will be null if the condition does not compare values. Only THRESHOLD - * and BASELINE condition categories use comparators; other types of conditions - * will return <code>null</code>. + * Will be one of these comparators: "<", ">" or "=" but only for THRESHOLD + * and BASELINE condition categories. For calltime alert conditions (i.e. category + * CHANGE for calltime metric definitions), comparator will be one of these + * comparators: "HI", "LO", "CH" (where "CH" means "change"). * + * Other types of conditions will return <code>null</code> (i.e. this will be + * null if the condition does not compare values). + * * @return comparator string */ public String getComparator() { @@ -422,7 +427,8 @@ public class AlertCondition implements Serializable {
/** * Returns the threshold to compare a measurement value to see if the condition is true. - * This is only valid for conditions of category THRESHOLD and BASELINE. All other + * This is only valid for conditions of category THRESHOLD, BASELINE and CHANGE (but + * only where CHANGE is for a calltime metric alert condition). All other * condition types will return <code>null</code>. * * @return threshold value or null @@ -438,9 +444,9 @@ public class AlertCondition implements Serializable { /** * The option string is optional and its semantics differ based on the category of this condition: * AVAILABILITY: the {@link AvailabilityType} to trigger off of (DOWN or UP) - * THRESHOLD: n/a + * THRESHOLD: for calltime metric conditions, one of "MIN, "MAX", "AVG" - all others are n/a * BASELINE: one of "min", "max" or "mean" - indicates what the threshold is compared to (min/max/avg baseline value) - * CHANGE: n/a + * CHANGE: for calltime metric conditions, one of "MIN, "MAX", "AVG" - all others are n/a * TRAIT: n/a * CONTROL: the {@link OperationRequestStatus} name (SUCCESS, FAILURE, etc). * EVENT: the regular expression of the message to match (which may be empty string if not specified)
commit 24ba99780531d2f187528d7b555d79fab807467b Author: Filip Drabek fdrabek@dhcp-lab-136.englab.brq.redhat.com Date: Mon Sep 20 13:47:47 2010 +0200
BZ - 617603,617649,617653 - permission checks.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java index cb17046..d4451bc 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java @@ -985,7 +985,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
// make sure the user has the proper permissions to do this Resource resource = doomedRequest.getResource(); - if (!authorizationManager.hasResourcePermission(subject, Permission.CONFIGURE_WRITE, resource.getId())) { + if (!authorizationManager.hasResourcePermission(subject, Permission.MODIFY_RESOURCE, resource.getId())) { throw new PermissionException("User [" + subject.getName() + "] does not have permission to purge a configuration update audit trail for resource [" + resource + "]"); @@ -1909,10 +1909,10 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf public int deleteGroupResourceConfigurationUpdates(Subject subject, Integer resourceGroupId, Integer[] groupResourceConfigurationUpdateIds) {
- if (authorizationManager.hasGroupPermission(subject, Permission.CONFIGURE_WRITE, resourceGroupId) == false) { + if (authorizationManager.hasGroupPermission(subject, Permission.MODIFY_RESOURCE, resourceGroupId) == false) { log.error(subject + " attempted to delete " + groupResourceConfigurationUpdateIds.length + " group resource configuration updates for ResourceGroup[id" + resourceGroupId - + "], but did not have the " + Permission.CONFIGURE_WRITE.name() + " permission for this group"); + + "], but did not have the " + Permission.MODIFY_RESOURCE.name() + " permission for this group"); return 0; }
@@ -1983,7 +1983,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf GroupPluginConfigurationUpdate update = getGroupPluginConfigurationById(configurationUpdateId);
int groupId = update.getGroup().getId(); - if (authorizationManager.hasGroupPermission(subject, Permission.CONFIGURE_READ, groupId) == false) { + if (authorizationManager.hasGroupPermission(subject, Permission.MODIFY_RESOURCE, groupId) == false) { throw new PermissionException("User[" + subject.getName() + "] does not have permission to view group resourceConfiguration[id=" + configurationUpdateId + "]"); }
commit c7986f9c539a6f93002eb02a846692ed09ddcc10 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Sep 17 17:44:30 2010 -0400
Work on Group CRUD - Group category now determined on the fly, a la group def calculation, by group membership. This means a manually group can change category in its lifetime by editing the membership. That may be less important than the fact that it simplifies initial creation and users really only have to care about adding members. - Added basic support for mixed-group tree/detail view. Just enough to get us moving. - Added Inventory->Membership subtab for changing group members. - Changed ResourceManagerLocal.ensureMembershipMatches() to .setMembership() The name is cleaner and in line with naming for a series of new calls that simply syncs associated data to be the set passed in. Also, optionally can reset the group's category based on the membership change. - A couple of locatorId fixes in touched files -
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 c4a4bca..333427f 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 @@ -34,23 +34,26 @@ import org.rhq.core.domain.util.PageList; @RemoteServiceRelativePath("ResourceGroupGWTService") public interface ResourceGroupGWTService extends RemoteService {
- PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria); + GroupDefinition createGroupDefinition(GroupDefinition groupDefinition);
- PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria); + ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds);
- PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria); + void deleteGroupDefinitions(int[] groupDefinitionIds);
- void ensureMembershipMatches(int groupId, int[] resourceIds); + void deleteResourceGroups(int[] groupIds);
- ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds); + PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria);
- void deleteResourceGroups(int[] groupIds); + PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria);
- void updateResourceGroup(ResourceGroup group); + PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria); + + void setMembership(int groupId, int[] resourceIds, boolean setType);
void updateGroupDefinition(GroupDefinition groupDefinition);
- void deleteGroupDefinitions(int[] groupDefinitionIds); + void updateResourceGroup(ResourceGroup group);
- GroupDefinition createGroupDefinition(GroupDefinition groupDefinition); -} + void updateResourceGroup(ResourceGroup group, boolean updateMembership); + +} \ No newline at end of file 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 128dff8..6603a00 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 @@ -45,6 +45,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.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; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.summary.OverviewView; @@ -52,10 +53,9 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchVi import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository;
/** - * Right panel of the group view. + * Be able to view members as a resource list, or edit members via selector. * - * @author Greg Hinkle - * @author Ian Springer + * @author Jay Shaughnessy */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { private static final String BASE_VIEW_PATH = "ResourceGroup"; @@ -83,6 +83,7 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource private SubTab monitorCallTime; private SubTab inventoryMembers; private SubTab inventoryConn; + private SubTab inventoryMembership; private SubTab opHistory; private SubTab opSched; private SubTab alertHistory; @@ -91,12 +92,24 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource private SubTab configHistory; private SubTab eventHistory;
+ private String currentTab; + private String currentSubTab; + public ResourceGroupDetailView(String locatorId) { super(locatorId, BASE_VIEW_PATH); }
@Override public Integer getSelectedItemId() { + // if moving from membership subtab then re-load the detail view as the membership and + // group type may have changed. + if (this.inventoryTab.getTitle().equals(currentTab) + && this.inventoryMembership.getTitle().equals(currentSubTab)) { + this.currentTab = null; + this.currentSubTab = null; + this.groupId = null; + } + return this.groupId; }
@@ -130,7 +143,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource "/images/icons/Inventory_grey_16.png"); inventoryMembers = new SubTab(inventoryTab.extendLocatorId("Members"), "Members", null); inventoryConn = new SubTab(inventoryTab.extendLocatorId("ConnectionSettings"), "Connection Settings", null); - inventoryTab.registerSubTabs(this.inventoryMembers, this.inventoryConn); + inventoryMembership = new SubTab(inventoryTab.extendLocatorId("Membership"), "Membership", null); + inventoryTab.registerSubTabs(this.inventoryMembers, this.inventoryConn, this.inventoryMembership); tabs.add(inventoryTab);
operationsTab = new TwoLevelTab(getTabSet().extendLocatorId("Operations"), "Operations", @@ -184,9 +198,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource this.monitorSched.setCanvas(new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId)); this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId));
- this.inventoryMembers.setCanvas(ResourceSearchView.getMembersOf(groupId)); + this.inventoryMembers.setCanvas(ResourceSearchView.getMembersOf(this.inventoryTab + .extendLocatorId("MembersView"), groupId)); // TODO: Uncomment this once the group config component is done. //this.inventoryConn.setCanvas(new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin)); + this.inventoryMembership.setCanvas(new ResourceGroupMembershipView(this.inventoryTab + .extendLocatorId("MembershipView"), groupId));
this.opHistory.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" + groupId)); @@ -290,6 +307,9 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource }); } }); + } else { + updateTabContent(groupComposite); + selectTab(getTabName(), getSubTabName(), viewPath); } }
@@ -305,4 +325,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource } return false; } + + @Override + public void selectTab(String tabTitle, String subtabTitle, ViewPath viewPath) { + currentTab = tabTitle; + currentSubTab = subtabTitle; + super.selectTab(tabTitle, subtabTitle, 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 aa2ee61..ba57920 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 @@ -43,6 +43,7 @@ import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler; import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ClusterKey; +import org.rhq.core.domain.resource.group.GroupCategory; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.resource.group.composite.ClusterFlyweight; import org.rhq.core.domain.resource.group.composite.ClusterKeyFlyweight; @@ -89,14 +90,11 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { treeGrid.setSortField("name"); treeGrid.setShowHeader(false);
- addMember(this.treeGrid);
- contextMenu = new ResourceGroupTreeContextMenu(); treeGrid.setContextMenu(contextMenu);
- treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { @Override public void onSelectionChanged(SelectionEvent selectionEvent) { @@ -141,17 +139,29 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { criteria.fetchResourceType(true);
GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, - new AsyncCallback<PageList<ResourceGroup>>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load group", caught); - } - - @Override - public void onSuccess(PageList<ResourceGroup> result) { - ResourceGroup group = result.get(0); - ResourceGroupTreeView.this.selectedGroup = group; + new AsyncCallback<PageList<ResourceGroup>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load group", caught); + }
+ @Override + public void onSuccess(PageList<ResourceGroup> result) { + ResourceGroup group = result.get(0); + ResourceGroupTreeView.this.selectedGroup = group; + + if (GroupCategory.MIXED == group.getGroupCategory()) { + ResourceGroupTreeView.this.rootResourceGroup = group; + ResourceGroupTreeView.this.rootGroupId = rootResourceGroup.getId(); + TreeNode fakeRoot = new TreeNode("fakeRootNode"); + TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); + rootNode.setID(String.valueOf(rootResourceGroup.getId())); //getClusterKey().toString()); + fakeRoot.setChildren(new TreeNode[] { rootNode }); + Tree tree = new Tree(); + tree.setRoot(fakeRoot); + treeGrid.setData(tree); + treeGrid.markForRedraw(); + } else { if (group.getClusterResourceGroup() == null) { ResourceGroupTreeView.this.rootResourceGroup = group; // This is a straight up group @@ -164,12 +174,12 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView {
loadGroup(rootGroup.getId()); } - } - });
- } + } + });
+ }
private void loadGroup(int groupId) {
@@ -193,19 +203,17 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { treeGrid.selectRecord(selectedNode); }
- } else { this.rootGroupId = groupId; - GWTServiceLookup.getClusterService().getClusterTree(groupId, - new AsyncCallback<ClusterFlyweight>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load tree", caught); - } + GWTServiceLookup.getClusterService().getClusterTree(groupId, new AsyncCallback<ClusterFlyweight>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load tree", caught); + }
- public void onSuccess(ClusterFlyweight result) { - loadTreeTypes(result); - } - }); + public void onSuccess(ClusterFlyweight result) { + loadTreeTypes(result); + } + }); }
} @@ -215,60 +223,54 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { typeIds.add(this.rootResourceGroup.getResourceType().getId()); getTreeTypes(root, typeIds);
- ResourceTypeRepository.Cache.getInstance().getResourceTypes( - typeIds.toArray(new Integer[typeIds.size()]), - new ResourceTypeRepository.TypesLoadedCallback() { - @Override - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { - ResourceGroupTreeView.this.typeMap = types; - loadTree(root); - } + ResourceTypeRepository.Cache.getInstance().getResourceTypes(typeIds.toArray(new Integer[typeIds.size()]), + new ResourceTypeRepository.TypesLoadedCallback() { + @Override + public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + ResourceGroupTreeView.this.typeMap = types; + loadTree(root); } - ); + }); }
- private void selectClusterGroup(ClusterKey key) {
GWTServiceLookup.getClusterService().createAutoClusterBackingGroup(key, true, - new AsyncCallback<ResourceGroup>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create or update auto cluster group", caught); - } + new AsyncCallback<ResourceGroup>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to create or update auto cluster group", caught); + }
- @Override - public void onSuccess(ResourceGroup result) { - int groupId = result.getId(); - History.newItem("ResourceGroup/" + groupId); - } - }); + @Override + public void onSuccess(ResourceGroup result) { + int groupId = result.getId(); + History.newItem("ResourceGroup/" + groupId); + } + });
}
private void loadTree(ClusterFlyweight root) { TreeNode fakeRoot = new TreeNode("fakeRootNode");
- TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); rootNode.setID(String.valueOf(root.getGroupId())); //getClusterKey().toString()); + ResourceType rootResourceType = typeMap.get(rootResourceGroup.getResourceType().getId()); rootNode.setAttribute("resourceType", rootResourceType); String icon = "types/" + rootResourceType.getCategory().getDisplayName() + "_up_16.png"; rootNode.setIcon(icon);
- fakeRoot.setChildren(new TreeNode[]{rootNode}); + fakeRoot.setChildren(new TreeNode[] { rootNode });
ClusterKey rootKey = new ClusterKey(root.getGroupId()); loadTree(rootNode, root, rootKey);
- - Tree tree = new Tree();
tree.setRoot(fakeRoot);
- treeGrid.setData(tree); treeGrid.markForRedraw(); } @@ -286,7 +288,8 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { TreeNode node = new TreeNode(child.getName());
ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); - ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight.getResourceKey()); + ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight + .getResourceKey());
ResourceType type = this.typeMap.get(keyFlyweight.getResourceTypeId());
@@ -294,7 +297,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView {
node.setIcon(icon);
- node.setID(key.getKey()); node.setAttribute("key", key); node.setAttribute("resourceType", type); @@ -317,7 +319,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { setSelectedGroup(groupId); }
- private void getTreeTypes(ClusterFlyweight clusterFlyweight, Set<Integer> typeIds) { if (clusterFlyweight.getClusterKey() != null) { typeIds.add(clusterFlyweight.getClusterKey().getResourceTypeId()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java new file mode 100644 index 0000000..e08b57d --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java @@ -0,0 +1,129 @@ +/* + * 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.inventory; + +import java.util.HashSet; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.layout.LayoutSpacer; +import com.smartgwt.client.widgets.toolbar.ToolStrip; + +import org.rhq.core.domain.criteria.ResourceGroupCriteria; +import org.rhq.core.domain.resource.group.ResourceGroup; +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.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * @author Jay Shaughnessy + */ +public class ResourceGroupMembershipView extends LocatableVLayout { + + private int resourceGroupId; + private ResourceGroup resourceGroup; + private ResourceGroupResourceSelector selector; + + public ResourceGroupMembershipView(String locatorId, int resourceGroupId) { + super(locatorId); + + this.resourceGroupId = resourceGroupId; + } + + @Override + protected void onDraw() { + super.onDraw(); + + build(); + } + + public void build() { + ToolStrip toolStrip = new ToolStrip(); + toolStrip.setWidth100(); + + toolStrip.addMember(new LayoutSpacer()); + + IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + saveButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + save(); + } + }); + + toolStrip.addMember(saveButton); + this.addMember(toolStrip); + + ResourceGroupCriteria c = new ResourceGroupCriteria(); + c.addFilterId(this.resourceGroupId); + c.fetchExplicitResources(true); + GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(c, + new AsyncCallback<PageList<ResourceGroup>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch Resource Group", caught); + } + + public void onSuccess(PageList<ResourceGroup> result) { + ResourceGroupMembershipView.this.resourceGroup = result.get(0); + ResourceGroupMembershipView.this.selector = new ResourceGroupResourceSelector( + ResourceGroupMembershipView.this.getLocatorId(), ResourceGroupMembershipView.this.resourceGroup + .getExplicitResources()); + ResourceGroupMembershipView.this.selector.setOverflow(Overflow.AUTO); + + addMember(ResourceGroupMembershipView.this.selector); + } + }); + } + + private void save() { + int[] resourceIds = getSelectedResourceIds(); + + GWTServiceLookup.getResourceGroupService().setMembership(this.resourceGroup.getId(), resourceIds, true, + new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to update configuration", caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Group membership updated for [" + + ResourceGroupMembershipView.this.resourceGroup.getName() + "]", Message.Severity.Info)); + CoreGUI.refresh(); + } + }); + } + + private int[] getSelectedResourceIds() { + int[] selection = new int[this.selector.getSelection().size()]; + HashSet<Integer> selectedIds = this.selector.getSelection(); + int i = 0; + for (Integer id : selectedIds) { + selection[i++] = id; + } + + return selection; + } + +} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java new file mode 100644 index 0000000..6bc96fb --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java @@ -0,0 +1,45 @@ +/* + * 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.inventory.groups.detail.inventory; + +import java.util.Collection; + +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.resource.Resource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDatasource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector; + +/** + * @author Jay Shaughnessy + */ +public class ResourceGroupResourceSelector extends ResourceSelector { + + public ResourceGroupResourceSelector(String locatorId, Collection<Resource> resources) { + super(locatorId); + if (null != resources) { + ListGridRecord[] data = (new ResourceDatasource()).buildRecords(resources); + setAssigned(data); + } + } +} 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 41aff20..2c3f364 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 @@ -91,7 +91,7 @@ public class OverviewView extends LocatableVLayout { return; } group.setName(newName); - OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { + OverviewView.this.resourceGroupService.updateResourceGroup(group, false, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "Failed to change name of Resource group with id " + group.getId() + " from "" @@ -141,7 +141,7 @@ public class OverviewView extends LocatableVLayout { return; } group.setDescription(newDescription); - OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { + OverviewView.this.resourceGroupService.updateResourceGroup(group, false, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "Failed to change description of Resource group with id " + group.getId() + " from "" @@ -177,7 +177,7 @@ public class OverviewView extends LocatableVLayout { return; } group.setLocation(newLocation); - OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { + 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 "" @@ -224,7 +224,8 @@ public class OverviewView extends LocatableVLayout { StaticTextItem groupDefinitionItem = new StaticTextItem("groupDefinition", "Group Definition"); GroupDefinition groupDefinition = group.getGroupDefinition(); String groupDefinitionUrl = LinkManager.getGroupDefinitionLink(groupDefinition.getId()); - groupDefinitionItem.setValue("<a href="" + groupDefinitionUrl + "">" + groupDefinition.getName() + "</a>"); + groupDefinitionItem + .setValue("<a href="" + groupDefinitionUrl + "">" + groupDefinition.getName() + "</a>"); formItems.add(groupDefinitionItem); }
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 f06f6ae..6b4664a 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 @@ -22,22 +22,16 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.wizard;
-import java.util.LinkedHashMap; - import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.ValuesManager; import com.smartgwt.client.widgets.form.fields.AutoFitTextAreaItem; import com.smartgwt.client.widgets.form.fields.CheckboxItem; -import com.smartgwt.client.widgets.form.fields.IPickTreeItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.TextItem;
-import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ResourceGroup; -import org.rhq.enterprise.gui.coregui.client.components.form.RadioGroupWithComponentsItem; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypePluginTreeDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
/** @@ -68,42 +62,14 @@ public class GroupCreateStep extends AbstractWizardStep {
CheckboxItem recursive = new CheckboxItem("recursive", "Recursive");
- LinkedHashMap<String, Canvas> options = new LinkedHashMap<String, Canvas>(); - options.put("Mixed", null); - - IPickTreeItem typeSelectItem = new IPickTreeItem("type", "Type"); - typeSelectItem.setDataSource(new ResourceTypePluginTreeDataSource()); - typeSelectItem.setValueField("id"); - typeSelectItem.setCanSelectParentItems(true); - typeSelectItem.setLoadDataOnDemand(false); - typeSelectItem.setEmptyMenuMessage("Loading..."); - typeSelectItem.setShowIcons(true); - - DynamicForm form2 = new LocatableDynamicForm("TypeTree"); - form2.setValuesManager(form.getValuesManager()); - form2.setFields(typeSelectItem); - options.put("Compatible", form2); - - RadioGroupWithComponentsItem kind = new RadioGroupWithComponentsItem("groupType", "Group Type", options, - form); - kind.setValue("Mixed"); - form.setFields(name, description, location, recursive, kind); - + form.setFields(name, description, location, recursive); } + return form; }
public boolean nextPage() { - boolean valid = form.validate(); - if (valid) { - RadioGroupWithComponentsItem kind = (RadioGroupWithComponentsItem) form.getField("groupType"); - if ("Compatible".equals(kind.getSelected())) { - DynamicForm form2 = (DynamicForm) kind.getSelectedComponent(); - valid = (null != form2.getValue("type")); - } - } - - return valid; + return form.validate(); }
public String getName() { @@ -116,16 +82,6 @@ public class GroupCreateStep extends AbstractWizardStep { group.setLocation(form.getValueAsString("location")); group.setRecursive(form.getValue("recursive") != null ? true : false);
- RadioGroupWithComponentsItem kind = (RadioGroupWithComponentsItem) form.getField("groupType"); - if ("Compatible".equals(kind.getSelected())) { - DynamicForm form2 = (DynamicForm) kind.getSelectedComponent(); - if (null != form2.getValue("type")) { - ResourceType rt = new ResourceType(); - rt.setId(Integer.parseInt(form2.getValueAsString("type"))); - group.setResourceType(rt); - } - } - return group; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java index a55b334..fbbf71e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java @@ -28,7 +28,6 @@ import java.util.List; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.IButton;
-import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizard; @@ -67,23 +66,11 @@ public class GroupCreateWizard extends AbstractWizard { }
public String getSubtitle() { - return null; // TODO: Implement this method. + return null; }
public List<IButton> getCustomButtons(int step) { - return null; // TODO: Implement this method. - } - - /** - * @return only the rt id is set - */ - public ResourceType getCompatibleGroupResourceType() { - ResourceGroup rg = createStep.getGroup(); - ResourceType rt = null; - if (null != rg) { - rt = rg.getResourceType(); - } - return rt; + return null; }
public void cancel() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java index 3a3048d..2e3e9c7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java @@ -26,7 +26,6 @@ import java.util.HashSet;
import com.smartgwt.client.widgets.Canvas;
-import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector;
@@ -37,18 +36,14 @@ public class GroupMembersStep extends AbstractWizardStep {
private GroupCreateWizard wizard = null; private ResourceSelector selector = null; - private ResourceType requireType = null;
public GroupMembersStep(GroupCreateWizard wizard) { this.wizard = wizard; }
public Canvas getCanvas() { - ResourceType rt = wizard.getCompatibleGroupResourceType(); - if ((selector == null) || (rt != requireType)) { + if (selector == null) { selector = new ResourceSelector(getName()); - requireType = rt; - selector.setRequireType(rt); } return selector; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index faa406e..ed442b2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -57,8 +57,8 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView private static final String SECTION_GROUPS = "Groups"; private static final String SECTION_RESOURCES = "Resources";
- private static final String SUBSECTION_RESOURCE_INVENTORY = "Resource Inventory"; - private static final String SUBSECTION_GROUP_INVENTORY = "Group Inventory"; + private static final String SUBSECTION_RESOURCE_INVENTORY = "Resources"; + private static final String SUBSECTION_GROUP_INVENTORY = "Groups"; private static final String SUBSECTION_SAVED_SEARCHES = "Saved Searches";
private static final String PAGE_ADQ = "Discovery Manager"; 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 9817819..71f1996 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 @@ -182,14 +182,13 @@ public class ResourceSearchView extends Table {
// -------- Static Utility loaders ------------
- public static ResourceSearchView getChildrenOf(int resourceId) { - return new ResourceSearchView("ResourceSearchChildren", new Criteria("parentId", String.valueOf(resourceId)), + public static ResourceSearchView getChildrenOf(String locatorId, int resourceId) { + return new ResourceSearchView(locatorId, new Criteria("parentId", String.valueOf(resourceId)), "Child Resources"); }
- public static ResourceSearchView getMembersOf(int groupId) { - return new ResourceSearchView("ResourceSearchMemberOf", new Criteria("groupId", String.valueOf(groupId)), - "Member Resources"); + public static ResourceSearchView getMembersOf(String locatorId, int groupId) { + return new ResourceSearchView(locatorId, new Criteria("groupId", String.valueOf(groupId)), "Member Resources"); }
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 2edb50f..e80be32 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -207,7 +207,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()));
- this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(resource.getId())); + this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(this.extendLocatorId("Children"), resource + .getId())); this.inventoryConn.setCanvas(new PluginConfigurationEditView(this.extendLocatorId("PluginConfig"), resource));
// comment out GWT-based operation history until... diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java index e9f773d..b1ad07f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java @@ -49,8 +49,8 @@ public class ResourceSelector extends AbstractSelector<Resource> {
private ResourceType requireType;
- public ResourceSelector(String id) { - super(id); + public ResourceSelector(String locatorId) { + super(locatorId); }
public ResourceType getRequireType() { 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 b2ec813..b9642d6 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
+import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; import org.rhq.core.domain.resource.group.GroupDefinition; @@ -36,34 +37,57 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implements ResourceGroupGWTService {
+ private static final long serialVersionUID = 1L; + private ResourceGroupManagerLocal groupManager = LookupUtil.getResourceGroupManager(); private GroupDefinitionManagerLocal definitionManager = LookupUtil.getGroupDefinitionManager();
public PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria) { - return SerialUtility.prepare(groupManager.findResourceGroupsByCriteria(getSessionSubject(), criteria), - "ResourceGroupService.findResourceGroupsByCriteria"); + try { + PageList<ResourceGroup> groups = groupManager.findResourceGroupsByCriteria(getSessionSubject(), criteria); + return SerialUtility.prepare(groups, "ResourceGroupService.findResourceGroupsByCriteria"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria) { - return SerialUtility.prepare(groupManager.findResourceGroupCompositesByCriteria(getSessionSubject(), criteria), - "ResourceGroupService.findResourceGroupCompositesByCriteria"); + try { + PageList<ResourceGroupComposite> composites = groupManager.findResourceGroupCompositesByCriteria( + getSessionSubject(), criteria); + return SerialUtility.prepare(composites, "ResourceGroupService.findResourceGroupCompositesByCriteria"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria) { - return SerialUtility.prepare(definitionManager.findGroupDefinitionsByCriteria(getSessionSubject(), criteria), - "ResourceGroupService.findGroupDefinitionsByCriteria"); + try { + PageList<GroupDefinition> definitions = definitionManager.findGroupDefinitionsByCriteria( + getSessionSubject(), criteria); + return SerialUtility.prepare(definitions, "ResourceGroupService.findGroupDefinitionsByCriteria"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
- public void ensureMembershipMatches(int groupId, int[] resourceIds) { - groupManager.ensureMembershipMatches(getSessionSubject(), groupId, resourceIds); + public void setMembership(int groupId, int[] resourceIds, boolean setType) { + try { + groupManager.setMembership(getSessionSubject(), groupId, resourceIds, setType); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds) { - group = groupManager.createResourceGroup(getSessionSubject(), group); - - ensureMembershipMatches(group.getId(), resourceIds); - - return SerialUtility.prepare(group, "ResourceGroupService.createResourceGroup"); + try { + Subject user = getSessionSubject(); + group = groupManager.createResourceGroup(user, group); + groupManager.setMembership(user, group.getId(), resourceIds, true); + return SerialUtility.prepare(group, "ResourceGroupService.createResourceGroup"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public void deleteResourceGroups(int[] groupIds) { @@ -75,7 +99,19 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen }
public void updateResourceGroup(ResourceGroup group) { - groupManager.updateResourceGroup(getSessionSubject(), group); + try { + groupManager.updateResourceGroup(getSessionSubject(), group); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } + } + + public void updateResourceGroup(ResourceGroup group, boolean updateMembership) { + try { + groupManager.updateResourceGroup(getSessionSubject(), group, null, updateMembership); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public GroupDefinition createGroupDefinition(GroupDefinition groupDefinition) { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java index 10611fa..4aaf7ca 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java @@ -48,7 +48,6 @@ import org.rhq.enterprise.server.authz.AuthorizationManagerLocal; import org.rhq.enterprise.server.authz.PermissionException; import org.rhq.enterprise.server.resource.group.ResourceGroupAlreadyExistsException; import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; -import org.rhq.enterprise.server.resource.group.ResourceGroupUpdateException;
/** * @@ -139,9 +138,9 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe try { // You are allowed to cause the creation of an auto cluster backing group as long as you can // view the parent group. (That check was done above) - resourceGroupManager.ensureMembershipMatches(subjectManager.getOverlord(), autoClusterBackingGroup - .getId(), resourceIds); - } catch (ResourceGroupUpdateException e) { + resourceGroupManager.setMembership(subjectManager.getOverlord(), autoClusterBackingGroup.getId(), + resourceIds, false); + } catch (Exception e) { log.error("Could not add resources to group:" + e); } } @@ -177,11 +176,10 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe }
public ClusterFlyweight getClusterTree(Subject subject, int groupId) { - Query query = entityManager.createQuery( - "SELECT r.id, r.resourceType.id, r.parentResource.id, r.resourceKey, r.name, " + - "(SELECT count(r2) FROM Resource r2 join r2.explicitGroups g2 WHERE g2.id = :groupId and r2.id = r.id) " + - "FROM Resource r join r.implicitGroups g " + - "WHERE g.id = :groupId"); + Query query = entityManager + .createQuery("SELECT r.id, r.resourceType.id, r.parentResource.id, r.resourceKey, r.name, " + + "(SELECT count(r2) FROM Resource r2 join r2.explicitGroups g2 WHERE g2.id = :groupId and r2.id = r.id) " + + "FROM Resource r join r.implicitGroups g " + "WHERE g.id = :groupId");
query.setParameter("groupId", groupId); List<Object[]> rs = query.getResultList(); @@ -203,7 +201,6 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe } }
- ClusterFlyweight key = new ClusterFlyweight(groupId);
buildTree(groupId, key, explicitResources, dataMap); @@ -211,7 +208,8 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe return key; }
- private void buildTree(int groupId, ClusterFlyweight parent, Set<Integer> parentIds, Map<Integer,List<Object[]>> data) { + private void buildTree(int groupId, ClusterFlyweight parent, Set<Integer> parentIds, + Map<Integer, List<Object[]>> data) {
for (Integer parentId : parentIds) {
@@ -219,32 +217,29 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe Map<ClusterKeyFlyweight, Set<Integer>> members = new HashMap<ClusterKeyFlyweight, Set<Integer>>();
if (data.get(parentId) != null) { - for (Object[] child : data.get(parentId)) { - ClusterKeyFlyweight n = new ClusterKeyFlyweight((Integer)child[1], (String)child[3]); + for (Object[] child : data.get(parentId)) { + ClusterKeyFlyweight n = new ClusterKeyFlyweight((Integer) child[1], (String) child[3]); ClusterFlyweight flyweight = children.get(n); - Set<Integer> memberList = members.get(n); - if (flyweight == null) { - flyweight = new ClusterFlyweight(n); - children.put(n, flyweight); - memberList = new HashSet<Integer>(); - members.put(n, memberList); + Set<Integer> memberList = members.get(n); + if (flyweight == null) { + flyweight = new ClusterFlyweight(n); + children.put(n, flyweight); + memberList = new HashSet<Integer>(); + members.put(n, memberList); + } + flyweight.addResource((String) child[4]); + memberList.add((Integer) child[0]); } - flyweight.addResource((String)child[4]); - memberList.add((Integer) child[0]); - } }
parent.setChildren(new ArrayList<ClusterFlyweight>(children.values()));
- for (ClusterFlyweight child : children.values()) { buildTree(groupId, child, members.get(child.getClusterKey()), data); } } }
- - private String getClusterKeyQuery(ClusterKey clusterKey) { if (null == clusterKey) return null; 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 04dd614..28ae218 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 @@ -171,8 +171,19 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso }
@RequiredPermission(Permission.MANAGE_INVENTORY) - public ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType) + public ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group) throws ResourceGroupUpdateException { + return updateResourceGroup(subject, group, null, true); + } + + @RequiredPermission(Permission.MANAGE_INVENTORY) + public ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group, RecursivityChangeType changeType) throws ResourceGroupUpdateException { + return updateResourceGroup(subject, group, null, true); + } + + @RequiredPermission(Permission.MANAGE_INVENTORY) + public ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType, + boolean updateMembership) throws ResourceGroupUpdateException {
int groupId = group.getId(); ResourceGroup attachedGroup = entityManager.find(ResourceGroup.class, groupId); @@ -198,6 +209,11 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso } }
+ if (!updateMembership) { + group.setExplicitResources(attachedGroup.getExplicitResources()); + group.setImplicitResources(attachedGroup.getImplicitResources()); + } + group.setMtime(System.currentTimeMillis()); group.setModifiedBy(user.getName());
@@ -320,7 +336,9 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso try { operationManager.unscheduleGroupOperation(overlord, schedule.getJobId().toString(), group.getId()); } catch (UnscheduleException e) { - log.warn("Failed to unschedule job [" + schedule + "] for a group being deleted [" + group + "]", e); + log + .warn("Failed to unschedule job [" + schedule + "] for a group being deleted [" + group + "]", + e); } } } catch (Exception e) { @@ -759,8 +777,8 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso * to this method, we can just do simple RHQ_RESOURCE_GROUP_RES_IMP_MAP table insertions */ String insertImplicitQueryString = JDBCUtil.transformQueryForMultipleInParameters( - ResourceGroup.QUERY_NATIVE_ADD_RESOURCES_TO_GROUP_IMPLICIT, "@@RESOURCE_IDS@@", - resourceIdsToAdd.size()); + ResourceGroup.QUERY_NATIVE_ADD_RESOURCES_TO_GROUP_IMPLICIT, "@@RESOURCE_IDS@@", resourceIdsToAdd + .size()); insertImplicitStatement = conn.prepareStatement(insertImplicitQueryString); insertImplicitStatement.setInt(1, implicitRecursiveGroupId); JDBCUtil.bindNTimes(insertImplicitStatement, ArrayUtils.unwrapCollection(resourceIdsToAdd), 2); @@ -822,9 +840,9 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso ResourceGroup group = getResourceGroupById(subject, groupId, category); Set<Resource> res = group.getExplicitResources(); if (res != null && res.size() > 0) { - List<Resource> resources = PersistenceUtility.getHibernateSession(entityManager) - .createFilter(res, "where this.inventoryStatus = :inventoryStatus") - .setParameter("inventoryStatus", InventoryStatus.COMMITTED).list(); + List<Resource> resources = PersistenceUtility.getHibernateSession(entityManager).createFilter(res, + "where this.inventoryStatus = :inventoryStatus").setParameter("inventoryStatus", + InventoryStatus.COMMITTED).list();
return resources; } else { @@ -1278,7 +1296,8 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso return groupIds; }
- public void ensureMembershipMatches(Subject subject, int groupId, int[] resourceIds) { + public void setMembership(Subject subject, int groupId, int[] resourceIds, boolean setType) + throws ResourceGroupDeleteException { //throws ResourceGroupUpdateException { List<Integer> currentMembers = resourceManager.findExplicitResourceIdsByResourceGroup(groupId);
@@ -1293,6 +1312,11 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso if (extraMembers.size() > 0) { removeResourcesFromGroup(subject, groupId, ArrayUtils.unwrapCollection(extraMembers)); } + + // As a result of the membership change ensure that the group type is set correctly. + if (setType) { + setResourceType(groupId); + } }
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -1402,11 +1426,6 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso : RecursivityChangeType.RemovedRecursion); }
- @RequiredPermission(Permission.MANAGE_INVENTORY) - public ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group) throws ResourceGroupUpdateException { - return updateResourceGroup(subject, group, null); - } - @SuppressWarnings("unchecked") public PageList<ResourceGroup> findResourceGroupsByCriteria(Subject subject, ResourceGroupCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); 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 2919879..45f7cc4 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,9 +42,6 @@ import org.rhq.core.domain.util.PageList; @Local public interface ResourceGroupManagerLocal {
- ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType) - throws ResourceGroupAlreadyExistsException, ResourceGroupUpdateException; - ResourceGroup getResourceGroupById(Subject user, int id, GroupCategory category) throws ResourceGroupNotFoundException;
@@ -108,10 +105,30 @@ public interface ResourceGroupManagerLocal {
List<Integer> findDeletedResourceGroupIds(int[] groupIds);
- void ensureMembershipMatches(Subject subject, int groupId, int[] resourceIds) throws ResourceGroupUpdateException; + /** + * 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. + * + * @param subject + * @param groupId + * @param resourceIds + * @param setType Set to false if the specified resourceIds will not alter the group type (compatible or + * mixed). Set true to have the group type (re)set automatically, based on the new group membership. + * @throws ResourceGroupUpdateException + * @throws ResourceGroupDeleteException + */ + void setMembership(Subject subject, int groupId, int[] resourceIds, boolean setType) + throws ResourceGroupUpdateException, ResourceGroupDeleteException;
void uninventoryMembers(Subject subject, int groupId);
+ ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType) + throws ResourceGroupAlreadyExistsException, ResourceGroupUpdateException; + + ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType, + boolean updateMembership) throws ResourceGroupAlreadyExistsException, ResourceGroupUpdateException; + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // The following are shared with the Remote Interface @@ -141,5 +158,4 @@ public interface ResourceGroupManagerLocal { ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group);
PageList<ResourceGroup> findResourceGroupsByCriteria(Subject subject, ResourceGroupCriteria criteria); - } \ No newline at end of file
commit 3f9bf4117760546e9efd7284cee6ee61e0090405 Merge: e7d80ea... 19cc4a4... Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Sep 17 17:58:39 2010 -0400
Merge branch 'master' into master-jay
commit 19cc4a49d4041a3dcfdf4cb05bff2ab0b56edec1 Author: Ian Springer ian.springer@redhat.com Date: Fri Sep 17 17:40:48 2010 -0400
add support to as5 plugin for managing AS 6.0 M4 and later (https://bugzilla.redhat.com/show_bug.cgi?id=619240); add support to as5 plugin for discovering and managing AS instances with non-standard lib dirs, e.g. jboss.lib.url (https://bugzilla.redhat.com/show_bug.cgi?id=635158); move JmxConnectionHelper to jboss-as-common module
diff --git a/modules/common/jboss-as/pom.xml b/modules/common/jboss-as/pom.xml index d69311c..b60da0b 100644 --- a/modules/common/jboss-as/pom.xml +++ b/modules/common/jboss-as/pom.xml @@ -45,6 +45,12 @@ </dependency>
<dependency> + <groupId>mc4j</groupId> + <artifactId>org-mc4j-ems</artifactId> + <!-- NOTE: The version is defined in the root POM's dependencyManagement section. --> + </dependency> + + <dependency> <groupId>${project.groupId}</groupId> <artifactId>rhq-core-plugin-api</artifactId> <version>${project.version}</version> diff --git a/modules/common/jboss-as/src/main/java/org/jboss/on/common/jbossas/JmxConnectionHelper.java b/modules/common/jboss-as/src/main/java/org/jboss/on/common/jbossas/JmxConnectionHelper.java new file mode 100644 index 0000000..dc57a78 --- /dev/null +++ b/modules/common/jboss-as/src/main/java/org/jboss/on/common/jbossas/JmxConnectionHelper.java @@ -0,0 +1,262 @@ +/* + * 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.jboss.on.common.jbossas; + +import java.io.File; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mc4j.ems.connection.ConnectionFactory; +import org.mc4j.ems.connection.EmsConnection; +import org.mc4j.ems.connection.settings.ConnectionSettings; +import org.mc4j.ems.connection.support.ConnectionProvider; +import org.mc4j.ems.connection.support.metadata.ConnectionTypeDescriptor; +import org.mc4j.ems.connection.support.metadata.InternalVMTypeDescriptor; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; + +/** + * Shared helper class to connect to a remote JMX server. + * + * @author Heiko W. Rupp + */ +public class JmxConnectionHelper { + public static final String CONNECTOR_DESCRIPTOR_TYPE = "connectorDescriptorType"; + public static final String CONNECTOR_ADDRESS = "connectorAddress"; + public static final String CONNECTOR_PRINCIPAL = "connectorPrincipal"; + public static final String CONNECTOR_CREDENTIALS = "connectorCredentials"; + public static final String JBOSS_HOME_DIR = "jbossHomeDir"; + + private static final Log log = LogFactory.getLog(JmxConnectionHelper.class); + + private static EmsConnection connection; + private static Configuration configuration; + + private static final String JNP_DISABLE_DISCOVERY_JNP_INIT_PROP = "jnp.disableDiscovery"; + + /** + * This is the timeout for the initial connection to the MBeanServer that is made by the AS ResourceComponent's + * start method. + */ + private static final int JNP_TIMEOUT = 30 * 1000; // 30 seconds + /** + * This is the timeout for MBean attribute gets/sets and operations invoked on the remote MBeanServer. + * NOTE: This timeout comes into play if the JBossAS instance has gone down since the original JNP connection was made. + */ + private static final int JNP_SO_TIMEOUT = 15 * 1000; // 15 seconds + + /** + * Controls the dampening of connection error stack traces in an attempt to control spam to the log file. Each time + * a connection error is encountered, this will be incremented. When the connection is finally established, this + * will be reset to zero. + */ + private static int consecutiveConnectionErrors; + + private boolean copyConnectionLibraries; + private File tmpDir; + + /** + * Constructs a new connection helper. + * + * @param copyConnectionLibraries whether to copy the libraries need for the connection so that + * the ems classloader doesn't block the application access to them. + * @param tmpDir the temporary directory to use when copying the libraries + */ + public JmxConnectionHelper(boolean copyConnectionLibraries, File tmpDir) { + this.copyConnectionLibraries = copyConnectionLibraries; + this.tmpDir = tmpDir; + } + + /** + * Obtain an EmsConnection for the passed connection properties. The properties will be retained. + * To create a connection with different properties, use this method again with a different set + * of properties. + * @param config Configuration properties for this connection + * @return an EmsConnection or null in case of failure + * @see #getEmsConnection() + */ + public EmsConnection getEmsConnection(Configuration config) { + EmsConnection emsConnection = null; + configuration = config; + + try { + emsConnection = loadConnection(config, copyConnectionLibraries, tmpDir); + } catch (Exception e) { + log.error("Component attempting to access a connection that could not be loaded"); + } + + return emsConnection; + } + + /** + * Obtain an EmsConnection. This will only work if the connection properties have passed + * before via a call to {@link #getEmsConnection(Configuration)} + * @return an EmsConnection or null in case of failure + * @see #getEmsConnection(org.rhq.core.domain.configuration.Configuration) + */ + public EmsConnection getEmsConnection() { + EmsConnection emsConnection = null; + if (configuration == null) { + throw new RuntimeException("No configuration set"); + } + + try { + emsConnection = loadConnection(configuration, copyConnectionLibraries, tmpDir); + } catch (Exception e) { + log.error("Component attempting to access a connection that could not be loaded"); + } + + return emsConnection; + } + + /** + * This is the preferred way to use a connection from within this class; methods should not access the connection + * property directly as it may not have been instantiated if the connection could not be made. + * <p/> + * <p>If the connection has already been established, return the object reference to it. If not, attempt to make a + * live connection to the JMX server.</p> + * <p/> + * <p>If the connection could not be made in the start(org.rhq.core.pluginapi.inventory.ResourceContext) method, + * this method will effectively try to load the connection on each attempt to use it. As such, multiple threads may + * attempt to access the connection through this means at a time. Therefore, the method has been made synchronized + * on instances of the class.</p> + * <p/> + * <p>If any errors are encountered, this method will log the error, taking into account logic to prevent spamming + * the log file. Calling methods should take care to not redundantly log the exception thrown by this method.</p> + * + * @param pluginConfig + * @return live connection to the JMX server; this will not be <code>null</code> + * @throws Exception if there are any issues at all connecting to the server + */ + private static synchronized EmsConnection loadConnection(Configuration pluginConfig, + boolean copyConnectionLibraries, File tmpDir) throws Exception { + if (connection == null) { + try { + //Configuration pluginConfig = this.resourceContext.getPluginConfiguration(); + + ConnectionSettings connectionSettings = new ConnectionSettings(); + + String connectionTypeDescriptorClass = pluginConfig.getSimple(CONNECTOR_DESCRIPTOR_TYPE) + .getStringValue(); + PropertySimple serverUrl = pluginConfig.getSimple(CONNECTOR_ADDRESS); + + connectionSettings.initializeConnectionType((ConnectionTypeDescriptor) Class.forName( + connectionTypeDescriptorClass).newInstance()); + // if not provided use the default serverUrl + if (null != serverUrl) { + connectionSettings.setServerUrl(serverUrl.getStringValue()); + } + + connectionSettings.setPrincipal(pluginConfig.getSimpleValue(CONNECTOR_PRINCIPAL, null)); + connectionSettings.setCredentials(pluginConfig.getSimpleValue(CONNECTOR_CREDENTIALS, null)); + connectionSettings.setLibraryURI(pluginConfig.getSimpleValue(JBOSS_HOME_DIR, null)); + + if (connectionSettings.getAdvancedProperties() == null) { + connectionSettings.setAdvancedProperties(new Properties()); + } + + connectionSettings.getAdvancedProperties().setProperty(ConnectionFactory.USE_CONTEXT_CLASSLOADER, "true"); + connectionSettings.getAdvancedProperties().setProperty(JNP_DISABLE_DISCOVERY_JNP_INIT_PROP, "true"); + + // Make sure the timeout always happens, even if the JBoss server is hung. + connectionSettings.getAdvancedProperties().setProperty("jnp.timeout", String.valueOf(JNP_TIMEOUT)); + connectionSettings.getAdvancedProperties().setProperty("jnp.sotimeout", String.valueOf(JNP_SO_TIMEOUT)); + + // TODO (ips): Remove this? + connectionSettings.getAdvancedProperties().setProperty(ConnectionFactory.USE_CONTEXT_CLASSLOADER, + Boolean.TRUE.toString()); + + if (copyConnectionLibraries) { + // Tell EMS to make copies of jar files so that the ems classloader doesn't lock + // application files (making us unable to update them) Bug: JBNADM-670 + connectionSettings.getControlProperties().setProperty(ConnectionFactory.COPY_JARS_TO_TEMP, + String.valueOf(Boolean.TRUE)); + } + + // Tell EMS to use the plugin's temp dir, so the PC will be able to clean it up and so an access control + // policy can easily be defined for the dir. EMS will use this for connection libraries (i.e. client + // jars) if COPY_JARS control prop is true, but it will also use it for the ems-mpl jar no matter what, + // so we need to always set it. + connectionSettings.getControlProperties().setProperty(ConnectionFactory.JAR_TEMP_DIR, + tmpDir.getAbsolutePath()); + + connectionSettings.getAdvancedProperties().setProperty(InternalVMTypeDescriptor.DEFAULT_DOMAIN_SEARCH, + "jboss"); + + ConnectionFactory connectionFactory = new ConnectionFactory(); + connectionFactory.discoverServerClasses(connectionSettings); + + ConnectionProvider connectionProvider = connectionFactory.getConnectionProvider(connectionSettings); + connection = connectionProvider.connect(); + + connection.loadSynchronous(false); // this loads all the MBeans + + consecutiveConnectionErrors = 0; + + if (log.isDebugEnabled()) + log.debug("Successfully made connection to the remote server instance"); + } catch (Exception e) { + + // The connection will be established even in the case that the principal cannot be authenticated, + // but the connection will not work. That failure seems to come from the call to loadSynchronous after + // the connection is established. If we get to this point that an exception was thrown, close any + // connection that was made and null it out so we can try to establish it again. + if (connection != null) { + if (log.isDebugEnabled()) + log.debug("Connection created but an exception was thrown. Closing the connection.", e); + connection.close(); + connection = null; + } + + // Since the connection is attempted each time it's used, failure to connect could result in log + // file spamming. Log it once for every 10 consecutive times it's encountered. + if (consecutiveConnectionErrors % 10 == 0) { + log.warn("Could not establish connection to the instance [" + (consecutiveConnectionErrors + 1) + + "] times.", e); + } + + if (log.isDebugEnabled()) + log.debug("Could not connect to the instance for resource ", e); + + consecutiveConnectionErrors++; + + throw e; + } + } + + return connection; + } + + /** + * If necessary attempt to close the EMS connection, then set this.connection null. Synchronized ensure we play + * well with loadConnection. + */ + public synchronized void closeConnection() { + if (connection != null) { + try { + connection.close(); + } catch (Exception e) { + log.error("Error closing EMS connection: " + e); + } + connection = 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 720d1ab..361ac15 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 @@ -353,8 +353,13 @@ public class InventoryManager extends AgentService implements ContainerService, 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. + Configuration pluginConfigClone = resource.getPluginConfiguration().deepCopy(false); + // TODO (ips): Clone the ResourceType too for the same reason. + DiscoveredResourceDetails details = new DiscoveredResourceDetails(resourceType, resource.getResourceKey(), - resource.getName(), resource.getVersion(), resource.getDescription(), resource.getPluginConfiguration(), + 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); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java index bef5806..f8ac5a1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java @@ -75,9 +75,10 @@ public class UpdateCollectionIntervalWidget extends LocatableHLayout implements refresh(UpdateCollectionIntervalWidget.this.schedulesView.getListGrid()); } }); + // Specify a null title so no label is rendered to the left of the combo box. SelectItem unitsItem = new SelectItem("units", null); - unitsItem.setValueMap("seconds", "minutes", "hours"); - unitsItem.setDefaultValue("seconds"); + unitsItem.setValueMap("second(s)", "minute(s)", "hour(s)"); + unitsItem.setDefaultValue("second(s)"); unitsItem.setShowTitle(false); this.form.setFields(intervalItem, unitsItem); addMember(this.form); diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerComponent.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerComponent.java index 6b5dfa4..855791a 100644 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerComponent.java +++ b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerComponent.java @@ -47,6 +47,7 @@ import org.jboss.managed.api.ManagedComponent; import org.jboss.metatype.api.values.SimpleValue; import org.jboss.on.common.jbossas.JBPMWorkflowManager; import org.jboss.on.common.jbossas.JBossASPaths; +import org.jboss.on.common.jbossas.JmxConnectionHelper;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -88,7 +89,6 @@ import org.rhq.plugins.jbossas5.connection.ProfileServiceConnectionProvider; import org.rhq.plugins.jbossas5.connection.RemoteProfileServiceConnectionProvider; import org.rhq.plugins.jbossas5.helper.CreateChildResourceFacetDelegate; import org.rhq.plugins.jbossas5.helper.JBossAS5ConnectionTypeDescriptor; -import org.rhq.plugins.jbossas5.helper.JmxConnectionHelper; import org.rhq.plugins.jbossas5.helper.InPluginControlActionFacade; import org.rhq.plugins.jbossas5.util.ManagedComponentUtils;
diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java index 94cad13..1eb9df6 100644 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java +++ b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java @@ -1,6 +1,6 @@ /* * Jopr Management Platform -* Copyright (C) 2005-2009 Red Hat, Inc. +* Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -24,10 +24,11 @@ package org.rhq.plugins.jbossas5;
import java.io.BufferedReader; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; import java.net.InetAddress; +import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; @@ -66,9 +67,10 @@ import org.rhq.plugins.jbossas5.helper.JBossInstanceInfo; import org.rhq.plugins.jbossas5.helper.JBossProductType; import org.rhq.plugins.jbossas5.helper.JBossProperties; import org.rhq.plugins.jbossas5.util.JnpConfig; +import org.rhq.plugins.jbossas5.util.ResourceComponentUtils;
/** - * A Resource discovery component for JBoss AS Server Resources, which include the following: + * A Resource discovery component for JBoss application server Resources, which include the following: * * JBoss AS, 5.2.0.Beta1 and later * JBoss EAP, 5.0.0.Beta and later @@ -78,6 +80,7 @@ import org.rhq.plugins.jbossas5.util.JnpConfig; * @author Ian Springer * @author Mark Spritzler */ +@SuppressWarnings({"UnusedDeclaration"}) public class ApplicationServerDiscoveryComponent implements ResourceDiscoveryComponent, ClassLoaderFacet, ManualAddFacet { private static final String CHANGE_ME = "***CHANGE_ME***"; @@ -87,7 +90,8 @@ public class ApplicationServerDiscoveryComponent implements ResourceDiscoveryCom private static final String LOCALHOST = "127.0.0.1"; private static final String JAVA_HOME_ENV_VAR = "JAVA_HOME";
- private static final Map<JBossProductType, ComparableVersion> MINIMUM_PRODUCT_VERSIONS = new HashMap(3); + private static final Map<JBossProductType, ComparableVersion> MINIMUM_PRODUCT_VERSIONS = + new HashMap<JBossProductType, ComparableVersion>(4); static { MINIMUM_PRODUCT_VERSIONS.put(JBossProductType.AS, new ComparableVersion("5.2.0.Beta1")); MINIMUM_PRODUCT_VERSIONS.put(JBossProductType.EAP, new ComparableVersion("5.0.0.Beta")); @@ -95,19 +99,23 @@ public class ApplicationServerDiscoveryComponent implements ResourceDiscoveryCom MINIMUM_PRODUCT_VERSIONS.put(JBossProductType.SOA, new ComparableVersion("5.0.0.Beta")); }
- private static final List<String> CLIENT_JARS = Arrays.asList( + private static final String[] CLIENT_JAR_URLS = new String[] { // NOTE: The jbossall-client.jar aggregates a whole bunch of other jars from the client dir via its // MANIFEST.MF Class-Path. - "client/jbossall-client.jar", "client/trove.jar", "client/javassist.jar", - "common/lib/jboss-security-aspects.jar", "lib/jboss-managed.jar", "lib/jboss-metatype.jar", - "lib/jboss-dependency.jar"); - - private static final List<String> AS6_CLIENT_JARS = new ArrayList<String>(CLIENT_JARS); - static { - // The below jars are required for JBoss AS 6.0 M1, M2, and M3. - AS6_CLIENT_JARS.add("lib/jboss-classpool.jar"); - AS6_CLIENT_JARS.add("lib/jboss-classpool-scoped.jar"); - } + "%clientUrl%/jbossall-client.jar", // + "%clientUrl%/trove.jar", // + "%clientUrl%/javassist.jar", // + "%commonLibUrl%/jboss-security-aspects.jar", // + "%libUrl%/jboss-managed.jar", // + "%libUrl%/jboss-metatype.jar", // + "%libUrl%/jboss-dependency.jar", // + // AS 6.0 M1 and later + "%libUrl%/jboss-classpool.jar", // + "%libUrl%/jboss-classpool-scoped.jar", // + // AS 6.0 M4 and later + "%commonLibUrl%/jboss-as-profileservice.jar", // + "%libUrl%/jboss-profileservice-spi.jar" // + };
private final Log log = LogFactory.getLog(this.getClass());
@@ -149,34 +157,63 @@ public class ApplicationServerDiscoveryComponent implements ResourceDiscoveryCom public List<URL> getAdditionalClasspathUrls(ResourceDiscoveryContext context, DiscoveredResourceDetails details) throws Exception { Configuration pluginConfig = details.getPluginConfiguration(); - String homeDir = pluginConfig.getSimple(ApplicationServerPluginConfigurationProperties.HOME_DIR) - .getStringValue(); + setValuesForUnsetClientJarUrlProperties(pluginConfig); + + List<URL> clientJarUrls = new ArrayList<URL>(); + for (String clientJarUrlString : CLIENT_JAR_URLS) { + // Substitute values in for any templated plugin config props. + clientJarUrlString = ResourceComponentUtils.replacePropertyExpressionsInTemplate(clientJarUrlString, + pluginConfig); + URL clientJarUrl = new URL(clientJarUrlString); + if (isReadable(clientJarUrl)) { + clientJarUrls.add(clientJarUrl); + } else { + log.warn("Client JAR [" + clientJarUrl + "] does not exist or is not readable (note, this JAR " + + " may not be required for some app server versions)."); + } + }
- List<URL> clientJars = new ArrayList<URL>(); + return clientJarUrls; + }
- for (String jarFileName : getClientJars(pluginConfig)) { - File clientJar = new File(homeDir, jarFileName); - if (!clientJar.exists()) { - throw new FileNotFoundException("Cannot find [" + clientJar + "] - unable to manage server."); + private boolean isReadable(URL url) { + try { + InputStream inputStream = url.openStream(); + try { + inputStream.close(); } - if (!clientJar.canRead()) { - throw new IOException("Cannot read [" + clientJar + "] - unable to manage server."); + catch (IOException e) { + log.error("Failed to close input stream for URL [" + url + "].", e); } - clientJars.add(clientJar.toURI().toURL()); + return true; + } + catch (IOException e) { + return false; } - - return clientJars; }
- private List<String> getClientJars(Configuration pluginConfig) throws IOException { - PropertySimple jbossHomeDir = pluginConfig.getSimple("homeDir"); - JBossInstallationInfo installationInfo = new JBossInstallationInfo(new File(jbossHomeDir.getStringValue())); + private void setValuesForUnsetClientJarUrlProperties(Configuration pluginConfig) throws MalformedURLException { + String homeDir = pluginConfig.getSimple(ApplicationServerPluginConfigurationProperties.HOME_DIR) + .getStringValue(); + URL homeUrl = new File(homeDir).toURI().toURL(); + + String clientUrlString = pluginConfig.getSimpleValue(ApplicationServerPluginConfigurationProperties.CLIENT_URL, null); + if (clientUrlString == null) { + URL clientUrl = new URL(homeUrl, "client"); + pluginConfig.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.CLIENT_URL, clientUrl)); + }
- if (installationInfo.getMajorVersion().equals("6")) { - return AS6_CLIENT_JARS; + String libUrlString = pluginConfig.getSimpleValue(ApplicationServerPluginConfigurationProperties.LIB_URL, null); + if (libUrlString == null) { + URL libUrl = new URL(homeUrl, "lib"); + pluginConfig.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.LIB_URL, libUrl)); }
- return CLIENT_JARS; + String commonLibUrlString = pluginConfig.getSimpleValue(ApplicationServerPluginConfigurationProperties.COMMON_LIB_URL, null); + if (commonLibUrlString == null) { + URL commonLibUrl = new URL(homeUrl, "common/lib"); + pluginConfig.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.COMMON_LIB_URL, commonLibUrl)); + } }
private Set<DiscoveredResourceDetails> discoverExternalJBossAsProcesses(ResourceDiscoveryContext discoveryContext) { diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerPluginConfigurationProperties.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerPluginConfigurationProperties.java index c87a82f..3489fd4 100644 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerPluginConfigurationProperties.java +++ b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerPluginConfigurationProperties.java @@ -31,6 +31,9 @@ public class ApplicationServerPluginConfigurationProperties { public static final String PRINCIPAL = "principal"; public static final String CREDENTIALS = "credentials"; public static final String HOME_DIR = "homeDir"; + public static final String CLIENT_URL = "clientUrl"; + public static final String LIB_URL = "libUrl"; + public static final String COMMON_LIB_URL = "commonLibUrl"; public static final String SERVER_HOME_DIR = "serverHomeDir"; public static final String JAVA_HOME = "javaHome"; public static final String BIND_ADDRESS = "bindAddress"; diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossProperties.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossProperties.java index 4c88d99..7fa6360 100644 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossProperties.java +++ b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossProperties.java @@ -23,7 +23,8 @@ package org.rhq.plugins.jbossas5.helper;
/** - * The properties that are used by the JBossAS micro-kernel during bootstrap (see http://wiki.jboss.org/wiki/Wiki.jsp?page=JBossProperties). + * The properties that are used by the JBossAS micro-kernel during bootstrap + * (see http://community.jboss.org/wiki/JBossProperties). * * @author Ian Springer */ @@ -44,6 +45,7 @@ public abstract class JBossProperties { public static final String HOME_URL = "jboss.home.url"; public static final String LIB_URL = "jboss.lib.url"; public static final String PATCH_URL = "jboss.patch.url"; + public static final String COMMON_LIB_URL = "jboss.common.lib.url";
/** * The configuration name of the server - default 'default' for AS, or 'production' for EAP or SOA diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JmxConnectionHelper.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JmxConnectionHelper.java deleted file mode 100644 index c07254a..0000000 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JmxConnectionHelper.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2009 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.plugins.jbossas5.helper; - -import java.io.File; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mc4j.ems.connection.ConnectionFactory; -import org.mc4j.ems.connection.EmsConnection; -import org.mc4j.ems.connection.settings.ConnectionSettings; -import org.mc4j.ems.connection.support.ConnectionProvider; -import org.mc4j.ems.connection.support.metadata.ConnectionTypeDescriptor; -import org.mc4j.ems.connection.support.metadata.InternalVMTypeDescriptor; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.PropertySimple; - -/** - * Shared helper class to connect to a remote server - * - * @author Heiko W. Rupp - */ -public class JmxConnectionHelper { - - public static final String CONNECTOR_DESCRIPTOR_TYPE = "connectorDescriptorType"; - public static final String CONNECTOR_ADDRESS = "connectorAddress"; - public static final String CONNECTOR_PRINCIPAL = "connectorPrincipal"; - public static final String CONNECTOR_CREDENTIALS = "connectorCredentials"; - public static final String JBOSS_HOME_DIR = "jbossHomeDir"; - - private static final Log log = LogFactory.getLog(JmxConnectionHelper.class); - - private static EmsConnection connection; - private static Configuration configuration; - - private static final String JNP_DISABLE_DISCOVERY_JNP_INIT_PROP = "jnp.disableDiscovery"; - - /** - * This is the timeout for the initial connection to the MBeanServer that is made by - * {@link org.rhq.plugins.jbossas5.ApplicationServerComponent#start(org.rhq.core.pluginapi.inventory.ResourceContext)}. - */ - private static final int JNP_TIMEOUT = 30 * 1000; // 30 seconds - /** - * This is the timeout for MBean attribute gets/sets and operations invoked on the remote MBeanServer. - * NOTE: This timeout comes into play if the JBossAS instance has gone down since the original JNP connection was made. - */ - private static final int JNP_SO_TIMEOUT = 15 * 1000; // 15 seconds - - /** - * Controls the dampening of connection error stack traces in an attempt to control spam to the log file. Each time - * a connection error is encountered, this will be incremented. When the connection is finally established, this - * will be reset to zero. - */ - private static int consecutiveConnectionErrors; - - private boolean copyConnectionLibraries; - private File tmpDir; - - /** - * Constructs a new connection helper. - * - * @param copyConnectionLibraries whether to copy the libraries need for the connection so that - * the ems classloader doesn't block the application access to them. - * @param tmpDir the temporary directory to use when copying the libraries - */ - public JmxConnectionHelper(boolean copyConnectionLibraries, File tmpDir) { - this.copyConnectionLibraries = copyConnectionLibraries; - this.tmpDir = tmpDir; - } - - /** - * Obtain an EmsConnection for the passed connection properties. The properties will be retained. - * To create a connection with different properties, use this method again with a different set - * of properties. - * @param config Configuration properties for this connection - * @return an EmsConnection or null in case of failure - * @see #getEmsConnection() - */ - public EmsConnection getEmsConnection(Configuration config) { - EmsConnection emsConnection = null; - configuration = config; - - try { - emsConnection = loadConnection(config, copyConnectionLibraries, tmpDir); - } catch (Exception e) { - log.error("Component attempting to access a connection that could not be loaded"); - } - - return emsConnection; - } - - /** - * Obtain an EmsConnection. This will only work if the connection properties have passed - * before via a call to {@link #getEmsConnection(Configuration)} - * @return an EmsConnection or null in case of failure - * @see #getEmsConnection(org.rhq.core.domain.configuration.Configuration) - */ - public EmsConnection getEmsConnection() { - EmsConnection emsConnection = null; - if (configuration == null) { - throw new RuntimeException("No configuration set"); - } - - try { - emsConnection = loadConnection(configuration, copyConnectionLibraries, tmpDir); - } catch (Exception e) { - log.error("Component attempting to access a connection that could not be loaded"); - } - - return emsConnection; - } - - /** - * This is the preferred way to use a connection from within this class; methods should not access the connection - * property directly as it may not have been instantiated if the connection could not be made. - * <p/> - * <p>If the connection has already been established, return the object reference to it. If not, attempt to make a - * live connection to the JMX server.</p> - * <p/> - * <p>If the connection could not be made in the start(org.rhq.core.pluginapi.inventory.ResourceContext) method, - * this method will effectively try to load the connection on each attempt to use it. As such, multiple threads may - * attempt to access the connection through this means at a time. Therefore, the method has been made synchronized - * on instances of the class.</p> - * <p/> - * <p>If any errors are encountered, this method will log the error, taking into account logic to prevent spamming - * the log file. Calling methods should take care to not redundantly log the exception thrown by this method.</p> - * - * @param pluginConfig - * @return live connection to the JMX server; this will not be <code>null</code> - * @throws Exception if there are any issues at all connecting to the server - */ - private static synchronized EmsConnection loadConnection(Configuration pluginConfig, - boolean copyConnectionLibraries, File tmpDir) throws Exception { - if (connection == null) { - try { - //Configuration pluginConfig = this.resourceContext.getPluginConfiguration(); - - ConnectionSettings connectionSettings = new ConnectionSettings(); - - String connectionTypeDescriptorClass = pluginConfig.getSimple(CONNECTOR_DESCRIPTOR_TYPE) - .getStringValue(); - PropertySimple serverUrl = pluginConfig.getSimple(CONNECTOR_ADDRESS); - - connectionSettings.initializeConnectionType((ConnectionTypeDescriptor) Class.forName( - connectionTypeDescriptorClass).newInstance()); - // if not provided use the default serverUrl - if (null != serverUrl) { - connectionSettings.setServerUrl(serverUrl.getStringValue()); - } - - connectionSettings.setPrincipal(pluginConfig.getSimpleValue(CONNECTOR_PRINCIPAL, null)); - connectionSettings.setCredentials(pluginConfig.getSimpleValue(CONNECTOR_CREDENTIALS, null)); - connectionSettings.setLibraryURI(pluginConfig.getSimpleValue(JBOSS_HOME_DIR, null)); - - if (connectionSettings.getAdvancedProperties() == null) { - connectionSettings.setAdvancedProperties(new Properties()); - } - - connectionSettings.getAdvancedProperties().setProperty(ConnectionFactory.USE_CONTEXT_CLASSLOADER, "true"); - connectionSettings.getAdvancedProperties().setProperty(JNP_DISABLE_DISCOVERY_JNP_INIT_PROP, "true"); - - // Make sure the timeout always happens, even if the JBoss server is hung. - connectionSettings.getAdvancedProperties().setProperty("jnp.timeout", String.valueOf(JNP_TIMEOUT)); - connectionSettings.getAdvancedProperties().setProperty("jnp.sotimeout", String.valueOf(JNP_SO_TIMEOUT)); - - // TODO (ips): Remove this? - connectionSettings.getAdvancedProperties().setProperty(ConnectionFactory.USE_CONTEXT_CLASSLOADER, - Boolean.TRUE.toString()); - - if (copyConnectionLibraries) { - // Tell EMS to make copies of jar files so that the ems classloader doesn't lock - // application files (making us unable to update them) Bug: JBNADM-670 - connectionSettings.getControlProperties().setProperty(ConnectionFactory.COPY_JARS_TO_TEMP, - String.valueOf(Boolean.TRUE)); - } - - // Tell EMS to use the plugin's temp dir, so the PC will be able to clean it up and so an access control - // policy can easily be defined for the dir. EMS will use this for connection libraries (i.e. client - // jars) if COPY_JARS control prop is true, but it will also use it for the ems-mpl jar no matter what, - // so we need to always set it. - connectionSettings.getControlProperties().setProperty(ConnectionFactory.JAR_TEMP_DIR, - tmpDir.getAbsolutePath()); - - connectionSettings.getAdvancedProperties().setProperty(InternalVMTypeDescriptor.DEFAULT_DOMAIN_SEARCH, - "jboss"); - - ConnectionFactory connectionFactory = new ConnectionFactory(); - connectionFactory.discoverServerClasses(connectionSettings); - - ConnectionProvider connectionProvider = connectionFactory.getConnectionProvider(connectionSettings); - connection = connectionProvider.connect(); - - connection.loadSynchronous(false); // this loads all the MBeans - - consecutiveConnectionErrors = 0; - - if (log.isDebugEnabled()) - log.debug("Successfully made connection to the remote server instance"); - } catch (Exception e) { - - // The connection will be established even in the case that the principal cannot be authenticated, - // but the connection will not work. That failure seems to come from the call to loadSynchronous after - // the connection is established. If we get to this point that an exception was thrown, close any - // connection that was made and null it out so we can try to establish it again. - if (connection != null) { - if (log.isDebugEnabled()) - log.debug("Connection created but an exception was thrown. Closing the connection.", e); - connection.close(); - connection = null; - } - - // Since the connection is attempted each time it's used, failure to connect could result in log - // file spamming. Log it once for every 10 consecutive times it's encountered. - if (consecutiveConnectionErrors % 10 == 0) { - log.warn("Could not establish connection to the instance [" + (consecutiveConnectionErrors + 1) - + "] times.", e); - } - - if (log.isDebugEnabled()) - log.debug("Could not connect to the instance for resource ", e); - - consecutiveConnectionErrors++; - - throw e; - } - } - - return connection; - } - - /** - * If necessary attempt to close the EMS connection, then set this.connection null. Synchronized ensure we play - * well with loadConnection. - */ - public synchronized void closeConnection() { - if (connection != null) { - try { - connection.close(); - } catch (Exception e) { - log.error("Error closing EMS connection: " + e); - } - connection = null; - } - } - -} 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 ea8ff2d..47ca3e0 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 @@ -972,8 +972,17 @@ description="The name of the server configuration (e.g. minimal, default, or all); if not specified, it will default to the last path component of {serverHomeDir}." default="default"/> + <c:simple-property name="clientUrl" required="false" + description="The URL of the server's client JAR library directory; + if not specified, it will default to {homeDir}/client."/> + <c:simple-property name="libUrl" required="false" + description="The URL of the server's main JAR library directory; + if not specified, it will default to {homeDir}/lib."/> + <c:simple-property name="commonLibUrl" required="false" + description="The URL of the server's common JAR library directory; + if not specified, it will default to {homeDir}/common/lib."/> </c:group> - <c:group name="control" displayName="Operations"> + <c:group name="control" displayName="Operations"> <c:simple-property name="scriptPrefix" displayName="Script Prefix" type="string" required="false" description="A prefix applied to script execution commands. Typically a sudo for applicable platforms. The prefix is applied verbatim. As such, a @@ -1011,7 +1020,7 @@ to 'shutdown script'."/> </c:group>
- <c:group name="advanced" displayName="Advanced" hiddenByDefault="true"> + <c:group name="advanced" displayName="Advanced" hiddenByDefault="true"> <c:simple-property name="shutdownMBeanName" displayName="Shutdown MBean Name" default="jboss.system:type=Server" description="Name of the MBean to use when shutting down this server through JMX."/> @@ -1029,7 +1038,7 @@ <c:simple-property name="childJmxServerName" displayName="JBoss AS JVM Name" default="JVM" readOnly="true" required="false" description="The name of the JBoss AS JVM resource."/> - </c:group> + </c:group>
<c:group name="events"> <c:list-property name="logEventSources"> diff --git a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/JBossASServerComponent.java b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/JBossASServerComponent.java index 5fac37b..8e967ae 100644 --- a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/JBossASServerComponent.java +++ b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/JBossASServerComponent.java @@ -115,7 +115,7 @@ import org.rhq.plugins.jmx.JMXDiscoveryComponent; import org.rhq.plugins.jmx.ObjectNameQueryUtility;
/** -* Supports JBoss 3.2.3 through 4.2.x +* Resource component for managing JBoss AS 3.2.3 through 4.2.x, and JBoss EAP and SOA-P 4.x. * * @author Greg Hinkle * @author John Mazzitelli @@ -156,10 +156,6 @@ public class JBossASServerComponent implements MeasurementFacet, OperationFacet, private static final String RESOURCE_TYPE_WAR = "Web Application (WAR)"; private static final String RESOURCE_TYPE_SAR = "Service Archive (SAR)"; // Not yet used
- // The following constants reference the exact name of the package types as defined in the plugin descriptor - private static final String PACKAGE_TYPE_PATCH = "cumulativePatch"; - private static final String PACKAGE_TYPE_LIBRARY = "library"; - private static final String JNP_DISABLE_DISCOVERY_JNP_INIT_PROP = "jnp.disableDiscovery";
private static final String DISTRIBUTED_REPLICANT_MANAGER_MBEAN_NAME_TEMPLATE = "jboss:partitionName=%partitionName%,service=DistributedReplicantManager"; @@ -1070,6 +1066,8 @@ public class JBossASServerComponent implements MeasurementFacet, OperationFacet, * * @throws Exception if there are any issues at all connecting to the server */ + // TODO (ips): Refactor this method to use the JmxConnectionHelper class from the jboss-as-common module, which is + // what the jboss-as-5 plugin uses. private synchronized EmsConnection loadConnection() throws Exception { if (this.connection == null) { try { diff --git a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossProperties.java b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossProperties.java index 7cfb2b2..680898f 100644 --- a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossProperties.java +++ b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossProperties.java @@ -24,7 +24,7 @@ package org.rhq.plugins.jbossas.helper;
/** * The properties that are used by the JBossAS micro-kernel during bootstrap - * (see http://wiki.jboss.org/wiki/Wiki.jsp?page=JBossProperties). + * (see http://community.jboss.org/wiki/JBossProperties). * * @author Ian Springer */
commit 03d5f59b902515e77f998600875130d476cff61d Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 16 18:42:13 2010 -0400
misc minor
diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java index 4181721..f5350fd 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java @@ -44,13 +44,13 @@ import org.rhq.core.system.ProcessInfo; * @author John Mazzitelli */ public class DiscoveredResourceDetails { - private final Log log = LogFactory.getLog(this.getClass()); - private static final int RESOURCE_KEY_MAX_LENGTH = 500; private static final int RESOURCE_NAME_MAX_LENGTH = 500; private static final int RESOURCE_VERSION_MAX_LENGTH = 100; private static final int RESOURCE_DESCRIPTION_MAX_LENGTH = 1000;
+ private final Log log = LogFactory.getLog(this.getClass()); + private ResourceType resourceType; private String resourceKey; private String resourceName; @@ -289,7 +289,7 @@ public class DiscoveredResourceDetails {
@Override public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder();
buf.append("key="); buf.append(getResourceKey());
commit e7d80ea51297197d838d2810814e25eb73a47776 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Sep 17 17:44:30 2010 -0400
Work on Group CRUD - Group category now determined on the fly, a la group def calculation, by group membership. This means a manually group can change category in its lifetime by editing the membership. That may be less important than the fact that it simplifies initial creation and users really only have to care about adding members. - Added basic support for mixed-group tree/detail view. Just enough to get us moving. - Added Inventory->Membership subtab for changing group members. - Changed ResourceManagerLocal.ensureMembershipMatches() to .setMembership() The name is cleaner and in line with naming for a series of new calls that simply syncs associated data to be the set passed in. Also, optionally can reset the group's category based on the membership change. - A couple of locatorId fixes in touched files -
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 c4a4bca..333427f 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 @@ -34,23 +34,26 @@ import org.rhq.core.domain.util.PageList; @RemoteServiceRelativePath("ResourceGroupGWTService") public interface ResourceGroupGWTService extends RemoteService {
- PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria); + GroupDefinition createGroupDefinition(GroupDefinition groupDefinition);
- PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria); + ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds);
- PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria); + void deleteGroupDefinitions(int[] groupDefinitionIds);
- void ensureMembershipMatches(int groupId, int[] resourceIds); + void deleteResourceGroups(int[] groupIds);
- ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds); + PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria);
- void deleteResourceGroups(int[] groupIds); + PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria);
- void updateResourceGroup(ResourceGroup group); + PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria); + + void setMembership(int groupId, int[] resourceIds, boolean setType);
void updateGroupDefinition(GroupDefinition groupDefinition);
- void deleteGroupDefinitions(int[] groupDefinitionIds); + void updateResourceGroup(ResourceGroup group);
- GroupDefinition createGroupDefinition(GroupDefinition groupDefinition); -} + void updateResourceGroup(ResourceGroup group, boolean updateMembership); + +} \ No newline at end of file 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 128dff8..6603a00 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 @@ -45,6 +45,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.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; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.summary.OverviewView; @@ -52,10 +53,9 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchVi import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository;
/** - * Right panel of the group view. + * Be able to view members as a resource list, or edit members via selector. * - * @author Greg Hinkle - * @author Ian Springer + * @author Jay Shaughnessy */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { private static final String BASE_VIEW_PATH = "ResourceGroup"; @@ -83,6 +83,7 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource private SubTab monitorCallTime; private SubTab inventoryMembers; private SubTab inventoryConn; + private SubTab inventoryMembership; private SubTab opHistory; private SubTab opSched; private SubTab alertHistory; @@ -91,12 +92,24 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource private SubTab configHistory; private SubTab eventHistory;
+ private String currentTab; + private String currentSubTab; + public ResourceGroupDetailView(String locatorId) { super(locatorId, BASE_VIEW_PATH); }
@Override public Integer getSelectedItemId() { + // if moving from membership subtab then re-load the detail view as the membership and + // group type may have changed. + if (this.inventoryTab.getTitle().equals(currentTab) + && this.inventoryMembership.getTitle().equals(currentSubTab)) { + this.currentTab = null; + this.currentSubTab = null; + this.groupId = null; + } + return this.groupId; }
@@ -130,7 +143,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource "/images/icons/Inventory_grey_16.png"); inventoryMembers = new SubTab(inventoryTab.extendLocatorId("Members"), "Members", null); inventoryConn = new SubTab(inventoryTab.extendLocatorId("ConnectionSettings"), "Connection Settings", null); - inventoryTab.registerSubTabs(this.inventoryMembers, this.inventoryConn); + inventoryMembership = new SubTab(inventoryTab.extendLocatorId("Membership"), "Membership", null); + inventoryTab.registerSubTabs(this.inventoryMembers, this.inventoryConn, this.inventoryMembership); tabs.add(inventoryTab);
operationsTab = new TwoLevelTab(getTabSet().extendLocatorId("Operations"), "Operations", @@ -184,9 +198,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource this.monitorSched.setCanvas(new SchedulesView(this.monitoringTab.extendLocatorId("SchedulesView"), groupId)); this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/group/monitor/response-plain.xhtml?groupId=" + groupId));
- this.inventoryMembers.setCanvas(ResourceSearchView.getMembersOf(groupId)); + this.inventoryMembers.setCanvas(ResourceSearchView.getMembersOf(this.inventoryTab + .extendLocatorId("MembersView"), groupId)); // TODO: Uncomment this once the group config component is done. //this.inventoryConn.setCanvas(new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin)); + this.inventoryMembership.setCanvas(new ResourceGroupMembershipView(this.inventoryTab + .extendLocatorId("MembershipView"), groupId));
this.opHistory.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" + groupId)); @@ -290,6 +307,9 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource }); } }); + } else { + updateTabContent(groupComposite); + selectTab(getTabName(), getSubTabName(), viewPath); } }
@@ -305,4 +325,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource } return false; } + + @Override + public void selectTab(String tabTitle, String subtabTitle, ViewPath viewPath) { + currentTab = tabTitle; + currentSubTab = subtabTitle; + super.selectTab(tabTitle, subtabTitle, 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 aa2ee61..ba57920 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 @@ -43,6 +43,7 @@ import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler; import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ClusterKey; +import org.rhq.core.domain.resource.group.GroupCategory; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.resource.group.composite.ClusterFlyweight; import org.rhq.core.domain.resource.group.composite.ClusterKeyFlyweight; @@ -89,14 +90,11 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { treeGrid.setSortField("name"); treeGrid.setShowHeader(false);
- addMember(this.treeGrid);
- contextMenu = new ResourceGroupTreeContextMenu(); treeGrid.setContextMenu(contextMenu);
- treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { @Override public void onSelectionChanged(SelectionEvent selectionEvent) { @@ -141,17 +139,29 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { criteria.fetchResourceType(true);
GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, - new AsyncCallback<PageList<ResourceGroup>>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load group", caught); - } - - @Override - public void onSuccess(PageList<ResourceGroup> result) { - ResourceGroup group = result.get(0); - ResourceGroupTreeView.this.selectedGroup = group; + new AsyncCallback<PageList<ResourceGroup>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load group", caught); + }
+ @Override + public void onSuccess(PageList<ResourceGroup> result) { + ResourceGroup group = result.get(0); + ResourceGroupTreeView.this.selectedGroup = group; + + if (GroupCategory.MIXED == group.getGroupCategory()) { + ResourceGroupTreeView.this.rootResourceGroup = group; + ResourceGroupTreeView.this.rootGroupId = rootResourceGroup.getId(); + TreeNode fakeRoot = new TreeNode("fakeRootNode"); + TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); + rootNode.setID(String.valueOf(rootResourceGroup.getId())); //getClusterKey().toString()); + fakeRoot.setChildren(new TreeNode[] { rootNode }); + Tree tree = new Tree(); + tree.setRoot(fakeRoot); + treeGrid.setData(tree); + treeGrid.markForRedraw(); + } else { if (group.getClusterResourceGroup() == null) { ResourceGroupTreeView.this.rootResourceGroup = group; // This is a straight up group @@ -164,12 +174,12 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView {
loadGroup(rootGroup.getId()); } - } - });
- } + } + });
+ }
private void loadGroup(int groupId) {
@@ -193,19 +203,17 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { treeGrid.selectRecord(selectedNode); }
- } else { this.rootGroupId = groupId; - GWTServiceLookup.getClusterService().getClusterTree(groupId, - new AsyncCallback<ClusterFlyweight>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load tree", caught); - } + GWTServiceLookup.getClusterService().getClusterTree(groupId, new AsyncCallback<ClusterFlyweight>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load tree", caught); + }
- public void onSuccess(ClusterFlyweight result) { - loadTreeTypes(result); - } - }); + public void onSuccess(ClusterFlyweight result) { + loadTreeTypes(result); + } + }); }
} @@ -215,60 +223,54 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { typeIds.add(this.rootResourceGroup.getResourceType().getId()); getTreeTypes(root, typeIds);
- ResourceTypeRepository.Cache.getInstance().getResourceTypes( - typeIds.toArray(new Integer[typeIds.size()]), - new ResourceTypeRepository.TypesLoadedCallback() { - @Override - public void onTypesLoaded(HashMap<Integer, ResourceType> types) { - ResourceGroupTreeView.this.typeMap = types; - loadTree(root); - } + ResourceTypeRepository.Cache.getInstance().getResourceTypes(typeIds.toArray(new Integer[typeIds.size()]), + new ResourceTypeRepository.TypesLoadedCallback() { + @Override + public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + ResourceGroupTreeView.this.typeMap = types; + loadTree(root); } - ); + }); }
- private void selectClusterGroup(ClusterKey key) {
GWTServiceLookup.getClusterService().createAutoClusterBackingGroup(key, true, - new AsyncCallback<ResourceGroup>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create or update auto cluster group", caught); - } + new AsyncCallback<ResourceGroup>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to create or update auto cluster group", caught); + }
- @Override - public void onSuccess(ResourceGroup result) { - int groupId = result.getId(); - History.newItem("ResourceGroup/" + groupId); - } - }); + @Override + public void onSuccess(ResourceGroup result) { + int groupId = result.getId(); + History.newItem("ResourceGroup/" + groupId); + } + });
}
private void loadTree(ClusterFlyweight root) { TreeNode fakeRoot = new TreeNode("fakeRootNode");
- TreeNode rootNode = new TreeNode(rootResourceGroup.getName()); rootNode.setID(String.valueOf(root.getGroupId())); //getClusterKey().toString()); + ResourceType rootResourceType = typeMap.get(rootResourceGroup.getResourceType().getId()); rootNode.setAttribute("resourceType", rootResourceType); String icon = "types/" + rootResourceType.getCategory().getDisplayName() + "_up_16.png"; rootNode.setIcon(icon);
- fakeRoot.setChildren(new TreeNode[]{rootNode}); + fakeRoot.setChildren(new TreeNode[] { rootNode });
ClusterKey rootKey = new ClusterKey(root.getGroupId()); loadTree(rootNode, root, rootKey);
- - Tree tree = new Tree();
tree.setRoot(fakeRoot);
- treeGrid.setData(tree); treeGrid.markForRedraw(); } @@ -286,7 +288,8 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { TreeNode node = new TreeNode(child.getName());
ClusterKeyFlyweight keyFlyweight = child.getClusterKey(); - ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight.getResourceKey()); + ClusterKey key = new ClusterKey(parentKey, keyFlyweight.getResourceTypeId(), keyFlyweight + .getResourceKey());
ResourceType type = this.typeMap.get(keyFlyweight.getResourceTypeId());
@@ -294,7 +297,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView {
node.setIcon(icon);
- node.setID(key.getKey()); node.setAttribute("key", key); node.setAttribute("resourceType", type); @@ -317,7 +319,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { setSelectedGroup(groupId); }
- private void getTreeTypes(ClusterFlyweight clusterFlyweight, Set<Integer> typeIds) { if (clusterFlyweight.getClusterKey() != null) { typeIds.add(clusterFlyweight.getClusterKey().getResourceTypeId()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java new file mode 100644 index 0000000..e08b57d --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupMembershipView.java @@ -0,0 +1,129 @@ +/* + * 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.inventory; + +import java.util.HashSet; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.layout.LayoutSpacer; +import com.smartgwt.client.widgets.toolbar.ToolStrip; + +import org.rhq.core.domain.criteria.ResourceGroupCriteria; +import org.rhq.core.domain.resource.group.ResourceGroup; +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.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * @author Jay Shaughnessy + */ +public class ResourceGroupMembershipView extends LocatableVLayout { + + private int resourceGroupId; + private ResourceGroup resourceGroup; + private ResourceGroupResourceSelector selector; + + public ResourceGroupMembershipView(String locatorId, int resourceGroupId) { + super(locatorId); + + this.resourceGroupId = resourceGroupId; + } + + @Override + protected void onDraw() { + super.onDraw(); + + build(); + } + + public void build() { + ToolStrip toolStrip = new ToolStrip(); + toolStrip.setWidth100(); + + toolStrip.addMember(new LayoutSpacer()); + + IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + saveButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + save(); + } + }); + + toolStrip.addMember(saveButton); + this.addMember(toolStrip); + + ResourceGroupCriteria c = new ResourceGroupCriteria(); + c.addFilterId(this.resourceGroupId); + c.fetchExplicitResources(true); + GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(c, + new AsyncCallback<PageList<ResourceGroup>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch Resource Group", caught); + } + + public void onSuccess(PageList<ResourceGroup> result) { + ResourceGroupMembershipView.this.resourceGroup = result.get(0); + ResourceGroupMembershipView.this.selector = new ResourceGroupResourceSelector( + ResourceGroupMembershipView.this.getLocatorId(), ResourceGroupMembershipView.this.resourceGroup + .getExplicitResources()); + ResourceGroupMembershipView.this.selector.setOverflow(Overflow.AUTO); + + addMember(ResourceGroupMembershipView.this.selector); + } + }); + } + + private void save() { + int[] resourceIds = getSelectedResourceIds(); + + GWTServiceLookup.getResourceGroupService().setMembership(this.resourceGroup.getId(), resourceIds, true, + new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to update configuration", caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Group membership updated for [" + + ResourceGroupMembershipView.this.resourceGroup.getName() + "]", Message.Severity.Info)); + CoreGUI.refresh(); + } + }); + } + + private int[] getSelectedResourceIds() { + int[] selection = new int[this.selector.getSelection().size()]; + HashSet<Integer> selectedIds = this.selector.getSelection(); + int i = 0; + for (Integer id : selectedIds) { + selection[i++] = id; + } + + return selection; + } + +} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java new file mode 100644 index 0000000..6bc96fb --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/ResourceGroupResourceSelector.java @@ -0,0 +1,45 @@ +/* + * 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.inventory.groups.detail.inventory; + +import java.util.Collection; + +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.resource.Resource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDatasource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector; + +/** + * @author Jay Shaughnessy + */ +public class ResourceGroupResourceSelector extends ResourceSelector { + + public ResourceGroupResourceSelector(String locatorId, Collection<Resource> resources) { + super(locatorId); + if (null != resources) { + ListGridRecord[] data = (new ResourceDatasource()).buildRecords(resources); + setAssigned(data); + } + } +} 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 41aff20..2c3f364 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 @@ -91,7 +91,7 @@ public class OverviewView extends LocatableVLayout { return; } group.setName(newName); - OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { + OverviewView.this.resourceGroupService.updateResourceGroup(group, false, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "Failed to change name of Resource group with id " + group.getId() + " from "" @@ -141,7 +141,7 @@ public class OverviewView extends LocatableVLayout { return; } group.setDescription(newDescription); - OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { + OverviewView.this.resourceGroupService.updateResourceGroup(group, false, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "Failed to change description of Resource group with id " + group.getId() + " from "" @@ -177,7 +177,7 @@ public class OverviewView extends LocatableVLayout { return; } group.setLocation(newLocation); - OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { + 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 "" @@ -224,7 +224,8 @@ public class OverviewView extends LocatableVLayout { StaticTextItem groupDefinitionItem = new StaticTextItem("groupDefinition", "Group Definition"); GroupDefinition groupDefinition = group.getGroupDefinition(); String groupDefinitionUrl = LinkManager.getGroupDefinitionLink(groupDefinition.getId()); - groupDefinitionItem.setValue("<a href="" + groupDefinitionUrl + "">" + groupDefinition.getName() + "</a>"); + groupDefinitionItem + .setValue("<a href="" + groupDefinitionUrl + "">" + groupDefinition.getName() + "</a>"); formItems.add(groupDefinitionItem); }
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 f06f6ae..6b4664a 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 @@ -22,22 +22,16 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.wizard;
-import java.util.LinkedHashMap; - import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.ValuesManager; import com.smartgwt.client.widgets.form.fields.AutoFitTextAreaItem; import com.smartgwt.client.widgets.form.fields.CheckboxItem; -import com.smartgwt.client.widgets.form.fields.IPickTreeItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.TextItem;
-import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ResourceGroup; -import org.rhq.enterprise.gui.coregui.client.components.form.RadioGroupWithComponentsItem; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypePluginTreeDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
/** @@ -68,42 +62,14 @@ public class GroupCreateStep extends AbstractWizardStep {
CheckboxItem recursive = new CheckboxItem("recursive", "Recursive");
- LinkedHashMap<String, Canvas> options = new LinkedHashMap<String, Canvas>(); - options.put("Mixed", null); - - IPickTreeItem typeSelectItem = new IPickTreeItem("type", "Type"); - typeSelectItem.setDataSource(new ResourceTypePluginTreeDataSource()); - typeSelectItem.setValueField("id"); - typeSelectItem.setCanSelectParentItems(true); - typeSelectItem.setLoadDataOnDemand(false); - typeSelectItem.setEmptyMenuMessage("Loading..."); - typeSelectItem.setShowIcons(true); - - DynamicForm form2 = new LocatableDynamicForm("TypeTree"); - form2.setValuesManager(form.getValuesManager()); - form2.setFields(typeSelectItem); - options.put("Compatible", form2); - - RadioGroupWithComponentsItem kind = new RadioGroupWithComponentsItem("groupType", "Group Type", options, - form); - kind.setValue("Mixed"); - form.setFields(name, description, location, recursive, kind); - + form.setFields(name, description, location, recursive); } + return form; }
public boolean nextPage() { - boolean valid = form.validate(); - if (valid) { - RadioGroupWithComponentsItem kind = (RadioGroupWithComponentsItem) form.getField("groupType"); - if ("Compatible".equals(kind.getSelected())) { - DynamicForm form2 = (DynamicForm) kind.getSelectedComponent(); - valid = (null != form2.getValue("type")); - } - } - - return valid; + return form.validate(); }
public String getName() { @@ -116,16 +82,6 @@ public class GroupCreateStep extends AbstractWizardStep { group.setLocation(form.getValueAsString("location")); group.setRecursive(form.getValue("recursive") != null ? true : false);
- RadioGroupWithComponentsItem kind = (RadioGroupWithComponentsItem) form.getField("groupType"); - if ("Compatible".equals(kind.getSelected())) { - DynamicForm form2 = (DynamicForm) kind.getSelectedComponent(); - if (null != form2.getValue("type")) { - ResourceType rt = new ResourceType(); - rt.setId(Integer.parseInt(form2.getValueAsString("type"))); - group.setResourceType(rt); - } - } - return group; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java index a55b334..fbbf71e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateWizard.java @@ -28,7 +28,6 @@ import java.util.List; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.IButton;
-import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizard; @@ -67,23 +66,11 @@ public class GroupCreateWizard extends AbstractWizard { }
public String getSubtitle() { - return null; // TODO: Implement this method. + return null; }
public List<IButton> getCustomButtons(int step) { - return null; // TODO: Implement this method. - } - - /** - * @return only the rt id is set - */ - public ResourceType getCompatibleGroupResourceType() { - ResourceGroup rg = createStep.getGroup(); - ResourceType rt = null; - if (null != rg) { - rt = rg.getResourceType(); - } - return rt; + return null; }
public void cancel() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java index 3a3048d..2e3e9c7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupMembersStep.java @@ -26,7 +26,6 @@ import java.util.HashSet;
import com.smartgwt.client.widgets.Canvas;
-import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceSelector;
@@ -37,18 +36,14 @@ public class GroupMembersStep extends AbstractWizardStep {
private GroupCreateWizard wizard = null; private ResourceSelector selector = null; - private ResourceType requireType = null;
public GroupMembersStep(GroupCreateWizard wizard) { this.wizard = wizard; }
public Canvas getCanvas() { - ResourceType rt = wizard.getCompatibleGroupResourceType(); - if ((selector == null) || (rt != requireType)) { + if (selector == null) { selector = new ResourceSelector(getName()); - requireType = rt; - selector.setRequireType(rt); } return selector; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index faa406e..ed442b2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -57,8 +57,8 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView private static final String SECTION_GROUPS = "Groups"; private static final String SECTION_RESOURCES = "Resources";
- private static final String SUBSECTION_RESOURCE_INVENTORY = "Resource Inventory"; - private static final String SUBSECTION_GROUP_INVENTORY = "Group Inventory"; + private static final String SUBSECTION_RESOURCE_INVENTORY = "Resources"; + private static final String SUBSECTION_GROUP_INVENTORY = "Groups"; private static final String SUBSECTION_SAVED_SEARCHES = "Saved Searches";
private static final String PAGE_ADQ = "Discovery Manager"; 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 9817819..71f1996 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 @@ -182,14 +182,13 @@ public class ResourceSearchView extends Table {
// -------- Static Utility loaders ------------
- public static ResourceSearchView getChildrenOf(int resourceId) { - return new ResourceSearchView("ResourceSearchChildren", new Criteria("parentId", String.valueOf(resourceId)), + public static ResourceSearchView getChildrenOf(String locatorId, int resourceId) { + return new ResourceSearchView(locatorId, new Criteria("parentId", String.valueOf(resourceId)), "Child Resources"); }
- public static ResourceSearchView getMembersOf(int groupId) { - return new ResourceSearchView("ResourceSearchMemberOf", new Criteria("groupId", String.valueOf(groupId)), - "Member Resources"); + public static ResourceSearchView getMembersOf(String locatorId, int groupId) { + return new ResourceSearchView(locatorId, new Criteria("groupId", String.valueOf(groupId)), "Member Resources"); }
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index 2edb50f..e80be32 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -207,7 +207,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()));
- this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(resource.getId())); + this.inventoryChildren.setCanvas(ResourceSearchView.getChildrenOf(this.extendLocatorId("Children"), resource + .getId())); this.inventoryConn.setCanvas(new PluginConfigurationEditView(this.extendLocatorId("PluginConfig"), resource));
// comment out GWT-based operation history until... diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java index e9f773d..b1ad07f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java @@ -49,8 +49,8 @@ public class ResourceSelector extends AbstractSelector<Resource> {
private ResourceType requireType;
- public ResourceSelector(String id) { - super(id); + public ResourceSelector(String locatorId) { + super(locatorId); }
public ResourceType getRequireType() { 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 b2ec813..b9642d6 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
+import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; import org.rhq.core.domain.resource.group.GroupDefinition; @@ -36,34 +37,57 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implements ResourceGroupGWTService {
+ private static final long serialVersionUID = 1L; + private ResourceGroupManagerLocal groupManager = LookupUtil.getResourceGroupManager(); private GroupDefinitionManagerLocal definitionManager = LookupUtil.getGroupDefinitionManager();
public PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria) { - return SerialUtility.prepare(groupManager.findResourceGroupsByCriteria(getSessionSubject(), criteria), - "ResourceGroupService.findResourceGroupsByCriteria"); + try { + PageList<ResourceGroup> groups = groupManager.findResourceGroupsByCriteria(getSessionSubject(), criteria); + return SerialUtility.prepare(groups, "ResourceGroupService.findResourceGroupsByCriteria"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria) { - return SerialUtility.prepare(groupManager.findResourceGroupCompositesByCriteria(getSessionSubject(), criteria), - "ResourceGroupService.findResourceGroupCompositesByCriteria"); + try { + PageList<ResourceGroupComposite> composites = groupManager.findResourceGroupCompositesByCriteria( + getSessionSubject(), criteria); + return SerialUtility.prepare(composites, "ResourceGroupService.findResourceGroupCompositesByCriteria"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria) { - return SerialUtility.prepare(definitionManager.findGroupDefinitionsByCriteria(getSessionSubject(), criteria), - "ResourceGroupService.findGroupDefinitionsByCriteria"); + try { + PageList<GroupDefinition> definitions = definitionManager.findGroupDefinitionsByCriteria( + getSessionSubject(), criteria); + return SerialUtility.prepare(definitions, "ResourceGroupService.findGroupDefinitionsByCriteria"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
- public void ensureMembershipMatches(int groupId, int[] resourceIds) { - groupManager.ensureMembershipMatches(getSessionSubject(), groupId, resourceIds); + public void setMembership(int groupId, int[] resourceIds, boolean setType) { + try { + groupManager.setMembership(getSessionSubject(), groupId, resourceIds, setType); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds) { - group = groupManager.createResourceGroup(getSessionSubject(), group); - - ensureMembershipMatches(group.getId(), resourceIds); - - return SerialUtility.prepare(group, "ResourceGroupService.createResourceGroup"); + try { + Subject user = getSessionSubject(); + group = groupManager.createResourceGroup(user, group); + groupManager.setMembership(user, group.getId(), resourceIds, true); + return SerialUtility.prepare(group, "ResourceGroupService.createResourceGroup"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public void deleteResourceGroups(int[] groupIds) { @@ -75,7 +99,19 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen }
public void updateResourceGroup(ResourceGroup group) { - groupManager.updateResourceGroup(getSessionSubject(), group); + try { + groupManager.updateResourceGroup(getSessionSubject(), group); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } + } + + public void updateResourceGroup(ResourceGroup group, boolean updateMembership) { + try { + groupManager.updateResourceGroup(getSessionSubject(), group, null, updateMembership); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
public GroupDefinition createGroupDefinition(GroupDefinition groupDefinition) { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java index 10611fa..4aaf7ca 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/cluster/ClusterManagerBean.java @@ -48,7 +48,6 @@ import org.rhq.enterprise.server.authz.AuthorizationManagerLocal; import org.rhq.enterprise.server.authz.PermissionException; import org.rhq.enterprise.server.resource.group.ResourceGroupAlreadyExistsException; import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; -import org.rhq.enterprise.server.resource.group.ResourceGroupUpdateException;
/** * @@ -139,9 +138,9 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe try { // You are allowed to cause the creation of an auto cluster backing group as long as you can // view the parent group. (That check was done above) - resourceGroupManager.ensureMembershipMatches(subjectManager.getOverlord(), autoClusterBackingGroup - .getId(), resourceIds); - } catch (ResourceGroupUpdateException e) { + resourceGroupManager.setMembership(subjectManager.getOverlord(), autoClusterBackingGroup.getId(), + resourceIds, false); + } catch (Exception e) { log.error("Could not add resources to group:" + e); } } @@ -177,11 +176,10 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe }
public ClusterFlyweight getClusterTree(Subject subject, int groupId) { - Query query = entityManager.createQuery( - "SELECT r.id, r.resourceType.id, r.parentResource.id, r.resourceKey, r.name, " + - "(SELECT count(r2) FROM Resource r2 join r2.explicitGroups g2 WHERE g2.id = :groupId and r2.id = r.id) " + - "FROM Resource r join r.implicitGroups g " + - "WHERE g.id = :groupId"); + Query query = entityManager + .createQuery("SELECT r.id, r.resourceType.id, r.parentResource.id, r.resourceKey, r.name, " + + "(SELECT count(r2) FROM Resource r2 join r2.explicitGroups g2 WHERE g2.id = :groupId and r2.id = r.id) " + + "FROM Resource r join r.implicitGroups g " + "WHERE g.id = :groupId");
query.setParameter("groupId", groupId); List<Object[]> rs = query.getResultList(); @@ -203,7 +201,6 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe } }
- ClusterFlyweight key = new ClusterFlyweight(groupId);
buildTree(groupId, key, explicitResources, dataMap); @@ -211,7 +208,8 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe return key; }
- private void buildTree(int groupId, ClusterFlyweight parent, Set<Integer> parentIds, Map<Integer,List<Object[]>> data) { + private void buildTree(int groupId, ClusterFlyweight parent, Set<Integer> parentIds, + Map<Integer, List<Object[]>> data) {
for (Integer parentId : parentIds) {
@@ -219,32 +217,29 @@ public class ClusterManagerBean implements ClusterManagerLocal, ClusterManagerRe Map<ClusterKeyFlyweight, Set<Integer>> members = new HashMap<ClusterKeyFlyweight, Set<Integer>>();
if (data.get(parentId) != null) { - for (Object[] child : data.get(parentId)) { - ClusterKeyFlyweight n = new ClusterKeyFlyweight((Integer)child[1], (String)child[3]); + for (Object[] child : data.get(parentId)) { + ClusterKeyFlyweight n = new ClusterKeyFlyweight((Integer) child[1], (String) child[3]); ClusterFlyweight flyweight = children.get(n); - Set<Integer> memberList = members.get(n); - if (flyweight == null) { - flyweight = new ClusterFlyweight(n); - children.put(n, flyweight); - memberList = new HashSet<Integer>(); - members.put(n, memberList); + Set<Integer> memberList = members.get(n); + if (flyweight == null) { + flyweight = new ClusterFlyweight(n); + children.put(n, flyweight); + memberList = new HashSet<Integer>(); + members.put(n, memberList); + } + flyweight.addResource((String) child[4]); + memberList.add((Integer) child[0]); } - flyweight.addResource((String)child[4]); - memberList.add((Integer) child[0]); - } }
parent.setChildren(new ArrayList<ClusterFlyweight>(children.values()));
- for (ClusterFlyweight child : children.values()) { buildTree(groupId, child, members.get(child.getClusterKey()), data); } } }
- - private String getClusterKeyQuery(ClusterKey clusterKey) { if (null == clusterKey) return null; 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 04dd614..28ae218 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 @@ -171,8 +171,19 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso }
@RequiredPermission(Permission.MANAGE_INVENTORY) - public ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType) + public ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group) throws ResourceGroupUpdateException { + return updateResourceGroup(subject, group, null, true); + } + + @RequiredPermission(Permission.MANAGE_INVENTORY) + public ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group, RecursivityChangeType changeType) throws ResourceGroupUpdateException { + return updateResourceGroup(subject, group, null, true); + } + + @RequiredPermission(Permission.MANAGE_INVENTORY) + public ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType, + boolean updateMembership) throws ResourceGroupUpdateException {
int groupId = group.getId(); ResourceGroup attachedGroup = entityManager.find(ResourceGroup.class, groupId); @@ -198,6 +209,11 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso } }
+ if (!updateMembership) { + group.setExplicitResources(attachedGroup.getExplicitResources()); + group.setImplicitResources(attachedGroup.getImplicitResources()); + } + group.setMtime(System.currentTimeMillis()); group.setModifiedBy(user.getName());
@@ -320,7 +336,9 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso try { operationManager.unscheduleGroupOperation(overlord, schedule.getJobId().toString(), group.getId()); } catch (UnscheduleException e) { - log.warn("Failed to unschedule job [" + schedule + "] for a group being deleted [" + group + "]", e); + log + .warn("Failed to unschedule job [" + schedule + "] for a group being deleted [" + group + "]", + e); } } } catch (Exception e) { @@ -759,8 +777,8 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso * to this method, we can just do simple RHQ_RESOURCE_GROUP_RES_IMP_MAP table insertions */ String insertImplicitQueryString = JDBCUtil.transformQueryForMultipleInParameters( - ResourceGroup.QUERY_NATIVE_ADD_RESOURCES_TO_GROUP_IMPLICIT, "@@RESOURCE_IDS@@", - resourceIdsToAdd.size()); + ResourceGroup.QUERY_NATIVE_ADD_RESOURCES_TO_GROUP_IMPLICIT, "@@RESOURCE_IDS@@", resourceIdsToAdd + .size()); insertImplicitStatement = conn.prepareStatement(insertImplicitQueryString); insertImplicitStatement.setInt(1, implicitRecursiveGroupId); JDBCUtil.bindNTimes(insertImplicitStatement, ArrayUtils.unwrapCollection(resourceIdsToAdd), 2); @@ -822,9 +840,9 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso ResourceGroup group = getResourceGroupById(subject, groupId, category); Set<Resource> res = group.getExplicitResources(); if (res != null && res.size() > 0) { - List<Resource> resources = PersistenceUtility.getHibernateSession(entityManager) - .createFilter(res, "where this.inventoryStatus = :inventoryStatus") - .setParameter("inventoryStatus", InventoryStatus.COMMITTED).list(); + List<Resource> resources = PersistenceUtility.getHibernateSession(entityManager).createFilter(res, + "where this.inventoryStatus = :inventoryStatus").setParameter("inventoryStatus", + InventoryStatus.COMMITTED).list();
return resources; } else { @@ -1278,7 +1296,8 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso return groupIds; }
- public void ensureMembershipMatches(Subject subject, int groupId, int[] resourceIds) { + public void setMembership(Subject subject, int groupId, int[] resourceIds, boolean setType) + throws ResourceGroupDeleteException { //throws ResourceGroupUpdateException { List<Integer> currentMembers = resourceManager.findExplicitResourceIdsByResourceGroup(groupId);
@@ -1293,6 +1312,11 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso if (extraMembers.size() > 0) { removeResourcesFromGroup(subject, groupId, ArrayUtils.unwrapCollection(extraMembers)); } + + // As a result of the membership change ensure that the group type is set correctly. + if (setType) { + setResourceType(groupId); + } }
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -1402,11 +1426,6 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso : RecursivityChangeType.RemovedRecursion); }
- @RequiredPermission(Permission.MANAGE_INVENTORY) - public ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group) throws ResourceGroupUpdateException { - return updateResourceGroup(subject, group, null); - } - @SuppressWarnings("unchecked") public PageList<ResourceGroup> findResourceGroupsByCriteria(Subject subject, ResourceGroupCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); 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 2919879..45f7cc4 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,9 +42,6 @@ import org.rhq.core.domain.util.PageList; @Local public interface ResourceGroupManagerLocal {
- ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType) - throws ResourceGroupAlreadyExistsException, ResourceGroupUpdateException; - ResourceGroup getResourceGroupById(Subject user, int id, GroupCategory category) throws ResourceGroupNotFoundException;
@@ -108,10 +105,30 @@ public interface ResourceGroupManagerLocal {
List<Integer> findDeletedResourceGroupIds(int[] groupIds);
- void ensureMembershipMatches(Subject subject, int groupId, int[] resourceIds) throws ResourceGroupUpdateException; + /** + * 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. + * + * @param subject + * @param groupId + * @param resourceIds + * @param setType Set to false if the specified resourceIds will not alter the group type (compatible or + * mixed). Set true to have the group type (re)set automatically, based on the new group membership. + * @throws ResourceGroupUpdateException + * @throws ResourceGroupDeleteException + */ + void setMembership(Subject subject, int groupId, int[] resourceIds, boolean setType) + throws ResourceGroupUpdateException, ResourceGroupDeleteException;
void uninventoryMembers(Subject subject, int groupId);
+ ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType) + throws ResourceGroupAlreadyExistsException, ResourceGroupUpdateException; + + ResourceGroup updateResourceGroup(Subject user, ResourceGroup group, RecursivityChangeType changeType, + boolean updateMembership) throws ResourceGroupAlreadyExistsException, ResourceGroupUpdateException; + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // The following are shared with the Remote Interface @@ -141,5 +158,4 @@ public interface ResourceGroupManagerLocal { ResourceGroup updateResourceGroup(Subject subject, ResourceGroup group);
PageList<ResourceGroup> findResourceGroupsByCriteria(Subject subject, ResourceGroupCriteria criteria); - } \ No newline at end of file
commit 33544cd9e57622d9484fc8f7a60146c14f9af3de Merge: b097cf3... 08f582b... Author: Heiko W. Rupp hwr@redhat.com Date: Fri Sep 17 10:09:38 2010 +0200
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 08f582bad0e9cbf41aa41f92c1358849c0c6f8f7 Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 16 18:27:40 2010 -0400
increase max length of Resource.version from 50 to 100 chars and make PC more forgiving if a discovery component returns a Resource details with a name, version, or description longer than the max length (fix for https://bugzilla.redhat.com/show_bug.cgi?id=634306)
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 3233d47..bf83991 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml @@ -89,7 +89,7 @@ <column name="INVENTORY_STATUS" type="VARCHAR2" size="20"/> <column name="CONNECTED" type="BOOLEAN"/> <column name="DESCRIPTION" type="VARCHAR2" size="1000"/> - <column name="VERSION" type="VARCHAR2" size="50"/> + <column name="VERSION" type="VARCHAR2" size="100"/> <column name="CTIME" type="LONG"/> <column name="MTIME" type="LONG"/> <column name="ITIME" 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 f32e5e3..ddb1974 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -32,7 +32,7 @@
<schemaSpec version="2.1"> <!-- Keep the columnType VARCHAR2, but increase size; - (see note for RHQ_ALERT_CONDITION table in alert-schema.xml for more ifo) --> + (see note for RHQ_ALERT_CONDITION table in alert-schema.xml for more info) --> <schema-alterColumn table="RHQ_ALERT_CONDITION" column="OPTION_STATUS" columnType="VARCHAR2" precision="256" /> </schemaSpec>
@@ -3210,6 +3210,11 @@ </schema-directSQL> </schemaSpec>
+ <schemaSpec version="2.95"> + <!-- Increase the max length of a Resource's version from 50 to 100. --> + <schema-alterColumn table="RHQ_RESOURCE" column="VERSION" columnType="VARCHAR2" precision="100" /> + </schemaSpec> + </dbupgrade> </target> </project> diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java index c175dc3..4181721 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/inventory/DiscoveredResourceDetails.java @@ -1,6 +1,6 @@ /* * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. + * Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -22,6 +22,8 @@ */ package org.rhq.core.pluginapi.inventory;
+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.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; @@ -42,9 +44,11 @@ import org.rhq.core.system.ProcessInfo; * @author John Mazzitelli */ public class DiscoveredResourceDetails { + private final Log log = LogFactory.getLog(this.getClass()); + private static final int RESOURCE_KEY_MAX_LENGTH = 500; private static final int RESOURCE_NAME_MAX_LENGTH = 500; - private static final int RESOURCE_VERSION_MAX_LENGTH = 50; + private static final int RESOURCE_VERSION_MAX_LENGTH = 100; private static final int RESOURCE_DESCRIPTION_MAX_LENGTH = 1000;
private ResourceType resourceType; @@ -134,8 +138,9 @@ public class DiscoveredResourceDetails { }
if (resourceKey.length() > RESOURCE_KEY_MAX_LENGTH) { - throw new IllegalArgumentException("Resource key is longer than maximum length (" + RESOURCE_KEY_MAX_LENGTH - + ") [" + resourceKey + "]"); + throw new IllegalArgumentException("Plugin error: Resource key [" + resourceKey + "] specified by [" + + this.resourceType + "] discovery component is longer than the maximum length (" + + RESOURCE_KEY_MAX_LENGTH + ")."); }
this.resourceKey = resourceKey; @@ -166,11 +171,13 @@ public class DiscoveredResourceDetails { }
if (resourceName.length() > RESOURCE_NAME_MAX_LENGTH) { - throw new IllegalArgumentException("Resource name is longer than maximum length (" - + RESOURCE_NAME_MAX_LENGTH + ") [" + resourceName + "]"); + log.warn("Plugin error: Resource name [" + resourceName + "] specified by [" + this.resourceType + + "] discovery component is longer than the maximum length (" + RESOURCE_NAME_MAX_LENGTH + + " - truncating it to " + RESOURCE_NAME_MAX_LENGTH + " characters..."); + this.resourceName = resourceName.substring(0, RESOURCE_NAME_MAX_LENGTH); + } else { + this.resourceName = resourceName; } - - this.resourceName = resourceName; }
/** @@ -198,11 +205,13 @@ public class DiscoveredResourceDetails { }
if (resourceVersion.length() > RESOURCE_VERSION_MAX_LENGTH) { - throw new IllegalArgumentException("Resource version is longer than maximum length (" - + RESOURCE_VERSION_MAX_LENGTH + ") [" + resourceVersion + "]"); + log.warn("Plugin error: Resource version [" + resourceVersion + "] specified by [" + this.resourceType + + "] discovery component is longer than the maximum length (" + RESOURCE_VERSION_MAX_LENGTH + + " - truncating it to " + RESOURCE_VERSION_MAX_LENGTH + " characters..."); + this.resourceVersion = resourceVersion.substring(0, RESOURCE_VERSION_MAX_LENGTH); + } else { + this.resourceVersion = resourceVersion; } - - this.resourceVersion = resourceVersion; }
/** @@ -228,11 +237,13 @@ public class DiscoveredResourceDetails { }
if (resourceDescription.length() > RESOURCE_DESCRIPTION_MAX_LENGTH) { - throw new IllegalArgumentException("Resource description is longer than maximum length (" - + RESOURCE_DESCRIPTION_MAX_LENGTH + ") [" + resourceDescription + "]"); + log.warn("Plugin error: Resource description [" + resourceDescription + "] specified by [" + this.resourceType + + "] discovery component is longer than the maximum length (" + RESOURCE_DESCRIPTION_MAX_LENGTH + + " - truncating it to " + RESOURCE_DESCRIPTION_MAX_LENGTH + " characters..."); + this.resourceDescription = resourceDescription.substring(0, RESOURCE_DESCRIPTION_MAX_LENGTH); + } else { + this.resourceDescription = resourceDescription; } - - this.resourceDescription = resourceDescription; }
/** @@ -339,6 +350,7 @@ public class DiscoveredResourceDetails { } }
- return new Configuration(); // there is no default plugin config available, return an empty one + // There is no default plugin config template defined - return an empty one. + return new Configuration(); } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java index 6e62db3..1a5e44a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertsView.java @@ -1,7 +1,8 @@ /* * RHQ Management Platform - * Copyright (C) 2010 Red Hat, Inc. - * All rights reserved. + * 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
commit cbda8abbbe6e35206f27bbb95430620f3a702c3e Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 17:03:56 2010 -0400
wrap all table cells by default. subclasses are free to override this in configureTable method
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 5196c71..a0487db 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 @@ -186,6 +186,8 @@ public class Table extends LocatableHLayout { listGrid.setAutoFitData(Autofit.HORIZONTAL); listGrid.setAlternateRecordStyles(true); listGrid.setResizeFieldsInRealTime(false); + listGrid.setWrapCells(true); + listGrid.setFixedRecordHeights(false);
// By default, SmartGWT will disable any rows that have a record named "enabled" with a value of false - setting // these fields to a bogus field name will disable this behavior. Note, setting them to null does *not* disable
commit 41e95c0bc4b435c4fbf12495e2110b4c31311c2b Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 16:24:59 2010 -0400
able to now create a new alert def and update alert def in the DB
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java index ce834da..818aaca 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractAlertDefinitionsView.java @@ -25,6 +25,7 @@ import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridRecord;
+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.alert.BooleanExpression; @@ -71,7 +72,7 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { public void executeAction(ListGridRecord[] selection) { newButtonPressed(selection); // I don't think you want this refresh, it will recreate the new alert detail - //CoreGUI.refresh(); + //refresh(); } });
@@ -79,7 +80,7 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { : SelectionEnablement.NEVER, "Are You Sure?", new TableAction() { public void executeAction(ListGridRecord[] selection) { enableButtonPressed(selection); - CoreGUI.refresh(); + refresh(); } });
@@ -87,7 +88,7 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { : SelectionEnablement.NEVER, "Are You Sure?", new TableAction() { public void executeAction(ListGridRecord[] selection) { disableButtonPressed(selection); - CoreGUI.refresh(); + refresh(); } });
@@ -95,7 +96,7 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { : SelectionEnablement.NEVER, "Are You Sure?", new TableAction() { public void executeAction(ListGridRecord[] selection) { deleteButtonPressed(selection); - CoreGUI.refresh(); + refresh(); } }); } @@ -133,11 +134,14 @@ public abstract class AbstractAlertDefinitionsView extends TableSection { AlertDefinition newAlertDef = new AlertDefinition(); newAlertDef.setDeleted(false); newAlertDef.setEnabled(true); - newAlertDef.setNotifyFiltered(false); - newAlertDef.setParentId(Integer.valueOf(0)); - newAlertDef.setConditionExpression(BooleanExpression.ALL); newAlertDef.setPriority(AlertPriority.MEDIUM); + newAlertDef.setParentId(Integer.valueOf(0)); + newAlertDef.setConditionExpression(BooleanExpression.ANY); newAlertDef.setWillRecover(false); + newAlertDef.setRecoveryId(Integer.valueOf(0)); + newAlertDef.setAlertDampening(new AlertDampening(AlertDampening.Category.NONE)); + newAlertDef.setNotifyFiltered(false); + newAlertDef.setControlFiltered(false); singleAlertDefinitionView.setAlertDefinition(newAlertDef); singleAlertDefinitionView.makeEditable(); } else { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java index fcb018d..cbf368d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java @@ -94,6 +94,16 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { }
@Override + public SingleAlertDefinitionView getDetailsView(int id) { + SingleAlertDefinitionView view = super.getDetailsView(id); + if (id == 0) { + // when creating a new alert def, make sure to set this in the new alert def + view.getAlertDefinition().setResource(resource); + } + return view; + } + + @Override protected boolean isAllowedToModifyAlertDefinitions() { return this.permissions.isAlert(); } @@ -185,19 +195,34 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { }
@Override - protected void commitAlertDefinition(AlertDefinition alertDefinition) { - GWTServiceLookup.getAlertDefinitionService().updateAlertDefinition(alertDefinition.getId(), alertDefinition, - true, new AsyncCallback<AlertDefinition>() { - @Override - public void onSuccess(AlertDefinition result) { - CoreGUI.getMessageCenter().notify(new Message("Alert definition is updated", Severity.Info)); - ResourceAlertDefinitionsView.this.refresh(); - } - - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to update alert definition", caught); - } - }); + protected void commitAlertDefinition(final AlertDefinition alertDefinition) { + if (alertDefinition.getId() == 0) { + GWTServiceLookup.getAlertDefinitionService().createAlertDefinition(alertDefinition, + Integer.valueOf(resource.getId()), new AsyncCallback<Integer>() { + @Override + public void onSuccess(Integer result) { + CoreGUI.getMessageCenter().notify(new Message("Alert definition is created", Severity.Info)); + alertDefinition.setId(result.intValue()); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to create alert definition", caught); + } + }); + } else { + GWTServiceLookup.getAlertDefinitionService().updateAlertDefinition(alertDefinition.getId(), + alertDefinition, true, new AsyncCallback<AlertDefinition>() { + @Override + public void onSuccess(AlertDefinition result) { + CoreGUI.getMessageCenter().notify(new Message("Alert definition is updated", Severity.Info)); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to update alert definition", caught); + } + }); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java index e309eea..14c123c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java @@ -23,6 +23,9 @@ import com.google.gwt.user.client.rpc.RemoteService; import org.rhq.core.domain.alert.AlertDefinition;
public interface AlertDefinitionGWTService extends RemoteService { + + int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception; + AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, boolean updateInternals) throws Exception;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java index 169b758..606195b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java @@ -30,6 +30,15 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem
private AlertDefinitionManagerLocal alertDefManager = LookupUtil.getAlertDefinitionManager();
+ public int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception { + try { + int results = alertDefManager.createAlertDefinition(getSessionSubject(), alertDefinition, resourceId); + return results; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + public AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, boolean updateInternals) throws Exception { try {
commit 106f6e489ec0552325e6645ecfe9cc801aa9c34e Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 16:09:25 2010 -0400
most times, people only have a sinlge condition, and the internals for condition checking on the server are more efficient when using ANY so rather than default to ALL, which to ANY (even though logically it doesn't matter when most times you just have a single condition, in reality, ANY processes a bit faster so use that)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java index 182173a..571daed 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsAlertDefinitionForm.java @@ -138,10 +138,10 @@ public class ConditionsAlertDefinitionForm extends LocatableVLayout implements E conditionExpressionForm = new LocatableDynamicForm(this.extendLocatorId("conditionExpressionForm")); conditionExpression = new SelectItem("conditionExpression", "Fire alert when"); LinkedHashMap<String, String> condExprs = new LinkedHashMap<String, String>(2); - condExprs.put(BooleanExpression.ALL.name(), BooleanExpression.ALL.toString()); condExprs.put(BooleanExpression.ANY.name(), BooleanExpression.ANY.toString()); + condExprs.put(BooleanExpression.ALL.name(), BooleanExpression.ALL.toString()); conditionExpression.setValueMap(condExprs); - conditionExpression.setDefaultValue(BooleanExpression.ALL.name()); + conditionExpression.setDefaultValue(BooleanExpression.ANY.name()); conditionExpression.setWrapTitle(false);
conditionExpressionStatic = new StaticTextItem("conditionExpressionStatic", "Fire alert when");
commit cb14e77be0c963c7b63b153c2cb258667ec75f07 Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 14:28:23 2010 -0400
don't show the trends up/down metrics when building the baseline condition since it doesn't make sense to choose trending metrics (then never get baselines)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java index b17e25a..7e81a0e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java @@ -46,6 +46,7 @@ import org.rhq.core.domain.event.EventSeverity; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.measurement.NumericType; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.OperationRequestStatus; import org.rhq.core.domain.resource.ResourceType; @@ -294,7 +295,7 @@ public class NewConditionEditor extends LocatableDynamicForm { StaticTextItem helpItem = buildHelpTextItem("thresholdHelp", helpStr, ifFunc); formItems.add(helpItem);
- formItems.add(buildMetricDropDownMenu(THRESHOLD_METRIC_ITEMNAME, ifFunc)); + formItems.add(buildMetricDropDownMenu(THRESHOLD_METRIC_ITEMNAME, false, ifFunc)); formItems.add(buildComparatorDropDownMenu(THRESHOLD_COMPARATOR_ITEMNAME, ifFunc)); TextItem absoluteValue = new TextItem(THRESHOLD_ABSVALUE_ITEMNAME, "Metric Value"); absoluteValue.setWrapTitle(false); @@ -317,7 +318,8 @@ public class NewConditionEditor extends LocatableDynamicForm { StaticTextItem helpItem = buildHelpTextItem("baselineHelp", helpStr, ifFunc); formItems.add(helpItem);
- formItems.add(buildMetricDropDownMenu(BASELINE_METRIC_ITEMNAME, ifFunc)); + // if a metric is trending (up or down), it will never have baselines calculated for it so only show dynamic metrics + formItems.add(buildMetricDropDownMenu(BASELINE_METRIC_ITEMNAME, true, ifFunc)); formItems.add(buildComparatorDropDownMenu(BASELINE_COMPARATOR_ITEMNAME, ifFunc));
TextItem baselinePercentage = new TextItem(BASELINE_PERCENTAGE_ITEMNAME, "Baseline Percentage"); @@ -353,7 +355,7 @@ public class NewConditionEditor extends LocatableDynamicForm { StaticTextItem helpItem = buildHelpTextItem("changeMetricHelp", helpStr, ifFunc); formItems.add(helpItem);
- formItems.add(buildMetricDropDownMenu(CHANGE_METRIC_ITEMNAME, ifFunc)); + formItems.add(buildMetricDropDownMenu(CHANGE_METRIC_ITEMNAME, false, ifFunc));
return formItems; } @@ -488,12 +490,14 @@ public class NewConditionEditor extends LocatableDynamicForm { return formItems; }
- private SelectItem buildMetricDropDownMenu(String itemName, FormItemIfFunction ifFunc) { + private SelectItem buildMetricDropDownMenu(String itemName, boolean dynamicOnly, FormItemIfFunction ifFunc) {
LinkedHashMap<String, String> metricsMap = new LinkedHashMap<String, String>(); for (MeasurementDefinition def : this.resourceType.getMetricDefinitions()) { if (def.getDataType() == DataType.MEASUREMENT) { - metricsMap.put(def.getName(), def.getDisplayName()); + if (!dynamicOnly || def.getNumericType() == NumericType.DYNAMIC) { + metricsMap.put(def.getName(), def.getDisplayName()); + } } }
commit 0990342d29af546cacce185ac0a14b6f5972ad57 Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 14:27:26 2010 -0400
make sure the caller gave us the numeric type - if not, we have to query it
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java index 0a2f201..3c41812 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/AlertDefinitionManagerBean.java @@ -591,7 +591,12 @@ public class AlertDefinitionManagerBean implements AlertDefinitionManagerLocal, if (alertConditionCategory == AlertConditionCategory.BASELINE) {
MeasurementDefinition def = alertCondition.getMeasurementDefinition(); - if (def.getNumericType() != NumericType.DYNAMIC) { + NumericType numType = def.getNumericType(); + if (numType == null) { + def = entityManager.getReference(MeasurementDefinition.class, def.getId()); + numType = def.getNumericType(); + } + if (numType != NumericType.DYNAMIC) { throw new InvalidAlertDefinitionException("Invalid Condition: '" + def.getDisplayName() + "' is a trending metric, and thus will never have baselines calculated for it."); }
commit b21b0b9124584943641dfb0698c574da28fe5234 Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 14:03:06 2010 -0400
set proper locator on the table
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java index 6a3c6f0..2d4e85a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java @@ -84,7 +84,7 @@ public class ConditionsEditor extends LocatableVLayout { protected void onInit() { super.onInit();
- table = new Table("conditionsTable"); + table = new Table(extendLocatorId("conditionsTable")); table.setShowHeader(false);
final ConditionDataSource dataSource = new ConditionDataSource();
commit ac55b68d928e6cb3be670cadd49fd447c1f73f9c Author: John Mazzitelli mazz@redhat.com Date: Thu Sep 16 13:12:49 2010 -0400
add the new alert def gwt service to the servlet mappings
diff --git a/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml b/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml index 6e5d56b..377ae0d 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml +++ b/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml @@ -46,6 +46,11 @@ </servlet-class> </servlet> <servlet> + <servlet-name>org.rhq.enterprise.gui.coregui.CoreGUI AlertDefinitionGWTService</servlet-name> + <servlet-class>org.rhq.enterprise.gui.coregui.server.gwt.AlertDefinitionGWTServiceImpl + </servlet-class> + </servlet> + <servlet> <servlet-name>org.rhq.enterprise.gui.coregui.CoreGUI OperationGWTService</servlet-name> <servlet-class>org.rhq.enterprise.gui.coregui.server.gwt.OperationGWTServiceImpl </servlet-class> @@ -149,6 +154,10 @@ <url-pattern>/org.rhq.enterprise.gui.coregui.CoreGUI/AlertGWTService</url-pattern> </servlet-mapping> <servlet-mapping> + <servlet-name>org.rhq.enterprise.gui.coregui.CoreGUI AlertDefinitionGWTService</servlet-name> + <url-pattern>/org.rhq.enterprise.gui.coregui.CoreGUI/AlertDefinitionGWTService</url-pattern> + </servlet-mapping> + <servlet-mapping> <servlet-name>org.rhq.enterprise.gui.coregui.CoreGUI OperationGWTService</servlet-name> <url-pattern>/org.rhq.enterprise.gui.coregui.CoreGUI/OperationGWTService</url-pattern> </servlet-mapping>
commit 11226063e918f7bd9fc622afc2189d1c32d3f359 Merge: a36991e... f439da6... Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Sep 16 12:39:12 2010 -0400
Merge branch 'master' into master-jay
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java index 759f569,08f3290..41aff20 --- 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 @@@ -222,11 -220,11 +223,11 @@@ public class OverviewView extends Locat if (dynamic) { StaticTextItem groupDefinitionItem = new StaticTextItem("groupDefinition", "Group Definition"); GroupDefinition groupDefinition = group.getGroupDefinition(); - // TODO (ips): Make this a link to the group def. - groupDefinitionItem.setValue(groupDefinition.getName()); + String groupDefinitionUrl = LinkManager.getGroupDefinitionLink(groupDefinition.getId()); + groupDefinitionItem.setValue("<a href="" + groupDefinitionUrl + "">" + groupDefinition.getName() + "</a>"); formItems.add(groupDefinitionItem); } - + generalPropsForm.setItems(formItems.toArray(new FormItem[formItems.size()])); addMember(generalPropsForm);
commit a36991e58dbc6623c8a0d027d30b5c6bfb927ffb Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Sep 16 12:37:58 2010 -0400
Made OverviewView and EnhancedDynamicForm Locatable
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/EnhancedDynamicForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/EnhancedDynamicForm.java index 02592c8..b0f5042 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/EnhancedDynamicForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/EnhancedDynamicForm.java @@ -22,7 +22,9 @@ */ package org.rhq.enterprise.gui.coregui.client.components.form;
-import com.google.gwt.core.client.JavaScriptObject; +import java.util.ArrayList; +import java.util.List; + import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.FormItemIfFunction; @@ -38,8 +40,7 @@ import com.smartgwt.client.widgets.form.fields.events.ItemHoverHandler; import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent; import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
-import java.util.ArrayList; -import java.util.List; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
/** * A subclass of SmartGWT's DynamicForm widget that provides the following additional feature: @@ -51,13 +52,9 @@ import java.util.List; * * @author Ian Springer */ -public class EnhancedDynamicForm extends DynamicForm { - public EnhancedDynamicForm(JavaScriptObject jsObj) { - super(jsObj); - } - - public EnhancedDynamicForm() { - super(); +public class EnhancedDynamicForm extends LocatableDynamicForm { + public EnhancedDynamicForm(String locatorId) { + super(locatorId); }
@Override @@ -78,9 +75,8 @@ public class EnhancedDynamicForm extends DynamicForm { final TogglableTextItem togglableTextItem = (TogglableTextItem) item; togglableTextItemNames.add(togglableTextItem.getName());
- final StaticTextItem staticTextItem = - new StaticTextItem(getStaticTextItemName(togglableTextItem.getName()), - togglableTextItem.getTitle()); + final StaticTextItem staticTextItem = new StaticTextItem(getStaticTextItemName(togglableTextItem + .getName()), togglableTextItem.getTitle()); staticTextItem.setAttribute("editing", false); staticTextItem.setTextBoxStyle("editableText");
@@ -147,7 +143,7 @@ public class EnhancedDynamicForm extends DynamicForm { itemsList.add(togglableTextItem); } else { itemsList.add(item); - } + } }
super.setItems((FormItem[]) itemsList.toArray(new FormItem[itemsList.size()])); 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 b51bc00..128dff8 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 @@ -108,14 +108,15 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource protected List<TwoLevelTab> createTabs() { List<TwoLevelTab> tabs = new ArrayList<TwoLevelTab>();
- summaryTab = new TwoLevelTab(getTabSet().extendLocatorId("Summary"), "Summary", "/images/icons/Service_up_16.png"); + summaryTab = new TwoLevelTab(getTabSet().extendLocatorId("Summary"), "Summary", + "/images/icons/Service_up_16.png"); summaryOverview = new SubTab(summaryTab.extendLocatorId("Overview"), "Overview", null); summaryTimeline = new SubTab(summaryTab.extendLocatorId("Timeline"), "Timeline", null); summaryTab.registerSubTabs(summaryOverview, summaryTimeline); tabs.add(summaryTab);
monitoringTab = new TwoLevelTab(getTabSet().extendLocatorId("Monitoring"), "Monitoring", - "/images/icons/Monitor_grey_16.png"); + "/images/icons/Monitor_grey_16.png"); monitorGraphs = new SubTab(monitoringTab.extendLocatorId("Graphs"), "Graphs", null); monitorTables = new SubTab(monitoringTab.extendLocatorId("Tables"), "Tables", null); monitorTraits = new SubTab(monitoringTab.extendLocatorId("Traits"), "Traits", null); @@ -126,14 +127,14 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource tabs.add(monitoringTab);
inventoryTab = new TwoLevelTab(getTabSet().extendLocatorId("Inventory"), "Inventory", - "/images/icons/Inventory_grey_16.png"); + "/images/icons/Inventory_grey_16.png"); inventoryMembers = new SubTab(inventoryTab.extendLocatorId("Members"), "Members", null); inventoryConn = new SubTab(inventoryTab.extendLocatorId("ConnectionSettings"), "Connection Settings", null); inventoryTab.registerSubTabs(this.inventoryMembers, this.inventoryConn); tabs.add(inventoryTab);
operationsTab = new TwoLevelTab(getTabSet().extendLocatorId("Operations"), "Operations", - "/images/icons/Operation_grey_16.png"); + "/images/icons/Operation_grey_16.png"); this.opHistory = new SubTab(operationsTab.extendLocatorId("History"), "History", null); this.opSched = new SubTab(operationsTab.extendLocatorId("Scheduled"), "Scheduled", null); operationsTab.registerSubTabs(this.opHistory, this.opSched); @@ -146,7 +147,7 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource tabs.add(alertsTab);
configurationTab = new TwoLevelTab(getTabSet().extendLocatorId("Configuration"), "Configuration", - "/images/icons/Configure_grey_16.png"); + "/images/icons/Configure_grey_16.png"); this.configCurrent = new SubTab(configurationTab.extendLocatorId("Current"), "Current", null); this.configHistory = new SubTab(configurationTab.extendLocatorId("History"), "History", null); configurationTab.registerSubTabs(this.configCurrent, this.configHistory); @@ -172,7 +173,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource // FullHTMLPane timelinePane = new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()); // summaryTab.updateSubTab("Overview", new DashboardView(resource)); // summaryTab.updateSubTab("Timeline", timelinePane); - this.summaryOverview.setCanvas(new OverviewView(this.groupComposite)); + this.summaryOverview.setCanvas(new OverviewView(this.summaryTab.extendLocatorId("Overview"), + this.groupComposite));
int groupId = this.groupComposite.getResourceGroup().getId();
@@ -187,19 +189,19 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource //this.inventoryConn.setCanvas(new GroupPluginConfigurationEditView(this.group.getId(), this.group.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin));
this.opHistory.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationHistory-plain.xhtml?groupId=" - + groupId)); + + groupId)); this.opSched.setCanvas(new FullHTMLPane("/rhq/group/operation/groupOperationSchedules-plain.xhtml?groupId=" - + groupId)); + + groupId));
this.alertHistory.setCanvas(new FullHTMLPane("/rhq/group/alert/listGroupAlertHistory-plain.xhtml?groupId=" - + groupId)); + + groupId)); this.alertDef.setCanvas(new FullHTMLPane("/rhq/group/alert/listGroupAlertDefinitions-plain.xhtml?groupId=" - + groupId)); + + groupId));
this.configCurrent.setCanvas(new FullHTMLPane("/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" - + groupId)); + + groupId)); this.configHistory - .setCanvas(new FullHTMLPane("/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId)); + .setCanvas(new FullHTMLPane("/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId));
this.eventHistory.setCanvas(EventCompositeHistoryView.get(groupComposite));
@@ -214,11 +216,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
// Only enable "Call Time" and "Traits" subtabs for groups that implement them. this.monitoringTab.setSubTabEnabled(this.monitorTraits.getLocatorId(), hasTraits(this.groupComposite)); - this.monitoringTab.setSubTabEnabled(this.monitorCallTime.getLocatorId(), facets.contains(ResourceTypeFacet.CALL_TIME)); + this.monitoringTab.setSubTabEnabled(this.monitorCallTime.getLocatorId(), facets + .contains(ResourceTypeFacet.CALL_TIME));
// Inventory>Connection Settings subtab is only enabled for compat groups that define conn props. this.inventoryTab.setSubTabEnabled(this.inventoryConn.getLocatorId(), groupCategory == GroupCategory.COMPATIBLE - && facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); + && facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION));
// Monitoring and Alerts tabs are always enabled for compatible groups and always disabled for mixed groups. // TODO (ips): Break out mixed groups into a separate view. @@ -230,8 +233,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
// Configuration tab is only enabled for compatible groups of a type that supports the Configuration facet // and when the current user has the CONFIGURE_READ permission. - getTabSet().setTabEnabled(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION) - && this.permissions.isConfigureRead()); + getTabSet().setTabEnabled(this.configurationTab, + facets.contains(ResourceTypeFacet.CONFIGURATION) && this.permissions.isConfigureRead());
// Events tab is only enabled for compatible groups of a type that supports the Events facet. getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); @@ -245,17 +248,17 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource criteria.addFilterVisible(null);
GWTServiceLookup.getResourceGroupService().findResourceGroupCompositesByCriteria(criteria, - new AsyncCallback<PageList<ResourceGroupComposite>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load group composite for group with id " - + groupId, caught); - } + new AsyncCallback<PageList<ResourceGroupComposite>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failed to load group composite for group with id " + groupId, caught); + }
- public void onSuccess(PageList<ResourceGroupComposite> result) { - groupComposite = result.get(0); - loadResourceType(groupComposite, viewPath); - } - }); + public void onSuccess(PageList<ResourceGroupComposite> result) { + groupComposite = result.get(0); + loadResourceType(groupComposite, viewPath); + } + }); }
private void loadResourceType(final ResourceGroupComposite groupComposite, final ViewPath viewPath) { @@ -266,29 +269,27 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource // Load the fully fetched ResourceType. ResourceType groupType = group.getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( - groupType.getId(), - EnumSet.of(ResourceTypeRepository.MetadataType.content, - ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.measurements, - ResourceTypeRepository.MetadataType.events, - ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), - new ResourceTypeRepository.TypeLoadedCallback() { - public void onTypesLoaded(ResourceType type) { - group.setResourceType(type); - GWTServiceLookup.getAuthorizationService().getImplicitGroupPermissions(group.getId(), - new AsyncCallback<Set<Permission>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load group permissions.", caught); - } - - public void onSuccess(Set<Permission> result) { - ResourceGroupDetailView.this.permissions = new ResourcePermission(result); - updateTabContent(groupComposite); - selectTab(getTabName(), getSubTabName(), viewPath); - } - }); - } - }); + groupType.getId(), + EnumSet.of(ResourceTypeRepository.MetadataType.content, ResourceTypeRepository.MetadataType.operations, + ResourceTypeRepository.MetadataType.measurements, ResourceTypeRepository.MetadataType.events, + ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), + new ResourceTypeRepository.TypeLoadedCallback() { + public void onTypesLoaded(ResourceType type) { + group.setResourceType(type); + GWTServiceLookup.getAuthorizationService().getImplicitGroupPermissions(group.getId(), + new AsyncCallback<Set<Permission>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load group permissions.", caught); + } + + public void onSuccess(Set<Permission> result) { + ResourceGroupDetailView.this.permissions = new ResourcePermission(result); + updateTabContent(groupComposite); + selectTab(getTabName(), getSubTabName(), viewPath); + } + }); + } + }); } }
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 41de300..759f569 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 @@ -18,13 +18,17 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.summary;
+import java.util.ArrayList; +import java.util.Date; +import java.util.List; + import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.HLayout; -import com.smartgwt.client.widgets.layout.VLayout; + import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.GroupDefinition; import org.rhq.core.domain.resource.group.ResourceGroup; @@ -36,22 +40,19 @@ 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.ResourceGroupGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.util.message.Message; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * The group Inventory>Overview subtab. * * @author Ian Springer */ -public class OverviewView extends VLayout { +public class OverviewView extends LocatableVLayout { private ResourceGroupGWTServiceAsync resourceGroupService = GWTServiceLookup.getResourceGroupService(); private ResourceGroupComposite groupComposite;
- public OverviewView(ResourceGroupComposite groupComposite) { - super(); + public OverviewView(String locatorId, ResourceGroupComposite groupComposite) { + super(locatorId); this.groupComposite = groupComposite; }
@@ -65,7 +66,7 @@ public class OverviewView extends VLayout { spacer.setHeight(15); addMember(spacer);
- final EnhancedDynamicForm generalPropsForm = new EnhancedDynamicForm(); + final EnhancedDynamicForm generalPropsForm = new EnhancedDynamicForm(this.extendLocatorId("General"));
List<FormItem> formItems = new ArrayList<FormItem>();
@@ -91,9 +92,9 @@ public class OverviewView extends VLayout { group.setName(newName); OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to change name of Resource group with id " - + group.getId() - + " from "" + oldName + "" to "" + newName + "".", caught); + CoreGUI.getErrorHandler().handleError( + "Failed to change name of Resource group with id " + group.getId() + " from "" + + oldName + "" to "" + newName + "".", caught); // We failed to update it on the Server, so change back the ResourceGroup and the form item // to the original value. group.setName(oldName); @@ -101,9 +102,9 @@ public class OverviewView extends VLayout { }
public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Name of Resource group with id " - + group.getId() + " was changed from "" - + oldName + "" to "" + newName + "".", Message.Severity.Info)); + CoreGUI.getMessageCenter().notify( + new Message("Name of Resource group with id " + group.getId() + " was changed from "" + + oldName + "" to "" + newName + "".", Message.Severity.Info)); } }); } @@ -128,7 +129,7 @@ public class OverviewView extends VLayout {
final FormItem descriptionItem = (dynamic) ? new StaticTextItem() : new TogglableTextItem(); descriptionItem.setName("description"); - descriptionItem.setTitle("Description"); + descriptionItem.setTitle("Description"); descriptionItem.setValue(group.getDescription()); if (descriptionItem instanceof TogglableTextItem) { final TogglableTextItem togglableDescriptionItem = (TogglableTextItem) descriptionItem; @@ -141,9 +142,9 @@ public class OverviewView extends VLayout { group.setDescription(newDescription); OverviewView.this.resourceGroupService.updateResourceGroup(group, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to change description of Resource group with id " - + group.getId() - + " from "" + oldDescription + "" to "" + newDescription + "".", caught); + CoreGUI.getErrorHandler().handleError( + "Failed to change description of Resource group with id " + group.getId() + " from "" + + oldDescription + "" to "" + newDescription + "".", caught); // We failed to update it on the Server, so change back the ResourceGroup and the form item // to the original value. group.setDescription(oldDescription); @@ -151,9 +152,10 @@ public class OverviewView extends VLayout { }
public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Description of Resource group with id " - + group.getId() + " was changed from "" - + oldDescription + "" to "" + newDescription + "".", Message.Severity.Info)); + CoreGUI.getMessageCenter().notify( + new Message("Description of Resource group with id " + group.getId() + + " was changed from "" + oldDescription + "" to "" + newDescription + "".", + Message.Severity.Info)); } }); } @@ -176,9 +178,9 @@ public class OverviewView extends VLayout { group.setLocation(newLocation); OverviewView.this.resourceGroupService.updateResourceGroup(group, 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); + 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); @@ -186,9 +188,10 @@ public class OverviewView extends VLayout { }
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)); + CoreGUI.getMessageCenter().notify( + new Message("Location of Resource group with id " + group.getId() + + " was changed from "" + oldLocation + "" to "" + newLocation + "".", + Message.Severity.Info)); } }); } @@ -223,7 +226,7 @@ public class OverviewView extends VLayout { groupDefinitionItem.setValue(groupDefinition.getName()); formItems.add(groupDefinitionItem); } - + generalPropsForm.setItems(formItems.toArray(new FormItem[formItems.size()])); addMember(generalPropsForm);
@@ -231,9 +234,10 @@ public class OverviewView extends VLayout { spacer = new HLayout(); spacer.setHeight(10); addMember(spacer); - + HTMLFlow note = new HTMLFlow(); - note.setContents("<b>*</b> Dynamic group names and descriptions are managed, and therefore are not editable."); + note + .setContents("<b>*</b> Dynamic group names and descriptions are managed, and therefore are not editable."); note.setAlign(Alignment.CENTER); addMember(note); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index e4bb9fd..65ed1be 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -112,7 +112,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo List<TwoLevelTab> tabs = new ArrayList<TwoLevelTab>();
summaryTab = new TwoLevelTab(getTabSet().extendLocatorId("Summary"), "Summary", - "/images/icons/Service_up_16.png"); + "/images/icons/Service_up_16.png"); summaryOverview = new SubTab(summaryTab.extendLocatorId("Overview"), "Overview", null); summaryDashboard = new SubTab(summaryTab.extendLocatorId("Dashboard"), "Dashboard", null); summaryTimeline = new SubTab(summaryTab.extendLocatorId("Timeline"), "Timeline", null); @@ -190,17 +190,20 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo ((TwoLevelTab) top).getLayout().destroyViews(); }
- this.summaryOverview.setCanvas(new OverviewView(this.resourceComposite)); + this.summaryOverview.setCanvas(new OverviewView(this.summaryTab.extendLocatorId("OverviewView"), + this.resourceComposite)); this.summaryDashboard.setCanvas(new DashboardView(this.resourceComposite)); this.summaryTimeline.setCanvas(new FullHTMLPane("/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()));
this.monitorGraphs.setCanvas(new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource)); this.monitorTables.setCanvas(new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId())); - this.monitorTraits.setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId())); + this.monitorTraits + .setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId())); this.monitorAvail.setCanvas(new FullHTMLPane("/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId())); - this.monitorSched.setCanvas(new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId())); + this.monitorSched + .setCanvas(new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId())); this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()));
@@ -256,12 +259,14 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo monitoringTab.setSubTabEnabled(monitorTraits.getLocatorId(), hasTraits(this.resourceComposite)); monitoringTab.setSubTabEnabled(monitorCallTime.getLocatorId(), facets.contains(ResourceTypeFacet.CALL_TIME));
- inventoryTab.setSubTabEnabled(inventoryConn.getLocatorId(), facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); + inventoryTab.setSubTabEnabled(inventoryConn.getLocatorId(), facets + .contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); ResourceType type = this.resourceComposite.getResource().getResourceType(); inventoryTab.setSubTabEnabled(inventoryChildren.getLocatorId(), !type.getChildResourceTypes().isEmpty());
getTabSet().setTabEnabled(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION)); - getTabSet().setTabEnabled(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION) && permissions.isConfigureRead()); + getTabSet().setTabEnabled(this.configurationTab, + facets.contains(ResourceTypeFacet.CONFIGURATION) && permissions.isConfigureRead()); getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); getTabSet().setTabEnabled(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT)); } @@ -303,11 +308,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo final Resource resource = resourceComposite.getResource(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( resource.getResourceType().getId(), - EnumSet.of( - ResourceTypeRepository.MetadataType.children, - ResourceTypeRepository.MetadataType.content, - ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.measurements, + EnumSet.of(ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.content, + ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.measurements, ResourceTypeRepository.MetadataType.events, ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypeLoadedCallback() { 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..4cf2119 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 @@ -59,13 +59,11 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); private ResourceComposite resourceComposite;
- - public OverviewView(ResourceComposite resourceComposite) { - super(); + public OverviewView(String locatorId, ResourceComposite resourceComposite) { + super(locatorId); this.resourceComposite = resourceComposite; }
- @Override protected void onDraw() { super.onDraw(); @@ -78,7 +76,6 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL } }
- public void onResourceSelected(ResourceComposite resourceComposite) {
this.resourceComposite = resourceComposite; @@ -86,45 +83,41 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL
// 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(); - } + 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); - } + 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); + 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()); - } + if (item != null) { + setValue(formId, trait.getValue()); } - markForRedraw(); } + markForRedraw(); } - ); + });
}
@@ -172,9 +165,9 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL 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); + 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); @@ -182,9 +175,9 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL }
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)); + CoreGUI.getMessageCenter().notify( + new Message("Name of Resource with id " + resource.getId() + " was changed from "" + + oldName + "" to "" + newName + "".", Message.Severity.Info)); } }); } @@ -207,9 +200,9 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL 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); + 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); @@ -217,9 +210,10 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL }
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)); + CoreGUI.getMessageCenter().notify( + new Message("Description of Resource with id " + resource.getId() + + " was changed from "" + oldDescription + "" to "" + newDescription + "".", + Message.Severity.Info)); } }); } @@ -242,9 +236,9 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL 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); + 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); @@ -252,9 +246,9 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL }
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)); + CoreGUI.getMessageCenter().notify( + new Message("Location of Resource with id " + resource.getId() + " was changed from "" + + oldLocation + "" to "" + newLocation + "".", Message.Severity.Info)); } }); } @@ -262,7 +256,6 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL } formItems.add(locationItem);
- StaticTextItem versionItem = new StaticTextItem("version", "Version"); formItems.add(versionItem);
@@ -275,16 +268,16 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL StaticTextItem item = new StaticTextItem(id, trait.getDisplayName()); item.setTooltip(trait.getDescription()); formItems.add(item); -// item.setValue("?"); + // 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); + // 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()])); @@ -295,8 +288,7 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL 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>"); + setValue("parent", parentResource != null ? ("<a href="#Resource/" + parentResource.getId() + "">" + + parentResource.getName() + "</a>") : "<i>none</i>"); } }
commit 423339c8a5cae0b627d196751b5a0cf37f3630ed Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Sep 16 12:36:29 2010 -0400
There seems to be an OS-specific issue when handling the runTarget if it contains url parameters. On linux it needs to be single-quoted but on Win the quotes don't get eaten. Added OS-activated profile to handle the difference.
diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index 950ce71..c8dce21 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -32,6 +32,7 @@ <gwt-plugin.localWorkers>2</gwt-plugin.localWorkers>
<coreGuiParams></coreGuiParams> + <coreGuiRunTarget>'http://localhost:7080/coregui/CoreGUI.html$%7BcoreGuiParams%7D'</coreGuiRunTarget> </properties>
@@ -237,7 +238,7 @@ <inplace>false</inplace> <!-- <logLevel>INFO' -bindAddress 0.0.0.0 -logLevel 'INFO</logLevel> --> <logLevel>INFO</logLevel> - <runTarget>http://localhost:7080/coregui/CoreGUI.html$%7BcoreGuiParams%7D</runTarget> + <runTarget>${coreGuiRunTarget}</runTarget> <extraJvmArgs>${gwt-plugin.extraJvmArgs}</extraJvmArgs> <localWorkers>${gwt-plugin.localWorkers}</localWorkers> <draftCompile>true</draftCompile> @@ -416,6 +417,18 @@ </build> </profile>
+ <!-- Change the runTarget to not have single quotes. The quotes work for linux but not win --> + <profile> + <activation> + <os> + <family>Windows</family> + </os> + </activation> + <properties> + <coreGuiRunTarget>http://localhost:7080/coregui/CoreGUI.html$%7BcoreGuiParams%7D</coreGuiRunTarget> + </properties> + </profile> + </profiles>
commit f439da6dd89dbbad0a4f57cad5038a555136d54d Author: Ian Springer ian.springer@redhat.com Date: Thu Sep 16 11:12:39 2010 -0400
make the group def name on the group Summary>Overview subtab a link to the corresponding group def
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java index 0df613d..073ef0c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java @@ -30,7 +30,6 @@ public class LinkManager { private static boolean GWT = true;
public static String getResourceLink(int resourceId) { - if (GWT) { return "#Resource/" + resourceId + "/Summary/Overview"; } else { @@ -38,12 +37,19 @@ public class LinkManager { } }
- public static String getResourceGroupLink(int resouceGroupId) { + public static String getResourceGroupLink(int groupId) { + if (GWT) { + return "#ResourceGroup/" + groupId; + } else { + return "/rhq/group/inventory/view.xhtml?groupId=" + groupId; + } + }
+ public static String getGroupDefinitionLink(int groupDefinitionId) { if (GWT) { - return "#ResourceGroup/" + resouceGroupId; + return "#Inventory/Groups/DynaGroup%20Manager/" + groupDefinitionId; } else { - return "/rhq/group/inventory/view.xhtml?groupId=" + resouceGroupId; + return "/rhq/definition/group/view.xhtml?groupDefinitionId=" + groupDefinitionId; } }
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 41de300..08f3290 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 @@ -30,6 +30,7 @@ import org.rhq.core.domain.resource.group.GroupDefinition; 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.LinkManager; 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; @@ -219,8 +220,8 @@ public class OverviewView extends VLayout { if (dynamic) { StaticTextItem groupDefinitionItem = new StaticTextItem("groupDefinition", "Group Definition"); GroupDefinition groupDefinition = group.getGroupDefinition(); - // TODO (ips): Make this a link to the group def. - groupDefinitionItem.setValue(groupDefinition.getName()); + String groupDefinitionUrl = LinkManager.getGroupDefinitionLink(groupDefinition.getId()); + groupDefinitionItem.setValue("<a href="" + groupDefinitionUrl + "">" + groupDefinition.getName() + "</a>"); formItems.add(groupDefinitionItem); }
commit ad8060db3499243b1b59b15d72aec9940a6e150c Author: Joseph Marques joseph@redhat.com Date: Thu Sep 16 03:39:43 2010 -0400
refinement of CRUD functionality for group definitions:
* expose several more fields in the group definition datasource * mark group definition datasource fields required as appropriate * add form validation and halt create/update workflow until errors are resolved * push the create/update functionality into the datasource impl * update the details-form to use the create/update functionality on the datasource * add hooks to return to the list view after create/update
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java index c373dd7..a95e0e6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java @@ -18,13 +18,19 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions;
+import java.util.HashMap; +import java.util.Map; + +import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSourceField; +import com.smartgwt.client.data.Record; import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.rpc.RPCResponse; +import com.smartgwt.client.types.FieldType; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; @@ -55,17 +61,31 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { private GroupDefinitionDataSource() { super();
- DataSourceField idDataField = new DataSourceIntegerField("id", "ID"); - idDataField.setPrimaryKey(true); - idDataField.setCanEdit(false); + DataSourceField idField = new DataSourceIntegerField("id", "ID"); + idField.setPrimaryKey(true); + idField.setCanEdit(false);
DataSourceTextField nameField = new DataSourceTextField("name", "Name"); + nameField.setRequired(true); + DataSourceTextField descriptionField = new DataSourceTextField("description", "Description"); + DataSourceTextField expressionField = new DataSourceTextField("expression", "Expression"); + expressionField.setRequired(true); + + DataSourceTextField recursiveField = new DataSourceTextField("recursive", "Recursive"); + recursiveField.setType(FieldType.BOOLEAN); + + /* + DataSourceTextField recalculationIntervalField = new DataSourceTextField("recalculationInterval", + "Recalculation Interval"); + */ + DataSourceTextField nextCalculationTimeField = new DataSourceTextField("nextCalculationTime", "Next Calculation Time");
- setFields(idDataField, nameField, descriptionField, expressionField, nextCalculationTimeField); + setFields(idField, nameField, descriptionField, expressionField, recursiveField, /*recalculationIntervalField,*/ + nextCalculationTimeField);
}
@@ -91,8 +111,71 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { }
@Override + protected void executeAdd(final DSRequest request, final DSResponse response) { + JavaScriptObject data = request.getData(); + final ListGridRecord record = new ListGridRecord(data); + final GroupDefinition newGroupDefinition = copyValues(record); + final String name = newGroupDefinition.getName(); + + GWTServiceLookup.getResourceGroupService().createGroupDefinition(newGroupDefinition, + new AsyncCallback<GroupDefinition>() { + @Override + public void onFailure(Throwable caught) { + Map<String, String> errors = new HashMap<String, String>(); + errors.put("name", "A group definition with this name already exists."); + response.setErrors(errors); + response.setStatus(RPCResponse.STATUS_VALIDATION_ERROR); + processResponse(request.getRequestId(), response); + } + + @Override + public void onSuccess(GroupDefinition result) { + CoreGUI.getErrorHandler().handleError("Successfully created group definition '" + name + "'"); + response.setData(new Record[] { copyValues(result) }); + processResponse(request.getRequestId(), response); + } + }); + } + + @Override + protected void executeUpdate(final DSRequest request, final DSResponse response) { + final ListGridRecord record = getEditedRecord(request); + final GroupDefinition updatedGroupDefinition = copyValues(record); + final String name = updatedGroupDefinition.getName(); + + GWTServiceLookup.getResourceGroupService().updateGroupDefinition(updatedGroupDefinition, + new AsyncCallback<Void>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failure saving group definition '" + name + "'", caught); + } + + @Override + public void onSuccess(Void result) { + CoreGUI.getErrorHandler().handleError("Successfully saved group definition '" + name + "'"); + response.setData(new Record[] { copyValues(updatedGroupDefinition) }); + processResponse(request.getRequestId(), response); + } + }); + } + + @Override public GroupDefinition copyValues(ListGridRecord from) { - return null; // TODO: Implement this method. + GroupDefinition groupDefinition = new GroupDefinition(); + String[] attributes = from.getAttributes(); + for (String nextAttribute : attributes) { + System.out.println("ListGridRecord attribute: " + nextAttribute); + } + groupDefinition.setId(from.getAttributeAsInt("id")); + groupDefinition.setName(from.getAttributeAsString("name")); + groupDefinition.setDescription(from.getAttributeAsString("description")); + groupDefinition.setExpression(from.getAttributeAsString("expression")); + groupDefinition.setRecursive(from.getAttributeAsBoolean("recursive")); + groupDefinition.setRecalculationInterval(Long.valueOf(from.getAttributeAsString("recalculationInterval"))); + // modifiedTime, createdTime, and lastCalculationTime are updated by GroupDefinitionManagerBean only + // nextCalculationTime is a non-persistent, derived field + + return groupDefinition; }
@Override @@ -102,11 +185,12 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { record.setAttribute("name", from.getName()); record.setAttribute("description", from.getDescription()); record.setAttribute("expression", from.getExpression()); + record.setAttribute("recursive", from.isRecursive()); record.setAttribute("recalculationInterval", from.getRecalculationInterval()); record.setAttribute("modifiedTime", from.getModifiedTime()); record.setAttribute("createdTime", from.getCreatedTime()); record.setAttribute("lastCalculationTime", from.getLastCalculationTime()); - record.setAttribute("nextCalculationTime", from.getNextCalculationTime()); + record.setAttribute("nextCalculationTime", from.getNextCalculationTime()); // derived // record.setAttribute("managedResourceGroups", from.getManagedResourceGroups());
return record; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index 328794e..7b5ea42 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -23,17 +23,19 @@ import java.util.Set;
import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.DSCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.types.DSOperationType; import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.widgets.form.fields.ButtonItem; +import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.form.fields.CheckboxItem; -import com.smartgwt.client.widgets.form.fields.ResetItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.SpinnerItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.TextItem; -import com.smartgwt.client.widgets.form.fields.events.ClickEvent; -import com.smartgwt.client.widgets.form.fields.events.ClickHandler; +import com.smartgwt.client.widgets.layout.HLayout;
import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; @@ -44,8 +46,8 @@ 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.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.util.FormUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -58,6 +60,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
private ViewId viewId;
+ // editable form + private TextItem id; private TextItem name; private TextAreaItem description; private CheckboxItem recursive; @@ -65,14 +69,14 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm private TextAreaItem expression; private SpinnerItem recalculationInterval;
+ // read-only form + private StaticTextItem idStatic; private StaticTextItem nameStatic; private StaticTextItem descriptionStatic; private StaticTextItem recursiveStatic; private StaticTextItem expressionStatic; private StaticTextItem recalculationIntervalStatic;
- private boolean formBuilt = false; - private GroupDefinitionDataSource dataSource;
public SingleGroupDefinitionView(String locatorId) { @@ -85,7 +89,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm this.dataSource = GroupDefinitionDataSource.getInstance();
setPadding(10); - setOverflow(Overflow.AUTO); + setOverflow(Overflow.VISIBLE); + setWidth(5);
buildForm();
@@ -95,42 +100,69 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm public void setGroupDefinition(GroupDefinition groupDefinition) { this.groupDefinition = groupDefinition;
- if (groupDefinition == null) { - clearFormValues(); - } else { - name.setValue(groupDefinition.getName()); - nameStatic.setValue(groupDefinition.getName()); + // form setup + id.setValue(groupDefinition.getId()); + idStatic.setValue(groupDefinition.getId()); + + name.setValue(groupDefinition.getName()); + nameStatic.setValue(groupDefinition.getName());
- recursive.setValue(groupDefinition.isRecursive() ? "Yes" : "No"); - recursiveStatic.setValue(groupDefinition.isRecursive() ? "Yes" : "No"); + recursive.setValue(groupDefinition.isRecursive()); + recursiveStatic.setValue(groupDefinition.isRecursive());
- description.setValue(groupDefinition.getDescription()); - descriptionStatic.setValue(groupDefinition.getDescription()); + description.setValue(groupDefinition.getDescription()); + descriptionStatic.setValue(groupDefinition.getDescription());
- recalculationInterval.setValue(groupDefinition.getRecalculationInterval()); - recalculationIntervalStatic.setValue(groupDefinition.getRecalculationInterval()); + recalculationInterval.setValue(groupDefinition.getRecalculationInterval()); + recalculationIntervalStatic.setValue(groupDefinition.getRecalculationInterval());
- expression.setValue(groupDefinition.getExpression()); - expressionStatic.setValue(groupDefinition.getExpression()); + expression.setValue(groupDefinition.getExpression()); + expressionStatic.setValue(groupDefinition.getExpression());
- ButtonItem saveButton = new ButtonItem("save", "Save"); - ResetItem resetButton = new ResetItem("reset", "Reset"); + final LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("GroupDefinitionForm")); + form.setFields(id, idStatic, name, nameStatic, description, descriptionStatic, expression, expressionStatic, + recursive, recursiveStatic, recalculationInterval, recalculationIntervalStatic); + form.setNumCols(2); + form.setDataSource(dataSource); + form.setHiliteRequiredFields(true); + form.setRequiredTitleSuffix(" <span style="color: red;">* </span>:"); + if (groupDefinition.getId() == 0) { + form.setSaveOperationType(DSOperationType.ADD); + } else { + form.setSaveOperationType(DSOperationType.UPDATE); + }
- saveButton.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - createOrUpdate(); + // button setup + IButton saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + saveButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { + if (form.validate()) { + //createOrUpdate(); + form.saveData(new DSCallback() { + @Override + public void execute(DSResponse response, Object rawData, DSRequest request) { + History.back(); + } + }); } - }); + } + }); + + IButton resetButton = new LocatableIButton(this.extendLocatorId("Reset"), "Reset"); + resetButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) { + form.reset(); + } + });
- LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("GroupDefinitionForm")); - form.setFields(name, nameStatic, recursive, recursiveStatic, description, descriptionStatic, - recalculationInterval, recalculationIntervalStatic, expression, expressionStatic, saveButton, - resetButton); - form.setNumCols(4); + HLayout buttonLayout = new HLayout(10); // margin between members + buttonLayout.setMargin(10); // margin around layout widget + buttonLayout.addMember(saveButton); + buttonLayout.addMember(resetButton);
- addMember(form); - formBuilt = true; - } + // canvas setup + addMember(form); + addMember(buttonLayout);
markForRedraw(); } @@ -176,98 +208,40 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm markForRedraw(); }
- public void createOrUpdate() { - groupDefinition.setName(FormUtility.getStringSafely(name)); - groupDefinition.setDescription(FormUtility.getStringSafely(description)); - groupDefinition.setRecursive("Yes".equals(recursive.getValue())); - groupDefinition.setExpression(FormUtility.getStringSafely(expression)); - groupDefinition.setRecalculationInterval(Long.valueOf(FormUtility.getStringSafely(recalculationInterval, "0"))); - - final String name = groupDefinition.getName(); - if (groupDefinitionId == 0) { - GWTServiceLookup.getResourceGroupService().createGroupDefinition(groupDefinition, - new AsyncCallback<GroupDefinition>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failure to create group definition '" + name + "'", - caught); - } - - @Override - public void onSuccess(GroupDefinition result) { - CoreGUI.getErrorHandler().handleError("Successfully created group definition '" + name + "'"); - History.back(); - } - }); - } else { - GWTServiceLookup.getResourceGroupService().updateGroupDefinition(groupDefinition, - new AsyncCallback<Void>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failure saving group definition '" + name + "'", caught); - } - - @Override - public void onSuccess(Void result) { - CoreGUI.getErrorHandler().handleError("Successfully saved group definition '" + name + "'"); - History.back(); - } - }); - } - } - - public void clearFormValues() { - name.clearValue(); - description.clearValue(); - recursive.clearValue(); - expression.clearValue(); - recalculationInterval.clearValue(); - - nameStatic.clearValue(); - descriptionStatic.clearValue(); - recursiveStatic.clearValue(); - expressionStatic.clearValue(); - recalculationIntervalStatic.clearValue(); - - markForRedraw(); - } - private void buildForm() { - if (!formBuilt) { - - name = new TextItem("name", "Name"); - name.setWidth(400); - name.setDefaultValue(""); - nameStatic = new StaticTextItem("nameStatic", "Name"); - - description = new TextAreaItem("description", "Description"); - description.setWidth(400); - description.setHeight(50); - description.setDefaultValue(""); - descriptionStatic = new StaticTextItem("descriptionStatic", "Description"); - - recursive = new CheckboxItem("recursive", "Recursive"); - recursive.setValueMap("Yes", "No"); - recursive.setDefaultValue("Yes"); - recursiveStatic = new StaticTextItem("recursiveStatic", "Recursive"); - - expression = new TextAreaItem("expression", "Expression"); - expression.setWidth(400); - expression.setHeight(150); - expression.setDefaultValue(""); - expressionStatic = new StaticTextItem("expressionStatic", "Expression"); - - recalculationInterval = new SpinnerItem("recalculationInterval", "Recalculation Interval"); - recalculationInterval.setWrapTitle(false); - recalculationInterval.setMin(0); - recalculationInterval.setDefaultValue(0); - recalculationIntervalStatic = new StaticTextItem("recalculationIntervalStatic", "Recalculation Interval"); - - templateSelector = new SelectItem(); - templateSelector.setValueMap(getTemplates()); - - formBuilt = true; - } + id = new TextItem("id", "ID"); + id.setVisible(false); + idStatic = new StaticTextItem("idStatic", "ID"); + idStatic.setVisible(false); + + name = new TextItem("name", "Name"); + name.setWidth(400); + name.setDefaultValue(""); + nameStatic = new StaticTextItem("nameStatic", "Name"); + + description = new TextAreaItem("description", "Description"); + description.setWidth(400); + description.setHeight(50); + description.setDefaultValue(""); + descriptionStatic = new StaticTextItem("descriptionStatic", "Description"); + + recursive = new CheckboxItem("recursive", "Recursive"); + recursiveStatic = new StaticTextItem("recursiveStatic", "Recursive"); + + expression = new TextAreaItem("expression", "Expression"); + expression.setWidth(400); + expression.setHeight(150); + expression.setDefaultValue(""); + expressionStatic = new StaticTextItem("expressionStatic", "Expression"); + + recalculationInterval = new SpinnerItem("recalculationInterval", "Recalculation Interval"); + recalculationInterval.setWrapTitle(false); + recalculationInterval.setMin(0); + recalculationInterval.setDefaultValue(0); + recalculationIntervalStatic = new StaticTextItem("recalculationIntervalStatic", "Recalculation Interval"); + + templateSelector = new SelectItem(); + templateSelector.setValueMap(getTemplates()); }
public static LinkedHashMap<String, String> getTemplates() { @@ -345,12 +319,18 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm }
public void onSuccess(PageList<GroupDefinition> result) { - GroupDefinition existingGroupDefinition = result.get(0); - setGroupDefinition(existingGroupDefinition); - if (hasEditPermission) { - switchToEditMode(); + if (result.size() == 0) { + CoreGUI.getErrorHandler().handleError( + "No group definition exists with id=" + groupDefinitionId); + History.back(); } else { - switchToViewMode(); + GroupDefinition existingGroupDefinition = result.get(0); + setGroupDefinition(existingGroupDefinition); + if (hasEditPermission) { + switchToEditMode(); + } else { + switchToViewMode(); + } } } });
commit 888dfe3a0fe5e171e108a5d7fb5e619d17e64888 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 16 03:36:10 2010 -0400
remove dead code, buildRecords already exists on the RPCDataSource component
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java index bdfe27e..9af7064 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java @@ -18,7 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.roles;
-import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -73,8 +72,6 @@ public class RolesDataSource extends RPCDataSource<Role> { }
public void executeFetch(final DSRequest request, final DSResponse response) { - final long start = System.currentTimeMillis(); - RoleCriteria criteria = new RoleCriteria(); criteria.setPageControl(getPageControl(request));
@@ -120,7 +117,6 @@ public class RolesDataSource extends RPCDataSource<Role> { public void onSuccess(Role result) { CoreGUI.getMessageCenter().notify( new Message("Role [" + result.getName() + "] added", Message.Severity.Info)); - ListGridRecord record = new ListGridRecord(); response.setData(new Record[] { copyValues(result) }); processResponse(request.getRequestId(), response); } @@ -191,14 +187,4 @@ public class RolesDataSource extends RPCDataSource<Role> { to.setAttribute("entity", from); return to; } - - public ListGridRecord[] buildRecords(Collection<Role> roles) { - ListGridRecord[] roleRecords = new ListGridRecord[roles.size()]; - int i = 0; - for (Role role : roles) { - ListGridRecord record = copyValues(role); - roleRecords[i++] = record; - } - return roleRecords; - } }
commit fbdf98e530f549f4f3f30d514b8e712c0d03a882 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 16 03:35:51 2010 -0400
remove getEditedRecord from Roles/UsersDataSource, leveraging the RPCDataSource common impl
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java index 3b9aafb..bdfe27e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java @@ -32,7 +32,6 @@ import com.smartgwt.client.data.Record; import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.rpc.RPCResponse; -import com.smartgwt.client.util.JSOHelper; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.auth.Subject; @@ -193,20 +192,6 @@ public class RolesDataSource extends RPCDataSource<Role> { return to; }
- private 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; - } - public ListGridRecord[] buildRecords(Collection<Role> roles) { ListGridRecord[] roleRecords = new ListGridRecord[roles.size()]; int i = 0; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java index 0fa21cf..af9acd6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java @@ -32,7 +32,6 @@ import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.rpc.RPCResponse; import com.smartgwt.client.types.FieldType; -import com.smartgwt.client.util.JSOHelper; import com.smartgwt.client.widgets.form.validator.LengthRangeValidator; import com.smartgwt.client.widgets.form.validator.MatchesFieldValidator; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -253,18 +252,4 @@ public class UsersDataSource extends RPCDataSource<Subject> { return to; }
- private 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 6d3e8fc6b72f84efa69005497fcbb058528147f6 Author: Joseph Marques joseph@redhat.com Date: Thu Sep 16 03:34:44 2010 -0400
add RPCDataSource method for getting the in-flight edits from the DSRequest
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 cb2768f..dd5e77b 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 @@ -23,6 +23,7 @@ import java.util.Collection; import java.util.List; import java.util.Map;
+import com.google.gwt.core.client.JavaScriptObject; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSource; @@ -30,6 +31,7 @@ import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.types.DSDataFormat; import com.smartgwt.client.types.DSProtocol; +import com.smartgwt.client.util.JSOHelper; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.util.PageControl; @@ -224,4 +226,18 @@ public abstract class RPCDataSource<T> extends DataSource { addField(field); } } + + 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 a0f4c0d3702eae637735186647aa7090e3911dcf Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 17:42:41 2010 -0400
capture all exception messages from errors in ResourceGroupGWTService
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 46c965c..b2ec813 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 @@ -24,9 +24,9 @@ import org.rhq.core.domain.resource.group.GroupDefinition; 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.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGroupGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; -import org.rhq.enterprise.server.resource.group.ResourceGroupDeleteException; import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; import org.rhq.enterprise.server.resource.group.definition.GroupDefinitionManagerLocal; import org.rhq.enterprise.server.util.LookupUtil; @@ -69,8 +69,8 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen public void deleteResourceGroups(int[] groupIds) { try { groupManager.deleteResourceGroups(getSessionSubject(), groupIds); - } catch (ResourceGroupDeleteException e) { - throw new RuntimeException(e.getMessage()); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -84,7 +84,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen
return SerialUtility.prepare(results, "ResourceGroupService.createGroupDefinition"); } catch (Throwable t) { - throw new RuntimeException(t.getMessage()); + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -92,7 +92,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen try { definitionManager.updateGroupDefinition(getSessionSubject(), groupDefinition); } catch (Throwable t) { - throw new RuntimeException(t.getMessage()); + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -102,7 +102,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen definitionManager.removeGroupDefinition(getSessionSubject(), nextGroupDefinitionId); } } catch (Throwable t) { - throw new RuntimeException(t.getMessage()); + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
commit b097cf35ac6c674747e0fc951103ff77a9d4ee57 Merge: b589ac3... 14fd401... Author: Heiko W. Rupp hwr@redhat.com Date: Thu Sep 16 09:20:23 2010 +0200
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit b589ac31791ea0a77666cc638b7e3afa10d91337 Author: Heiko W. Rupp hwr@redhat.com Date: Thu Sep 16 09:18:45 2010 +0200
Don't spam the agent console if the connection fails.
diff --git a/modules/plugins/mysql/src/main/java/org/rhq/plugins/mysql/MySqlComponent.java b/modules/plugins/mysql/src/main/java/org/rhq/plugins/mysql/MySqlComponent.java index e3da0aa..737634b 100644 --- a/modules/plugins/mysql/src/main/java/org/rhq/plugins/mysql/MySqlComponent.java +++ b/modules/plugins/mysql/src/main/java/org/rhq/plugins/mysql/MySqlComponent.java @@ -19,6 +19,8 @@
package org.rhq.plugins.mysql;
+import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.MeasurementDataNumeric; @@ -47,6 +49,7 @@ public class MySqlComponent implements DatabaseComponent, ResourceComponent, Mea
private ResourceContext resourceContext; private Connection connection; + private static final Log log = LogFactory.getLog(MySqlComponent.class);
public void start(ResourceContext resourceContext) throws InvalidPluginConfigurationException, Exception { this.resourceContext = resourceContext; @@ -57,7 +60,7 @@ public class MySqlComponent implements DatabaseComponent, ResourceComponent, Mea try { this.connection.close(); } catch (SQLException e) { - e.printStackTrace(); + log.warn(e); } }
@@ -67,7 +70,9 @@ public class MySqlComponent implements DatabaseComponent, ResourceComponent, Mea getConnection().createStatement().executeQuery("select 1"); return AvailabilityType.UP; } catch (SQLException e) { - e.printStackTrace(); + if (log.isDebugEnabled()) { + log.debug("getAvail failed: " + e.getMessage()); + } return AvailabilityType.DOWN; } } @@ -105,7 +110,9 @@ public class MySqlComponent implements DatabaseComponent, ResourceComponent, Mea this.connection = MySqlDiscoveryComponent.buildConnection(resourceContext.getPluginConfiguration());
} catch (SQLException e) { - e.printStackTrace(); + if (log.isDebugEnabled()) { + log.debug("getAvail failed: " + e.getMessage()); + } } return connection; } @@ -146,9 +153,9 @@ public class MySqlComponent implements DatabaseComponent, ResourceComponent, Mea } } catch (SQLException ex) { // handle any errors - System.out.println("SQLException: " + ex.getMessage()); - System.out.println("SQLState: " + ex.getSQLState()); - System.out.println("VendorError: " + ex.getErrorCode()); + log.info("SQLException: " + ex.getMessage()); + log.info("SQLState: " + ex.getSQLState()); + log.info("VendorError: " + ex.getErrorCode()); } } }
commit 14fd401a427a68a17cbf7f4e4356d66387b73ef7 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 17:34:02 2010 -0400
start using the gwt service for alert defs
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java index f986562..fcb018d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java @@ -26,15 +26,21 @@ package org.rhq.enterprise.gui.coregui.client.alert.definitions; import java.util.ArrayList; import java.util.EnumSet;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.alert.AlertDefinition; 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.core.domain.resource.composite.ResourcePermission; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +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.inventory.resource.type.ResourceTypeRepository.MetadataType; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** * @author John Mazzitelli @@ -44,10 +50,12 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { public static final String CRITERIA_RESOURCE_ID = "resourceId";
private Resource resource; + private ResourcePermission permissions;
- public ResourceAlertDefinitionsView(String locatorId, Resource resource) { + public ResourceAlertDefinitionsView(String locatorId, ResourceComposite resourceComposite) { super(locatorId, "Alert Definitions"); - this.resource = resource; + this.resource = resourceComposite.getResource(); + this.permissions = resourceComposite.getResourcePermission();
// make sure we loaded all the type info we'll need. if one of these is null, either the type // doesn't have it or we haven't loaded it yet. since we can't know for sure if it was loaded, we have to ask. @@ -87,8 +95,7 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView {
@Override protected boolean isAllowedToModifyAlertDefinitions() { - // TODO: see if user can modify alerts on this resource - return true; + return this.permissions.isAlert(); }
@Override @@ -98,39 +105,99 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView {
@Override protected void enableButtonPressed(ListGridRecord[] selection) { - // TODO Auto-generated method stub - String str = "this is not implemented yet but you selected"; + if (selection.length == 0) { + return; + } + + Integer[] alertDefIds = new Integer[selection.length]; + int i = 0; for (ListGridRecord record : selection) { - str += ": " + record.getAttribute("name"); + Integer id = record.getAttributeAsInt(AbstractAlertDefinitionsDataSource.FIELD_ID); + alertDefIds[i++] = id; } - SC.say(str); + GWTServiceLookup.getAlertDefinitionService().enableAlertDefinitions(alertDefIds, new AsyncCallback<Integer>() { + @Override + public void onSuccess(Integer result) { + CoreGUI.getMessageCenter().notify( + new Message("[" + result + "] alert definitions enabled", Severity.Info)); + ResourceAlertDefinitionsView.this.refresh(); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to enable alert definitions", caught); + } + }); }
@Override protected void disableButtonPressed(ListGridRecord[] selection) { - // TODO Auto-generated method stub - String str = "this is not implemented yet but you selected"; + if (selection.length == 0) { + return; + } + + Integer[] alertDefIds = new Integer[selection.length]; + int i = 0; for (ListGridRecord record : selection) { - str += ": " + record.getAttribute("name"); + Integer id = record.getAttributeAsInt(AbstractAlertDefinitionsDataSource.FIELD_ID); + alertDefIds[i++] = id; } - SC.say(str); + GWTServiceLookup.getAlertDefinitionService().disableAlertDefinitions(alertDefIds, new AsyncCallback<Integer>() { + @Override + public void onSuccess(Integer result) { + CoreGUI.getMessageCenter().notify( + new Message("[" + result + "] alert definitions disabled", Severity.Info)); + ResourceAlertDefinitionsView.this.refresh(); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to disable alert definitions", caught); + } + }); }
@Override protected void deleteButtonPressed(ListGridRecord[] selection) { - // TODO Auto-generated method stub - String str = "this is not implemented yet but you selected"; + if (selection.length == 0) { + return; + } + + Integer[] alertDefIds = new Integer[selection.length]; + int i = 0; for (ListGridRecord record : selection) { - str += ": " + record.getAttribute("name"); + Integer id = record.getAttributeAsInt(AbstractAlertDefinitionsDataSource.FIELD_ID); + alertDefIds[i++] = id; } - SC.say(str); + GWTServiceLookup.getAlertDefinitionService().removeAlertDefinitions(alertDefIds, new AsyncCallback<Integer>() { + @Override + public void onSuccess(Integer result) { + CoreGUI.getMessageCenter().notify( + new Message("[" + result + "] alert definitions deleted", Severity.Info)); + ResourceAlertDefinitionsView.this.refresh(); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to delete alert definitions", caught); + } + }); }
@Override protected void commitAlertDefinition(AlertDefinition alertDefinition) { - System.out.println("=======================================>" + alertDefinition); - // TODO call into server SLSB to store alert def - // AlertDefinitionManagerLocal alertDefinitionManager = LookupUtil.getAlertDefinitionManager(); - // alertDefinitionManager.updateAlertDefinition(subject, alertDef.getId(), alertDef, true); + GWTServiceLookup.getAlertDefinitionService().updateAlertDefinition(alertDefinition.getId(), alertDefinition, + true, new AsyncCallback<AlertDefinition>() { + @Override + public void onSuccess(AlertDefinition result) { + CoreGUI.getMessageCenter().notify(new Message("Alert definition is updated", Severity.Info)); + ResourceAlertDefinitionsView.this.refresh(); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to update alert definition", caught); + } + }); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java index e4bb9fd..c9f1104 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java @@ -112,7 +112,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo List<TwoLevelTab> tabs = new ArrayList<TwoLevelTab>();
summaryTab = new TwoLevelTab(getTabSet().extendLocatorId("Summary"), "Summary", - "/images/icons/Service_up_16.png"); + "/images/icons/Service_up_16.png"); summaryOverview = new SubTab(summaryTab.extendLocatorId("Overview"), "Overview", null); summaryDashboard = new SubTab(summaryTab.extendLocatorId("Dashboard"), "Dashboard", null); summaryTimeline = new SubTab(summaryTab.extendLocatorId("Timeline"), "Timeline", null); @@ -197,10 +197,12 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo
this.monitorGraphs.setCanvas(new GraphListView(this.monitoringTab.extendLocatorId("GraphListView"), resource)); this.monitorTables.setCanvas(new FullHTMLPane("/rhq/common/monitor/tables-plain.xhtml?id=" + resource.getId())); - this.monitorTraits.setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId())); + this.monitorTraits + .setCanvas(new TraitsView(this.monitoringTab.extendLocatorId("TraitsView"), resource.getId())); this.monitorAvail.setCanvas(new FullHTMLPane("/rhq/resource/monitor/availabilityHistory-plain.xhtml?id=" + resource.getId())); - this.monitorSched.setCanvas(new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId())); + this.monitorSched + .setCanvas(new SchedulesView(monitoringTab.extendLocatorId("SchedulesView"), resource.getId())); this.monitorCallTime.setCanvas(new FullHTMLPane("/rhq/resource/monitor/response-plain.xhtml?id=" + resource.getId()));
@@ -225,7 +227,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo // 4) user can search alert history by: date alert was fired, alert priority, or alert definition this.alertHistory.setCanvas(new FullHTMLPane("/rhq/resource/alert/listAlertHistory-plain.xhtml?id=" + resource.getId())); - this.alertDef.setCanvas(new ResourceAlertDefinitionsView(alertsTab.extendLocatorId("Def"), resource)); + this.alertDef.setCanvas(new ResourceAlertDefinitionsView(alertsTab.extendLocatorId("AlertDef"), + resourceComposite)); this.alertDelete.setCanvas(new FullHTMLPane("/rhq/resource/alert/listAlertDefinitions-plain.xhtml?id=" + resource.getId()));
@@ -256,12 +259,14 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo monitoringTab.setSubTabEnabled(monitorTraits.getLocatorId(), hasTraits(this.resourceComposite)); monitoringTab.setSubTabEnabled(monitorCallTime.getLocatorId(), facets.contains(ResourceTypeFacet.CALL_TIME));
- inventoryTab.setSubTabEnabled(inventoryConn.getLocatorId(), facets.contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); + inventoryTab.setSubTabEnabled(inventoryConn.getLocatorId(), facets + .contains(ResourceTypeFacet.PLUGIN_CONFIGURATION)); ResourceType type = this.resourceComposite.getResource().getResourceType(); inventoryTab.setSubTabEnabled(inventoryChildren.getLocatorId(), !type.getChildResourceTypes().isEmpty());
getTabSet().setTabEnabled(this.operationsTab, facets.contains(ResourceTypeFacet.OPERATION)); - getTabSet().setTabEnabled(this.configurationTab, facets.contains(ResourceTypeFacet.CONFIGURATION) && permissions.isConfigureRead()); + getTabSet().setTabEnabled(this.configurationTab, + facets.contains(ResourceTypeFacet.CONFIGURATION) && permissions.isConfigureRead()); getTabSet().setTabEnabled(this.eventsTab, facets.contains(ResourceTypeFacet.EVENT)); getTabSet().setTabEnabled(this.contentTab, facets.contains(ResourceTypeFacet.CONTENT)); } @@ -303,11 +308,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo final Resource resource = resourceComposite.getResource(); ResourceTypeRepository.Cache.getInstance().getResourceTypes( resource.getResourceType().getId(), - EnumSet.of( - ResourceTypeRepository.MetadataType.children, - ResourceTypeRepository.MetadataType.content, - ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.measurements, + EnumSet.of(ResourceTypeRepository.MetadataType.children, ResourceTypeRepository.MetadataType.content, + ResourceTypeRepository.MetadataType.operations, ResourceTypeRepository.MetadataType.measurements, ResourceTypeRepository.MetadataType.events, ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypeLoadedCallback() {
commit 5a56ceb783f95a857fdf174e9d77d598c60344f6 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 17:33:47 2010 -0400
add the lookup method for the new alert def service
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 9965430..373f87c 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 @@ -36,6 +36,10 @@ public class GWTServiceLookup {
public static final String SESSION_NAME = "RHQ_Sesssion";
+ public static AlertDefinitionGWTServiceAsync getAlertDefinitionService() { + return secure(AlertDefinitionGWTServiceAsync.Util.getInstance()); + } + public static ConfigurationGWTServiceAsync getConfigurationService() { return secure(ConfigurationGWTServiceAsync.Util.getInstance()); } @@ -124,9 +128,6 @@ public class GWTServiceLookup { return secure(ClusterGWTServiceAsync.Util.getInstance()); }
- - - private static <T> T secure(Object sdt) { if (!(sdt instanceof ServiceDefTarget)) return null;
commit 0487a6aa2c203ff991e72ecfeacb235dcf11fb96 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 17:20:04 2010 -0400
add alert def manager gwt service
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 aa2b040..8db747c 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 @@ -48,6 +48,7 @@ <entry-point class='org.rhq.enterprise.gui.coregui.client.SearchGUI'/>
<servlet path="/AlertGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AlertGWTServiceImpl"/> + <servlet path="/AlertDefinitionGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AlertDefinitionGWTServiceImpl"/> <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"/> diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java new file mode 100644 index 0000000..e309eea --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java @@ -0,0 +1,34 @@ +/* + * 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.gwt; + +import com.google.gwt.user.client.rpc.RemoteService; + +import org.rhq.core.domain.alert.AlertDefinition; + +public interface AlertDefinitionGWTService extends RemoteService { + AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, + boolean updateInternals) throws Exception; + + int enableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception; + + int disableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception; + + int removeAlertDefinitions(Integer[] alertDefinitionIds) throws Exception; +} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java new file mode 100644 index 0000000..169b758 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.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.enterprise.gui.coregui.server.gwt; + +import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.util.exception.ThrowableUtil; +import org.rhq.enterprise.gui.coregui.client.gwt.AlertDefinitionGWTService; +import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; +import org.rhq.enterprise.server.alert.AlertDefinitionManagerLocal; +import org.rhq.enterprise.server.util.LookupUtil; + +public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implements AlertDefinitionGWTService { + private static final long serialVersionUID = 1L; + + private AlertDefinitionManagerLocal alertDefManager = LookupUtil.getAlertDefinitionManager(); + + public AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, + boolean updateInternals) throws Exception { + try { + AlertDefinition results = alertDefManager.updateAlertDefinition(getSessionSubject(), alertDefinitionId, + alertDefinition, updateInternals); + return SerialUtility.prepare(results, "updateAlertDefinition"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + public int enableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception { + try { + int results = alertDefManager.enableAlertDefinitions(getSessionSubject(), alertDefinitionIds); + return results; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + public int disableAlertDefinitions(Integer[] alertDefinitionIds) throws Exception { + try { + int results = alertDefManager.disableAlertDefinitions(getSessionSubject(), alertDefinitionIds); + return results; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + public int removeAlertDefinitions(Integer[] alertDefinitionIds) throws Exception { + try { + int results = alertDefManager.removeAlertDefinitions(getSessionSubject(), alertDefinitionIds); + return results; + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } +} \ No newline at end of file
commit 695b267b435bfed82b1d2384b618085766950fce Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 17:20:31 2010 -0400
update users datasource to expose factive property
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java index 470b144..0fa21cf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java @@ -97,13 +97,14 @@ public class UsersDataSource extends RPCDataSource<Subject> {
DataSourceTextField department = new DataSourceTextField("department", "Department", 100, false);
+ DataSourceTextField enabled = new DataSourceTextField("factive", "Enabled"); + enabled.setType(FieldType.BOOLEAN); + setFields(idDataField, usernameField, firstName, lastName, password, passwordVerify, phone, emailAddress, - department); + department, enabled); }
public void executeFetch(final DSRequest request, final DSResponse response) { - final long start = System.currentTimeMillis(); - SubjectCriteria criteria = new SubjectCriteria(); criteria.setPageControl(getPageControl(request)); criteria.fetchRoles(true); @@ -228,6 +229,7 @@ public class UsersDataSource extends RPCDataSource<Subject> { to.setDepartment(from.getAttributeAsString("department")); to.setPhoneNumber(from.getAttributeAsString("phoneNumber")); to.setEmailAddress(from.getAttributeAsString("emailAddress")); + to.setFactive(from.getAttributeAsBoolean("factive"));
to.setRoles((Set<Role>) from.getAttributeAsObject("roles")); return to; @@ -243,6 +245,7 @@ public class UsersDataSource extends RPCDataSource<Subject> { to.setAttribute("department", from.getDepartment()); to.setAttribute("phoneNumber", from.getPhoneNumber()); to.setAttribute("emailAddress", from.getEmailAddress()); + to.setAttribute("factive", from.getFactive());
to.setAttribute("roles", from.getRoles());
commit 48805cca6b617fdc1c0f49e5a2b47fcae748b703 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 17:19:42 2010 -0400
create new users in the 'enabled' state
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java index 279fa33..9ea9467 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java @@ -197,6 +197,7 @@ public class UserEditView extends LocatableVLayout implements BookmarkableView {
private void editNewInternal() { subject = new Subject(); + subject.setFactive(true); ListGridRecord r = dataSource.copyValues(subject); editRecord(r);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index 6bafa7b..328794e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -19,7 +19,9 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions;
import java.util.LinkedHashMap; +import java.util.Set;
+import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.form.fields.ButtonItem; @@ -33,12 +35,12 @@ import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
+import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; import org.rhq.core.domain.resource.group.GroupDefinition; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; @@ -71,6 +73,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
private boolean formBuilt = false;
+ private GroupDefinitionDataSource dataSource; + public SingleGroupDefinitionView(String locatorId) { this(locatorId, null); } @@ -78,6 +82,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm public SingleGroupDefinitionView(String locatorId, GroupDefinition groupDefinition) { super(locatorId);
+ this.dataSource = GroupDefinitionDataSource.getInstance(); + setPadding(10); setOverflow(Overflow.AUTO);
@@ -165,6 +171,8 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm expressionStatic.show(); recalculationIntervalStatic.show();
+ viewId.getBreadcrumbs().get(0).setDisplayName("Viewing '" + nameStatic.getValue().toString() + "'"); + markForRedraw(); }
@@ -251,8 +259,9 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
recalculationInterval = new SpinnerItem("recalculationInterval", "Recalculation Interval"); recalculationInterval.setWrapTitle(false); + recalculationInterval.setMin(0); recalculationInterval.setDefaultValue(0); - recalculationIntervalStatic = new StaticTextItem("recalculationInterval", "Recalculation Interval"); + recalculationIntervalStatic = new StaticTextItem("recalculationIntervalStatic", "Recalculation Interval");
templateSelector = new SelectItem(); templateSelector.setValueMap(getTemplates()); @@ -314,26 +323,35 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm return results.toString(); }
- private void lookupDetails(final int groupDefinitionId) { + private void lookupDetails(final int groupDefinitionId, final boolean hasEditPermission) { ResourceGroupDefinitionCriteria criteria = new ResourceGroupDefinitionCriteria(); criteria.addFilterId(groupDefinitionId);
if (groupDefinitionId == 0) { GroupDefinition newGroupDefinition = new GroupDefinition(); setGroupDefinition(newGroupDefinition); - switchToEditMode(); + if (hasEditPermission) { + switchToEditMode(); + } else { + switchToViewMode(); + } } else { GWTServiceLookup.getResourceGroupService().findGroupDefinitionsByCriteria(criteria, new AsyncCallback<PageList<GroupDefinition>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "Failure loading group definition[id=" + groupDefinitionId + "]", caught); + History.back(); }
public void onSuccess(PageList<GroupDefinition> result) { GroupDefinition existingGroupDefinition = result.get(0); setGroupDefinition(existingGroupDefinition); - switchToEditMode(); + if (hasEditPermission) { + switchToEditMode(); + } else { + switchToViewMode(); + } } }); } @@ -343,7 +361,21 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm public void renderView(ViewPath viewPath) { groupDefinitionId = viewPath.getCurrentAsInt(); viewId = viewPath.getCurrent(); - lookupDetails(groupDefinitionId); + GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Could not determine whether user had MANAGE_INVENTORY permission, defaulting to view-only mode", + caught); + lookupDetails(groupDefinitionId, false); + } + + @Override + public void onSuccess(Set<Permission> result) { + lookupDetails(groupDefinitionId, result.contains(Permission.MANAGE_INVENTORY)); + } + }); + }
}
commit dc486e85b51d9487f4594d96b3eaf371fdd5d548 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 15:54:18 2010 -0400
use singleton pattern for GroupDefinitionDataSource
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java index 8d9fba7..c373dd7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java @@ -43,7 +43,16 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
private ResourceGroupGWTServiceAsync groupService = GWTServiceLookup.getResourceGroupService();
- public GroupDefinitionDataSource() { + private static GroupDefinitionDataSource INSTANCE; + + public static GroupDefinitionDataSource getInstance() { + if (INSTANCE == null) { + INSTANCE = new GroupDefinitionDataSource(); + } + return INSTANCE; + } + + private GroupDefinitionDataSource() { super();
DataSourceField idDataField = new DataSourceIntegerField("id", "ID"); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index ce31dd5..d6d78e5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -45,7 +45,7 @@ public class GroupDefinitionListView extends TableSection {
setHeaderIcon(headerIcon);
- setDataSource(new GroupDefinitionDataSource()); + setDataSource(GroupDefinitionDataSource.getInstance()); }
@Override
commit bd7459d658837d7a5525519def8ec2cb33a990a8 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 15:53:48 2010 -0400
instead of explicitly going to the master view, go backwards in the history
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index d96880d..6bafa7b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -188,8 +188,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm @Override public void onSuccess(GroupDefinition result) { CoreGUI.getErrorHandler().handleError("Successfully created group definition '" + name + "'"); - String listViewLink = LinkManager.getHubGroupDefinitionsLink(); - CoreGUI.goToView(listViewLink.substring(1)); + History.back(); } }); } else { @@ -203,8 +202,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm @Override public void onSuccess(Void result) { CoreGUI.getErrorHandler().handleError("Successfully saved group definition '" + name + "'"); - String listViewLink = LinkManager.getHubGroupDefinitionsLink(); - CoreGUI.goToView(listViewLink.substring(1)); + History.back(); } }); }
commit c01f40557f67bb7ed93e746a8196e453fca34a6f Merge: 0367592... b8d2720... Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 16:12:35 2010 -0400
Merge branch 'master' into master-jay
commit 03675928109b9eb3cfa398401db4c6a8dfbbdeb6 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 16:09:30 2010 -0400
take away the empty property setting, the pom no defines the empty default
diff --git a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch index a523723..6f5b7c2 100644 --- a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch +++ b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch @@ -6,6 +6,6 @@ <listEntry value="org.eclipse.ui.externaltools.launchGroup"/> </listAttribute> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${env_var:M2_HOME}/bin/${MAVEN_EXE}"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams="/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/rhq/modules/enterprise/gui/coregui}"/> </launchConfiguration>
commit b8d27202c55b4ebc0285562df1c7ce7b1adb32fc Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 15:59:15 2010 -0400
try to clean up the utility that formats the alert condition strings. make sure its more easily i18n'able for later
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java index 2554746..098e92a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertFormatUtility.java @@ -26,31 +26,134 @@ import org.rhq.core.domain.alert.Alert; 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.measurement.MeasurementBaseline; import org.rhq.core.domain.measurement.MeasurementConverterClient; -import org.rhq.core.domain.measurement.MeasurementSchedule; import org.rhq.core.domain.measurement.MeasurementUnits; -import org.rhq.core.domain.measurement.util.MeasurementConversionException; - -import java.util.ArrayList; -import java.util.List;
/** * The methods in this class are ported from AlertDefUtil from portal-war and MeasurementFormatter from * server-jar. * * @author Ian Springer + * @author John Mazzitelli */ public class AlertFormatUtility { - private static final String BASELINE_OPT_MEAN = "mean"; - private static final String BASELINE_OPT_MIN = "min"; - private static final String BASELINE_OPT_MAX = "max"; + private AlertFormatUtility() { + } + + public static String formatAlertConditionForDisplay(AlertCondition condition) { + StringBuilder str = new StringBuilder(); + + AlertConditionCategory category = condition.getCategory(); + switch (category) { + case AVAILABILITY: { + str.append("Availability Change"); + str.append(" ["); + str.append("Going").append(' '); // to reinforce this is on the state transition + str.append(condition.getOption()); + str.append("]"); + break; + } + case THRESHOLD: { + str.append("Metric Value Exceeds Threshold"); + str.append(" ["); + str.append(condition.getName()); + str.append(" "); + str.append(condition.getComparator()); + str.append(" "); + double value = condition.getThreshold(); + MeasurementUnits units = condition.getMeasurementDefinition().getUnits(); + String formatted = MeasurementConverterClient.format(value, units, true); + str.append(formatted); + str.append("]"); + break; + } + case BASELINE: { + str.append("Metric Value Exceeds Baseline"); + str.append(" ["); + str.append(condition.getName()); + str.append(" "); + str.append(condition.getComparator()); + str.append(" "); + + double value = condition.getThreshold(); + MeasurementUnits units = MeasurementUnits.PERCENTAGE; + String formatted = MeasurementConverterClient.format(value, units, true); + str.append(formatted);
- private static final String MEASUREMENT_BASELINE_MIN_TEXT = "Min Value"; - private static final String MEASUREMENT_BASELINE_MEAN_TEXT = "Baseline Value"; - private static final String MEASUREMENT_BASELINE_MAX_TEXT = "Max Value"; + str.append(" ").append("of").append(" "); + str.append(condition.getOption()); + str.append("]"); + break; + } + case CHANGE: { + str.append("Metric Value Change"); + str.append(" ["); + str.append(condition.getName()); + str.append("]"); + break; + } + case TRAIT: { + str.append("Trait Change"); + str.append(" ["); + str.append(condition.getName()); + str.append("]"); + break; + } + case CONTROL: { + str.append("Operation Execution"); + str.append(" ["); + str.append(condition.getName()); + str.append("] "); + str.append("with result status"); + str.append(" ["); + str.append(condition.getOption()); + str.append("]"); + break; + } + case RESOURCE_CONFIG: { + str.append("Resource Configuration Change"); + break; + } + case EVENT: { + str.append("Event Detection"); + str.append(" ["); + str.append(condition.getName()); + str.append("]"); + if (condition.getOption() != null && condition.getOption().length() > 0) { + str.append(" "); + str.append("matching"); + str.append(" ["); + str.append(condition.getOption()); + str.append("]"); + } + break; + } + default: { + str.append("BAD CATEGORY: ").append(category.name()); + break; + } + } + return str.toString(); + } + + public static String getAlertRecoveryInfo(Alert alert) { + String recoveryInfo; + AlertDefinition recoveryAlertDefinition = alert.getRecoveryAlertDefinition(); + if (recoveryAlertDefinition != null && recoveryAlertDefinition.getId() != 0) { + int resourceId = alert.getAlertDefinition().getResource().getId(); + recoveryInfo = "Triggered '<a href="/alerts/Config.do?mode=viewRoles&id=" + resourceId + "&ad=" + + recoveryAlertDefinition.getId() + "">" + recoveryAlertDefinition.getName() + + "</a>' to be re-enabled."; + } else if (alert.getWillRecover()) { + recoveryInfo = "This alert caused its alert definition to be disabled."; + } else { + recoveryInfo = "N/A"; + } + return recoveryInfo; + } + + /* THIS IS THE OLD CODE - IT HAS LOTS OF TODOs AND DIDN'T FULLY WORK
- @SuppressWarnings("deprecation") public static String formatAlertConditionForDisplay(AlertCondition condition) { AlertConditionCategory category = condition.getCategory();
@@ -60,11 +163,11 @@ public class AlertFormatUtility { if (category == AlertConditionCategory.CONTROL) { try { String operationName = condition.getName(); - /*Integer resourceTypeId = condition.getAlertDefinition().getResource().getResourceType().getId(); - OperationManagerLocal operationManager = LookupUtil.getOperationManager(); - OperationDefinition definition = operationManager.getOperationDefinitionByResourceTypeAndName( - resourceTypeId, operationName, false); - String operationDisplayName = definition.getDisplayName();*/ + //Integer resourceTypeId = condition.getAlertDefinition().getResource().getResourceType().getId(); + //OperationManagerLocal operationManager = LookupUtil.getOperationManager(); + //OperationDefinition definition = operationManager.getOperationDefinitionByResourceTypeAndName( + // resourceTypeId, operationName, false); + //String operationDisplayName = definition.getDisplayName(); textValue.append(operationName).append(' '); } catch (Exception e) { textValue.append(condition.getName()).append(' '); @@ -124,22 +227,15 @@ public class AlertFormatUtility { return textValue.toString(); }
- public static String getAlertRecoveryInfo(Alert alert) { - String recoveryInfo; - AlertDefinition recoveryAlertDefinition = alert.getRecoveryAlertDefinition(); - if (recoveryAlertDefinition != null && recoveryAlertDefinition.getId() != 0) { - int resourceId = alert.getAlertDefinition().getResource().getId(); - recoveryInfo = "Triggered '<a href="/alerts/Config.do?mode=viewRoles&id=" + resourceId + "&ad=" + recoveryAlertDefinition.getId() - + "">" + recoveryAlertDefinition.getName() + "</a>' to be re-enabled."; - } else if (alert.getWillRecover()) { - recoveryInfo = "This alert caused its alert definition to be disabled."; - } else { - recoveryInfo = "N/A"; - } - return recoveryInfo; - } - private static String getBaselineText(String baselineOption, MeasurementSchedule schedule) { + final String BASELINE_OPT_MEAN = "mean"; + final String BASELINE_OPT_MIN = "min"; + final String BASELINE_OPT_MAX = "max"; + + final String MEASUREMENT_BASELINE_MIN_TEXT = "Min Value"; + final String MEASUREMENT_BASELINE_MEAN_TEXT = "Baseline Value"; + final String MEASUREMENT_BASELINE_MAX_TEXT = "Max Value"; + if ((null != schedule) && (null != schedule.getBaseline())) { MeasurementBaseline baseline = schedule.getBaseline();
@@ -165,10 +261,9 @@ public class AlertFormatUtility { return lookupText; } } - /* - * will need a fall-through here because the value was null; this can happen when the user requests to view - * the formatted baseline before the first time it has been calculated - */ + + // will need a fall-through here because the value was null; this can happen when the user requests to view + // the formatted baseline before the first time it has been calculated }
// here is the fall-through @@ -181,6 +276,5 @@ public class AlertFormatUtility { } }
- private AlertFormatUtility() { - } + */ }
commit 450baca8071b03cdc9ad9ed5bd0647554a3c53f3 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 15 15:14:14 2010 -0400
fix group bookmarking
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 8f0f711..aa2ee61 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 @@ -29,6 +29,7 @@ import java.util.Set;
import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Record; import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler; import com.smartgwt.client.widgets.grid.events.SelectionEvent; @@ -100,13 +101,20 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { @Override public void onSelectionChanged(SelectionEvent selectionEvent) { if (selectionEvent.getState()) { - ClusterKey key = (ClusterKey) selectionEvent.getRecord().getAttributeAsObject("key"); + Record selectedNode = selectionEvent.getRecord(); + System.out.println("Node selected in tree: " + selectedNode); + ClusterKey key = (ClusterKey) selectedNode.getAttributeAsObject("key"); if (key == null) { - // selected the root group - History.newItem("ResourceGroup/" + selectionEvent.getRecord().getAttribute("id")); + // The root group was selected. + String groupId = selectedNode.getAttribute("id"); + //System.out.println("Selecting group [" + groupId + "]..."); + String viewPath = "ResourceGroup/" + groupId; + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); + } } else { - System.out.println("Select group: " + key); - + //System.out.println("Selecting cluster group [" + key + "]..."); selectClusterGroup(key); } } @@ -160,7 +168,6 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView { } });
- }
@@ -232,7 +239,8 @@ public class ResourceGroupTreeView extends VLayout implements BookmarkableView {
@Override public void onSuccess(ResourceGroup result) { - History.newItem("ResourceGroup/" + result.getId()); + int groupId = result.getId(); + History.newItem("ResourceGroup/" + groupId); } });
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java index 7fae500..ec96874 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java @@ -21,10 +21,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail; import com.smartgwt.client.widgets.Canvas;
import org.rhq.enterprise.gui.coregui.client.BookmarkableView; -import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; -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.selenium.LocatableHLayout;
/** @@ -33,11 +30,9 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; public class ResourceTopView extends LocatableHLayout implements BookmarkableView {
private Canvas contentCanvas; - private ResourceTreeView treeView; private ResourceDetailView detailView = new ResourceDetailView(extendLocatorId("Detail"));
- private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService();
public ResourceTopView(String locatorId) { super(locatorId); @@ -54,13 +49,16 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie setContent(detailView); }
+ public void setContent(Canvas newContent) { - if (contentCanvas.getChildren().length > 0) - contentCanvas.getChildren()[0].destroy(); - contentCanvas.addChild(newContent); - contentCanvas.markForRedraw(); + for (Canvas child : this.contentCanvas.getChildren()) { + child.destroy(); + } + this.contentCanvas.addChild(newContent); + this.contentCanvas.markForRedraw(); }
+ public void renderView(ViewPath viewPath) { this.treeView.renderView(viewPath); this.detailView.renderView(viewPath);
commit fbbdb7e785d6acf996432c38cfeeab05db8f4236 Merge: bee88fc... d20fd07... Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 15 15:06:16 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit bee88fcb8d8ef26c881c1ba9f28149858d6cd7a6 Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 15 15:00:30 2010 -0400
fix going to bookmark via browser for subviews of the Inventory view that have details (e.g. http://localhost:7080/coregui/CoreGUI.html?gwt.codesvr=127.0.0.1:9997#Invent...)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java index a205584..ac0281c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java @@ -64,10 +64,11 @@ public class ResourceGroupTopView extends LocatableHLayout implements Bookmarkab
public void setContent(Canvas newContent) { - if (contentCanvas.getChildren().length > 0) - contentCanvas.getChildren()[0].destroy(); - contentCanvas.addChild(newContent); - contentCanvas.markForRedraw(); + for (Canvas child : this.contentCanvas.getChildren()) { + child.destroy(); + } + this.contentCanvas.addChild(newContent); + this.contentCanvas.markForRedraw(); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java index c31881c..faa406e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/InventoryView.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource;
import java.util.LinkedHashMap; +import java.util.Map;
import com.google.gwt.user.client.History; import com.smartgwt.client.data.Criteria; @@ -77,7 +78,7 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView
private Canvas contentCanvas; private Canvas currentContent; - private LinkedHashMap<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>(); + private Map<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>();
private SectionStack sectionStack;
@@ -105,18 +106,23 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView buildResourcesSection(); buildGroupsSection();
- for (final String name : treeGrids.keySet()) { - TreeGrid grid = treeGrids.get(name); + for (final String sectionName : treeGrids.keySet()) { + TreeGrid grid = treeGrids.get(sectionName);
grid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { if (selectionEvent.getState()) { - CoreGUI.goToView("Inventory/" + name + "/" + selectionEvent.getRecord().getAttribute("name")); + String pageName = selectionEvent.getRecord().getAttribute("name"); + String viewPath = "Inventory/" + sectionName + "/" + pageName; + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); + } } } });
- SectionStackSection section = new SectionStackSection(name); + SectionStackSection section = new SectionStackSection(sectionName); section.setExpanded(true); section.addItem(grid);
@@ -196,15 +202,11 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView }
public void setContent(Canvas newContent) { - - if (contentCanvas.getChildren().length > 0) { - for (Canvas child : contentCanvas.getChildren()) { - child.destroy(); - } + for (Canvas child : this.contentCanvas.getChildren()) { + child.destroy(); } - - contentCanvas.addChild(newContent); - contentCanvas.markForRedraw(); + this.contentCanvas.addChild(newContent); + this.contentCanvas.markForRedraw(); this.currentContent = newContent; }
@@ -288,22 +290,19 @@ public class InventoryView extends LocatableHLayout implements BookmarkableView }
public void renderView(ViewPath viewPath) { - if (!viewPath.isCurrent(currentSectionViewId) || !viewPath.isNext(currentPageViewId)) { - if (viewPath.isEnd()) { - // Display default view - History.newItem("Inventory/Resources/Platforms"); + // i.e. "Inventory" - display default view + History.newItem("Inventory/Resources/Platforms", false); } else { - + // e.g. Inventory/Administration" renderContentView(viewPath); } } else { if (this.currentContent instanceof BookmarkableView) { ((BookmarkableView) this.currentContent).renderView(viewPath.next().next()); } - } - } + }
commit d20fd07a539d5e2d420144014c72a4cc826556d6 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 15:05:20 2010 -0400
further work for creating new group definitions
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 b2cbadb..c4a4bca 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 @@ -51,4 +51,6 @@ public interface ResourceGroupGWTService extends RemoteService { void updateGroupDefinition(GroupDefinition groupDefinition);
void deleteGroupDefinitions(int[] groupDefinitionIds); + + GroupDefinition createGroupDefinition(GroupDefinition groupDefinition); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java index e5885f4..d96880d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -22,12 +22,12 @@ import java.util.LinkedHashMap;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.widgets.form.fields.RadioGroupItem; +import com.smartgwt.client.widgets.form.fields.ButtonItem; +import com.smartgwt.client.widgets.form.fields.CheckboxItem; import com.smartgwt.client.widgets.form.fields.ResetItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.SpinnerItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; -import com.smartgwt.client.widgets.form.fields.SubmitItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; @@ -42,6 +42,7 @@ import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.FormUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
@@ -57,7 +58,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
private TextItem name; private TextAreaItem description; - private RadioGroupItem recursive; + private CheckboxItem recursive; private SelectItem templateSelector; private TextAreaItem expression; private SpinnerItem recalculationInterval; @@ -106,13 +107,12 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm expression.setValue(groupDefinition.getExpression()); expressionStatic.setValue(groupDefinition.getExpression());
- SubmitItem saveButton = new SubmitItem("save", "Save"); + ButtonItem saveButton = new ButtonItem("save", "Save"); ResetItem resetButton = new ResetItem("reset", "Reset");
saveButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { - save(); - System.out.println("Save is done"); + createOrUpdate(); } });
@@ -168,28 +168,46 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm markForRedraw(); }
- public void save() { - groupDefinition.setName(name.getValue().toString()); - groupDefinition.setDescription(description.getValue().toString()); + public void createOrUpdate() { + groupDefinition.setName(FormUtility.getStringSafely(name)); + groupDefinition.setDescription(FormUtility.getStringSafely(description)); groupDefinition.setRecursive("Yes".equals(recursive.getValue())); - groupDefinition.setExpression(expression.getValue().toString()); - groupDefinition.setRecalculationInterval(Long.valueOf(recalculationInterval.getValue().toString())); - - GWTServiceLookup.getResourceGroupService().updateGroupDefinition(groupDefinition, new AsyncCallback<Void>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failure saving group definition[id=" + groupDefinitionId + "]", - caught); - } + groupDefinition.setExpression(FormUtility.getStringSafely(expression)); + groupDefinition.setRecalculationInterval(Long.valueOf(FormUtility.getStringSafely(recalculationInterval, "0")));
- @Override - public void onSuccess(Void result) { - CoreGUI.getErrorHandler().handleError( - "Successfully saved group definition[id=" + groupDefinitionId + "]"); - String listViewLink = LinkManager.getHubGroupDefinitionsLink(); - CoreGUI.goToView(listViewLink.substring(1)); - } - }); + final String name = groupDefinition.getName(); + if (groupDefinitionId == 0) { + GWTServiceLookup.getResourceGroupService().createGroupDefinition(groupDefinition, + new AsyncCallback<GroupDefinition>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failure to create group definition '" + name + "'", + caught); + } + + @Override + public void onSuccess(GroupDefinition result) { + CoreGUI.getErrorHandler().handleError("Successfully created group definition '" + name + "'"); + String listViewLink = LinkManager.getHubGroupDefinitionsLink(); + CoreGUI.goToView(listViewLink.substring(1)); + } + }); + } else { + GWTServiceLookup.getResourceGroupService().updateGroupDefinition(groupDefinition, + new AsyncCallback<Void>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failure saving group definition '" + name + "'", caught); + } + + @Override + public void onSuccess(Void result) { + CoreGUI.getErrorHandler().handleError("Successfully saved group definition '" + name + "'"); + String listViewLink = LinkManager.getHubGroupDefinitionsLink(); + CoreGUI.goToView(listViewLink.substring(1)); + } + }); + } }
public void clearFormValues() { @@ -222,7 +240,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm description.setDefaultValue(""); descriptionStatic = new StaticTextItem("descriptionStatic", "Description");
- recursive = new RadioGroupItem("recursive", "Recursive"); + recursive = new CheckboxItem("recursive", "Recursive"); recursive.setValueMap("Yes", "No"); recursive.setDefaultValue("Yes"); recursiveStatic = new StaticTextItem("recursiveStatic", "Recursive"); 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 ccb4db5..46c965c 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 @@ -78,6 +78,16 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen groupManager.updateResourceGroup(getSessionSubject(), group); }
+ public GroupDefinition createGroupDefinition(GroupDefinition groupDefinition) { + try { + GroupDefinition results = definitionManager.createGroupDefinition(getSessionSubject(), groupDefinition); + + return SerialUtility.prepare(results, "ResourceGroupService.createGroupDefinition"); + } catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + public void updateGroupDefinition(GroupDefinition groupDefinition) { try { definitionManager.updateGroupDefinition(getSessionSubject(), groupDefinition);
commit 733a2e6f9da1ae93ac22ea8e40ccce5ec26139b9 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 15:04:22 2010 -0400
form utility class
* initial functions will safely get the string value of a form item
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/FormUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/FormUtility.java new file mode 100644 index 0000000..9f118a7 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/FormUtility.java @@ -0,0 +1,46 @@ +/* + * 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.util; + +import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.fields.FormItem; + +/** + * A collection of utility methods for working with SmartGWT {@link DynamicForm}s. + * + * @author Joseph Marques + */ +public class FormUtility { + private FormUtility() { + // statuc utility class only + } + + public static String getStringSafely(FormItem item) { + return getStringSafely(item, null); + } + + public static String getStringSafely(FormItem item, String defaultValue) { + if (item.getValue() == null) { + return defaultValue; + } else { + return item.getValue().toString(); + } + } + +}
commit 96f824472b703f28a0c927af4fd06fce94d2b3db Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 13:57:53 2010 -0400
add ability to remove existing group definitions from the list view
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 d6a638a..b2cbadb 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 @@ -50,4 +50,5 @@ public interface ResourceGroupGWTService extends RemoteService {
void updateGroupDefinition(GroupDefinition groupDefinition);
+ void deleteGroupDefinitions(int[] groupDefinitionIds); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index 1a1d32f..ce31dd5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -18,14 +18,21 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridRecord;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGroupGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.util.TableUtility; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** * @author Greg Hinkle @@ -61,6 +68,27 @@ public class GroupDefinitionListView extends TableSection { newDetails(); } }); + + addTableAction(extendLocatorId("Delete"), "Delete", Table.SelectionEnablement.ANY, null, new TableAction() { + public void executeAction(ListGridRecord[] selection) { + final int[] groupDefinitionIds = TableUtility.getIds(selection); + ResourceGroupGWTServiceAsync groupManager = GWTServiceLookup.getResourceGroupService(); + groupManager.deleteGroupDefinitions(groupDefinitionIds, new AsyncCallback<Void>() { + @Override + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Successfully deleted " + groupDefinitionIds.length + " group definitions", + Severity.Info)); + GroupDefinitionListView.this.refresh(); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to delete selected group definitions", caught); + } + }); + } + }); }
@Override 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 4b59caf..ccb4db5 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 @@ -86,4 +86,14 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
+ public void deleteGroupDefinitions(int[] groupDefinitionIds) { + try { + for (int nextGroupDefinitionId : groupDefinitionIds) { + definitionManager.removeGroupDefinition(getSessionSubject(), nextGroupDefinitionId); + } + } catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } \ No newline at end of file
commit af400930f6873b0e3d7ff6ec7fb8b1672e7cf580 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 13:57:15 2010 -0400
update ResourceSearchView to use new TableUtility id extract method
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 a77a9d9..9817819 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 @@ -44,6 +44,7 @@ import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; 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.TableUtility; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
@@ -130,12 +131,8 @@ public class ResourceSearchView extends Table {
addTableAction(extendLocatorId("Uninventory"), "Uninventory", Table.SelectionEnablement.ANY, "Are you sure you want to uninventory # resources?", new TableAction() { - public void executeAction(ListGridRecord[] selections) { - int[] resourceIds = new int[selections.length]; - int index = 0; - for (ListGridRecord selection : selections) { - resourceIds[index++] = selection.getAttributeAsInt("id"); - } + public void executeAction(ListGridRecord[] selection) { + int[] resourceIds = TableUtility.getIds(selection); ResourceGWTServiceAsync resourceManager = GWTServiceLookup.getResourceService();
resourceManager.uninventoryResources(resourceIds, new AsyncCallback<List<Integer>>() {
commit 64a808768f65ce9deab73407e25ed8dd4cb4f12a Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 13:56:32 2010 -0400
add utility to extract primary keys of selected list grid records
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TableUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TableUtility.java new file mode 100644 index 0000000..1cb0b2c --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/TableUtility.java @@ -0,0 +1,44 @@ +/* + * 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.util; + +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.enterprise.gui.coregui.client.components.table.Table; + +/** + * A collection of utility methods for working with {@link Table}s. + * + * @author Joseph Marques + */ +public class TableUtility { + private TableUtility() { + // statuc utility class only + } + + public static int[] getIds(ListGridRecord[] selections) { + int[] ids = new int[selections.length]; + int index = 0; + for (ListGridRecord selection : selections) { + ids[index++] = selection.getAttributeAsInt("id"); + } + return ids; + } + +}
commit fbe80740ce2ed5b6eb2e392fbc52baccd87b4c63 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 13:50:58 2010 -0400
pass in empty param
diff --git a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode.launch b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode.launch index f1b94d5..cd53875 100644 --- a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode.launch +++ b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode.launch @@ -6,6 +6,6 @@ <listEntry value="org.eclipse.ui.externaltools.launchGroup"/> </listAttribute> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${env_var:M2_HOME}/bin/${MAVEN_EXE}"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:run"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:run -DcoreGuiParams="/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/rhq/modules/enterprise/gui/coregui}"/> </launchConfiguration>
commit 381de84c3db865e761a48acea6cba0f7787e6f2a Merge: 09a697d... bf86450... Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 13:43:56 2010 -0400
Merge branch 'master' into master-jay
commit 09a697d7b10f12837cd5e752b0e7601ae91d5922 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 13:42:40 2010 -0400
initialize coreGuiParams to ""
diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index 4e9532b..950ce71 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -30,6 +30,8 @@ in your settings.xml --> <gwt-plugin.extraJvmArgs>-Xms512M -Xmx512M -XX:PermSize=128M -XX:MaxPermSize=256M</gwt-plugin.extraJvmArgs> <gwt-plugin.localWorkers>2</gwt-plugin.localWorkers> + + <coreGuiParams></coreGuiParams> </properties>
commit bf86450cb49576b96ec4065380e52f297eedcd24 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 13:30:02 2010 -0400
pass in an empty params string prop
diff --git a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch index 6f5b7c2..a523723 100644 --- a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch +++ b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch @@ -6,6 +6,6 @@ <listEntry value="org.eclipse.ui.externaltools.launchGroup"/> </listAttribute> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${env_var:M2_HOME}/bin/${MAVEN_EXE}"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams="/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/rhq/modules/enterprise/gui/coregui}"/> </launchConfiguration>
commit d818ed9126d252fcec040ef57388c03601c51e37 Author: Joseph Marques joseph@redhat.com Date: Wed Sep 15 13:16:59 2010 -0400
start of CRUD functionality for group definitions
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/GroupDefinition.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/GroupDefinition.java index 48e35cd..42ff182 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/GroupDefinition.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/GroupDefinition.java @@ -131,7 +131,7 @@ public class GroupDefinition implements Serializable { private Set<ResourceGroup> managedResourceGroups;
/* no-arg constructor required by EJB spec */ - protected GroupDefinition() { + public GroupDefinition() { }
public GroupDefinition(String name) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java index b648f57..0df613d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java @@ -132,7 +132,11 @@ public class LinkManager { }
public static String getHubGroupDefinitionsLink() { - return "/rhq/definition/group/list.xhtml"; + if (GWT) { + return "#Inventory/Groups/DynaGroup Manager"; + } else { + return "/rhq/definition/group/list.xhtml"; + } }
public static String getHubNewGroupLink() { 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 ff3be5b..d6a638a 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 @@ -48,4 +48,6 @@ public interface ResourceGroupGWTService extends RemoteService {
void updateResourceGroup(ResourceGroup group);
+ void updateGroupDefinition(GroupDefinition groupDefinition); + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java index 308f5f5..8d9fba7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionDataSource.java @@ -18,14 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions;
-import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; -import org.rhq.core.domain.resource.group.GroupDefinition; -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; - import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@ -35,15 +27,22 @@ 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.ResourceGroupDefinitionCriteria; +import org.rhq.core.domain.resource.group.GroupDefinition; +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 Greg Hinkle + * @author Joseph Marques */ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> {
- private ResourceGroupGWTServiceAsync groupService = GWTServiceLookup.getResourceGroupService();
- public GroupDefinitionDataSource() { super();
@@ -54,16 +53,10 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { DataSourceTextField nameField = new DataSourceTextField("name", "Name"); DataSourceTextField descriptionField = new DataSourceTextField("description", "Description"); DataSourceTextField expressionField = new DataSourceTextField("expression", "Expression"); - DataSourceTextField recalculationIntervalField = new DataSourceTextField("recalculationInterval", "Recalculation Interval"); - DataSourceTextField modifiedTimeField = new DataSourceTextField("modifiedTime", "Modified Time"); - DataSourceTextField createdTimeField = new DataSourceTextField("createdTime", "Created Time"); - DataSourceTextField lastCalculationTimeField = new DataSourceTextField("lastCalculationTime", "Last Calculation Time"); - DataSourceTextField nextCalculationTimeField = new DataSourceTextField("nextCalculationTime", "Next Calculation Time"); -// DataSourceTextField managedResourceGroupsField = new DataSourceTextField("managedResourceGroups", "Managed Resource Groups"); + DataSourceTextField nextCalculationTimeField = new DataSourceTextField("nextCalculationTime", + "Next Calculation Time");
- - setFields(idDataField, nameField, descriptionField, expressionField, recalculationIntervalField, - modifiedTimeField, createdTimeField, lastCalculationTimeField, nextCalculationTimeField); + setFields(idDataField, nameField, descriptionField, expressionField, nextCalculationTimeField);
}
@@ -75,23 +68,22 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { groupService.findGroupDefinitionsByCriteria(criteria, new AsyncCallback<PageList<GroupDefinition>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to load group definitions", caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); }
public void onSuccess(PageList<GroupDefinition> result) { - - response.setStatus(RPCResponse.STATUS_SUCCESS); response.setData(buildRecords(result)); response.setTotalRows(result.getTotalSize()); processResponse(request.getRequestId(), response); - } }); }
@Override public GroupDefinition copyValues(ListGridRecord from) { - return null; // TODO: Implement this method. + return null; // TODO: Implement this method. }
@Override @@ -106,7 +98,7 @@ public class GroupDefinitionDataSource extends RPCDataSource<GroupDefinition> { record.setAttribute("createdTime", from.getCreatedTime()); record.setAttribute("lastCalculationTime", from.getLastCalculationTime()); record.setAttribute("nextCalculationTime", from.getNextCalculationTime()); -// record.setAttribute("managedResourceGroups", from.getManagedResourceGroups()); + // record.setAttribute("managedResourceGroups", from.getManagedResourceGroups());
return record; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java index dc81946..1a1d32f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java @@ -18,44 +18,56 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions;
-import com.smartgwt.client.types.ListGridFieldType; -import com.smartgwt.client.types.SelectionAppearance; -import com.smartgwt.client.types.SelectionStyle; +import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.CellFormatter; -import com.smartgwt.client.widgets.grid.ListGridField; +import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.enterprise.gui.coregui.client.components.table.Table; +import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; +import org.rhq.enterprise.gui.coregui.client.components.table.TableSection;
/** * @author Greg Hinkle + * @author Joseph Marques */ -public class GroupDefinitionListView extends Table { +public class GroupDefinitionListView extends TableSection {
public GroupDefinitionListView(String locatorId, String headerIcon) { super(locatorId, "Group Definitions");
setHeaderIcon(headerIcon);
- final GroupDefinitionDataSource datasource = new GroupDefinitionDataSource(); - setDataSource(datasource); + setDataSource(new GroupDefinitionDataSource()); }
@Override protected void configureTable() { super.configureTable();
- getListGrid().setSelectionType(SelectionStyle.SIMPLE); - getListGrid().setSelectionAppearance(SelectionAppearance.CHECKBOX); + ListGrid grid = getListGrid();
- ListGridField idField = new ListGridField("id", "Id", 55); - idField.setType(ListGridFieldType.INTEGER); - ListGridField nameField = new ListGridField("name", "Name", 250); - nameField.setCellFormatter(new CellFormatter() { - public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - return "<a href="#ResourceGroupDefinition/" + listGridRecord.getAttribute("id") + "">" + o + "</a>"; + grid.getField("nextCalculationTime").setCellFormatter(new CellFormatter() { + public String format(Object value, ListGridRecord record, int rowNum, int colNum) { + if ("0".equals(value.toString())) { + return "N/A"; + } + return value.toString(); } });
+ addTableAction(extendLocatorId("New"), "New", Table.SelectionEnablement.ALWAYS, null, new TableAction() { + public void executeAction(ListGridRecord[] selection) { + newDetails(); + } + }); + } + + @Override + public Canvas getDetailsView(int id) { + final SingleGroupDefinitionView singleGroupDefinitionView = new SingleGroupDefinitionView(this + .extendLocatorId("Empty")); + return singleGroupDefinitionView; } + } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java new file mode 100644 index 0000000..e5885f4 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java @@ -0,0 +1,333 @@ +/* + * 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.definitions; + +import java.util.LinkedHashMap; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.form.fields.RadioGroupItem; +import com.smartgwt.client.widgets.form.fields.ResetItem; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.SpinnerItem; +import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.SubmitItem; +import com.smartgwt.client.widgets.form.fields.TextAreaItem; +import com.smartgwt.client.widgets.form.fields.TextItem; +import com.smartgwt.client.widgets.form.fields.events.ClickEvent; +import com.smartgwt.client.widgets.form.fields.events.ClickHandler; + +import org.rhq.core.domain.criteria.ResourceGroupDefinitionCriteria; +import org.rhq.core.domain.resource.group.GroupDefinition; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.BookmarkableView; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; +import org.rhq.enterprise.gui.coregui.client.ViewId; +import org.rhq.enterprise.gui.coregui.client.ViewPath; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * @author Joseph Marques + */ +public class SingleGroupDefinitionView extends LocatableVLayout implements BookmarkableView { + + private int groupDefinitionId; + private GroupDefinition groupDefinition; + + private ViewId viewId; + + private TextItem name; + private TextAreaItem description; + private RadioGroupItem recursive; + private SelectItem templateSelector; + private TextAreaItem expression; + private SpinnerItem recalculationInterval; + + private StaticTextItem nameStatic; + private StaticTextItem descriptionStatic; + private StaticTextItem recursiveStatic; + private StaticTextItem expressionStatic; + private StaticTextItem recalculationIntervalStatic; + + private boolean formBuilt = false; + + public SingleGroupDefinitionView(String locatorId) { + this(locatorId, null); + } + + public SingleGroupDefinitionView(String locatorId, GroupDefinition groupDefinition) { + super(locatorId); + + setPadding(10); + setOverflow(Overflow.AUTO); + + buildForm(); + + this.groupDefinition = groupDefinition; + } + + public void setGroupDefinition(GroupDefinition groupDefinition) { + this.groupDefinition = groupDefinition; + + if (groupDefinition == null) { + clearFormValues(); + } else { + name.setValue(groupDefinition.getName()); + nameStatic.setValue(groupDefinition.getName()); + + recursive.setValue(groupDefinition.isRecursive() ? "Yes" : "No"); + recursiveStatic.setValue(groupDefinition.isRecursive() ? "Yes" : "No"); + + description.setValue(groupDefinition.getDescription()); + descriptionStatic.setValue(groupDefinition.getDescription()); + + recalculationInterval.setValue(groupDefinition.getRecalculationInterval()); + recalculationIntervalStatic.setValue(groupDefinition.getRecalculationInterval()); + + expression.setValue(groupDefinition.getExpression()); + expressionStatic.setValue(groupDefinition.getExpression()); + + SubmitItem saveButton = new SubmitItem("save", "Save"); + ResetItem resetButton = new ResetItem("reset", "Reset"); + + saveButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + save(); + System.out.println("Save is done"); + } + }); + + LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("GroupDefinitionForm")); + form.setFields(name, nameStatic, recursive, recursiveStatic, description, descriptionStatic, + recalculationInterval, recalculationIntervalStatic, expression, expressionStatic, saveButton, + resetButton); + form.setNumCols(4); + + addMember(form); + formBuilt = true; + } + + markForRedraw(); + } + + public void switchToEditMode() { + name.show(); + description.show(); + recursive.show(); + expression.show(); + recalculationInterval.show(); + + nameStatic.hide(); + descriptionStatic.hide(); + recursiveStatic.hide(); + expressionStatic.hide(); + recalculationIntervalStatic.hide(); + + if (groupDefinitionId == 0) { + viewId.getBreadcrumbs().get(0).setDisplayName("New Group Definition"); + } else { + viewId.getBreadcrumbs().get(0).setDisplayName("Editing '" + nameStatic.getValue().toString() + "'"); + } + CoreGUI.refreshBreadCrumbTrail(); + + markForRedraw(); + } + + public void switchToViewMode() { + name.hide(); + description.hide(); + recursive.hide(); + expression.hide(); + recalculationInterval.hide(); + + nameStatic.show(); + descriptionStatic.show(); + recursiveStatic.show(); + expressionStatic.show(); + recalculationIntervalStatic.show(); + + markForRedraw(); + } + + public void save() { + groupDefinition.setName(name.getValue().toString()); + groupDefinition.setDescription(description.getValue().toString()); + groupDefinition.setRecursive("Yes".equals(recursive.getValue())); + groupDefinition.setExpression(expression.getValue().toString()); + groupDefinition.setRecalculationInterval(Long.valueOf(recalculationInterval.getValue().toString())); + + GWTServiceLookup.getResourceGroupService().updateGroupDefinition(groupDefinition, new AsyncCallback<Void>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failure saving group definition[id=" + groupDefinitionId + "]", + caught); + } + + @Override + public void onSuccess(Void result) { + CoreGUI.getErrorHandler().handleError( + "Successfully saved group definition[id=" + groupDefinitionId + "]"); + String listViewLink = LinkManager.getHubGroupDefinitionsLink(); + CoreGUI.goToView(listViewLink.substring(1)); + } + }); + } + + public void clearFormValues() { + name.clearValue(); + description.clearValue(); + recursive.clearValue(); + expression.clearValue(); + recalculationInterval.clearValue(); + + nameStatic.clearValue(); + descriptionStatic.clearValue(); + recursiveStatic.clearValue(); + expressionStatic.clearValue(); + recalculationIntervalStatic.clearValue(); + + markForRedraw(); + } + + private void buildForm() { + if (!formBuilt) { + + name = new TextItem("name", "Name"); + name.setWidth(400); + name.setDefaultValue(""); + nameStatic = new StaticTextItem("nameStatic", "Name"); + + description = new TextAreaItem("description", "Description"); + description.setWidth(400); + description.setHeight(50); + description.setDefaultValue(""); + descriptionStatic = new StaticTextItem("descriptionStatic", "Description"); + + recursive = new RadioGroupItem("recursive", "Recursive"); + recursive.setValueMap("Yes", "No"); + recursive.setDefaultValue("Yes"); + recursiveStatic = new StaticTextItem("recursiveStatic", "Recursive"); + + expression = new TextAreaItem("expression", "Expression"); + expression.setWidth(400); + expression.setHeight(150); + expression.setDefaultValue(""); + expressionStatic = new StaticTextItem("expressionStatic", "Expression"); + + recalculationInterval = new SpinnerItem("recalculationInterval", "Recalculation Interval"); + recalculationInterval.setWrapTitle(false); + recalculationInterval.setDefaultValue(0); + recalculationIntervalStatic = new StaticTextItem("recalculationInterval", "Recalculation Interval"); + + templateSelector = new SelectItem(); + templateSelector.setValueMap(getTemplates()); + + formBuilt = true; + } + } + + public static LinkedHashMap<String, String> getTemplates() { + LinkedHashMap<String, String> items = new LinkedHashMap<String, String>(); + + // grouped items + items.put("JBossAS clusters in the system", // + get("groupby resource.trait[partitionName]", // + "resource.type.plugin = JBossAS", // + "resource.type.name = JBossAS Server")); + items.put("Clustered enterprise application archive (EAR)", // + get("groupby resource.parent.trait[partitionName]", // + "groupby resource.name", // + "resource.type.plugin = JBossAS", // + "resource.type.name = Enterprise Application (EAR)")); + items.put("Unique JBossAS versions in inventory", // + get("groupby resource.trait[jboss.system:type=Server:VersionName]", // + "resource.type.plugin = JBossAS", // + "resource.type.name = JBossAS Server")); + items.put("Platform resource in inventory", // + get("resource.type.category = PLATFORM", // + "groupby resource.name")); + items.put("Unique resource type in inventory", // + get("groupby resource.type.plugin", // + "groupby resource.type.name")); + + // simple items + items.put("All JBossAS hosting any version of 'my' app", // + get("resource.type.plugin = JBossAS", // + "resource.type.name = JBossAS Server", // + "resource.child.name.contains = my")); + items.put("All Non-secured JBossAS servers", // + get("empty resource.pluginConfiguration[principal]", // + "resource.type.plugin = JBossAS", // + "resource.type.name = JBossAS Server")); + items.put("All resources currently down", // + get("resource.availability = DOWN")); + + return items; + } + + private static String get(String... pieces) { + StringBuilder results = new StringBuilder(); + boolean first = true; + for (String next : pieces) { + if (first) { + first = false; + } else { + results.append('\n'); + } + results.append(next); + } + return results.toString(); + } + + private void lookupDetails(final int groupDefinitionId) { + ResourceGroupDefinitionCriteria criteria = new ResourceGroupDefinitionCriteria(); + criteria.addFilterId(groupDefinitionId); + + if (groupDefinitionId == 0) { + GroupDefinition newGroupDefinition = new GroupDefinition(); + setGroupDefinition(newGroupDefinition); + switchToEditMode(); + } else { + GWTServiceLookup.getResourceGroupService().findGroupDefinitionsByCriteria(criteria, + new AsyncCallback<PageList<GroupDefinition>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failure loading group definition[id=" + groupDefinitionId + "]", caught); + } + + public void onSuccess(PageList<GroupDefinition> result) { + GroupDefinition existingGroupDefinition = result.get(0); + setGroupDefinition(existingGroupDefinition); + switchToEditMode(); + } + }); + } + } + + @Override + public void renderView(ViewPath viewPath) { + groupDefinitionId = viewPath.getCurrentAsInt(); + viewId = viewPath.getCurrent(); + lookupDetails(groupDefinitionId); + } + +} 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 e6b5936..4b59caf 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 @@ -78,4 +78,12 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen groupManager.updateResourceGroup(getSessionSubject(), group); }
+ public void updateGroupDefinition(GroupDefinition groupDefinition) { + try { + definitionManager.updateGroupDefinition(getSessionSubject(), groupDefinition); + } catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } \ No newline at end of file
commit d46933a9d3b0fa0dd02a02500cad325a6118ffcf Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 14:19:13 2010 -0400
do not link crumbs - many are broken links, nearly all don't change the view anyway
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java index 44586b1..a153ee0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java @@ -106,12 +106,12 @@ public class BreadcrumbTrailPane extends ToolStrip {
private Label getCrumb(Breadcrumb crumb, String path) { Label l = null; - if (crumb.isHyperlink()) { - String fullPath = path.toString() + crumb.getName(); - l = new LocatableLabel(fullPath, "<a href="#" + fullPath + "">" + crumb.getDisplayName() + "</a>"); - } else { - l = new Label(crumb.getDisplayName()); - } + String fullPath = path.toString() + crumb.getName(); + //if (crumb.isHyperlink()) { + //l = new LocatableLabel(fullPath, "<a href="#" + fullPath + "">" + crumb.getDisplayName() + "</a>"); + //} else { + l = new LocatableLabel(fullPath, "<b>" + crumb.getDisplayName() + "</b>"); + //} if (crumb.getIcon() != null) { l.setIcon(crumb.getIcon()); l.setIconSize(16);
commit 097a1774d76ff27a72b8a6f9fbff80c20e48956d Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 14:10:53 2010 -0400
more tidy work for the reports view
* move 'platforms' report from inventory section to reports section * rename 'platforms' to 'cpu & memory utilization' * add icon for 'inventory summary' node
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 2e8fae2..f5f7dce 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 @@ -150,11 +150,9 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView final TreeNode alertDefinitions = new TreeNode("Alert Definitions"); alertDefinitions.setIcon("subsystems/alert/Alerts_16.png");
- final TreeNode platforms = new TreeNode("Platforms"); - platforms.setIcon("types/Platform_up_16.png"); - - tree.setRoot(new TreeNode(SECTION_INVENTORY, tagCloud, suspectMetrics, recentConfigurationChanges, - recentOperations, recentAlerts, alertDefinitions, platforms)); + TreeNode inventoryNode = new TreeNode(SECTION_INVENTORY, tagCloud, suspectMetrics, recentConfigurationChanges, + recentOperations, recentAlerts, alertDefinitions); + tree.setRoot(inventoryNode);
inventoryTreeGrid.setData(tree);
@@ -168,9 +166,13 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView reportsTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode inventorySummaryNode = new TreeNode("Inventory Summary"); + final TreeNode inventorySummary = new TreeNode("Inventory Summary"); + inventorySummary.setIcon("subsystems/inventory/Inventory_16.png"); + + final TreeNode platforms = new TreeNode("CPU & Memory Utilization"); + platforms.setIcon("types/Platform_up_16.png");
- TreeNode reportsNode = new TreeNode(SECTION_REPORTS, inventorySummaryNode); + TreeNode reportsNode = new TreeNode(SECTION_REPORTS, inventorySummary, platforms); tree.setRoot(reportsNode);
reportsTreeGrid.setData(tree); @@ -216,13 +218,13 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView content = new AlertsView(this.extendLocatorId("RecentAlerts")); } else if ("Alert Definitions".equals(page)) { //todo - } else if ("Platforms".equals(page)) { - content = new PlatformPortletView(this.extendLocatorId("Platforms")); }
} else if (SECTION_REPORTS.equals(section)) { if ("Inventory Summary".equals(page)) { content = new FullHTMLPane("/rhq/admin/report/resourceInstallReport-body.xhtml"); + } else if ("CPU & Memory Utilization".equals(page)) { + content = new PlatformPortletView(this.extendLocatorId("Platforms")); } } for (String name : treeGrids.keySet()) {
commit b3d884c5ff04671d892a2efb5c8b98bc40cee60d Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 13:57:40 2010 -0400
tidy up reports > inventory summary
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/admin/report/resourceInstallReport-body.xhtml b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/admin/report/resourceInstallReport-body.xhtml index 81ac667..cfcac68 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/rhq/admin/report/resourceInstallReport-body.xhtml +++ b/modules/enterprise/gui/portal-war/src/main/webapp/rhq/admin/report/resourceInstallReport-body.xhtml @@ -19,17 +19,11 @@
<ui:define name="body">
- rich:panel - <f:facet name="header"> - <h:outputText value="Resource Version Inventory Report"/> - </f:facet> - <h:panelGrid columns="1" width="100%">
<h:form> <h:selectBooleanCheckbox id="groupByVersion" value="#{ResourceInstallReportUIBean.groupByVersion}" label="gbvLabel"> - <a4j:support reRender="reportTable" event="onclick" status="commonStatus"/> </h:selectBooleanCheckbox> <h:outputText value="Group By Version" id="gbvLabel"/>
@@ -38,7 +32,6 @@ value="#{ResourceInstallReportUIBean.resourceInstallCounts}" var="installReport" width="100%" - columnsWidth="15%, 15%, 10%, 10%, 10%" headerClass="tableRowHeader" footerClass="on-pager-footer" onRowMouseOver="this.style.backgroundColor='#E7E7E7'" @@ -86,8 +79,6 @@
</h:panelGrid>
- </rich:panel> - </ui:define>
</ui:composition>
commit 5e8ccd7d51df020575a8602227f9ed39cf0f754a Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 13:51:58 2010 -0400
move the "Inventory Summary" report to the Reports top view (from Admin top view)
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 df0f4b5..8715366 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 @@ -83,7 +83,6 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable treeGrids.put("Security", buildSecuritySection()); treeGrids.put("Configuration", buildSystemConfigurationSection()); treeGrids.put("Cluster", buildManagementClusterSection()); - treeGrids.put("Reports", buildReportsSection());
for (final String name : treeGrids.keySet()) { TreeGrid grid = treeGrids.get(name); @@ -181,23 +180,6 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable return systemConfigTreeGrid; }
- private TreeGrid buildReportsSection() { - - final TreeGrid reportsTreeGrid = new LocatableTreeGrid("Reports"); - reportsTreeGrid.setLeaveScrollbarGap(false); - reportsTreeGrid.setShowHeader(false); - - Tree tree = new Tree(); - final TreeNode inventorySummaryNode = new TreeNode("Inventory Summary"); - - TreeNode reportsNode = new TreeNode("Reports", inventorySummaryNode); - tree.setRoot(reportsNode); - - reportsTreeGrid.setData(tree); - - return reportsTreeGrid; - } - public void setContent(Canvas newContent) {
if (contentCanvas.getChildren().length > 0) { @@ -220,13 +202,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable String page = currentPageViewId.getPath();
Canvas content = null; - if ("Reports".equals(section)) { - - if ("Inventory Summary".equals(page)) { - content = new FullHTMLPane("/rhq/admin/report/resourceInstallReport-body.xhtml"); - } - - } else if ("Security".equals(section)) { + if ("Security".equals(section)) {
if ("Manage Users".equals(page)) { content = new UsersView(this.extendLocatorId("Users")); 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 c507395..2e8fae2 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 @@ -42,6 +42,7 @@ 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.alert.AlertsView; +import org.rhq.enterprise.gui.coregui.client.components.FullHTMLPane; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.platform.PlatformPortletView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration.ConfigurationHistoryView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.OperationHistoryView; @@ -221,8 +222,7 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView
} else if (SECTION_REPORTS.equals(section)) { if ("Inventory Summary".equals(page)) { - // TODO - content = null; + content = new FullHTMLPane("/rhq/admin/report/resourceInstallReport-body.xhtml"); } } for (String name : treeGrids.keySet()) {
commit 2b9cbc4e7ebb975f22d480d168c400b80cb1f147 Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 11:42:16 2010 -0400
fix for "Run Operation" button being unnecessarily wide
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java index 7ce66ae..212a5ae 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java @@ -133,6 +133,7 @@ public class OperationHistoryView extends TableSection { IMenuButton operationsButton = new LocatableIMenuButton(this.extendLocatorId("Run"), "Run Operation", operationMenu); operationsButton.setShowMenuBelow(false); + operationsButton.setAutoFit(true); addExtraWidget(operationsButton); }
commit b23dfc62b878474ac43b5ba894e9d716ccdd6453 Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 11:41:57 2010 -0400
fix resource links for pages still included via iframe
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java index 2ae4974..b648f57 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java @@ -29,17 +29,15 @@ public class LinkManager {
private static boolean GWT = true;
- public static String getResourceLink(int resourceId) {
if (GWT) { return "#Resource/" + resourceId + "/Summary/Overview"; } else { - return "/rhq/resource/summary/summary.xhtml?id=" + resourceId; + return "/rhq/resource/summary/overview.xhtml?id=" + resourceId; } }
- public static String getResourceGroupLink(int resouceGroupId) {
if (GWT) { @@ -61,7 +59,6 @@ public class LinkManager { return "/rhq/subsystem/operationHistory.xhtml"; }
- public static String getSubsystemAlertHistoryLink() { return "/rhq/subsystem/alertHistory.xhtml"; } @@ -70,7 +67,6 @@ public class LinkManager { return "/rhq/subsystem/alertDefinitions.xhtml"; }
- public static String getAutodiscoveryQueueLink() { if (GWT) { return "#Administration/Security/Auto%20Discovery%20Queue"; @@ -87,7 +83,6 @@ public class LinkManager { } }
- public static String getHubAllResourcesLink() { if (GWT) { return "#Inventory"; @@ -120,12 +115,10 @@ public class LinkManager { } }
- public static String getSavedSearchLink(int searchId) { return "/rhq/inventory/browseResources.xhtml?subtab=all&searchId=" + searchId; }
- public static String getHubAllGroupsLink() { return "/rhq/inventory/browseGroups.xhtml?subtab=all"; } @@ -146,12 +139,10 @@ public class LinkManager { return "/resource/group/Inventory.do?mode=new"; }
- public static String getHubNewGroupDefLink() { return "/rhq/definition/group/new.xhtml"; }
- public static String getAdminUsersLink() { if (GWT) { return "#Administration/Security/Manage Users"; @@ -176,7 +167,6 @@ public class LinkManager { } }
- public static String getAdminPluginsLink() { if (GWT) { return "#Administration/Configuration/Plugins"; @@ -185,7 +175,6 @@ public class LinkManager { } }
- public static String getAdminTemplatesLink() { if (GWT) { return "#Administration/Configuration/Templates"; @@ -198,7 +187,6 @@ public class LinkManager { return "/rhq/admin/alert/template/notification/list.xhtml"; }
- public static String getAdminContentProvidersLink() { return "/rhq/content/listContentProviders.xhtml"; } @@ -207,7 +195,6 @@ public class LinkManager { return "/rhq/content/listRepos.xhtml"; }
- public static String getHAServersLink() { if (GWT) { return "#Administration/Cluster/Servers"; @@ -240,7 +227,6 @@ public class LinkManager { } }
- public static String getReportsInventoryLink() { if (GWT) { return "#Administration/Reports/Inventory Summary"; @@ -253,7 +239,6 @@ public class LinkManager { return "/rhq/admin/downloads.xhtml"; }
- public static String getAdminLicenseLink() { if (GWT) { return "#Administration/Configuration/License"; @@ -262,7 +247,6 @@ public class LinkManager { } }
- public static String getDebugSqlLink() { return "/admin/test/sql.jsp"; } @@ -283,7 +267,6 @@ public class LinkManager { return "/admin/user/UserAdmin.do?mode=editPass&u=" + subjectId; }
- public static String getTagLink(String tag) { return "#Reports/Inventory/Tag%20Cloud/" + tag; } diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/common/tag/FunctionTagLibrary.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/common/tag/FunctionTagLibrary.java index ad57e8b..c7ad60c 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/common/tag/FunctionTagLibrary.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/common/tag/FunctionTagLibrary.java @@ -351,13 +351,17 @@ public class FunctionTagLibrary extends AbstractTagLibrary {
// needs to exist separately from getDefaultContextTabURL because only some facelets understand EntityContext public static String getDefaultResourceTabURL() { - return "/rhq/resource/summary/summary.xhtml"; + return "/rhq/resource/summary/overview.xhtml"; }
public static String getDefaultGroupTabURL() { return "/rhq/group/inventory/view.xhtml"; }
+ public static String getDefaultAutoGroupTabURL() { + return "/rhq/autogroup/monitor/graphs.xhtml"; + } + public static String getAvailabilityURL(AvailabilityType type, int size) { if (size != 16 && size != 24) { throw new IllegalArgumentException("No availability icon for size " + size); diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/DisambiguatedResourceLineageRenderer.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/DisambiguatedResourceLineageRenderer.java index 56d5465..c862f61 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/DisambiguatedResourceLineageRenderer.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/DisambiguatedResourceLineageRenderer.java @@ -33,6 +33,7 @@ import javax.faces.context.ResponseWriter; import javax.faces.render.Renderer;
import org.rhq.core.domain.resource.composite.DisambiguationReport; +import org.rhq.enterprise.gui.common.tag.FunctionTagLibrary;
/** * Renderer for {@link DisambiguatedResourceLineageComponent} @@ -40,37 +41,36 @@ import org.rhq.core.domain.resource.composite.DisambiguationReport; * @author Lukas Krejci */ public class DisambiguatedResourceLineageRenderer extends Renderer { - private static final String RESOURCE_URL = "/rhq/resource/summary/summary.xhtml"; - + @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { DisambiguatedResourceLineageComponent lineageComponent = (DisambiguatedResourceLineageComponent) component; - + String separator = lineageComponent.getSeparator(); List<DisambiguationReport.Resource> parents = lineageComponent.getParents(); boolean renderLinks = lineageComponent.getRenderLinks(); - + if (parents != null && parents.size() > 0) { ResponseWriter writer = context.getResponseWriter(); - + Iterator<DisambiguationReport.Resource> parentsIt = parents.iterator(); - + if (renderLinks) { encodeUrl(writer, parentsIt.next()); - while(parentsIt.hasNext()) { + while (parentsIt.hasNext()) { writer.writeText(separator, null); encodeUrl(writer, parentsIt.next()); } } else { encodeSimple(writer, parentsIt.next()); - while(parentsIt.hasNext()) { + while (parentsIt.hasNext()) { writer.writeText(separator, null); encodeSimple(writer, parentsIt.next()); } } } } - + public static void encodeUrl(ResponseWriter writer, DisambiguationReport.Resource parent) throws IOException { encodePreName(writer, parent); writer.startElement("a", null); @@ -79,17 +79,17 @@ public class DisambiguatedResourceLineageRenderer extends Renderer { writer.endElement("a"); encodePostName(writer, parent); } - + public static void encodeSimple(ResponseWriter writer, DisambiguationReport.Resource parent) throws IOException { encodePreName(writer, parent); writeName(writer, parent); encodePostName(writer, parent); } - + private static String getUrl(DisambiguationReport.Resource parent) { - return RESOURCE_URL + "?id=" + parent.getId(); + return FunctionTagLibrary.getDefaultResourceTabURL() + "?id=" + parent.getId(); } - + private static void encodePreName(ResponseWriter writer, DisambiguationReport.Resource parent) throws IOException { if (!parent.getType().isSingleton()) { writer.startElement("span", null); @@ -118,7 +118,7 @@ public class DisambiguatedResourceLineageRenderer extends Renderer { writer.endElement("span"); } } - + private static void writeName(ResponseWriter writer, DisambiguationReport.Resource parent) throws IOException { writer.startElement("span", null); writer.writeAttribute("class", "disambiguated-resource-name", null); diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/ResourceLineageRenderer.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/ResourceLineageRenderer.java index 33310b6..73903a5 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/ResourceLineageRenderer.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/ResourceLineageRenderer.java @@ -27,6 +27,7 @@ import javax.faces.context.ResponseWriter; import javax.faces.render.Renderer;
import org.rhq.core.domain.resource.Resource; +import org.rhq.enterprise.gui.common.tag.FunctionTagLibrary; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.util.HibernatePerformanceMonitor; import org.rhq.enterprise.server.util.LookupUtil; @@ -37,7 +38,6 @@ import org.rhq.enterprise.server.util.LookupUtil; * @author Ian Springer */ public class ResourceLineageRenderer extends Renderer { - private static final String BASE_RESOURCE_URL = "/rhq/resource/summary/summary.xhtml"; private static final String SEPARATOR = " > ";
private ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); @@ -74,7 +74,7 @@ public class ResourceLineageRenderer extends Renderer { }
private String buildURL(Resource resource) { - String url = BASE_RESOURCE_URL + "?id=" + resource.getId(); + String url = FunctionTagLibrary.getDefaultResourceTabURL() + "?id=" + resource.getId();
// Session-encode the URL in case the client doesn't have cookies enabled. url = FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(url); diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/InventoryHierarchyTag.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/InventoryHierarchyTag.java index 4f5bfa9..76e437e 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/InventoryHierarchyTag.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/InventoryHierarchyTag.java @@ -32,6 +32,7 @@ import org.rhq.core.domain.resource.Resource; 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.enterprise.gui.common.tag.FunctionTagLibrary; import org.rhq.enterprise.gui.legacy.util.RequestUtils; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; @@ -46,11 +47,7 @@ import org.rhq.enterprise.server.util.LookupUtil; * @author Ian Springer */ public class InventoryHierarchyTag extends TagSupport { - private static final String BASE_RESOURCE_URL = "/rhq/resource/summary/summary.xhtml";
- //private static final String BASE_GROUP_URL = "/Resource.do?type=GROUP"; - private static final String BASE_GROUP_URL = "/rhq/group/inventory/view.xhtml"; - private static final String BASE_AUTOGROUP_URL = "/rhq/autogroup/monitor/graphs.xhtml"; private static final String SEPARATOR = " > ";
private Integer resourceId; @@ -177,7 +174,7 @@ public class InventoryHierarchyTag extends TagSupport { }
private String buildResourceURL(Resource resource) { - String url = BASE_RESOURCE_URL + "?id=" + resource.getId(); + String url = FunctionTagLibrary.getDefaultResourceTabURL() + "?id=" + resource.getId();
// Session-encode the URL in case the client doesn't have cookies enabled. return encodeURL(url); @@ -185,15 +182,16 @@ public class InventoryHierarchyTag extends TagSupport {
private String buildGroupURL(ResourceGroup resourceGroup) { GroupCategory category = resourceGroup.getGroupCategory(); - String url = BASE_GROUP_URL + "?category=" + category.name() + "&groupId=" + resourceGroup.getId(); + String url = FunctionTagLibrary.getDefaultGroupTabURL() + "?category=" + category.name() + "&groupId=" + + resourceGroup.getId();
// Session-encode the URL in case the client doesn't have cookies enabled. return encodeURL(url); }
private String buildAutoGroupURL() { - String url = BASE_AUTOGROUP_URL + "?id=" + parentResourceId + "&parent=" + parentResourceId + "&type=" - + resourceTypeId; + String url = FunctionTagLibrary.getDefaultAutoGroupTabURL() + "?id=" + parentResourceId + "&parent=" + + parentResourceId + "&type=" + resourceTypeId;
// Session-encode the URL in case the client doesn't have cookies enabled. return encodeURL(url); diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/display/DisambiguatedResourceNameTag.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/display/DisambiguatedResourceNameTag.java index 2efedc9..091fa19 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/display/DisambiguatedResourceNameTag.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/taglib/display/DisambiguatedResourceNameTag.java @@ -32,6 +32,7 @@ import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport;
import org.rhq.core.domain.resource.composite.DisambiguationReport; +import org.rhq.enterprise.gui.common.tag.FunctionTagLibrary;
/** * @@ -122,7 +123,7 @@ public class DisambiguatedResourceNameTag extends TagSupport { if (htmlOutput) { writer.append("<span class="disambiguated-resource-type">"); } - + writer.append(resourceType.getName()).append(" ");
if (resourceType.getPlugin() != null) { @@ -134,7 +135,7 @@ public class DisambiguatedResourceNameTag extends TagSupport { writer.append("</span>"); } } - + if (htmlOutput) { writer.append("</span>"); } @@ -151,7 +152,7 @@ public class DisambiguatedResourceNameTag extends TagSupport { if (htmlOutput) { writer.append("</span>"); } - + if (url != null) { writer.append("</a>"); } @@ -160,7 +161,7 @@ public class DisambiguatedResourceNameTag extends TagSupport { if (htmlOutput) { writer.append("<span class="disambiguated-resource-plugin">"); } - + writer.append(" (").append(resourceType.getPlugin()).append(" plugin)");
if (htmlOutput) { @@ -168,8 +169,8 @@ public class DisambiguatedResourceNameTag extends TagSupport { } } } - + public static String getDefaultResourceUrl(int resourceId) { - return "/rhq/resource/summary/summary.xhtml?id=" + resourceId; + return FunctionTagLibrary.getDefaultResourceTabURL() + "?id=" + resourceId; } } diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/navigation/group/ResourceGroupTreeContextMenuUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/navigation/group/ResourceGroupTreeContextMenuUIBean.java index 4650eef..e69c57e 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/navigation/group/ResourceGroupTreeContextMenuUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/navigation/group/ResourceGroupTreeContextMenuUIBean.java @@ -34,6 +34,7 @@ import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.group.ClusterKey; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.gui.util.FacesContextUtility; +import org.rhq.enterprise.gui.common.tag.FunctionTagLibrary; import org.rhq.enterprise.gui.navigation.contextmenu.MenuItemDescriptor; import org.rhq.enterprise.gui.navigation.contextmenu.MetricMenuItemDescriptor; import org.rhq.enterprise.gui.navigation.contextmenu.QuickLinksDescriptor; @@ -175,7 +176,7 @@ public class ResourceGroupTreeContextMenuUIBean extends TreeContextMenuBase { menuItem.setValue(res.getName()); menuItem.setId("groupMember_" + res.getId());
- String url = "/rhq/resource/summary/summary.xhtml?id=" + res.getId(); + String url = FunctionTagLibrary.getDefaultResourceTabURL() + "?id=" + res.getId();
menuItem.setSubmitMode("none"); menuItem.setOnclick("document.location.href='" + url + "'");
commit cc80b28867c8984b6da49e0f43aeab1900384014 Author: Joseph Marques joseph@redhat.com Date: Fri Sep 10 11:01:49 2010 -0400
remove "details" button from operation>history page in favor of double-click details trigger
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java index ae68de0..7ce66ae 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/OperationHistoryView.java @@ -32,12 +32,9 @@ import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.OperationRequestStatus; -import org.rhq.core.domain.operation.ResourceOperationHistory; 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.components.table.Table; -import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.create.OperationCreateWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.detail.OperationDetailsView; @@ -115,16 +112,6 @@ public class OperationHistoryView extends TableSection { getListGrid().hideField("resource"); }
- addTableAction(extendLocatorId("Details"), "Details", Table.SelectionEnablement.SINGLE, null, - new TableAction() { - public void executeAction(ListGridRecord[] selection) { - ResourceOperationHistory history = (ResourceOperationHistory) selection[0] - .getAttributeAsObject("entity"); - - showDetails(history.getId()); - } - }); - if (resource != null && composite.getResourcePermission().isControl()) { final Menu operationMenu = new LocatableMenu(this.extendLocatorId("Operation")); ResourceTypeRepository.Cache.getInstance().getResourceTypes(resource.getResourceType().getId(),
commit 83e9781e640d06fbe41208d6bec8a4b40c4b82ed Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 12:08:59 2010 -0400
make sure all data we need for the types are preloaded
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java index 0c7cdff..4775ee4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/GroupAlertDefinitionsView.java @@ -23,6 +23,9 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.ArrayList; +import java.util.EnumSet; + import com.smartgwt.client.data.Criteria; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -30,6 +33,8 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository.MetadataType;
/** * @author John Mazzitelli @@ -43,6 +48,24 @@ public class GroupAlertDefinitionsView extends AbstractAlertDefinitionsView { public GroupAlertDefinitionsView(String locatorId, ResourceGroup group) { super(locatorId, "Group Alert Definitions"); this.group = group; + + // make sure we loaded all the type info we'll need. if one of these is null, either the type + // doesn't have it or we haven't loaded it yet. since we can't know for sure if it was loaded, we have to ask. + ResourceType rt = this.group.getResourceType(); + EnumSet<MetadataType> metadata = EnumSet.noneOf(MetadataType.class); + if (rt.getEventDefinitions() == null) + metadata.add(MetadataType.events); + if (rt.getMetricDefinitions() == null) + metadata.add(MetadataType.measurements); + if (rt.getOperationDefinitions() == null) + metadata.add(MetadataType.operations); + if (rt.getResourceConfigurationDefinition() == null) + metadata.add(MetadataType.resourceConfigurationDefinition); + if (!metadata.isEmpty()) { + ArrayList<ResourceGroup> list = new ArrayList<ResourceGroup>(1); + list.add(this.group); + ResourceTypeRepository.Cache.getInstance().loadResourceTypes(list, metadata, null); + } }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java index da46f44..f986562 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceAlertDefinitionsView.java @@ -23,6 +23,9 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.ArrayList; +import java.util.EnumSet; + import com.smartgwt.client.data.Criteria; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -30,6 +33,8 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository.MetadataType;
/** * @author John Mazzitelli @@ -43,6 +48,24 @@ public class ResourceAlertDefinitionsView extends AbstractAlertDefinitionsView { public ResourceAlertDefinitionsView(String locatorId, Resource resource) { super(locatorId, "Alert Definitions"); this.resource = resource; + + // make sure we loaded all the type info we'll need. if one of these is null, either the type + // doesn't have it or we haven't loaded it yet. since we can't know for sure if it was loaded, we have to ask. + ResourceType rt = this.resource.getResourceType(); + EnumSet<MetadataType> metadata = EnumSet.noneOf(MetadataType.class); + if (rt.getEventDefinitions() == null) + metadata.add(MetadataType.events); + if (rt.getMetricDefinitions() == null) + metadata.add(MetadataType.measurements); + if (rt.getOperationDefinitions() == null) + metadata.add(MetadataType.operations); + if (rt.getResourceConfigurationDefinition() == null) + metadata.add(MetadataType.resourceConfigurationDefinition); + if (!metadata.isEmpty()) { + ArrayList<Resource> list = new ArrayList<Resource>(1); + list.add(this.resource); + ResourceTypeRepository.Cache.getInstance().loadResourceTypes(list, metadata, null); + } }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java index 3ef3dfe..4366291 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/TemplateAlertDefinitionsView.java @@ -23,12 +23,16 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.EnumSet; + import com.smartgwt.client.data.Criteria; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository.MetadataType;
/** * @author John Mazzitelli @@ -42,6 +46,27 @@ public class TemplateAlertDefinitionsView extends AbstractAlertDefinitionsView { public TemplateAlertDefinitionsView(String locatorId, ResourceType resourceType) { super(locatorId, "Alert Templates"); this.resourceType = resourceType; + + // make sure we loaded all the type info we'll need. if one of these is null, either the type + // doesn't have it or we haven't loaded it yet. since we can't know for sure if it was loaded, we have to ask. + EnumSet<MetadataType> metadata = EnumSet.noneOf(MetadataType.class); + if (resourceType.getEventDefinitions() == null) + metadata.add(MetadataType.events); + if (resourceType.getMetricDefinitions() == null) + metadata.add(MetadataType.measurements); + if (resourceType.getOperationDefinitions() == null) + metadata.add(MetadataType.operations); + if (resourceType.getResourceConfigurationDefinition() == null) + metadata.add(MetadataType.resourceConfigurationDefinition); + if (!metadata.isEmpty()) { + ResourceTypeRepository.Cache.getInstance().getResourceTypes(resourceType.getId(), metadata, + new ResourceTypeRepository.TypeLoadedCallback() { + @Override + public void onTypesLoaded(ResourceType type) { + TemplateAlertDefinitionsView.this.resourceType = type; + } + }); + } }
@Override
commit f22c6f4fa74deea8393f8e53414aa886b18054ce Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 12:08:26 2010 -0400
support the ability to load resource types for resource groups support the ability to pass in a null callback (i.e. just load the types and don't bother calling back into anything)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java index 550413c..d488d14 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java @@ -32,6 +32,7 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -49,11 +50,9 @@ public class ResourceTypeRepository { private static ResourceTypeGWTServiceAsync resourceTypeService = GWTServiceLookup.getResourceTypeGWTService();
public enum MetadataType { - children, operations, measurements, content, events, pluginConfigurationDefinition, resourceConfigurationDefinition, - subCategory, parentTypes, processScans, productVersions + children, operations, measurements, content, events, pluginConfigurationDefinition, resourceConfigurationDefinition, subCategory, parentTypes, processScans, productVersions }
- public static class Cache { private static final ResourceTypeRepository ourInstance = GWT.create(ResourceTypeRepository.class);
@@ -62,12 +61,10 @@ public class ResourceTypeRepository { } }
- public static interface TypeLoadedCallback { - void onTypesLoaded( ResourceType type); + void onTypesLoaded(ResourceType type); }
- public static interface TypesLoadedCallback { void onTypesLoaded(HashMap<Integer, ResourceType> types); } @@ -76,14 +73,20 @@ public class ResourceTypeRepository { void onResourceTypeLoaded(List<Resource> resources); }
+ public static interface ResourceTypeLoadedInGroupCallback { + void onResourceTypeLoaded(List<ResourceGroup> resources); + } + public void loadResourceTypes(final PageList<Resource> resources, final ResourceTypeLoadedCallback callback) { loadResourceTypes(resources, null, callback); }
public void loadResourceTypes(final List<Resource> resources, final EnumSet<MetadataType> metadataTypes, - final ResourceTypeLoadedCallback callback) { + final ResourceTypeLoadedCallback callback) { if (resources.size() == 0) { - callback.onResourceTypeLoaded(resources); + if (callback != null) { + callback.onResourceTypeLoaded(resources); + } return; }
@@ -98,41 +101,78 @@ public class ResourceTypeRepository { for (Resource res : resources) { res.setResourceType(types.get(res.getResourceType().getId())); } - callback.onResourceTypeLoaded(resources); + if (callback != null) { + callback.onResourceTypeLoaded(resources); + } } });
-// System.out.println("Loaded types from cache in " + (System.currentTimeMillis() - start)); + // System.out.println("Loaded types from cache in " + (System.currentTimeMillis() - start)); + }
+ public void loadResourceTypes(final PageList<ResourceGroup> groups, final ResourceTypeLoadedInGroupCallback callback) { + loadResourceTypes(groups, null, callback); }
+ public void loadResourceTypes(final List<ResourceGroup> groups, final EnumSet<MetadataType> metadataTypes, + final ResourceTypeLoadedInGroupCallback callback) { + if (groups.size() == 0) { + if (callback != null) { + callback.onResourceTypeLoaded(groups); + } + return; + } + + long start = System.currentTimeMillis(); + + Set<Integer> types = new HashSet<Integer>(); + for (ResourceGroup group : groups) { + types.add(group.getResourceType().getId()); + } + getResourceTypes(types.toArray(new Integer[types.size()]), metadataTypes, new TypesLoadedCallback() { + public void onTypesLoaded(HashMap<Integer, ResourceType> types) { + for (ResourceGroup group : groups) { + group.setResourceType(types.get(group.getResourceType().getId())); + } + if (callback != null) { + callback.onResourceTypeLoaded(groups); + } + } + }); + + // System.out.println("Loaded types from cache in " + (System.currentTimeMillis() - start)); + }
public void getResourceTypes(Integer[] resourceTypeIds, final TypesLoadedCallback callback) { getResourceTypes(resourceTypeIds, null, callback); }
- - public void getResourceTypes(final Integer resourceTypeId, final EnumSet<MetadataType> metadataTypes, final TypeLoadedCallback callback) { - getResourceTypes(new Integer[]{resourceTypeId}, metadataTypes, new TypesLoadedCallback() { + public void getResourceTypes(final Integer resourceTypeId, final EnumSet<MetadataType> metadataTypes, + final TypeLoadedCallback callback) { + getResourceTypes(new Integer[] { resourceTypeId }, metadataTypes, new TypesLoadedCallback() { public void onTypesLoaded(HashMap<Integer, ResourceType> types) { - callback.onTypesLoaded(types.get(resourceTypeId)); + if (callback != null) { + callback.onTypesLoaded(types.get(resourceTypeId)); + } } }); }
- public void getResourceTypes(Integer[] resourceTypeIds, final EnumSet<MetadataType> metadataTypes, final TypesLoadedCallback callback) { + public void getResourceTypes(Integer[] resourceTypeIds, final EnumSet<MetadataType> metadataTypes, + final TypesLoadedCallback callback) { ResourceTypeCriteria criteria = new ResourceTypeCriteria();
final HashMap<Integer, ResourceType> cachedTypes = new HashMap<Integer, ResourceType>();
- ArrayList<Integer> typesNeeded = new ArrayList<Integer>(); if (resourceTypeIds == null) { //preload all } else {
for (Integer typeId : resourceTypeIds) { - if (!typeCache.containsKey(typeId) || (metadataTypes != null && (typeCacheLevel.containsKey(typeId)) && !typeCacheLevel.get(typeId).containsAll(metadataTypes))) { + if (!typeCache.containsKey(typeId) + || (metadataTypes != null && (typeCacheLevel.containsKey(typeId)) && !typeCacheLevel.get(typeId) + .containsAll(metadataTypes))) { typesNeeded.add(typeId); } else { cachedTypes.put(typeId, typeCache.get(typeId)); @@ -140,7 +180,9 @@ public class ResourceTypeRepository { }
if (typesNeeded.isEmpty()) { - callback.onTypesLoaded(cachedTypes); + if (callback != null) { + callback.onTypesLoaded(cachedTypes); + } return; } criteria.addFilterIds(typesNeeded.toArray(new Integer[typesNeeded.size()])); @@ -149,50 +191,51 @@ public class ResourceTypeRepository { if (metadataTypes != null) { for (MetadataType metadataType : metadataTypes) { switch (metadataType) { - case children: - criteria.fetchChildResourceTypes(true); - break; - case content: - criteria.fetchPackageTypes(true); - break; - case measurements: - criteria.fetchMetricDefinitions(true); - break; - case operations: - criteria.fetchOperationDefinitions(true); - break; - case events: - criteria.fetchEventDefinitions(true); - break; - case pluginConfigurationDefinition: - criteria.fetchPluginConfigurationDefinition(true); - break; - case resourceConfigurationDefinition: - criteria.fetchResourceConfigurationDefinition(true); - break; - case subCategory: - criteria.fetchSubCategory(true); - break; - case parentTypes: - criteria.fetchParentResourceTypes(true); - break; - case processScans: - criteria.fetchProcessScans(true); - break; - case productVersions: - criteria.fetchProductVersions(true); - break; + case children: + criteria.fetchChildResourceTypes(true); + break; + case content: + criteria.fetchPackageTypes(true); + break; + case measurements: + criteria.fetchMetricDefinitions(true); + break; + case operations: + criteria.fetchOperationDefinitions(true); + break; + case events: + criteria.fetchEventDefinitions(true); + break; + case pluginConfigurationDefinition: + criteria.fetchPluginConfigurationDefinition(true); + break; + case resourceConfigurationDefinition: + criteria.fetchResourceConfigurationDefinition(true); + break; + case subCategory: + criteria.fetchSubCategory(true); + break; + case parentTypes: + criteria.fetchParentResourceTypes(true); + break; + case processScans: + criteria.fetchProcessScans(true); + break; + case productVersions: + criteria.fetchProductVersions(true); + break; } } }
criteria.setPageControl(PageControl.getUnlimitedInstance());
- System.out.println("Loading " + typesNeeded.size() + ((metadataTypes != null) ? (" types: " + metadataTypes.toString()) : "")); + System.out.println("Loading " + typesNeeded.size() + + ((metadataTypes != null) ? (" types: " + metadataTypes.toString()) : ""));
resourceTypeService.findResourceTypesByCriteria(criteria, new AsyncCallback<PageList<ResourceType>>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load resource type metadata",caught); + CoreGUI.getErrorHandler().handleError("Failed to load resource type metadata", caught); }
public void onSuccess(PageList<ResourceType> result) { @@ -202,27 +245,29 @@ public class ResourceTypeRepository { if (metadataTypes != null) { for (MetadataType metadataType : metadataTypes) { switch (metadataType) { - case children: - cachedType.setChildResourceTypes(type.getChildResourceTypes()); - break; - case operations: - cachedType.setOperationDefinitions(type.getOperationDefinitions()); - break; - case measurements: - cachedType.setMetricDefinitions(type.getMetricDefinitions()); - break; - case content: - cachedType.setPackageTypes(type.getPackageTypes()); - break; - case events: - cachedType.setPackageTypes(type.getPackageTypes()); - break; - case pluginConfigurationDefinition: - cachedType.setPluginConfigurationDefinition(type.getPluginConfigurationDefinition()); - break; - case resourceConfigurationDefinition: - cachedType.setResourceConfigurationDefinition(type.getResourceConfigurationDefinition()); - break; + case children: + cachedType.setChildResourceTypes(type.getChildResourceTypes()); + break; + case operations: + cachedType.setOperationDefinitions(type.getOperationDefinitions()); + break; + case measurements: + cachedType.setMetricDefinitions(type.getMetricDefinitions()); + break; + case content: + cachedType.setPackageTypes(type.getPackageTypes()); + break; + case events: + cachedType.setPackageTypes(type.getPackageTypes()); + break; + case pluginConfigurationDefinition: + cachedType + .setPluginConfigurationDefinition(type.getPluginConfigurationDefinition()); + break; + case resourceConfigurationDefinition: + cachedType.setResourceConfigurationDefinition(type + .getResourceConfigurationDefinition()); + break; } } } @@ -240,16 +285,17 @@ public class ResourceTypeRepository { } } } - callback.onTypesLoaded(cachedTypes); + if (callback != null) { + callback.onTypesLoaded(cachedTypes); + } } }); }
- public void preloadAll() { getResourceTypes((Integer[]) null, EnumSet.allOf(MetadataType.class), new TypesLoadedCallback() { public void onTypesLoaded(HashMap<Integer, ResourceType> types) { - System.out.println("Preloaded ["+ types.size() + "] resource types"); + System.out.println("Preloaded [" + types.size() + "] resource types"); } }); }
commit 4edb44646a4b0c816aa6b934704de65ef8e8a40a Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 12:06:49 2010 -0400
add the ability to add resource config change condition
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java index fceb893..b17e25a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java @@ -78,6 +78,7 @@ public class NewConditionEditor extends LocatableDynamicForm { private boolean supportsTraits = false; private boolean supportsOperations = false; private boolean supportsEvents = false; + private boolean supportsResourceConfig = false; private Runnable okFunction; // this is called after the OK button is pressed and a new condition is saved private ResourceType resourceType;
@@ -89,6 +90,7 @@ public class NewConditionEditor extends LocatableDynamicForm { this.resourceType = rtype;
this.supportsEvents = (rtype.getEventDefinitions() != null && rtype.getEventDefinitions().size() > 0); + this.supportsResourceConfig = (rtype.getResourceConfigurationDefinition() != null);
Set<MeasurementDefinition> metricDefinitions = rtype.getMetricDefinitions(); if (metricDefinitions != null && metricDefinitions.size() > 0) { @@ -135,6 +137,9 @@ public class NewConditionEditor extends LocatableDynamicForm { if (supportsOperations) { condTypes.put(AlertConditionCategory.CONTROL.name(), "Operation Execution"); } + if (supportsResourceConfig) { + condTypes.put(AlertConditionCategory.RESOURCE_CONFIG.name(), "Resource Configuration Change"); + } if (supportsEvents) { condTypes.put(AlertConditionCategory.EVENT.name(), "Event Detection"); } @@ -179,6 +184,9 @@ public class NewConditionEditor extends LocatableDynamicForm { if (supportsEvents) { formItems.addAll(buildEventFormItems()); } + if (supportsResourceConfig) { + formItems.addAll(buildResourceConfigChangeFormItems()); + } formItems.add(ok);
setFields(formItems.toArray(new FormItem[formItems.size()])); @@ -259,6 +267,15 @@ public class NewConditionEditor extends LocatableDynamicForm { break; }
+ case RESOURCE_CONFIG: { + newCondition.setName(null); + newCondition.setComparator(null); + newCondition.setThreshold(null); + newCondition.setOption(null); + newCondition.setMeasurementDefinition(null); + break; + } + default: { CoreGUI.getErrorHandler().handleError("Invalid alert category selected: " + category); // should never happen break; @@ -459,6 +476,18 @@ public class NewConditionEditor extends LocatableDynamicForm { return formItems; }
+ private ArrayList<FormItem> buildResourceConfigChangeFormItems() { + ArrayList<FormItem> formItems = new ArrayList<FormItem>(); + + ShowIfCategoryFunction ifFunc = new ShowIfCategoryFunction(AlertConditionCategory.RESOURCE_CONFIG); + + String helpStr = "This condition is triggered when the resource configuration changes."; + StaticTextItem helpItem = buildHelpTextItem("changeConfigHelp", helpStr, ifFunc); + formItems.add(helpItem); + + return formItems; + } + private SelectItem buildMetricDropDownMenu(String itemName, FormItemIfFunction ifFunc) {
LinkedHashMap<String, String> metricsMap = new LinkedHashMap<String, String>();
commit 8ffce671fa4d1977b2850a0ae3462969274a701c Author: Ian Springer ian.springer@redhat.com Date: Wed Sep 15 12:04:43 2010 -0400
make CoreGUI.html a welcome page, so http://localhost:7080/coregui/ works
diff --git a/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml b/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml index a86b217..6e5d56b 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml +++ b/modules/enterprise/gui/coregui/src/main/webapp/WEB-INF/web.xml @@ -1,10 +1,12 @@ -<?xml version="1.0" encoding="UTF-8"?> +<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - version="2.5"> + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" + version="2.5"> + + <display-name>RHQ GUI</display-name> +
<servlet> <servlet-name>org.rhq.enterprise.gui.coregui.CoreGUI RoleGWTService</servlet-name> @@ -214,4 +216,10 @@ <servlet-name>org.rhq.enterprise.gui.coregui.CoreGUI ClusterGWTService</servlet-name> <url-pattern>/org.rhq.enterprise.gui.coregui.CoreGUI/ClusterGWTService</url-pattern> </servlet-mapping> + + + <welcome-file-list> + <welcome-file>CoreGUI.html</welcome-file> + </welcome-file-list> + </web-app> diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/WEB-INF/web.xml b/modules/enterprise/gui/portal-war/src/main/webapp/WEB-INF/web.xml index ed22bc6..2cdedb1 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/WEB-INF/web.xml +++ b/modules/enterprise/gui/portal-war/src/main/webapp/WEB-INF/web.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
- <display-name>RHQ</display-name> + <display-name>RHQ Legacy GUI</display-name>
<!--=== Seam ===-->
commit cc727ab9928ec5463171ff4eac8f5d69315198da Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 11:33:23 2010 -0400
A few more locatorId hooks in the TopMenu Search bar
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 34d1621..403456c 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 @@ -232,7 +232,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // menuPane.setZIndex(400000); // layout.addMember(menuPane);
- MenuBarView menuBarView = new MenuBarView(); + MenuBarView menuBarView = new MenuBarView("TopMenu"); menuBarView.setWidth("100%"); // WidgetCanvas menuCanvas = new WidgetCanvas(menuBarView); // menuCanvas.setTop(0); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java index c98c16d..da5b92e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/DropDownMenuBarView.java @@ -28,7 +28,6 @@ import com.smartgwt.client.widgets.Img; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.HLayout; -import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.menu.Menu; import com.smartgwt.client.widgets.menu.MenuBar; import com.smartgwt.client.widgets.menu.MenuItem; @@ -37,23 +36,23 @@ import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.components.AboutModalWindow; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle */ -public class DropDownMenuBarView extends VLayout { +public class DropDownMenuBarView extends LocatableVLayout {
private AboutModalWindow aboutModalWindow;
- public DropDownMenuBarView() { - super(5); + public DropDownMenuBarView(String locatorId) { + super(locatorId, 5); + setHeight(50); setWidth100();
- }
- protected void onDraw3() { super.onDraw();
@@ -62,10 +61,9 @@ public class DropDownMenuBarView extends VLayout { HLayout topBar = new HLayout(); topBar.setHeight(28); topBar.setStyleName("topMenuBar"); -// url("./images/cssButton/button_stretch.png") repeat-x scroll 0 0 #DDDDDD -// topBar.setBackgroundImage("[SKIN]/cssButton/button_stretch.png"); -// topBar.setBackgroundRepeat(BkgndRepeat.REPEAT_X); - + // url("./images/cssButton/button_stretch.png") repeat-x scroll 0 0 #DDDDDD + // topBar.setBackgroundImage("[SKIN]/cssButton/button_stretch.png"); + // topBar.setBackgroundRepeat(BkgndRepeat.REPEAT_X);
Img logo = new Img("header/rhq_logo_28px.png", 80, 28); logo.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { @@ -74,36 +72,36 @@ public class DropDownMenuBarView extends VLayout { } });
- topBar.addMember(logo);
- // Create a menu bar final MenuBar menu = new MenuBar(); menu.setHeight(28);
- - Menu subsystemsMenu = new Menu();
subsystemsMenu.setTitle("Subsystems"); - subsystemsMenu.addItem(new EMenuItem("Configuration Changes", LinkManager.getSubsystemConfigurationLink(), "subsystems/configure/Configure_16.png"));//, new LinkCommand("#config")); - subsystemsMenu.addItem(new EMenuItem("Suspect Metrics", LinkManager.getSubsystemSuspectMetricsLink(), "subsystems/monitor/Monitor_failed_16.png"));//, new LinkCommand("#config")); - subsystemsMenu.addItem(new EMenuItem("Operations", LinkManager.getSubsystemOperationHistoryLink(), "subsystems/control/Operation_16.png"));//, new LinkCommand("#config")); - subsystemsMenu.addItem(new EMenuItem("Alerts", LinkManager.getSubsystemAlertHistoryLink(), "subsystems/alert/Alert_HIGH_16.png"));//, new LinkCommand("#config")); - subsystemsMenu.addItem(new EMenuItem("Alert Definitions", LinkManager.getSubsystemAlertDefsLink(), "subsystems/alert/Alerts_16.png"));//, new LinkCommand("#config")); - + subsystemsMenu.addItem(new EMenuItem("Configuration Changes", LinkManager.getSubsystemConfigurationLink(), + "subsystems/configure/Configure_16.png"));//, new LinkCommand("#config")); + subsystemsMenu.addItem(new EMenuItem("Suspect Metrics", LinkManager.getSubsystemSuspectMetricsLink(), + "subsystems/monitor/Monitor_failed_16.png"));//, new LinkCommand("#config")); + subsystemsMenu.addItem(new EMenuItem("Operations", LinkManager.getSubsystemOperationHistoryLink(), + "subsystems/control/Operation_16.png"));//, new LinkCommand("#config")); + subsystemsMenu.addItem(new EMenuItem("Alerts", LinkManager.getSubsystemAlertHistoryLink(), + "subsystems/alert/Alert_HIGH_16.png"));//, new LinkCommand("#config")); + subsystemsMenu.addItem(new EMenuItem("Alert Definitions", LinkManager.getSubsystemAlertDefsLink(), + "subsystems/alert/Alerts_16.png"));//, new LinkCommand("#config"));
final Menu overviewMenu = new Menu(); overviewMenu.setTitle("Overview"); overviewMenu.setStyleName("SimpleMenuBarButton"); overviewMenu.setBorder("none"); - com.smartgwt.client.widgets.menu.MenuItem subsystemsSubMenuItem = new com.smartgwt.client.widgets.menu.MenuItem("Subsystems"); + com.smartgwt.client.widgets.menu.MenuItem subsystemsSubMenuItem = new com.smartgwt.client.widgets.menu.MenuItem( + "Subsystems"); subsystemsSubMenuItem.setSubmenu(subsystemsMenu); overviewMenu.addItem(subsystemsSubMenuItem); - overviewMenu.addItem(new EMenuItem("AutoDiscovery Queue",LinkManager.getAutodiscoveryQueueLink()));//,new LinkCommand("#cofng")); - overviewMenu.addItem(new EMenuItem("Dashboard",LinkManager.getDashboardLink()));//,new LinkCommand("#cofng")); - + overviewMenu.addItem(new EMenuItem("AutoDiscovery Queue", LinkManager.getAutodiscoveryQueueLink()));//,new LinkCommand("#cofng")); + overviewMenu.addItem(new EMenuItem("Dashboard", LinkManager.getDashboardLink()));//,new LinkCommand("#cofng"));
Menu resourcesMenu = new Menu(); resourcesMenu.setTitle("Resources"); @@ -111,7 +109,8 @@ public class DropDownMenuBarView extends VLayout { resourcesMenu.setBorder("none"); resourcesMenu.setStyleName("menuBarMenuButton"); resourcesMenu.addItem(new EMenuItem("All Resources", LinkManager.getHubAllResourcesLink()));//, new LinkCommand("#fsdf")); - resourcesMenu.addItem(new EMenuItem("Platforms", LinkManager.getHubPlatformsLink(),"types/Platform_up_16.png"));//, new LinkCommand("#fsdf")); + resourcesMenu + .addItem(new EMenuItem("Platforms", LinkManager.getHubPlatformsLink(), "types/Platform_up_16.png"));//, new LinkCommand("#fsdf")); resourcesMenu.addItem(new EMenuItem("Servers", LinkManager.getHubServerssLink(), "types/Server_up_16.png"));//, new LinkCommand("#fsdf")); resourcesMenu.addItem(new EMenuItem("Services", LinkManager.getHubServicesLink(), "types/Service_up_16.png"));//, new LinkCommand("#fsdf")); resourcesMenu.addItem(new MenuItemSeparator()); @@ -136,52 +135,46 @@ public class DropDownMenuBarView extends VLayout { groupsMenu.addItem(new EMenuItem("New Group", LinkManager.getHubNewGroupLink())); //, new LinkCommand("#sf")); groupsMenu.addItem(new EMenuItem("New Group Definition", LinkManager.getHubNewGroupDefLink())); //, new LinkCommand("#sf")); groupsMenu.addItem(new MenuItemSeparator()); -// groupsMenu.addItem(new MenuItem("Favorites")); //, new LinkCommand("#sf")); - + // groupsMenu.addItem(new MenuItem("Favorites")); //, new LinkCommand("#sf"));
Menu securityMenu = new Menu(); securityMenu.setTitle("Security"); - securityMenu.addItem(new EMenuItem("Users",LinkManager.getAdminUsersLink())); - securityMenu.addItem(new EMenuItem("Roles",LinkManager.getAdminRolesLink())); + securityMenu.addItem(new EMenuItem("Users", LinkManager.getAdminUsersLink())); + securityMenu.addItem(new EMenuItem("Roles", LinkManager.getAdminRolesLink())); MenuItem securitySubMenuItem = new MenuItem("Security"); securitySubMenuItem.setSubmenu(securityMenu);
- Menu sysConfigMenu = new Menu(); sysConfigMenu.setTitle("System Configuration"); - sysConfigMenu.addItem(new EMenuItem("Settings",LinkManager.getAdminSysConfigLink())); - sysConfigMenu.addItem(new EMenuItem("Plugins",LinkManager.getAdminPluginsLink())); - sysConfigMenu.addItem(new EMenuItem("Templates",LinkManager.getAdminTemplatesLink())); + sysConfigMenu.addItem(new EMenuItem("Settings", LinkManager.getAdminSysConfigLink())); + sysConfigMenu.addItem(new EMenuItem("Plugins", LinkManager.getAdminPluginsLink())); + sysConfigMenu.addItem(new EMenuItem("Templates", LinkManager.getAdminTemplatesLink())); MenuItem sysConfigSubMenuItem = new MenuItem("System Configuration"); sysConfigSubMenuItem.setSubmenu(sysConfigMenu);
- Menu contentMenu = new Menu(); contentMenu.setTitle("Content"); - contentMenu.addItem(new EMenuItem("Bundles","#Bundles")); - contentMenu.addItem(new EMenuItem("Content Providers",LinkManager.getAdminContentProvidersLink())); - contentMenu.addItem(new EMenuItem("Content Repositories",LinkManager.getAdminContentReposLink())); + contentMenu.addItem(new EMenuItem("Bundles", "#Bundles")); + contentMenu.addItem(new EMenuItem("Content Providers", LinkManager.getAdminContentProvidersLink())); + contentMenu.addItem(new EMenuItem("Content Repositories", LinkManager.getAdminContentReposLink())); MenuItem contentSubMenuItem = new MenuItem("Content"); contentSubMenuItem.setSubmenu(contentMenu);
- Menu haMenu = new Menu(); haMenu.setTitle("High Availability"); - haMenu.addItem(new EMenuItem("Servers",LinkManager.getHAServersLink())); - haMenu.addItem(new EMenuItem("Agents",LinkManager.getHAAgentsLink())); - haMenu.addItem(new EMenuItem("Affinity Groups",LinkManager.getHAAffinityGroupsLink())); - haMenu.addItem(new EMenuItem("Partition Events",LinkManager.getHAEventsLink())); + haMenu.addItem(new EMenuItem("Servers", LinkManager.getHAServersLink())); + haMenu.addItem(new EMenuItem("Agents", LinkManager.getHAAgentsLink())); + haMenu.addItem(new EMenuItem("Affinity Groups", LinkManager.getHAAffinityGroupsLink())); + haMenu.addItem(new EMenuItem("Partition Events", LinkManager.getHAEventsLink())); MenuItem haSubMentItem = new MenuItem("High Availability"); haSubMentItem.setSubmenu(haMenu);
- Menu reportsMenu = new Menu(); reportsMenu.setTitle("Reports"); reportsMenu.addItem(new EMenuItem("Resource Version Inventory Report", LinkManager.getReportsInventoryLink())); MenuItem reportsSubMenuItem = new MenuItem("Reports"); reportsSubMenuItem.setSubmenu(reportsMenu);
- Menu adminMenu = new Menu(); adminMenu.setTitle("Administration"); adminMenu.addItem(securitySubMenuItem); @@ -192,29 +185,22 @@ public class DropDownMenuBarView extends VLayout { adminMenu.addItem(new EMenuItem("Downloads", LinkManager.getAdminDownloadsLink())); adminMenu.addItem(new EMenuItem("License", LinkManager.getAdminLicenseLink()));
- - - - Menu helpMenu = new Menu(); helpMenu.setStyleName("menuBarMenuButton"); helpMenu.setTitle("Help"); helpMenu.addItem(new EMenuItem("Online Documentation", "http://www.rhq-project.org")); //, new LinkCommand("#sdfs")); helpMenu.addItem(new EMenuItem("Open a support case", "http://www.rhq-project.org")); //, new LinkCommand("#sdfs")); -// helpMenu.addItem(new MenuItem("About")); //, new LinkCommand("#sdfs")); + // helpMenu.addItem(new MenuItem("About")); //, new LinkCommand("#sdfs"));
menu.setMenus(overviewMenu, resourcesMenu, groupsMenu, adminMenu, helpMenu);
- topBar.addMember(menu);
- addMember(topBar); - addMember(new SearchBarPane()); + addMember(new SearchBarPane(this.extendLocatorId("Search")));
}
- public static class EMenuItem extends com.smartgwt.client.widgets.menu.MenuItem {
String link; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java index dc5503f..cd1b7d9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java @@ -25,16 +25,16 @@ import com.google.gwt.user.client.ui.Hyperlink; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.Img; import com.smartgwt.client.widgets.layout.LayoutSpacer; -import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.enterprise.gui.coregui.client.components.AboutModalWindow; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** * @author Greg Hinkle */ -public class MenuBarView extends VLayout { +public class MenuBarView extends LocatableVLayout {
private AboutModalWindow aboutModalWindow;
@@ -44,6 +44,10 @@ public class MenuBarView extends VLayout {
private HTMLFlow linksPane;
+ public MenuBarView(String locatorId) { + super(locatorId); + } + protected void onDraw() { super.onDraw();
@@ -119,7 +123,7 @@ public class MenuBarView extends VLayout { topStrip.addMember(links); */ addMember(topStrip); - addMember(new SearchBarPane()); + addMember(new SearchBarPane(this.extendLocatorId("Search")));
markForRedraw(); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java index 523dc41..81abe79 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java @@ -18,12 +18,15 @@ */ package org.rhq.enterprise.gui.coregui.client.menu;
-import com.google.gwt.core.client.GWT; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.AVAILABILITY; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.CATEGORY; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.DESCRIPTION; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.PLUGIN; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.TYPE; + import com.google.gwt.user.client.History; -import com.google.gwt.user.client.ui.TextBox; import com.smartgwt.client.types.Alignment; -import com.smartgwt.client.types.FormLayoutType; -import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.types.TextMatchStyle; import com.smartgwt.client.widgets.Window; import com.smartgwt.client.widgets.form.DynamicForm; @@ -36,35 +39,22 @@ import com.smartgwt.client.widgets.form.fields.SpacerItem; 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.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGridField; -import com.smartgwt.client.widgets.grid.ListGridRecord; -import com.smartgwt.client.widgets.layout.HLayout; -import com.smartgwt.client.widgets.menu.Menu; -import com.smartgwt.client.widgets.menu.MenuButton; -import com.smartgwt.client.widgets.menu.MenuItem; -import com.smartgwt.client.widgets.menu.MenuItemSeparator; - -import java.util.LinkedHashMap;
import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupsDataSource; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDatasource; - -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.AVAILABILITY; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.CATEGORY; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.DESCRIPTION; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.PLUGIN; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.TYPE; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** * @author Greg Hinkle */ -public class SearchBarPane extends HLayout { +public class SearchBarPane extends LocatableHLayout { + + public SearchBarPane(String locatorId) { + super(locatorId);
- public SearchBarPane() { - super(); setWidth100(); setHeight(28); } @@ -73,7 +63,7 @@ public class SearchBarPane extends HLayout { protected void onDraw() { super.onDraw();
- final DynamicForm form = new DynamicForm(); + final DynamicForm form = new LocatableDynamicForm(this.getLocatorId()); form.setNumCols(6); form.setColWidths("120", "140", "400");
@@ -103,7 +93,6 @@ public class SearchBarPane extends HLayout { addMember(form); }
- private ComboBoxItem getResourceComboBox() {
final ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); @@ -122,7 +111,8 @@ public class SearchBarPane extends HLayout { ListGridField availabilityField = new ListGridField(AVAILABILITY.propertyName(), AVAILABILITY.title(), 55); availabilityField.setAlign(Alignment.CENTER);
- comboBox.setPickListFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField, availabilityField); + comboBox.setPickListFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField, + availabilityField);
comboBox.setValueField("id"); comboBox.setDisplayField("name"); @@ -150,19 +140,16 @@ public class SearchBarPane extends HLayout { return comboBox; }
- private ComboBoxItem getGroupComboBox() { ComboBoxItem comboBox = new ComboBoxItem("query", "Query"); comboBox.setWidth(400); comboBox.setShowTitle(false);
- comboBox.setOptionDataSource(new ResourceGroupsDataSource()); ListGridField nameField = new ListGridField("name"); ListGridField descriptionField = new ListGridField("description"); comboBox.setPickListFields(nameField, descriptionField);
- comboBox.setValueField("id"); comboBox.setDisplayField("name"); comboBox.setPickListWidth(600);
commit 10e628a4d743cb0cfaa9bbd9c156c3e996570acf Merge: af0ed91... 8acb1fb... Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 09:20:13 2010 -0400
Merge branch 'master' into master-jay
commit af0ed9107e4e39ffd14ce345a166ccb466e690a7 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 09:16:50 2010 -0400
Added selenium hooks to MessageCenter
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java index 39364d8..7b6d850 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java @@ -46,7 +46,8 @@ import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIMenuButton; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
/** * @author Greg Hinkle @@ -66,7 +67,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter super.onDraw(); CoreGUI.getMessageCenter().addMessageListener(this);
- final Menu recentEventsMenu = new Menu(); + final Menu recentEventsMenu = new LocatableMenu(this.extendLocatorId("Messages"));
IMenuButton recentEventsButton = new LocatableIMenuButton(extendLocatorId("RecentEvents"), "Messages", recentEventsMenu); @@ -99,7 +100,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter } });
- VLayout vl = new LocatableVLayout(extendLocatorId("Alignment")); + VLayout vl = new VLayout(); vl.setAutoWidth(); vl.setAlign(Alignment.LEFT); vl.setAlign(VerticalAlignment.CENTER); @@ -136,7 +137,7 @@ public class MessageCenterView extends LocatableHLayout implements MessageCenter
form.setItems(title, severity, date, detail, okButton);
- final Window window = new Window(); + final Window window = new LocatableWindow(this.extendLocatorId("Message")); window.setTitle(message.title); window.setWidth(600); window.setHeight(400);
commit 354316f55b57cef67a424b58acfb475ff95ea27f Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Sep 15 09:16:30 2010 -0400
Added support for enabling or disabling our selenium locatorIds via the coreGui url. We now look for url param:
enableLocators=true|false
If true we enable the use of our explicit locatorIds to be used as selenium hooks. If false, or omitted, we run with default Ids and will not be selenium-ready.
To support this from the maven command line and our eclipse external tools config you can now specify the 'coreGuiParams' property. I've added a new eclipse ext tools config called 'Run GWT DevMode-JPDA-Params' that specifies -D$coreGuiParams=?enableLocators=true.
diff --git a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch new file mode 100644 index 0000000..9791adc --- /dev/null +++ b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<launchConfiguration type="org.eclipse.ui.externaltools.ProgramLaunchConfigurationType"> +<stringAttribute key="bad_container_name" value="\rhq\etc\eclipse-tools\maven"/> +<booleanAttribute key="org.eclipse.debug.core.appendEnvironmentVariables" value="true"/> +<listAttribute key="org.eclipse.debug.ui.favoriteGroups"> +<listEntry value="org.eclipse.ui.externaltools.launchGroup"/> +</listAttribute> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${env_var:M2_HOME}/bin/${MAVEN_EXE}"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams=?enableLocators=true"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/rhq/modules/enterprise/gui/coregui}"/> +</launchConfiguration> diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index 2d92aba..fd24857 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -235,7 +235,7 @@ <inplace>false</inplace> <!-- <logLevel>INFO' -bindAddress 0.0.0.0 -logLevel 'INFO</logLevel> --> <logLevel>INFO</logLevel> - <runTarget>http://localhost:7080/coregui/CoreGUI.html</runTarget> + <runTarget>http://localhost:7080/coregui/CoreGUI.html$%7BcoreGuiParams%7D</runTarget> <extraJvmArgs>${gwt-plugin.extraJvmArgs}</extraJvmArgs> <localWorkers>${gwt-plugin.localWorkers}</localWorkers> <draftCompile>true</draftCompile> 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 77cc196..34d1621 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 @@ -31,6 +31,7 @@ import com.google.gwt.http.client.URL; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; +import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.RootPanel; import com.smartgwt.client.core.KeyIdentifier; @@ -60,6 +61,7 @@ import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.WidgetUtility; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; import org.rhq.enterprise.gui.coregui.client.util.preferences.UserPreferences; +import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** * @author Greg Hinkle @@ -103,11 +105,17 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { private static ProductInfo productInfo;
public void onModuleLoad() { - if (GWT.getHostPageBaseURL().indexOf("/coregui/") == -1) { + String hostPageBaseURL = GWT.getHostPageBaseURL(); + if (hostPageBaseURL.indexOf("/coregui/") == -1) { System.out.println("Suppressing load of CoreGUI module"); return; // suppress loading this module if not using the new GWT app }
+ String enableLocators = Location.getParameter("enableLocators"); + if ((null != enableLocators) && Boolean.parseBoolean(enableLocators)) { + SeleniumUtility.setUseDefaultIds(false); + } + coreGUI = this;
if (!GWT.isScript()) { @@ -358,7 +366,7 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { String currentViewPath = History.getToken(); if (currentViewPath.equals(viewPath)) { // We're already there - just refresh the view. - refresh(); + refresh(); } else { if (viewPath.matches("(Resource|ResourceGroup)/[^/]*")) { // e.g. "Resource/10001" diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/SeleniumUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/SeleniumUtility.java index e4b60bc..223d0d6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/SeleniumUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/SeleniumUtility.java @@ -17,11 +17,15 @@ import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; */ public class SeleniumUtility {
- private static final boolean USE_DEFAULT_IDS = true; - /** A default id that is not ecommended as it will clash with any other element set to the default */ public static final String DEFAULT_ID = "DefaultID";
+ /** + * When true ignore any explicit locatorId assignment and use the standard + * ids generated by smartgwt. + */ + private static boolean useDefaultIds = true; + /** * A utility for assigning an ID to a smartgwt widget. Any current ID will be overwritten. The algorithm is: * <pre> @@ -30,7 +34,7 @@ public class SeleniumUtility { * @return the updated widget */ static public <T extends BaseWidget> T setID(final T widget, String locatorId) { - if (USE_DEFAULT_IDS) { + if (useDefaultIds) { return widget; }
@@ -84,7 +88,7 @@ public class SeleniumUtility { * @return the updated uiObject */ static public <T extends UIObject> T setHtmlId(final T uiObject, String unsafeId) { - if (USE_DEFAULT_IDS) { + if (useDefaultIds) { return uiObject; }
@@ -143,7 +147,7 @@ public class SeleniumUtility { }
static public boolean isUseDefaultIds() { - return USE_DEFAULT_IDS; + return useDefaultIds; }
/** @@ -157,4 +161,13 @@ public class SeleniumUtility { currentMember.destroy(); } } + + public static boolean getUseDefaultIds() { + return SeleniumUtility.useDefaultIds; + } + + public static void setUseDefaultIds(boolean useDefaultIds) { + SeleniumUtility.useDefaultIds = useDefaultIds; + } + }
commit 8acb1fb31579eeeaf3283af315183383eae53f01 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 08:05:25 2010 -0400
use locatable window to facilitate selenium testing
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java index 7b85eae..6a3c6f0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java @@ -43,6 +43,7 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.Table.SelectionEnablement; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
/** * @author John Mazzitelli @@ -92,7 +93,8 @@ public class ConditionsEditor extends LocatableVLayout { table.addTableAction(this.extendLocatorId("add"), "Add", SelectionEnablement.ALWAYS, null, new TableAction() { @Override public void executeAction(ListGridRecord[] selection) { - final Window winModal = new Window(); + final Window winModal = new LocatableWindow(ConditionsEditor.this + .extendLocatorId("newConditionEditorWindow")); winModal.setTitle("Add Condition"); winModal.setOverflow(Overflow.VISIBLE); winModal.setShowMinimizeButton(false);
commit 6efe82d30d878ec3eb3e9eb6947adbe7b0cfd932 Author: John Mazzitelli mazz@redhat.com Date: Wed Sep 15 07:58:48 2010 -0400
opps... don't use bit op, need AND logical op
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java index bd20b0a..fceb893 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java @@ -88,7 +88,7 @@ public class NewConditionEditor extends LocatableDynamicForm { this.okFunction = okFunc; this.resourceType = rtype;
- this.supportsEvents = (rtype.getEventDefinitions() != null & rtype.getEventDefinitions().size() > 0); + this.supportsEvents = (rtype.getEventDefinitions() != null && rtype.getEventDefinitions().size() > 0);
Set<MeasurementDefinition> metricDefinitions = rtype.getMetricDefinitions(); if (metricDefinitions != null && metricDefinitions.size() > 0) {
commit 0807155b735ae33c21b69df4758d7f031d4a28a0 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 14 20:11:07 2010 -0400
fix potential cast exception when sp[ecified metric collection interval is larger than Integer.MAX
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 9b68f39..c00175a 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 @@ -87,7 +87,7 @@ public abstract class AbstractMeasurementScheduleListView extends Table { return ""; }
- long milliseconds = (Integer) value; + long milliseconds = ((Number) value).longValue(); if (milliseconds == 0) { return "0"; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java index 78fe1d3..bef5806 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java @@ -37,7 +37,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
/** - * Widget for updating the collection intervals on the selected metrics. It displays two form fields for + * Widget for updating the collection intervals for the selected metrics. It displays two form fields for * entering the interval and the interval's units (seconds, minutes, or hours), as well as a Set button * for submitting the update. *
commit 2a60df38568690f9b2b6a555e212c3a6934ea011 Author: Ian Springer ian.springer@redhat.com Date: Tue Sep 14 20:08:22 2010 -0400
add support for lofs and tmpfs filesystems on Solaris (https://bugzilla.redhat.com/show_bug.cgi?id=553034)
diff --git a/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/FileSystemDiscoveryComponent.java b/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/FileSystemDiscoveryComponent.java index b7960c2..a12d556 100644 --- a/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/FileSystemDiscoveryComponent.java +++ b/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/FileSystemDiscoveryComponent.java @@ -1,6 +1,6 @@ /* * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. + * Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -22,7 +22,7 @@ */ package org.rhq.plugins.platform;
-import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Set;
import org.apache.commons.logging.Log; @@ -38,14 +38,16 @@ import org.rhq.core.system.SystemInfo;
/** * @author Greg Hinkle + * @author Ian Springer */ +@SuppressWarnings({"UnusedDeclaration"}) public class FileSystemDiscoveryComponent implements ResourceDiscoveryComponent<PlatformComponent> { private final Log log = LogFactory.getLog(this.getClass());
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws Exception {
- Set<DiscoveredResourceDetails> results = new HashSet<DiscoveredResourceDetails>(); + Set<DiscoveredResourceDetails> results = new LinkedHashSet<DiscoveredResourceDetails>();
SystemInfo sysInfo = discoveryContext.getSystemInformation(); if (!sysInfo.isNative()) { @@ -54,22 +56,30 @@ public class FileSystemDiscoveryComponent implements ResourceDiscoveryComponent< return results; }
- String hostname = discoveryContext.getSystemInformation().getHostname(); - - for (FileSystemInfo fs : sysInfo.getFileSystems()) { - int fsType = fs.getFileSystem().getType(); - if (fsType != FileSystem.TYPE_LOCAL_DISK && fsType != FileSystem.TYPE_NETWORK) { - continue; + for (FileSystemInfo fsInfo : sysInfo.getFileSystems()) { + FileSystem fs = fsInfo.getFileSystem(); + int fsType = fs.getType(); + // We only support local, network (nfs), lofs, or tmpfs filesystems - skip any other types. + switch (fsType) { + case FileSystem.TYPE_LOCAL_DISK: + case FileSystem.TYPE_NETWORK: + break; + default: + if (!(fs.getDevName().equals("lofs") || + fs.getDevName().equals("tmpfs"))) { + continue; + } } + Configuration pluginConfig = discoveryContext.getDefaultPluginConfiguration(); try { - String key = fs.getMountPoint(); + String key = fsInfo.getMountPoint(); DiscoveredResourceDetails details = new DiscoveredResourceDetails(discoveryContext.getResourceType(), - key, key, null, fs.getFileSystem().getDevName() + ": " - + fs.getFileSystem().getDirName(), pluginConfig, null); + key, key, null, fsInfo.getFileSystem().getDevName() + ": " + + fsInfo.getFileSystem().getDirName(), pluginConfig, null); results.add(details); } catch (Exception e) { - log.error("File system discovery failed: " + e + ", skipping."); + log.error("File system discovery failed for [" + fsInfo + "]: " + e); } } return results;
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 497f3d6b13ef46643d68a09bcd46adac121e1b3f Author: Joseph Marques joseph@redhat.com Date: Fri Aug 27 13:06:17 2010 -0400
remove unused private inner class
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 1925c37..583fe36 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 @@ -57,14 +57,8 @@ public class ResourceGroupComposite implements Serializable { @XmlTransient private ResourcePermission resourcePermission;
- private class GroupDefinitionMember extends ResourceGroup { - public void setGroupCategory(GroupCategory category) { - super.setGroupCategory(category); - } - } - //def no args constructor for JAXB - private ResourceGroupComposite() { + public ResourceGroupComposite() { }
public ResourceGroupComposite(Long explicitCount, Double explicitAvailability, Long implicitCount,
commit ad54a80ad2a1737a960111f226f97f92b984c561 Author: Joseph Marques joseph@redhat.com Date: Fri Aug 27 13:05:59 2010 -0400
add serialVersionUID to all objects in core/domain missing it
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/AbstractGroupConfigurationUpdate.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/AbstractGroupConfigurationUpdate.java index 7e2c87d..b3ac785 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/AbstractGroupConfigurationUpdate.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/AbstractGroupConfigurationUpdate.java @@ -45,6 +45,9 @@ import org.rhq.core.domain.resource.group.ResourceGroup; @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_CONFIG_GROUP_UPDATE_ID_SEQ") @Table(name = "RHQ_CONFIG_GROUP_UPDATE") public abstract class AbstractGroupConfigurationUpdate extends AbstractConfigurationUpdate implements Serializable { + + private static final long serialVersionUID = 1L; + @GeneratedValue(generator = "SEQ", strategy = GenerationType.AUTO) @Id private int id; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java index 2165b34..5b4aca1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java @@ -35,6 +35,8 @@ import org.rhq.core.domain.content.PackageDetailsKey; */ public class ResourcePackageDetails extends PackageDetails {
+ private static final long serialVersionUID = 1L; + /** * Values the plugin should use when installing this package. */ diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java index 0ff464a..6ef2ce6 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TaggedCriteria.java @@ -27,23 +27,27 @@ import org.rhq.core.domain.tagging.Tag; /** * @author Greg Hinkle */ +@SuppressWarnings("unused") public abstract class TaggedCriteria extends Criteria {
+ private static final long serialVersionUID = 1L; + private Tag filterTag;
private boolean fetchTags;
- protected TaggedCriteria() {
String entityName = getPersistentClass().getName(); - entityName = entityName.substring(entityName.lastIndexOf(".")+1); - - filterOverrides.put("tag", "id IN (SELECT taggedEntity.id FROM " + entityName + " taggedEntity JOIN taggedEntity.tags tag \n " + - " WHERE \n" + - " (tag.namespace LIKE :tagNamespace OR :tagNamespace IS NULL ) AND \n" + // first '?' will get ordinal 1 - " (tag.semantic LIKE :tagSemantic OR :tagSemantic IS NULL ) AND \n" + // second '?' will get ordinal 2 - " (tag.name LIKE :tagName OR :tagName IS NULL ) )"); // third '?' will get ordinal 3 + entityName = entityName.substring(entityName.lastIndexOf(".") + 1); + + filterOverrides.put("tag", "" // + + "id IN ( SELECT taggedEntity.id \n" // + + " FROM " + entityName + " taggedEntity \n" // + + " JOIN taggedEntity.tags tag \n " // + + " WHERE (tag.namespace LIKE :tagNamespace OR :tagNamespace IS NULL ) \n" // first '?' will get ordinal 1 + + " AND (tag.semantic LIKE :tagSemantic OR :tagSemantic IS NULL ) \n" // second '?' will get ordinal 2 + + " AND (tag.name LIKE :tagName OR :tagName IS NULL ) )"); // third '?' will get ordinal 3 }
public void addFilterTagNamespace(String filterTagNamespace) { @@ -71,12 +75,10 @@ public abstract class TaggedCriteria extends Criteria { this.filterTag = tag; }
- public boolean isTagFiltered() { return this.filterTag != null; }
- public void fetchTags(boolean fetchTags) { this.fetchTags = fetchTags; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/Dashboard.java b/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/Dashboard.java index 6e99c4b..95e920d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/Dashboard.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/Dashboard.java @@ -24,7 +24,6 @@ package org.rhq.core.domain.dashboard;
import java.io.Serializable; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; @@ -64,6 +63,8 @@ import org.rhq.core.domain.configuration.PropertySimple; @XmlRootElement public class Dashboard implements Serializable {
+ private static final long serialVersionUID = 1L; + @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "RHQ_DASHBOARD_ID_SEQ") @Id @@ -72,36 +73,27 @@ public class Dashboard implements Serializable { @Column(name = "NAME", nullable = false) private String name;
- @Column(name = "SHARED", nullable = false) private boolean shared = false;
- @JoinColumn(name = "CONFIGURATION_ID", referencedColumnName = "ID") @OneToOne(cascade = { CascadeType.ALL }) private Configuration configuration = new Configuration();
- - @JoinColumn(name = "SUBJECT_ID", nullable = false) @ManyToOne(fetch = FetchType.LAZY) private Subject owner;
- @OneToMany(mappedBy = "dashboard", fetch = FetchType.EAGER) - @Cascade( { org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN }) + @Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, + org.hibernate.annotations.CascadeType.DELETE_ORPHAN }) private Set<DashboardPortlet> portlets = new HashSet<DashboardPortlet>();
- - - public static final String CFG_COLUMNS = "columns"; public static final String CFG_WIDTHS = "widths"; public static final String CFG_BACKGROUND = "background"; public static final String CFG_REFRESH_RATE = "refresh";
- - public int getId() { return id; } @@ -180,8 +172,6 @@ public class Dashboard implements Serializable { return columnPortlets; }
- - public boolean removePortlet(DashboardPortlet storedPortlet) { return portlets.remove(storedPortlet); } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/DashboardPortlet.java b/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/DashboardPortlet.java index 38b455a..5562dbe 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/DashboardPortlet.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/DashboardPortlet.java @@ -51,6 +51,7 @@ import org.rhq.core.domain.configuration.Configuration; @XmlRootElement public class DashboardPortlet implements Serializable {
+ private static final long serialVersionUID = 1L;
@Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "RHQ_DASHBOARD_PORTLET_ID_SEQ") @@ -80,7 +81,6 @@ public class DashboardPortlet implements Serializable { @JoinColumn(name = "DASHBOARD_ID", nullable = false) private Dashboard dashboard;
- public DashboardPortlet() { }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationLastCompletedComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationLastCompletedComposite.java index 9552e31..e18df58 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationLastCompletedComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationLastCompletedComposite.java @@ -25,6 +25,9 @@ package org.rhq.core.domain.operation.composite; import org.rhq.core.domain.operation.OperationRequestStatus;
public class GroupOperationLastCompletedComposite extends OperationLastCompletedComposite { + + private static final long serialVersionUID = 1L; + private final int groupId; private final String groupName; private final String groupResourceTypeName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationScheduleComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationScheduleComposite.java index ee0f103..b5fba55 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationScheduleComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationScheduleComposite.java @@ -30,6 +30,9 @@ import org.rhq.core.domain.operation.ScheduleJobId; * @author John Mazzitelli */ public class GroupOperationScheduleComposite extends OperationScheduleComposite { + + private static final long serialVersionUID = 1L; + private final int groupId; private final String groupName; private final String groupResourceTypeName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationLastCompletedComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationLastCompletedComposite.java index 5add81b..0b8bfbd 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationLastCompletedComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationLastCompletedComposite.java @@ -25,6 +25,9 @@ package org.rhq.core.domain.operation.composite; import org.rhq.core.domain.operation.OperationRequestStatus;
public class ResourceOperationLastCompletedComposite extends OperationLastCompletedComposite { + + private static final long serialVersionUID = 1L; + private int resourceId; private String resourceName; private String resourceTypeName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationScheduleComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationScheduleComposite.java index 4185035..a0996a7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationScheduleComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationScheduleComposite.java @@ -25,6 +25,9 @@ package org.rhq.core.domain.operation.composite; import org.rhq.core.domain.operation.ScheduleJobId;
public class ResourceOperationScheduleComposite extends OperationScheduleComposite { + + private static final long serialVersionUID = 1L; + private int resourceId; private String resourceName; private String resourceTypeName; 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 0d568d4..1e2af92 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 @@ -68,7 +68,9 @@ import org.rhq.core.domain.content.InstalledPackage; @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_CREATE_RES_HIST_ID_SEQ") @Table(name = "RHQ_CREATE_RES_HIST") public class CreateResourceHistory implements Serializable { + // Constants -------------------------------------------- + private static final long serialVersionUID = 1L;
public static final String QUERY_FIND_WITH_STATUS = "CreateResourceHistory.findWithStatus"; public static final String QUERY_FIND_BY_PARENT_RESOURCE_ID = "CreateResourceHistory.findByParentResourceId"; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventorySummary.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventorySummary.java index decafe2..375c79d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventorySummary.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventorySummary.java @@ -30,6 +30,9 @@ import java.io.Serializable; * @author Ian Springer */ public class InventorySummary implements Serializable { + + private static final long serialVersionUID = 1L; + private int platformCount; private int serverCount; private int serviceCount; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceAvailabilitySummary.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceAvailabilitySummary.java index b31fb5b..2770b70 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceAvailabilitySummary.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceAvailabilitySummary.java @@ -30,6 +30,8 @@ import org.rhq.core.domain.measurement.AvailabilityType; */ public class ResourceAvailabilitySummary implements Serializable {
+ private static final long serialVersionUID = 1L; + long upTime; long downTime; int failures; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceIdFlyWeight.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceIdFlyWeight.java index bf2c7ca..c3fef6c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceIdFlyWeight.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceIdFlyWeight.java @@ -26,6 +26,8 @@ import org.rhq.core.domain.resource.Resource;
public class ResourceIdFlyWeight extends Resource {
+ private static final long serialVersionUID = 1L; + public ResourceIdFlyWeight(int id, String uuid) { super(id); setUuid(uuid); diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceInstallCount.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceInstallCount.java index 5878192..5c0f0e7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceInstallCount.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceInstallCount.java @@ -18,15 +18,17 @@ */ package org.rhq.core.domain.resource.composite;
-import org.rhq.core.domain.resource.ResourceCategory; - import java.io.Serializable;
+import org.rhq.core.domain.resource.ResourceCategory; + /** * @author Greg Hinkle */ public class ResourceInstallCount implements Serializable {
+ private static final long serialVersionUID = 1L; + private long count; private String typeName; private String typePlugin; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ClusterKey.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ClusterKey.java index f57608d..5b7a9a6 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ClusterKey.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ClusterKey.java @@ -22,7 +22,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List;
- /** * A ClusterKey represents an AutoCluster of resources in a Cluster Hierarchy. Given the key it is * possible to determine specific membership of the AutoCluster at any time. It represents the Cluster @@ -47,7 +46,6 @@ public class ClusterKey implements Serializable {
private static final long serialVersionUID = 1L;
- static final String DELIM = ":"; static final String DELIM_NODE = "::";
@@ -57,7 +55,6 @@ public class ClusterKey implements Serializable { private String key = null; private String namedKey = null;
- public ClusterKey() { }
@@ -80,12 +77,10 @@ public class ClusterKey implements Serializable {
this.clusterGroupId = parentKey.getClusterGroupId(); this.hierarchy = new ArrayList<ClusterKey.Node>(rootClusterNodes); //.size() + 1); -// Collections.copy(this.hierarchy, rootClusterNodes); + // Collections.copy(this.hierarchy, rootClusterNodes); this.hierarchy.add(new ClusterKey.Node(childResourceTypeId, childResourceKey)); }
- - public int getClusterGroupId() { return clusterGroupId; } @@ -146,7 +141,6 @@ public class ClusterKey implements Serializable { return getKey(); }
- public static ClusterKey valueOf(String clusterKey) { ClusterKey result = null;
@@ -182,15 +176,17 @@ public class ClusterKey implements Serializable { return nodes.get(nodes.size() - 1).getResourceTypeId(); }
- @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClusterKey)) return false; + if (this == o) + return true; + if (!(o instanceof ClusterKey)) + return false;
ClusterKey that = (ClusterKey) o;
- if (!getKey().equals(that.getKey())) return false; + if (!getKey().equals(that.getKey())) + return false;
return true; } @@ -237,8 +233,9 @@ public class ClusterKey implements Serializable { }
private String encode(String info) { - return info.replace(":","%3a"); + return info.replace(":", "%3a"); } + private String decode(String code) { return code.replace("%3a", ":"); } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterFlyweight.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterFlyweight.java index a156804..5e2e207 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterFlyweight.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterFlyweight.java @@ -25,13 +25,13 @@ package org.rhq.core.domain.resource.group.composite; import java.io.Serializable; import java.util.List;
-import org.rhq.core.domain.resource.group.ClusterKey; - /** * @author Greg Hinkle */ public class ClusterFlyweight implements Serializable {
+ private static final long serialVersionUID = 1L; + private int groupId;
private ClusterKeyFlyweight clusterKey; @@ -89,11 +89,4 @@ public class ClusterFlyweight implements Serializable { return children; }
- - - - - - - } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterKeyFlyweight.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterKeyFlyweight.java index e546614..7ed08db 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterKeyFlyweight.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ClusterKeyFlyweight.java @@ -29,6 +29,8 @@ import java.io.Serializable; */ public class ClusterKeyFlyweight implements Serializable {
+ private static final long serialVersionUID = 1L; + private int resourceTypeId; private String resourceKey;
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/tagging/compsite/TagReportComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/tagging/compsite/TagReportComposite.java index 1804daa..57084e2 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/tagging/compsite/TagReportComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/tagging/compsite/TagReportComposite.java @@ -29,17 +29,25 @@ import org.rhq.core.domain.tagging.Tag; */ public class TagReportComposite extends Tag {
+ private static final long serialVersionUID = 1L; + private Tag tag; - private long total, resourceCount, resourceGroupCount, bundleCount, bundleVersionCount, bundleDeploymentCount, bundleDestinationCount; + private long total; + private long resourceCount; + private long resourceGroupCount; + private long bundleCount; + private long bundleVersionCount; + private long bundleDeploymentCount; + private long bundleDestinationCount;
public TagReportComposite() { }
- public TagReportComposite(int id, String namespace, String semantic, String name, - long total, - long resourceCount, long resourceGroupCount, long bundleCount, long bundleVersionCount, long bundleDeploymentCount, long bundleDestinationCount) { - tag = new Tag(namespace, semantic, name); - tag.setId(id); + public TagReportComposite(int id, String namespace, String semantic, String name, long total, long resourceCount, + long resourceGroupCount, long bundleCount, long bundleVersionCount, long bundleDeploymentCount, + long bundleDestinationCount) { + this.tag = new Tag(namespace, semantic, name); + this.tag.setId(id); this.total = total; this.resourceCount = resourceCount; this.resourceGroupCount = resourceGroupCount; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/UnlimitedPageControl.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/UnlimitedPageControl.java index cd6874f..b26aead 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/UnlimitedPageControl.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/UnlimitedPageControl.java @@ -7,6 +7,9 @@ package org.rhq.core.domain.util; * @author Ian Springer */ public class UnlimitedPageControl extends PageControl { + + private static final long serialVersionUID = 1L; + public UnlimitedPageControl() { this(new OrderingField[0]); } @@ -22,7 +25,8 @@ public class UnlimitedPageControl extends PageControl {
@Override public void setPageSize(int pageSize) { - throw new UnsupportedOperationException("page size cannot be changed from " + SIZE_UNLIMITED + " for an UnlimitedPageControl."); + throw new UnsupportedOperationException("page size cannot be changed from " + SIZE_UNLIMITED + + " for an UnlimitedPageControl."); }
@Override @@ -30,5 +34,4 @@ public class UnlimitedPageControl extends PageControl { getOrderingFields().clear(); }
- }
commit 583812edd609d72048b452ef01df9bf1de65e20e Author: Joseph Marques joseph@redhat.com Date: Fri Aug 27 13:00:21 2010 -0400
remove unused deprecated methods
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 03dd41b..3237c49 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 @@ -49,7 +49,11 @@ public class RoleCriteria extends Criteria { private PageOrdering sortName;
public RoleCriteria() { - filterOverrides.put("subjectId", "id in (select sr.id from Role sr JOIN sr.subjects s where s.id = :id)"); + filterOverrides.put("subjectId", "" // + + "id IN ( SELECT innerRole.id " // + + " FROM Role innerRole " // + + " JOIN innerRole.subjects innerSubject " // + + " WHERE innerSubject.id = ? )"); }
@Override @@ -106,81 +110,4 @@ public class RoleCriteria extends Criteria { public boolean isSecurityManagerRequired() { return (this.fetchSubjects || this.fetchResourceGroups); } - - /** - * @Deprecated use addFilterId - */ - @Deprecated - public void setFilterId(Integer filterId) { - this.filterId = filterId; - } - - /** - * @Deprecated use addFilterName - */ - @Deprecated - public void setFilterName(String filterName) { - this.filterName = filterName; - } - - /** - * @Deprecated use addFilterDescription - */ - @Deprecated - public void setFilterDescription(String filterDescription) { - this.filterDescription = filterDescription; - } - - @Deprecated - public Integer getFilterId() { - return this.filterId; - } - - @Deprecated - public boolean getFetchSubjects() { - return this.fetchSubjects; - } - - /** - * Requires MANAGE_SECURITY - * @param fetchSubjects - * @Deprecated use fetchSubjects - */ - @Deprecated - public void setFetchSubjects(boolean fetchSubjects) { - this.fetchSubjects = fetchSubjects; - } - - /** - * @Deprecated use fetchResourceGroups - */ - @Deprecated - public void setFetchResourceGroups(boolean fetchResourceGroups) { - this.fetchResourceGroups = fetchResourceGroups; - } - - /** - * @Deprecated use fetchPermissions - */ - @Deprecated - public void setFetchPermissions(boolean fetchPermissions) { - this.fetchPermissions = fetchPermissions; - } - - /** - * @Deprecated use fetchRoleNotifications - */ - @Deprecated - public void setFetchRoleNotifications(boolean fetchRoleNotifications) { - this.fetchRoleNotifications = fetchRoleNotifications; - } - - /** - * @Deprecated use addSortName - */ - @Deprecated - public void setSortName(PageOrdering sortName) { - addSortField("name"); - this.sortName = sortName; - } }
commit 1f6af685b55276fb7568abd334300de9b15ada32 Author: Joseph Marques joseph@redhat.com Date: Fri Aug 27 12:59:52 2010 -0400
add the ability to filter SubjectCriteria by roleId
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 e6e1780..4e9418c 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 @@ -45,6 +45,7 @@ public class SubjectCriteria extends Criteria { private String filterPhoneNumber; private String filterDepartment; private Boolean filterFactive; + private Integer filterRoleId;
private boolean fetchConfiguration; private boolean fetchRoles; @@ -58,6 +59,11 @@ public class SubjectCriteria extends Criteria { private PageOrdering sortDepartment;
public SubjectCriteria() { + filterOverrides.put("roleId", "" // + + "id IN ( SELECT innerSubject.id " // + + " FROM Subject innerSubject " // + + " JOIN innerSubject.roles innerRole " // + + " WHERE innerRole.id = ? )"); }
@Override @@ -101,6 +107,10 @@ public class SubjectCriteria extends Criteria { this.filterFactive = filterFactive; }
+ public void addFilterRoleId(Integer filterRoleId) { + this.filterRoleId = filterRoleId; + } + public void fetchConfiguration(boolean fetchConfiguration) { this.fetchConfiguration = fetchConfiguration; }
commit e92400fbdfb51149eb3444580c80d3113a13a0f6 Author: Joseph Marques joseph@redhat.com Date: Fri Aug 27 12:59:35 2010 -0400
get use of generics for getPersisttentClass method on Criteria classes
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertCriteria.java index a605adf..9470937 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertCriteria.java @@ -29,8 +29,8 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;
-import org.rhq.core.domain.alert.AlertPriority; import org.rhq.core.domain.alert.Alert; +import org.rhq.core.domain.alert.AlertPriority; import org.rhq.core.domain.util.PageOrdering;
/** @@ -100,7 +100,7 @@ public class AlertCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<Alert> getPersistentClass() { return Alert.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertDefinitionCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertDefinitionCriteria.java index 298a6e5..5c84c62 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertDefinitionCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AlertDefinitionCriteria.java @@ -71,7 +71,7 @@ public class AlertDefinitionCriteria extends Criteria { }
@Override - public Class<?> getPersistentClass() { + public Class<AlertDefinition> getPersistentClass() { return AlertDefinition.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleCriteria.java index e52333f..35c9367 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleCriteria.java @@ -71,7 +71,7 @@ public class BundleCriteria extends TaggedCriteria { }
@Override - public Class<?> getPersistentClass() { + public Class<Bundle> getPersistentClass() { return Bundle.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDeploymentCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDeploymentCriteria.java index 66d85c2..9e613c6 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDeploymentCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDeploymentCriteria.java @@ -60,7 +60,7 @@ public class BundleDeploymentCriteria extends TaggedCriteria { }
@Override - public Class<?> getPersistentClass() { + public Class<BundleDeployment> getPersistentClass() { return BundleDeployment.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDestinationCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDestinationCriteria.java index 62a42f8..dcd99d8 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDestinationCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleDestinationCriteria.java @@ -23,7 +23,6 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;
-import org.rhq.core.domain.bundle.BundleDeployment; import org.rhq.core.domain.bundle.BundleDeploymentStatus; import org.rhq.core.domain.bundle.BundleDestination;
@@ -45,22 +44,19 @@ public class BundleDestinationCriteria extends TaggedCriteria { private String filterDeployDir; private Integer filterGroupId; // needs override
- private boolean fetchBundle; private boolean fetchDeployments; private boolean fetchGroup;
public BundleDestinationCriteria() { - filterOverrides.put("bundleId", "bundle.id = ?"); filterOverrides.put("bundleVersionId", "deployments.bundleVersion.id = ?"); filterOverrides.put("status", "deployment.status like ?"); filterOverrides.put("groupId", "group.id = ?"); - }
@Override - public Class<?> getPersistentClass() { + public Class<BundleDestination> getPersistentClass() { return BundleDestination.class; }
@@ -84,12 +80,10 @@ public class BundleDestinationCriteria extends TaggedCriteria { this.filterDescription = filterDescription; }
- public void addFilterBundleVersionId(Integer filterBundleVersionId) { this.filterBundleVersionId = filterBundleVersionId; }
- public void addFilterGroupId(Integer filterGroupId) { this.filterGroupId = filterGroupId; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleFileCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleFileCriteria.java index 130b2b6..26f2b3e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleFileCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleFileCriteria.java @@ -42,8 +42,6 @@ public class BundleFileCriteria extends Criteria { private boolean fetchPackageVersion;
public BundleFileCriteria() { - super(); - filterOverrides.put("bundleVersionId", "bundleVersion.id = ?"); filterOverrides.put("packageVersionId", "packageVersion.id = ?"); } 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 4e38e46..98f77c1 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 @@ -53,7 +53,7 @@ public class BundleResourceDeploymentCriteria extends Criteria { }
@Override - public Class<?> getPersistentClass() { + public Class<BundleResourceDeployment> getPersistentClass() { return BundleResourceDeployment.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleVersionCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleVersionCriteria.java index c4240b4..bf8b885 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleVersionCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleVersionCriteria.java @@ -52,7 +52,7 @@ public class BundleVersionCriteria extends TaggedCriteria { }
@Override - public Class<?> getPersistentClass() { + public Class<BundleVersion> getPersistentClass() { return BundleVersion.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/CallTimeDataCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/CallTimeDataCriteria.java index 8156d9a..8d0116e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/CallTimeDataCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/CallTimeDataCriteria.java @@ -59,7 +59,7 @@ public class CallTimeDataCriteria extends Criteria { private PageOrdering sortCount; // requires overrides
@Override - public Class<?> getPersistentClass() { + public Class<CallTimeDataValue> getPersistentClass() { return CallTimeDataValue.class; }
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 d4e3fcb..4ad0376 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 @@ -64,7 +64,6 @@ public abstract class Criteria implements Serializable { private String searchExpression;
public Criteria() { - this.filterOverrides = new HashMap<String, String>(); this.sortOverrides = new HashMap<String, String>();
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/EventCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/EventCriteria.java index f4db72d..9aa52fd 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/EventCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/EventCriteria.java @@ -83,7 +83,7 @@ public class EventCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<Event> getPersistentClass() { return Event.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GroupOperationHistoryCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GroupOperationHistoryCriteria.java index e3fb715..1e5c91a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GroupOperationHistoryCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GroupOperationHistoryCriteria.java @@ -44,7 +44,7 @@ public class GroupOperationHistoryCriteria extends OperationHistoryCriteria { }
@Override - public Class getPersistentClass() { + public Class<GroupOperationHistory> getPersistentClass() { return GroupOperationHistory.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/InstalledPackageCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/InstalledPackageCriteria.java index 34fb9f9..bf9ba40 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/InstalledPackageCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/InstalledPackageCriteria.java @@ -3,8 +3,8 @@ package org.rhq.core.domain.criteria; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
-import org.rhq.core.domain.util.PageOrdering; import org.rhq.core.domain.content.InstalledPackage; +import org.rhq.core.domain.util.PageOrdering;
@XmlAccessorType(XmlAccessType.FIELD) @SuppressWarnings("unused") @@ -33,7 +33,7 @@ public class InstalledPackageCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<InstalledPackage> getPersistentClass() { return InstalledPackage.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDataTraitCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDataTraitCriteria.java index 2f13722..10cdcea 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDataTraitCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDataTraitCriteria.java @@ -22,12 +22,12 @@ */ package org.rhq.core.domain.criteria;
-import org.rhq.core.domain.measurement.MeasurementDataTrait; -import org.rhq.core.domain.util.PageOrdering; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
+import org.rhq.core.domain.measurement.MeasurementDataTrait; +import org.rhq.core.domain.util.PageOrdering; + /** * RHQ {@link Criteria} object for filtered, sortable queries of {@link MeasurementDataTrait trait} data sets. * @@ -85,7 +85,7 @@ public class MeasurementDataTraitCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<MeasurementDataTrait> getPersistentClass() { return MeasurementDataTrait.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDefinitionCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDefinitionCriteria.java index 2ce0f65..779e4c5 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDefinitionCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementDefinitionCriteria.java @@ -28,9 +28,9 @@ import javax.xml.bind.annotation.XmlAccessorType; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.DisplayType; import org.rhq.core.domain.measurement.MeasurementCategory; +import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.measurement.MeasurementUnits; import org.rhq.core.domain.measurement.NumericType; -import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.util.PageOrdering;
/** @@ -74,7 +74,7 @@ public class MeasurementDefinitionCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<MeasurementDefinition> getPersistentClass() { return MeasurementDefinition.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementScheduleCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementScheduleCriteria.java index a4c8a09..3a2b130 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementScheduleCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/MeasurementScheduleCriteria.java @@ -100,7 +100,7 @@ public class MeasurementScheduleCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<MeasurementSchedule> getPersistentClass() { return MeasurementSchedule.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationDefinitionCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationDefinitionCriteria.java index d66d118..854a561 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationDefinitionCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationDefinitionCriteria.java @@ -28,8 +28,8 @@ import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
-import org.rhq.core.domain.util.PageOrdering; import org.rhq.core.domain.operation.OperationDefinition; +import org.rhq.core.domain.util.PageOrdering;
/** * @author Joseph Marques @@ -72,7 +72,7 @@ public class OperationDefinitionCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<OperationDefinition> getPersistentClass() { return OperationDefinition.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationHistoryCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationHistoryCriteria.java index f54de21..5f879ea 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationHistoryCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/OperationHistoryCriteria.java @@ -26,9 +26,8 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
import org.rhq.core.domain.operation.JobId; -import org.rhq.core.domain.operation.OperationRequestStatus; import org.rhq.core.domain.operation.OperationHistory; -import org.rhq.core.domain.operation.ResourceOperationHistory; +import org.rhq.core.domain.operation.OperationRequestStatus; import org.rhq.core.domain.util.PageOrdering;
/** @@ -58,30 +57,26 @@ public abstract class OperationHistoryCriteria extends Criteria { private PageOrdering sortOperationName; // requires override
public OperationHistoryCriteria() { - init(); - } - - @Override - public Class getPersistentClass() { - return ResourceOperationHistory.class; - } - - private void init() { filterOverrides.put("operationDefinitionId", "operationDefinition.id = ?"); filterOverrides.put("operationName", "operationDefinition.name like ?"); filterOverrides.put("startTime", "startedTime >= ?"); filterOverrides.put("endTime", "modifiedTime <= ?");
filterOverrides.put("resourceIds", "id IN " // - + " ( SELECT roh.id " // - + " FROM ResourceOperationHistory roh " // - + " WHERE roh.resource.id IN ( ? ) ) "); + + " ( SELECT roh.id " // + + " FROM ResourceOperationHistory roh " // + + " WHERE roh.resource.id IN ( ? ) ) ");
sortOverrides.put("startTime", "startedTime"); sortOverrides.put("endTime", "modifiedTime"); sortOverrides.put("operationName", "operationDefinition.name"); }
+ @Override + public Class<? extends OperationHistory> getPersistentClass() { + return OperationHistory.class; + } + public void addFilterId(Integer filterId) { this.filterId = filterId; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/PackageVersionCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/PackageVersionCriteria.java index 3e304b6..592cea1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/PackageVersionCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/PackageVersionCriteria.java @@ -51,7 +51,7 @@ public class PackageVersionCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<PackageVersion> getPersistentClass() { return PackageVersion.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RepoCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RepoCriteria.java index 42e2ec8..60d23da 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RepoCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RepoCriteria.java @@ -56,14 +56,15 @@ public class RepoCriteria extends Criteria {
public RepoCriteria() { filterOverrides.put("resourceIds", "resourceRepos.resource.id IN ( ? )"); - filterOverrides.put("contentSourceIds", - "id IN (SELECT innerRepo FROM Repo innerRepo " + - "JOIN innerRepo.repoContentSources rcs " + - "WHERE rcs.contentSource.id IN ( ? ))"); + filterOverrides.put("contentSourceIds", "" // + + "id IN ( SELECT innerRepo " // + + " FROM Repo innerRepo " // + + " JOIN innerRepo.repoContentSources rcs " // + + " WHERE rcs.contentSource.id IN ( ? ))"); }
@Override - public Class getPersistentClass() { + public Class<Repo> getPersistentClass() { return Repo.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java index 3ccab5d..adf2cbd 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java @@ -84,7 +84,7 @@ public class ResourceConfigurationUpdateCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<ResourceConfigurationUpdate> getPersistentClass() { return ResourceConfigurationUpdate.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java index a332b77..1eae4a3 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java @@ -125,8 +125,7 @@ public class ResourceCriteria extends TaggedCriteria { + " FROM Resource ires " // + " JOIN ires.implicitGroups implicitGroup " // + " WHERE implicitGroup.id IN ( ? ) )"); - filterOverrides.put("rootResourceId", - "agent.id = (SELECT r2.agent.id FROM Resource r2 where r2.id = ?)"); + filterOverrides.put("rootResourceId", "agent.id = (SELECT r2.agent.id FROM Resource r2 where r2.id = ?)");
sortOverrides.put("resourceTypeName", "resourceType.name"); sortOverrides.put("resourceCategory", "resourceType.category"); @@ -137,7 +136,7 @@ public class ResourceCriteria extends TaggedCriteria { }
@Override - public Class getPersistentClass() { + public Class<Resource> getPersistentClass() { return Resource.class; }
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 7544422..1a54f0f 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 @@ -115,7 +115,7 @@ public class ResourceGroupCriteria extends TaggedCriteria { }
@Override - public Class getPersistentClass() { + public Class<ResourceGroup> getPersistentClass() { return ResourceGroup.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupDefinitionCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupDefinitionCriteria.java index 96925fb..356dabc 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupDefinitionCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupDefinitionCriteria.java @@ -22,12 +22,12 @@ */ package org.rhq.core.domain.criteria;
-import org.rhq.core.domain.resource.group.GroupDefinition; -import org.rhq.core.domain.util.PageOrdering; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
+import org.rhq.core.domain.resource.group.GroupDefinition; +import org.rhq.core.domain.util.PageOrdering; + /** * @author Greg Hinkle */ @@ -36,7 +36,6 @@ import javax.xml.bind.annotation.XmlAccessorType; public class ResourceGroupDefinitionCriteria extends Criteria { private static final long serialVersionUID = 1L;
- private Integer filterId; private String filterName; private String filterDescription; @@ -50,13 +49,12 @@ public class ResourceGroupDefinitionCriteria extends Criteria { private PageOrdering sortRecursive; private PageOrdering sortExpression;
- public ResourceGroupDefinitionCriteria() {
}
@Override - public Class getPersistentClass() { + public Class<GroupDefinition> getPersistentClass() { return GroupDefinition.class; }
@@ -80,12 +78,10 @@ public class ResourceGroupDefinitionCriteria extends Criteria { this.filterExpression = filterExpression; }
- public void fetchManagedResourceGroups(boolean fetchManagedResourceGroups) { this.fetchManagedResourceGroups = fetchManagedResourceGroups; }
- public void addSortName(PageOrdering sortName) { addSortField("name"); this.sortName = sortName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceOperationHistoryCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceOperationHistoryCriteria.java index e1ab4c4..8e58e69 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceOperationHistoryCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceOperationHistoryCriteria.java @@ -22,8 +22,6 @@ */ package org.rhq.core.domain.criteria;
-import org.rhq.core.domain.operation.ResourceOperationHistory; - import java.util.Arrays; import java.util.List;
@@ -31,6 +29,8 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;
+import org.rhq.core.domain.operation.ResourceOperationHistory; + /** * @author Joseph Marques */ @@ -49,7 +49,7 @@ public class ResourceOperationHistoryCriteria extends OperationHistoryCriteria { }
@Override - public Class getPersistentClass() { + public Class<ResourceOperationHistory> getPersistentClass() { return ResourceOperationHistory.class; }
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 ba5f05e..93ba523 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 @@ -83,7 +83,7 @@ public class ResourceTypeCriteria extends Criteria { }
@Override - public Class<?> getPersistentClass() { + public Class<ResourceType> getPersistentClass() { return ResourceType.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SavedSearchCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SavedSearchCriteria.java index a810df1..634dc15 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SavedSearchCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SavedSearchCriteria.java @@ -65,7 +65,7 @@ public class SavedSearchCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<SavedSearch> getPersistentClass() { return SavedSearch.class; }
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 7c39c50..e6e1780 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 @@ -61,7 +61,7 @@ public class SubjectCriteria extends Criteria { }
@Override - public Class getPersistentClass() { + public Class<Subject> getPersistentClass() { return Subject.class; }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TagCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TagCriteria.java index 2c93450..3e60bd0 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TagCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/TagCriteria.java @@ -46,13 +46,11 @@ public class TagCriteria extends Criteria { private PageOrdering sortSemantic; private PageOrdering sortName;
- @Override - public Class<?> getPersistentClass() { + public Class<Tag> getPersistentClass() { return Tag.class; }
- public void addFilterNamespace(String filterNamespace) { this.filterNamespace = filterNamespace; } @@ -65,7 +63,6 @@ public class TagCriteria extends Criteria { this.filterName = filterName; }
- public void addSortNamespace(PageOrdering sortNamespace) { addSortField("namespace"); this.sortNamespace = sortNamespace; @@ -81,6 +78,4 @@ public class TagCriteria extends Criteria { this.sortName = sortName; }
- - }
commit d139f3b79e62d87253e2ff846c1bde0a5b47afa7 Author: Joseph Marques joseph@redhat.com Date: Fri Aug 27 12:57:02 2010 -0400
cosmetic
* remove sections headers, e.g. constants/attributes/constructor/public * remove unused imports * reorder import statements
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/Advisory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/Advisory.java index 26291fb..e50214b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/Advisory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/Advisory.java @@ -19,7 +19,7 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table;
@Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = Advisory.QUERY_FIND_ALL, query = "SELECT adv FROM Advisory adv"), @NamedQuery(name = Advisory.QUERY_FIND_BY_ADV, query = "SELECT adv " + " FROM Advisory adv " + " WHERE adv.advisory = :advisory "), @@ -44,12 +44,12 @@ import javax.persistence.Table; public class Advisory implements Serializable {
private static final long serialVersionUID = 1L; + public static final String QUERY_FIND_ALL = "Advisory.findAll"; public static final String QUERY_FIND_BY_ADV = "Advisory.findByAdv"; public static final String QUERY_DELETE_BY_ADV_ID = "Advisory.deleteByAdvId"; public static final String QUERY_FIND_COMPOSITE_BY_ID = "Advisory.queryFindCompositeByAdvId"; public static final String QUERY_FIND_BY_ADV_ID = "Advisory.queryFindByAdvId"; - // Attributes --------------------------------------------
@Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @@ -101,8 +101,6 @@ public class Advisory implements Serializable { @OneToMany(mappedBy = "advisory", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<AdvisoryBuglist> advisorybugs;
- // Constructor ---------------------------------------- - public Advisory() { }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/Architecture.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/Architecture.java index 40c2c36..f47ec44 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/Architecture.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/Architecture.java @@ -43,15 +43,13 @@ import org.rhq.core.domain.resource.Resource; * @author Jason Dobies */ @Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = Architecture.QUERY_FIND_BY_NAME, query = "SELECT arch FROM Architecture arch WHERE arch.name = :name"), @NamedQuery(name = Architecture.QUERY_FIND_ALL, query = "SELECT arch FROM Architecture arch"), - @NamedQuery(name = Architecture.QUERY_DYNAMIC_CONFIG_VALUES, query = "SELECT arch.name, arch.name FROM Architecture arch") -}) + @NamedQuery(name = Architecture.QUERY_DYNAMIC_CONFIG_VALUES, query = "SELECT arch.name, arch.name FROM Architecture arch") }) @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_ARCHITECTURE_ID_SEQ") @Table(name = "RHQ_ARCHITECTURE") public class Architecture implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
@@ -60,8 +58,6 @@ public class Architecture implements Serializable {
public static final String QUERY_DYNAMIC_CONFIG_VALUES = "Architecture.dynamicConfigValues";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -70,8 +66,6 @@ public class Architecture implements Serializable { @Column(name = "NAME", nullable = false) private String name;
- // Constructor ---------------------------------------- - public Architecture() { // for JPA use } @@ -80,8 +74,6 @@ public class Architecture implements Serializable { setName(name); }
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/CVE.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/CVE.java index 72b0011..696796c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/CVE.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/CVE.java @@ -40,7 +40,7 @@ import javax.persistence.Table; */
@Entity -@NamedQueries( { @NamedQuery(name = CVE.DELETE_BY_CVE_ID, query = "DELETE CVE cve WHERE cve.id = :cveId"), +@NamedQueries({ @NamedQuery(name = CVE.DELETE_BY_CVE_ID, query = "DELETE CVE cve WHERE cve.id = :cveId"), @NamedQuery(name = CVE.FIND_BY_CVE_ID, query = "SELECT cve FROM CVE as cve WHERE cve.id = :cveId") }) @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_CVE_ID_SEQ") @Table(name = "RHQ_CVE") @@ -50,8 +50,6 @@ public class CVE implements Serializable { public static final String FIND_BY_CVE_ID = "CVE.findByCVEId"; public static final String DELETE_BY_CVE_ID = "CVE.deleteByCVEId";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -60,8 +58,6 @@ public class CVE implements Serializable { @Column(name = "NAME", nullable = false) private String name;
- // Constructor ---------------------------------------- - public CVE() { // for JPA use } @@ -70,8 +66,6 @@ public class CVE implements Serializable { this.name = name; }
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestStatus.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestStatus.java index 5d64d9c..de5bbe1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestStatus.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestStatus.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.content;
/** @@ -33,20 +33,20 @@ public enum ContentRequestStatus { * state are subject to cleanup if they have been in this state for an extended period of time without a reply * from the agent. */ - IN_PROGRESS("In Progress"), + IN_PROGRESS("In Progress"), //
/** * Indicates the result has been returned from the agent and the plugin was able to execute the actions * described by the request. */ - SUCCESS("Success"), + SUCCESS("Success"), //
/** * Indicates the agent has responded to this request and indicated a failure occurred in either the agent, * plugin container, or plugin itself. An error message will be provided in the request to further describe * the failure. */ - FAILURE("Failure"), + FAILURE("Failure"), //
/** * Indicates the request was successfully sent to the agent, however a response was not received in a timely manner. @@ -55,18 +55,12 @@ public enum ContentRequestStatus { */ TIMED_OUT("Timed Out");
- // Attributes -------------------------------------------- - private String displayText;
- // Constructors -------------------------------------------- - ContentRequestStatus(String displayText) { this.displayText = displayText; // not very I18N'ish :) }
- // Object Overridden Methods -------------------------------------------- - @Override public String toString() { return displayText; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestType.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestType.java index e7d50a3..dc8b1e1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestType.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentRequestType.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.content;
/** @@ -31,33 +31,27 @@ public enum ContentRequestType { /** * Request is to create/deploy new {@link Package}s to a resource. */ - DEPLOY("Deploy"), + DEPLOY("Deploy"), //
/** * Request is to delete {@link Package}s from a resource. */ - DELETE("Delete"), + DELETE("Delete"), //
/** * Request is to retrieve the content of {@link Package}s. */ GET_BITS("Retrieve Package Bits");
- // Attributes -------------------------------------------- - /** * Used by the user interface when rendering instances of this enumeration. */ private String displayName;
- // Constructors -------------------------------------------- - ContentRequestType(String displayName) { this.displayName = displayName; }
- // Object Overridden Methods -------------------------------------------- - @Override public String toString() { return displayName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentServiceRequest.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentServiceRequest.java index 101b61c..9569910 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentServiceRequest.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentServiceRequest.java @@ -22,8 +22,6 @@ */ package org.rhq.core.domain.content;
-import java.io.ByteArrayOutputStream; -import java.io.PrintStream; import java.io.Serializable; import java.util.Date; import java.util.HashSet; @@ -58,7 +56,7 @@ import org.rhq.core.domain.resource.Resource; * @author Jason Dobies */ @Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = ContentServiceRequest.QUERY_FIND_WITH_STATUS, query = "SELECT csr FROM ContentServiceRequest AS csr WHERE csr.status = :status"), @NamedQuery(name = ContentServiceRequest.QUERY_FIND_BY_RESOURCE_WITH_STATUS, query = "SELECT csr FROM ContentServiceRequest AS csr WHERE csr.resource.id = :resourceId AND csr.status = :status"), @NamedQuery(name = ContentServiceRequest.QUERY_FIND_BY_RESOURCE_WITH_NOT_STATUS, query = "SELECT csr FROM ContentServiceRequest AS csr WHERE csr.resource.id = :resourceId AND csr.status <> :status"), @@ -71,7 +69,6 @@ import org.rhq.core.domain.resource.Resource; @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_CONTENT_REQ_ID_SEQ") @Table(name = "RHQ_CONTENT_REQ") public class ContentServiceRequest implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
@@ -82,8 +79,6 @@ public class ContentServiceRequest implements Serializable { public static final String QUERY_FIND_BY_ID = "ContentServiceRequest.findById"; public static final String QUERY_DELETE_BY_RESOURCES = "ContentServiceRequest.deleteByResources";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(generator = "SEQ", strategy = GenerationType.AUTO) @Id @@ -119,8 +114,6 @@ public class ContentServiceRequest implements Serializable { @OneToMany(mappedBy = "contentServiceRequest", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private Set<InstalledPackageHistory> installedPackageHistory;
- // Constructors -------------------------------------------- - public ContentServiceRequest() { }
@@ -130,8 +123,6 @@ public class ContentServiceRequest implements Serializable { this.contentRequestType = contentRequestType; }
- // Public -------------------------------------------- - public int getId() { return id; } @@ -234,7 +225,6 @@ public class ContentServiceRequest implements Serializable { this.installedPackageHistory = installedPackageHistory; }
- /** * The duration of the configuration update request which simply is the difference between the * {@link #getCreatedTime()} and the {@link #getLastModifiedTime()}. If the request hasn't completed yet, this will @@ -253,15 +243,11 @@ public class ContentServiceRequest implements Serializable { return end - start; }
- // Package -------------------------------------------- - @PreUpdate void onUpdate() { this.mtime = System.currentTimeMillis(); }
- // Object Overridden -------------------------------------------- - @Override public int hashCode() { final int PRIME = 31; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSource.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSource.java index 511da1a..00877bd 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSource.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSource.java @@ -59,7 +59,7 @@ import org.rhq.core.domain.configuration.Configuration; * @author Jason Dobies */ @Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = ContentSource.QUERY_FIND_ALL, query = "SELECT cs FROM ContentSource cs "), @NamedQuery(name = ContentSource.QUERY_FIND_ALL_WITH_CONFIG, query = "SELECT cs FROM ContentSource cs LEFT JOIN FETCH cs.configuration"), @NamedQuery(name = ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME, query = "SELECT cs " + " FROM ContentSource cs " @@ -86,12 +86,8 @@ public class ContentSource implements Serializable { public static final String QUERY_FIND_BY_REPO_ID = "ContentSource.findByRepoId"; public static final String QUERY_FIND_AVAILABLE_BY_REPO_ID = "ContentSource.findAvailableByRepoId";
- // Constants -------------------------------------------- - private static final long serialVersionUID = 1L;
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -138,8 +134,6 @@ public class ContentSource implements Serializable { @OneToMany(mappedBy = "contentSource", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) private Set<RepoContentSource> repoContentSources;
- // Constructor asdf - public ContentSource() { // for JPA use } @@ -149,8 +143,6 @@ public class ContentSource implements Serializable { this.contentSourceType = contentSourceType; }
- // Public -------------------------------------------- - public int getId() { return id; } 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 a2d6142..5a046ab 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 " @@ -65,7 +65,6 @@ import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_CONTENT_SOURCE_TYPE_ID_SEQ") @Table(name = "RHQ_CONTENT_SOURCE_TYPE") public class ContentSourceType implements Serializable { - // Constants --------------------------------------------
public static final String QUERY_FIND_ALL = "ContentSourceType.findAll"; public static final String QUERY_FIND_BY_NAME_WITH_CONFIG_DEF = "ContentSourceType.findByNameWithConfigDef"; @@ -73,8 +72,6 @@ public class ContentSourceType implements Serializable {
private static final long serialVersionUID = 1L;
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -113,8 +110,6 @@ public class ContentSourceType implements Serializable { @OneToMany(mappedBy = "contentSourceType", fetch = FetchType.LAZY) private Set<ContentSource> contentSources;
- // Constructor ---------------------------------------- - public ContentSourceType() { // for JPA use } @@ -124,8 +119,6 @@ public class ContentSourceType implements Serializable { this.contentSourceApiClass = "undefined"; // TODO: I think we want this @Transient }
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/Distribution.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/Distribution.java index 5ae9acd..5d32c49 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/Distribution.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/Distribution.java @@ -22,8 +22,8 @@ */ package org.rhq.core.domain.content;
-import org.hibernate.annotations.NamedQueries; -import org.hibernate.annotations.NamedQuery; +import java.io.Serializable; +import java.util.Set;
import javax.persistence.CascadeType; import javax.persistence.Column; @@ -40,15 +40,15 @@ import javax.persistence.PreUpdate; import javax.persistence.SequenceGenerator; import javax.persistence.Table;
-import java.io.Serializable; -import java.util.Set; +import org.hibernate.annotations.NamedQueries; +import org.hibernate.annotations.NamedQuery;
/** * * @author Pradeep Kilambi */ @Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = Distribution.QUERY_FIND_ALL, query = "SELECT dt FROM Distribution dt"), @NamedQuery(name = Distribution.QUERY_FIND_PATH_BY_DIST_TYPE, query = "SELECT dt " + " FROM Distribution dt " + " WHERE dt.label = :label AND dt.distributionType.name = :typeName "), @@ -66,8 +66,6 @@ public class Distribution implements Serializable { public static final String QUERY_FIND_PATH_BY_DIST_TYPE = "Distribution.findPathByDistType"; public static final String QUERY_DELETE_BY_DIST_ID = "Distribution.deleteByDistId";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -95,8 +93,6 @@ public class Distribution implements Serializable { @OneToMany(mappedBy = "distribution", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private Set<DistributionFile> distributionFiles;
- // Constructor ---------------------------------------- - public Set<DistributionFile> getDistributionFiles() { return distributionFiles; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionFile.java index 1bf02b8..40a4a26 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionFile.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionFile.java @@ -46,7 +46,7 @@ import javax.xml.bind.annotation.XmlTransient; */ @Entity //@IdClass(DistributionFilePK.class) -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = DistributionFile.SELECT_BY_DIST_ID, query = "SELECT df from DistributionFile df WHERE df.distribution.id = :distId"), @NamedQuery(name = DistributionFile.DELETE_BY_DIST_ID, query = "DELETE DistributionFile df WHERE df.distribution.id = :distId") }) @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DISTRIBUTION_FILE_ID_SEQ") @@ -62,7 +62,6 @@ public class DistributionFile { * @IdClass and ignore these here, even though the mappings should be here and no mappings should be needed in the * @IdClass. */ - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -99,8 +98,6 @@ public class DistributionFile { this.distribution = pk.getDistribution(); }
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionType.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionType.java index 81adc75..135266c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionType.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/DistributionType.java @@ -29,10 +29,10 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table;
/** * Defines a type of (@link Distribution) @@ -44,8 +44,7 @@ import javax.persistence.NamedQuery; @Entity @NamedQueries({ @NamedQuery(name = DistributionType.QUERY_FIND_BY_NAME, query = "SELECT dt FROM DistributionType dt WHERE dt.name = :name"), - @NamedQuery(name = DistributionType.QUERY_DELETE_BY_NAME, query = "DELETE FROM DistributionType dt where dt.name = :name") -}) + @NamedQuery(name = DistributionType.QUERY_DELETE_BY_NAME, query = "DELETE FROM DistributionType dt where dt.name = :name") }) @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DISTRIBUTION_TYPE_ID_SEQ") @Table(name = "RHQ_DISTRIBUTION_TYPE") public class DistributionType implements Serializable { @@ -55,8 +54,6 @@ public class DistributionType implements Serializable { public static final String QUERY_FIND_BY_NAME = "DistributionType.findByName"; public static final String QUERY_DELETE_BY_NAME = "DistributionType.deleteByName";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -68,8 +65,6 @@ public class DistributionType implements Serializable { @Column(name = "DESCRIPTION", nullable = true) private String description;
- // Constructor ---------------------------------------- - public DistributionType() { // for JPA use } @@ -78,8 +73,6 @@ public class DistributionType implements Serializable { this.name = name; }
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/DownloadMode.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/DownloadMode.java index 3fda3cc..1b79ffb 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/DownloadMode.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/DownloadMode.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.content;
/** @@ -31,12 +31,12 @@ public enum DownloadMode { * is a simple pass-through, where all requests pull down content * directly from the remote repository. */ - NEVER, + NEVER, //
/** * The package bits will be stored in the database. */ - DATABASE, + DATABASE, //
/** * The package bits will be stored in the file system. diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackage.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackage.java index b7550f4..2bfc04f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackage.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackage.java @@ -46,7 +46,7 @@ import org.rhq.core.domain.resource.Resource; * @author Jason Dobies */ @Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = InstalledPackage.QUERY_FIND_BY_SET_OF_IDS, query = "SELECT ip FROM InstalledPackage AS ip WHERE ip.id IN ( :packageIds )"), @NamedQuery(name = InstalledPackage.QUERY_FIND_BY_SET_OF_PACKAGE_VER_IDS, query = "SELECT ip FROM InstalledPackage AS ip WHERE ip.packageVersion.id IN ( :packageIds )"), @NamedQuery(name = InstalledPackage.QUERY_FIND_BY_RESOURCE_ID, query = "SELECT ip FROM InstalledPackage AS ip WHERE ip.resource.id = :resourceId"), @@ -89,8 +89,6 @@ public class InstalledPackage implements Serializable { public static final String QUERY_FIND_INSTALLED_PACKAGE_HISTORY = "InstalledPackage.findInstalledPackageHistory"; public static final String QUERY_DELETE_BY_RESOURCES = "InstalledPackage.deleteByResources";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -111,14 +109,10 @@ public class InstalledPackage implements Serializable { @ManyToOne private Subject user;
- // Constructor ---------------------------------------- - public InstalledPackage() { // needed for JPA }
- // Public -------------------------------------------- - public int getId() { return id; } @@ -171,8 +165,6 @@ public class InstalledPackage implements Serializable { this.user = user; }
- // Object Overridden Methods -------------------------------------------- - @Override public String toString() { return "InstalledPackage[resource=" + resource.getName() + ",packageVersion=" + packageVersion.getDisplayName() diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackageHistory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackageHistory.java index 35ba747..9b21fe2 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackageHistory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/InstalledPackageHistory.java @@ -22,8 +22,6 @@ */ package org.rhq.core.domain.content;
-import java.io.ByteArrayOutputStream; -import java.io.PrintStream; import java.io.Serializable; import java.util.List;
@@ -56,7 +54,7 @@ import org.rhq.core.domain.resource.Resource; * @author Jason Dobies */ @Entity -@NamedQueries( { +@NamedQueries({ @NamedQuery(name = InstalledPackageHistory.QUERY_FIND_CONFIG_BY_PACKAGE_VERSION_AND_REQ, query = "SELECT dcv FROM InstalledPackageHistory iph JOIN iph.deploymentConfigurationValues dcv " + "WHERE iph.packageVersion = :packageVersion " + "AND iph.contentServiceRequest = :contentServiceRequest " @@ -77,7 +75,6 @@ import org.rhq.core.domain.resource.Resource; @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_INSTALLED_PKG_HIST_ID_SEQ") @Table(name = "RHQ_INSTALLED_PKG_HIST") public class InstalledPackageHistory implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
@@ -89,8 +86,6 @@ public class InstalledPackageHistory implements Serializable { public static final String QUERY_FIND_BY_ID = "InstalledPackageHistory.findById"; public static final String QUERY_DELETE_BY_RESOURCES = "InstalledPackageHistory.deleteByResources";
- // Attributes -------------------------------------------- - @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") @Id @@ -144,8 +139,6 @@ public class InstalledPackageHistory implements Serializable { @ManyToOne private ContentServiceRequest contentServiceRequest;
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/AdvisoryDetailsComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/AdvisoryDetailsComposite.java index db349f3..772b6d7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/AdvisoryDetailsComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/AdvisoryDetailsComposite.java @@ -30,7 +30,6 @@ import java.util.Set;
import org.rhq.core.domain.content.Advisory; import org.rhq.core.domain.content.AdvisoryBuglist; -import org.rhq.core.domain.content.AdvisoryCVE; import org.rhq.core.domain.content.AdvisoryPackage; import org.rhq.core.domain.content.PackageVersion; import org.rhq.core.domain.util.StringUtils; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/PackageListItemComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/PackageListItemComposite.java index 95a193e..76e886e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/PackageListItemComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/composite/PackageListItemComposite.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.content.composite;
import java.io.Serializable; @@ -30,7 +30,8 @@ import java.io.Serializable; * @author Jason Dobies */ public class PackageListItemComposite implements Serializable { - // Attributes -------------------------------------------- + + private static final long serialVersionUID = 1L;
private final int id; private final String packageName; @@ -38,8 +39,6 @@ public class PackageListItemComposite implements Serializable { private final String version; private final Long timestamp;
- // Constructors -------------------------------------------- - public PackageListItemComposite(int id, String packageName, String packageTypeName, String version) { this.id = id; this.packageName = packageName; @@ -56,8 +55,6 @@ public class PackageListItemComposite implements Serializable { this.timestamp = timestamp; }
- // Public -------------------------------------------- - public int getId() { return id; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ContentResponseResult.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ContentResponseResult.java index 1c7c416..982da7a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ContentResponseResult.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ContentResponseResult.java @@ -1,26 +1,26 @@ - /* - * 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.content.transfer; +/* + * 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.content.transfer;
/** * Describes the result of a content operation executed on a plugin. @@ -28,10 +28,8 @@ * @author Jason Dobies */ public enum ContentResponseResult { - SUCCESS("Success"), - - FAILURE("Failed"), - + SUCCESS("Success"), // + FAILURE("Failed"), // NOT_PERFORMED("Not Performed");
private String displayName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployIndividualPackageResponse.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployIndividualPackageResponse.java index 096a0b3..61e9339 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployIndividualPackageResponse.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployIndividualPackageResponse.java @@ -1,49 +1,45 @@ - /* - * 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.content.transfer; +/* + * 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.content.transfer;
import java.io.Serializable; -import java.util.List; import java.util.ArrayList; +import java.util.List; + import org.rhq.core.domain.content.PackageDetailsKey; -import org.rhq.core.domain.content.transfer.ContentResponseResult; -import org.rhq.core.domain.content.transfer.DeployPackageStep; - - /** - * Contains the data necessary to describe the result of deploying a single package. The overall result of the package - * installation and any error message (if there is one) will convey whether or not the package was successfully - * installed. Additionally, if installation steps were determined for this package, they and their respective - * success/failure flags, will be contained in this object as well. - * - * @author Jason Dobies - */ + +/** +* Contains the data necessary to describe the result of deploying a single package. The overall result of the package +* installation and any error message (if there is one) will convey whether or not the package was successfully +* installed. Additionally, if installation steps were determined for this package, they and their respective +* success/failure flags, will be contained in this object as well. +* +* @author Jason Dobies +*/ public class DeployIndividualPackageResponse implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
- // Attributes -------------------------------------------- - private PackageDetailsKey key;
private ContentResponseResult result; @@ -51,8 +47,6 @@ public class DeployIndividualPackageResponse implements Serializable {
private List<DeployPackageStep> deploymentSteps;
- // Constructors -------------------------------------------- - public DeployIndividualPackageResponse(PackageDetailsKey key) { this.key = key; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackageStep.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackageStep.java index fd5d9ba..57c62d1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackageStep.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackageStep.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.content.transfer;
import java.io.Serializable; @@ -31,12 +31,9 @@ import java.io.Serializable; * @author Jason Dobies */ public class DeployPackageStep implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
- // Attributes -------------------------------------------- - /** * Unique identifier for this step within the context of the overall package installation steps for a particular * package. @@ -58,8 +55,6 @@ public class DeployPackageStep implements Serializable { */ private String stepErrorMessage;
- // Public -------------------------------------------- - public DeployPackageStep(String stepKey, String description) { if (stepKey == null) throw new IllegalArgumentException("stepKey cannot be null"); @@ -79,12 +74,15 @@ public class DeployPackageStep implements Serializable { }
public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false;
DeployPackageStep that = (DeployPackageStep) o;
- if (!stepKey.equals(that.stepKey)) return false; + if (!stepKey.equals(that.stepKey)) + return false;
return true; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackagesResponse.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackagesResponse.java index 83f2957..40c1988 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackagesResponse.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/DeployPackagesResponse.java @@ -1,31 +1,27 @@ - /* - * 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.content.transfer; - -import org.rhq.core.domain.content.transfer.ContentResponseResult; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; +/* + * 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.content.transfer; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -34,12 +30,9 @@ import java.util.Set; * @author Jason Dobies */ public class DeployPackagesResponse implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
- // Attributes -------------------------------------------- - private int requestId;
private ContentResponseResult overallRequestResult; @@ -47,8 +40,6 @@ public class DeployPackagesResponse implements Serializable {
private Set<DeployIndividualPackageResponse> packageResponses = new HashSet<DeployIndividualPackageResponse>();
- // Constructors -------------------------------------------- - public DeployPackagesResponse() { }
@@ -97,5 +88,5 @@ public class DeployPackagesResponse implements Serializable {
packageResponses.add(response); } - + } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/RemovePackagesResponse.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/RemovePackagesResponse.java index 35eb273..dd3848d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/RemovePackagesResponse.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/RemovePackagesResponse.java @@ -1,28 +1,26 @@ - /* - * 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.content.transfer; - -import org.rhq.core.domain.content.transfer.ContentResponseResult; +/* + * 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.content.transfer;
import java.io.Serializable; import java.util.HashSet; @@ -32,12 +30,9 @@ import java.util.Set; * @author Jason Dobies */ public class RemovePackagesResponse implements Serializable { - // Constants --------------------------------------------
private static final long serialVersionUID = 1L;
- // Attributes -------------------------------------------- - private int requestId;
private ContentResponseResult overallRequestResult; @@ -45,8 +40,6 @@ public class RemovePackagesResponse implements Serializable {
private Set<RemoveIndividualPackageResponse> packageResponses = new HashSet<RemoveIndividualPackageResponse>();
- // Constructors -------------------------------------------- - public RemovePackagesResponse() { }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java index c1440cc..2165b34 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/transfer/ResourcePackageDetails.java @@ -34,7 +34,6 @@ import org.rhq.core.domain.content.PackageDetailsKey; * @author Jason Dobies */ public class ResourcePackageDetails extends PackageDetails { - // Attributes --------------------------------------------
/** * Values the plugin should use when installing this package. @@ -43,14 +42,10 @@ public class ResourcePackageDetails extends PackageDetails {
private long installationTimestamp;
- // Constructors -------------------------------------------- - public ResourcePackageDetails(PackageDetailsKey key) { super(key); }
- // Public -------------------------------------------- - public Configuration getDeploymentTimeConfiguration() { return deploymentTimeConfiguration; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java index af4f3b9..3ccab5d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceConfigurationUpdateCriteria.java @@ -88,8 +88,6 @@ public class ResourceConfigurationUpdateCriteria extends Criteria { return ResourceConfigurationUpdate.class; }
- // filters - public void addFilterId(Integer filterId) { this.filterId = filterId; } @@ -122,9 +120,6 @@ public class ResourceConfigurationUpdateCriteria extends Criteria { this.filterResourceGroupIds = Arrays.asList(filterResourceGroupIds); }
- - // Fetches - public void fetchResource(boolean fetchResource) { this.fetchResource = fetchResource; } @@ -137,9 +132,6 @@ public class ResourceConfigurationUpdateCriteria extends Criteria { this.fetchConfiguration = configuration; }
- - // Sorts - public void addSortCtime(PageOrdering sortCtime) { addSortField(SORT_FIELD_CTIME); this.sortCtime = sortCtime;
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