dev/null |binary modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java | 75 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java | 64 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/DeployPropertyNames.java | 4 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java | 3 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java | 101 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractBundleType.java | 61 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractFileType.java | 9 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractUrlFileType.java | 79 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/ArchiveType.java | 20 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java | 437 +++ modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/FileType.java | 17 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/InputPropertyType.java | 48 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/SystemServiceType.java | 57 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlArchiveType.java | 63 modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlFileType.java | 78 modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml | 6 modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java | 647 +++++ modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java | 156 + modules/common/ant-bundle/src/test/resources/file.zip |binary modules/common/ant-bundle/src/test/resources/test-audit-input.properties | 1 modules/common/ant-bundle/src/test/resources/test-audit.properties | 3 modules/common/ant-bundle/src/test/resources/test-bundle-audit.xml | 39 modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-input.properties | 1 modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-with-replace.xml | 21 modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives.xml | 14 modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml | 26 modules/common/ant-bundle/src/test/resources/test-bundle-url-input.properties | 1 modules/common/ant-bundle/src/test/resources/test-bundle-url.xml | 26 modules/common/ant-bundle/src/test/resources/test-bundle-v1.xml | 4 modules/common/ant-bundle/src/test/resources/test-bundle-v2-noManageRootDir.xml | 46 modules/common/ant-bundle/src/test/resources/test-bundle-v2.xml | 14 modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/ConfigDefRecipeCommand.java | 14 modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/RecipeContext.java | 34 modules/common/filetemplate-bundle/src/test/java/org/rhq/bundle/filetemplate/recipe/RecipeParserTest.java | 14 modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtility.java | 161 + modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtilityTest.java | 322 ++ modules/core/dbutils/pom.xml | 2 modules/core/dbutils/src/main/java/org/rhq/core/db/upgrade/OperationScheduleIdSetterUpgradeTask.java | 60 modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml | 4 modules/core/dbutils/src/main/scripts/dbsetup/operation-schema.xml | 19 modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml | 19 modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java | 65 modules/core/domain/src/main/java/org/rhq/core/domain/authz/Role.java | 20 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java | 5 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeployment.java | 21 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeploymentStatus.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDestination.java | 18 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeployment.java | 12 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeploymentHistory.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleVersion.java | 3 modules/core/domain/src/main/java/org/rhq/core/domain/common/JobTrigger.java | 298 ++ modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java | 279 -- modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionSimple.java | 28 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupCriteria.java | 10 modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/Dashboard.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/dashboard/DashboardPortlet.java | 38 modules/core/domain/src/main/java/org/rhq/core/domain/operation/GroupOperationScheduleEntity.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationScheduleEntity.java | 31 modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationScheduleEntity.java | 5 modules/core/domain/src/main/java/org/rhq/core/domain/operation/ScheduleJobId.java | 6 modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/GroupOperationSchedule.java | 98 modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java | 173 + modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/ResourceOperationSchedule.java | 56 modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/GroupOperationScheduleComposite.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/OperationScheduleComposite.java | 24 modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/ResourceOperationScheduleComposite.java | 8 modules/core/domain/src/test/java/org/rhq/core/domain/operation/test/JobIdTest.java | 7 modules/core/util/src/main/java/org/rhq/core/util/updater/ChangesFileHashcodeMap.java | 9 modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java | 160 + modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java | 44 modules/core/util/src/main/java/org/rhq/core/util/updater/FileHashcodeMap.java | 66 modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java | 28 modules/core/util/src/test/java/org/rhq/core/util/updater/FileHashcodeMapTest.java | 109 modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java | 1103 ++++++++++ modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java | 40 modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java | 40 modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java | 104 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java | 14 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java | 51 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java | 207 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Breadcrumb.java | 138 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java | 128 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java | 36 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ErrorMessageWindow.java | 78 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java | 36 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java | 44 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoadedListener.java | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoader.java | 117 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/View.java | 38 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewId.java | 34 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RoleEditView.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesDataSource.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RolesView.java | 33 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UserEditView.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java | 26 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDetailsView.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleSelector.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleTopView.java | 151 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/create/BundleUploadDataStep.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java | 29 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java | 61 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java | 114 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java | 297 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java | 123 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationDataSource.java | 76 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java | 95 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java | 211 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleVersionDataSource.java | 34 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleView.java | 203 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesDataSource.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesListView.java | 214 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java | 60 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java | 88 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/RevertStep.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeDataSource.java | 78 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java | 23 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionListView.java | 63 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java | 207 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/file/FileListView.java | 58 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java | 198 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/EnhancedDynamicForm.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/SearchBarItem.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java | 59 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java | 540 ++++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java | 214 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java | 83 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java | 95 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java | 69 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java | 72 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java | 40 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/GraphPortlet.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java | 39 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java | 43 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationsPortlet.java | 44 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java | 41 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java | 40 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertDefinitionGWTService.java | 16 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/AlertTemplateGWTService.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AuthorizationGWTService.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AvailabilityGWTService.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java | 49 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ClusterGWTService.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java | 47 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ContentGWTService.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DashboardGWTService.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/EventGWTService.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GroupAlertDefinitionGWTService.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/LdapGWTService.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/MeasurementDataGWTService.java | 52 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RemoteInstallGWTService.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceBossGWTService.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java | 33 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RoleGWTService.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SearchGWTService.java | 13 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SubjectGWTService.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SystemGWTService.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/TagGWTService.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java | 18 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/history/ResourceOperationHistoryDetailsView.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleCompositeDataSource.java | 74 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java | 142 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java | 19 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java | 209 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/event/EventCompositeDetailsView.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupsDataSource.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/GroupDefinitionListView.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/definitions/SingleGroupDefinitionView.java | 40 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java | 191 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTitleBar.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/CurrentGroupPluginConfigurationView.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java | 360 --- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java | 508 ---- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java | 19 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java | 79 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java | 74 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java | 53 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java | 618 +++++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/discovery/AutodiscoveryQueueDataSource.java | 65 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/MenuBarView.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/tag/TaggedView.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/AbstractSearchBar.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java | 106 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java | 19 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/CanvasUtility.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java | 99 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java | 56 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java | 25 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AgentGWTServiceImpl.java | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java | 55 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertTemplateGWTServiceImpl.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AuthorizationGWTServiceImpl.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java | 138 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ClusterGWTServiceImpl.java | 42 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java | 161 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ContentGWTServiceImpl.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java | 53 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/GroupAlertDefinitionGWTServiceImpl.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/LdapGWTServiceImpl.java | 52 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java | 124 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java | 58 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RemoteInstallGWTServiceImpl.java | 43 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java | 125 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java | 33 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RoleGWTServiceImpl.java | 42 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java | 89 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/TagGWTServiceImpl.java | 61 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties | 95 modules/enterprise/gui/coregui/src/main/webapp/css/search.css | 11 modules/enterprise/gui/coregui/src/main/webapp/images/info/icn_info_blank.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Delete_16_Disabled.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Deploy_16_Disabled.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Revert_16_Disabled.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16_Disabled.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16_Disabled.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16_Disabled.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/Error_11.png |binary modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/model/OperationParameters.java | 6 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleDetailsUIBean.java | 2 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleUIBean.java | 4 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleDetailsUIBean.java | 4 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleUIBean.java | 2 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleDetailsUIBean.java | 2 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleUIBean.java | 2 modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/proxy/ResourceClientProxy.java | 2 modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/utility/ScriptUtil.java | 2 modules/enterprise/remoting/cli/src/test/java/org/rhq/enterprise/client/ClientMainTest.java | 34 modules/enterprise/server/container/src/main/bin-resources/bin/rhq-server.sh | 1 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java | 52 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/RoleManagerBean.java | 12 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java | 22 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java | 14 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/RecipeParseResults.java | 16 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationJob.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationSchedule.java | 95 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java | 192 + modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerRemote.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java | 154 - modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationJob.java | 1 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationSchedule.java | 53 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java | 249 +- modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/AsyncResourceDeleteJob.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/tagging/TagManagerBean.java | 16 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java | 79 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java | 8 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java | 110 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java | 4 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java | 187 + modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/operation/OperationManagerBeanTest.java | 2 modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsSender.java | 2 modules/enterprise/server/plugins/ant-bundle/src/main/java/org/rhq/enterprise/server/plugins/ant/AntBundleServerPluginComponent.java | 2 modules/enterprise/server/plugins/filetemplate-bundle/src/main/java/org/rhq/enterprise/server/plugins/filetemplate/BundleServerPluginComponent.java | 1 modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java | 34 modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java | 58 modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java | 191 - modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml | 6 modules/plugins/perftest/src/main/resources/configurable-5.xml | 4 modules/pom.xml | 1 301 files changed, 11863 insertions(+), 5405 deletions(-)
New commits: commit eccc1f3fdf7011778624d72d89f07acabbe3d347 Merge: decd2b9... ff23902... Author: John Sanda jsanda@redhat.com Date: Mon Jan 3 09:18:50 2011 -0500
Merge branch 'master' into delete-agent-plugin
Conflicts: modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java
commit ff23902b5eba7b2fed45c2ec90861c53e73cc329 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Jan 3 12:55:16 2011 +0100
BZ 665855 - try to find the control script file only on the OSes that actually have a chance of having it. Be more careful about FS layout assumptions...
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java index bc23c09..4582f13 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java @@ -649,21 +649,28 @@ public class ApacheServerComponent implements AugeasRHQComponent<PlatformCompone } }
- if (!found) { + //only try harder on the control script path on OSes with UNIX file system layout + if (!found && resourceContext.getSystemInformation().getOperatingSystemType() != OperatingSystemType.WINDOWS) { String executablePath = pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, null); if (executablePath != null) { - // this is now somethig like /usr/sbin/httpd .. trim off the last 2 parts - int i = executablePath.lastIndexOf('/'); - executablePath = executablePath.substring(0, i); - i = executablePath.lastIndexOf('/'); - executablePath = executablePath.substring(0, i); - for (String path : CONTROL_SCRIPT_PATHS) { - controlScriptFile = new File(executablePath, path); - if (controlScriptFile.exists()) { - found = true; - break; - } + // this is now something like /usr/sbin/httpd .. trim off the last 2 parts + int i = executablePath.lastIndexOf(File.separatorChar); + + if (i >= 0) { + executablePath = executablePath.substring(0, i); + i = executablePath.lastIndexOf(File.separatorChar); } + + if (i >= 0) { + executablePath = executablePath.substring(0, i); + for (String path : CONTROL_SCRIPT_PATHS) { + controlScriptFile = new File(executablePath, path); + if (controlScriptFile.exists()) { + found = true; + break; + } + } + } } }
commit 52447ceaa38db78686d6cd102ac51f9adf29aa0a Author: Lukas Krejci lkrejci@redhat.com Date: Mon Jan 3 12:42:50 2011 +0100
code formatting
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java index 719d9cb..bc23c09 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java @@ -625,48 +625,51 @@ public class ApacheServerComponent implements AugeasRHQComponent<PlatformCompone File controlScriptFile = null; if (controlScriptPath != null) { controlScriptFile = resolvePathRelativeToServerRoot(controlScriptPath); - } else { - boolean found = false; - // First try server root as base - String serverRoot=null; - try { + } else { + boolean found = false; + // First try server root as base + String serverRoot = null; + try { ApacheDirectiveTree tree = loadParser(); List<ApacheDirective> directives = tree.search("/ServerRoot"); if (!directives.isEmpty()) - if (!directives.get(0).getValues().isEmpty()) - serverRoot = directives.get(0).getValues().get(0); - - }catch(Exception e){ - log.error("Could not load configuration parser.",e); - } - if (serverRoot!=null) - for (String path : CONTROL_SCRIPT_PATHS) { + if (!directives.get(0).getValues().isEmpty()) + serverRoot = directives.get(0).getValues().get(0); + + } catch (Exception e) { + log.error("Could not load configuration parser.", e); + } + if (serverRoot != null) { + for (String path : CONTROL_SCRIPT_PATHS) { controlScriptFile = new File(serverRoot, path); if (controlScriptFile.exists()) { found = true; break; } - } - if (!found) { - String executablePath = pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, null); - if (executablePath != null) { - // this is now somethig like /usr/sbin/httpd .. trim off the last 2 parts - int i = executablePath.lastIndexOf('/'); - executablePath = executablePath.substring(0, i); - i = executablePath.lastIndexOf('/'); - executablePath = executablePath.substring(0, i); - for (String path : CONTROL_SCRIPT_PATHS) { - controlScriptFile = new File(executablePath, path); - if (controlScriptFile.exists()) { - found = true; - break; - } + } + } + + if (!found) { + String executablePath = pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, null); + if (executablePath != null) { + // this is now somethig like /usr/sbin/httpd .. trim off the last 2 parts + int i = executablePath.lastIndexOf('/'); + executablePath = executablePath.substring(0, i); + i = executablePath.lastIndexOf('/'); + executablePath = executablePath.substring(0, i); + for (String path : CONTROL_SCRIPT_PATHS) { + controlScriptFile = new File(executablePath, path); + if (controlScriptFile.exists()) { + found = true; + break; } } } - if (!found) { - controlScriptFile = getExecutablePath(); // fall back to the httpd binary - } + } + + if (!found) { + controlScriptFile = getExecutablePath(); // fall back to the httpd binary + } }
return controlScriptFile;
commit 9f09183904e6c03dc81b058f715a12ce02bc662c Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 24 00:09:50 2010 -0500
BZ 609154 - be able to specify archives and raw files via remote URLs rather than bundle them directly in the bundle distro. The agents must have access to this URL for the bundle to be provisioned.
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java index f5d32eb..e26a7da 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java @@ -85,9 +85,9 @@ public class AntLauncher { public BundleAntProject executeBundleDeployFile(File buildFile, Properties buildProperties, List<BuildListener> buildListeners) throws InvalidBuildFileException { // Parse and validate the build file before even attempting to execute it. - BundleAntProject parsedProject = parseBundleDeployFile(buildFile); + BundleAntProject parsedProject = parseBundleDeployFile(buildFile, buildProperties);
- BundleAntProject project = createProject(buildFile, false); + BundleAntProject project = createProject(buildFile, false, buildProperties);
// The parse above got us all the bundle files names. The rest of this method // will be able to re-determine everything else for 'project' but these filenames. @@ -96,17 +96,6 @@ public class AntLauncher { project.getBundleFileNames().addAll(parsedProject.getBundleFileNames());
try { - if (buildProperties != null) { - for (Map.Entry<Object, Object> property : buildProperties.entrySet()) { - // On the assumption that these properties will be slurped in via Properties.load we - // need to escape backslashes to have them treated as literals - project.setUserProperty(property.getKey().toString(), property.getValue().toString().replace("\", - "\\")); - } - } - project.setUserProperty(MagicNames.ANT_FILE, buildFile.getAbsolutePath()); - project.setUserProperty(MagicNames.ANT_FILE_TYPE, MagicNames.ANT_FILE_TYPE_FILE); - if (buildListeners != null) { for (BuildListener buildListener : buildListeners) { project.addBuildListener(buildListener); @@ -131,8 +120,9 @@ public class AntLauncher { } }
- public BundleAntProject parseBundleDeployFile(File buildFile) throws InvalidBuildFileException { - BundleAntProject project = createProject(buildFile, true); + public BundleAntProject parseBundleDeployFile(File buildFile, Properties buildProperties) + throws InvalidBuildFileException { + BundleAntProject project = createProject(buildFile, true, buildProperties);
ProjectHelper2 projectHelper = new ProjectHelper2(); try { @@ -157,10 +147,23 @@ public class AntLauncher { return project; }
- private BundleAntProject createProject(File buildFile, boolean parseOnly) { + private BundleAntProject createProject(File buildFile, boolean parseOnly, Properties buildProperties) { + ClassLoader classLoader = getClass().getClassLoader();
BundleAntProject project = new BundleAntProject(parseOnly); + + if (buildProperties != null) { + for (Map.Entry<Object, Object> property : buildProperties.entrySet()) { + // On the assumption that these properties will be slurped in via Properties.load we + // need to escape backslashes to have them treated as literals + project.setUserProperty(property.getKey().toString(), property.getValue().toString().replace("\", + "\\")); + } + } + project.setUserProperty(MagicNames.ANT_FILE, buildFile.getAbsolutePath()); + project.setUserProperty(MagicNames.ANT_FILE_TYPE, MagicNames.ANT_FILE_TYPE_FILE); + project.setCoreLoader(classLoader); project.init(); project.setBaseDir(buildFile.getParentFile()); @@ -246,6 +249,13 @@ public class AntLauncher { for (String archive : archives.values()) { project.getBundleFileNames().add(archive); } + + // note that we do NOT add url-files and url-archives to the BundleFileNames because those are + // not true "bundle files" that are stored with the bundle version in the database. Those will + // be downloaded by the agents at the time the recipe is invoked. There is nothing server side + // that need to be known about the files/archives from URLs. + + return; }
private void abortIfTaskWithinTarget(Target target, Task task) throws InvalidBuildFileException { diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java index 6fab4ba..1beb540 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java @@ -69,9 +69,12 @@ public class BundleAntProject extends Project { private final Set<String> bundleFileNames = new HashSet<String>(); private int deploymentId; private DeploymentPhase deploymentPhase; - private DeployDifferences deployDiffs = new DeployDifferences(); private boolean dryRun;
+ // results of project execution + private DeployDifferences deployDiffs = new DeployDifferences(); + private Set<File> downloadedFiles = new HashSet<File>(); + public BundleAntProject() { this(false); } @@ -150,10 +153,6 @@ public class BundleAntProject extends Project { this.deploymentPhase = deploymentPhase; }
- public DeployDifferences getDeployDifferences() { - return deployDiffs; - } - public void setDryRun(boolean dryRun) { this.dryRun = dryRun; } @@ -162,6 +161,20 @@ public class BundleAntProject extends Project { return dryRun; }
+ public DeployDifferences getDeployDifferences() { + return deployDiffs; + } + + /** + * If there were url-file or url-archives, this returns the set of files + * that were downloaded from the URLs. + * + * @return downloaded files from remote URLs that contain our bundle content + */ + public Set<File> getDownloadedFiles() { + return downloadedFiles; + } + /** * Logs a message in a format that our audit task/agent-side audit log listener knows about. * When running in the agent, this audit log will be sent to the server. diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractUrlFileType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractUrlFileType.java new file mode 100644 index 0000000..8eecee4 --- /dev/null +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractUrlFileType.java @@ -0,0 +1,79 @@ +/* + * 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.bundle.ant.type; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.apache.tools.ant.BuildException; + +/** + * A base class for the functionality shared by {@link UrlFileType} and {@link UrlArchiveType}. + * + * @author Ian Springer + * @author John Mazzitelli + */ +public abstract class AbstractUrlFileType extends AbstractBundleType { + private String url; + private URL source; + + /** + * Returns the base filename of the URL (no parent paths will be in the returned name). + * If there is no path, the hostname of the URL is used. + * + * @return base filename of the source file + */ + public String getBaseName() { + String path = this.source.getPath(); + if (path.endsWith("/")) { + path = path.substring(0, path.length()); + } + int lastSlash = path.lastIndexOf('/'); + if (lastSlash != -1) { + path = path.substring(lastSlash + 1); + } + if (path.length() == 0) { + path = this.source.getHost(); + } + return path; + } + + public URL getSource() { + return this.source; + } + + public String getUrl() { + return this.url; + } + + public void setUrl(String urlString) { + this.url = urlString; + try { + this.source = new URL(urlString); + } catch (MalformedURLException e) { + throw new BuildException("URL specified by 'url' attribute [" + urlString + + "] is malformed - it must be a valid URL."); + } + } + +} \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java index 8d00a96..dfcbcab 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java @@ -18,7 +18,12 @@ package org.rhq.bundle.ant.type;
import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -31,10 +36,13 @@ import org.apache.tools.ant.Project; import org.apache.tools.ant.Target;
import org.rhq.bundle.ant.DeployPropertyNames; +import org.rhq.bundle.ant.BundleAntProject.AuditStatus; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.system.SystemInfoFactory; import org.rhq.core.template.TemplateEngine; +import org.rhq.core.util.exception.ThrowableUtil; +import org.rhq.core.util.stream.StreamUtil; import org.rhq.core.util.updater.DeployDifferences; import org.rhq.core.util.updater.Deployer; import org.rhq.core.util.updater.DeploymentData; @@ -48,13 +56,21 @@ import org.rhq.core.util.updater.DeploymentProperties; public class DeploymentUnitType extends AbstractBundleType { private String name; private String manageRootDir = Boolean.TRUE.toString(); + private Map<File, File> files = new LinkedHashMap<File, File>(); - private Map<File, String> localFileNames = new LinkedHashMap<File, String>(); + private Map<URL, File> urlFiles = new LinkedHashMap<URL, File>(); private Set<File> rawFilesToReplace = new LinkedHashSet<File>(); + private Set<URL> rawUrlFilesToReplace = new LinkedHashSet<URL>(); + private Map<File, String> localFileNames = new LinkedHashMap<File, String>(); + private Set<File> archives = new LinkedHashSet<File>(); - private Map<File, String> localArchiveNames = new LinkedHashMap<File, String>(); - private Map<File, Boolean> archivesExploded = new HashMap<File, Boolean>(); + private Set<URL> urlArchives = new LinkedHashSet<URL>(); private Map<File, Pattern> archiveReplacePatterns = new HashMap<File, Pattern>(); + private Map<URL, Pattern> urlArchiveReplacePatterns = new HashMap<URL, Pattern>(); + private Map<File, Boolean> archivesExploded = new HashMap<File, Boolean>(); + private Map<URL, Boolean> urlArchivesExploded = new HashMap<URL, Boolean>(); + private Map<File, String> localArchiveNames = new LinkedHashMap<File, String>(); + private SystemServiceType systemService; private Pattern ignorePattern; private String preinstallTarget; @@ -67,72 +83,282 @@ public class DeploymentUnitType extends AbstractBundleType { }
public void install(boolean revert, boolean clean) throws BuildException { - if (this.preinstallTarget != null) { - Target target = (Target) getProject().getTargets().get(this.preinstallTarget); - if (target == null) { - throw new BuildException("Specified preinstall target (" + this.preinstallTarget + ") does not exist."); - } - target.performTasks(); + if (clean) { + getProject().auditLog( + AuditStatus.WARN, + "Clean Requested", + "A clean deployment has been requested. Files will be deleted!", + "A clean deployment has been requested. Files will be deleted" + + " from the destination directory prior to the new deployment files getting written", null); + } + if (revert) { + getProject().auditLog( + AuditStatus.WARN, + "Revert Requested", + "The previous deployment will be reverted!", + "The previous deployment will be reverted. An attempt to restore" + + " backed up files and the old deployment content will be made", null); }
- int deploymentId = getProject().getDeploymentId(); - DeploymentProperties deploymentProps = new DeploymentProperties(deploymentId, getProject().getBundleName(), - getProject().getBundleVersion(), getProject().getBundleDescription()); - File deployDir = getProject().getDeployDir(); - TemplateEngine templateEngine = createTemplateEngine(); + try { + boolean dryRun = getProject().isDryRun();
- if (this.files.isEmpty() && this.archives.isEmpty()) { - throw new BuildException( - "You must specify at least one file to deploy via nested rhq:file, rhq:archive, and/or rhq:system-service elements."); - } - if (!this.files.isEmpty()) { - log("Deploying files " + this.files + "...", Project.MSG_VERBOSE); - } - if (!this.archives.isEmpty()) { - log("Deploying archives " + this.archives + "...", Project.MSG_VERBOSE); + if (this.preinstallTarget != null) { + getProject().auditLog(AuditStatus.SUCCESS, "Pre-Install Started", "The pre install target will start", + "The pre install target named [" + this.preinstallTarget + "] will start", null); + Target target = (Target) getProject().getTargets().get(this.preinstallTarget); + if (target == null) { + try { + getProject().auditLog( + AuditStatus.FAILURE, + "Pre-Install Failure", + "The pre install target does not exist", + "The pre install target specified in the recipe [" + this.preinstallTarget + + "] does not exist.", null); + } catch (Throwable ignore) { + // swallow any errors that occur here, we want to throw the real build exception + } + throw new BuildException("Specified preinstall target (" + this.preinstallTarget + + ") does not exist."); + } + target.performTasks(); + getProject().auditLog(AuditStatus.SUCCESS, "Pre-Install Finished", + "The pre install target has finished", null, null); + } + + int deploymentId = getProject().getDeploymentId(); + DeploymentProperties deploymentProps = new DeploymentProperties(deploymentId, getProject().getBundleName(), + getProject().getBundleVersion(), getProject().getBundleDescription()); + File deployDir = getProject().getDeployDir(); + TemplateEngine templateEngine = createTemplateEngine(); + + boolean haveSomethingToDo = false; + if (!this.files.isEmpty()) { + haveSomethingToDo = true; + log("Deploying files " + this.files + "...", Project.MSG_VERBOSE); + } + if (!this.urlFiles.isEmpty()) { + haveSomethingToDo = true; + log("Deploying files from URL " + this.urlFiles + "...", Project.MSG_VERBOSE); + } + if (!this.archives.isEmpty()) { + haveSomethingToDo = true; + log("Deploying archives " + this.archives + "...", Project.MSG_VERBOSE); + } + if (!this.urlArchives.isEmpty()) { + haveSomethingToDo = true; + log("Deploying archives from URL " + this.urlArchives + "...", Project.MSG_VERBOSE); + } + if (!haveSomethingToDo) { + throw new BuildException( + "You must specify at least one file to deploy via nested file, archive, url-file, url-archive types in your recipe"); + } + + boolean willManageRootDir = Boolean.parseBoolean(this.manageRootDir); + if (willManageRootDir) { + log("Managing the root directory of this deployment unit - unrelated files found will be removed", + Project.MSG_VERBOSE); + // don't send an audit message on this unless we are really going to move files out of the way (i.e. !dryrun) + if (!dryRun) { + getProject() + .auditLog( + AuditStatus.WARN, + "Managing Top Level Deployment Directory", + "The top level deployment directory will be managed - files found there will be backed up and removed!", + "The bundle recipe has requested that the top level deployment directory be fully managed by RHQ." + + "This means any files currently located in the top level deployment directory will be removed and backed up", + null); + } + } else { + log("Not managing the root directory of this deployment unit - unrelated files will remain intact", + Project.MSG_VERBOSE); + } + + Set<File> allArchives = new HashSet<File>(this.archives); + Map<File, File> allFiles = new HashMap<File, File>(this.files); + Map<File, Pattern> allArchiveReplacePatterns = new HashMap<File, Pattern>(this.archiveReplacePatterns); + Set<File> allRawFilesToReplace = new HashSet<File>(this.rawFilesToReplace); + Map<File, Boolean> allArchivesExploded = new HashMap<File, Boolean>(this.archivesExploded); + downloadFilesFromUrlEndpoints(allArchives, allFiles, allArchiveReplacePatterns, allRawFilesToReplace, + allArchivesExploded); + + try { + DeploymentData deploymentData = new DeploymentData(deploymentProps, allArchives, allFiles, getProject() + .getBaseDir(), deployDir, allArchiveReplacePatterns, allRawFilesToReplace, templateEngine, + this.ignorePattern, willManageRootDir, allArchivesExploded); + Deployer deployer = new Deployer(deploymentData); + DeployDifferences diffs = getProject().getDeployDifferences(); + + // we only want to emit audit trail when something is really going to happen on disk; don't log if doing a dry run + if (!dryRun) { + getProject().auditLog(AuditStatus.SUCCESS, "Deployer Started", "The deployer has started its work", + null, null); + } + + if (revert) { + deployer.redeployAndRestoreBackupFiles(diffs, clean, dryRun); + } else { + deployer.deploy(diffs, clean, dryRun); + } + + // we only want to emit audit trail when something is really going to happen on disk; don't log if doing a dry run + if (!dryRun) { + getProject().auditLog(AuditStatus.SUCCESS, "Deployer Finished", + "The deployer has finished its work", null, diffs.toString()); + } + } catch (Throwable t) { + try { + getProject().auditLog(AuditStatus.FAILURE, "Deployer Failed", + "The deployer encountered an error and could not finished", ThrowableUtil.getAllMessages(t), + ThrowableUtil.getStackAsString(t)); + } catch (Throwable ignore) { + // swallow any errors that occur here, we want to throw the real build exception + } + throw new BuildException("Failed to deploy bundle [" + getProject().getBundleName() + "] version [" + + getProject().getBundleVersion() + "]: " + t, t); + } + + if (this.systemService != null) { + this.systemService.install(); + } + + if (this.postinstallTarget != null) { + getProject().auditLog(AuditStatus.SUCCESS, "Post-Install Started", + "The post install target will start", + "The post install target named [" + this.postinstallTarget + "] will start", null); + Target target = (Target) getProject().getTargets().get(this.postinstallTarget); + if (target == null) { + try { + getProject().auditLog( + AuditStatus.FAILURE, + "Post-Install Failure", + "The post install target does not exist", + "The post install target specified in the recipe [" + this.postinstallTarget + + "] does not exist.", null); + } catch (Throwable ignore) { + // swallow any errors that occur here, we want to throw the real build exception + } + throw new BuildException("Specified postinstall target (" + this.postinstallTarget + + ") does not exist."); + } + target.performTasks(); + getProject().auditLog(AuditStatus.SUCCESS, "Post-Install Finished", + "The post install target has finished", null, null); + } + } catch (Throwable t) { + try { + getProject().auditLog(AuditStatus.FAILURE, "Error Occurred", + "The deployment could not complete successfully.", ThrowableUtil.getAllMessages(t), + ThrowableUtil.getStackAsString(t)); + } catch (Throwable ignore) { + // swallow any errors that occur here, we want to throw the real build exception + } + if (t instanceof BuildException) { + throw (BuildException) t; + } else { + throw new BuildException(t); + } } + return; + } + + /** + * This will download any files/archives that are found at URL endpoints as declared in the ant recipe. + * + * @param allArchives when a new archive is downloaded, its information is added to this + * @param allFiles when a new raw file is downloaded, its information is added to this + * @param allArchiveReplacePatterns when a new archive is downloaded, its information is added to this + * @param allRawFilesToReplace when a new raw file is downloaded, its information is added to this + * @param allArchivesExploded when a new archive is downloaded, its information is added to this + */ + private void downloadFilesFromUrlEndpoints(Set<File> allArchives, Map<File, File> allFiles, + Map<File, Pattern> allArchiveReplacePatterns, Set<File> allRawFilesToReplace, + Map<File, Boolean> allArchivesExploded) throws Exception {
- boolean willManageRootDir = Boolean.parseBoolean(this.manageRootDir); - if (willManageRootDir) { - log("Managing the root directory of this deployment unit - unrelated files found will be removed", - Project.MSG_VERBOSE); - } else { - log("Not managing the root directory of this deployment unit - unrelated files will remain intact", - Project.MSG_VERBOSE); + // check to see if we even need to download anything, if not, do nothing and return immediately + if (this.urlFiles.isEmpty() && this.urlArchives.isEmpty()) { + return; }
- DeploymentData deploymentData = new DeploymentData(deploymentProps, this.archives, this.files, getProject() - .getBaseDir(), deployDir, this.archiveReplacePatterns, this.rawFilesToReplace, templateEngine, - this.ignorePattern, willManageRootDir, this.archivesExploded); - Deployer deployer = new Deployer(deploymentData); + // download all our files in the base dir, as if they came with the bundle like normal files + File downloadDir = getProject().getBaseDir(); + Set<File> downloadedFiles = getProject().getDownloadedFiles(); + try { - DeployDifferences diffs = getProject().getDeployDifferences(); - boolean dryRun = getProject().isDryRun(); - if (revert) { - deployer.redeployAndRestoreBackupFiles(diffs, clean, dryRun); - } else { - deployer.deploy(diffs, clean, dryRun); + // do the raw files first + for (Map.Entry<URL, File> fileEntry : this.urlFiles.entrySet()) { + URL url = fileEntry.getKey(); + File destFile = fileEntry.getValue(); + File tmpFile = new File(downloadDir, destFile.getPath()); // use getPath in case they have 2+ raw files with the same name + download(url, tmpFile); + downloadedFiles.add(tmpFile); + allFiles.put(tmpFile, destFile); + if (this.rawUrlFilesToReplace.contains(url)) { + allRawFilesToReplace.add(tmpFile); + } } - getProject().log("Results:\n" + diffs + "\n"); + + // do the archives next + for (URL url : this.urlArchives) { + // determine what the base filename should be of our downloaded tmp archive file + String baseFileName = url.getPath(); + if (baseFileName.endsWith("/")) { + baseFileName = baseFileName.substring(0, baseFileName.length()); + } + int lastSlash = baseFileName.lastIndexOf('/'); + if (lastSlash != -1) { + baseFileName = baseFileName.substring(lastSlash + 1); + } + if (baseFileName.length() == 0) { + baseFileName = url.getHost(); + } + + File tmpFile = new File(downloadDir, baseFileName); + download(url, tmpFile); + downloadedFiles.add(tmpFile); + allArchives.add(tmpFile); + if (this.urlArchiveReplacePatterns.containsKey(url)) { + allArchiveReplacePatterns.put(tmpFile, this.urlArchiveReplacePatterns.get(url)); + } + if (this.urlArchivesExploded.containsKey(url)) { + allArchivesExploded.put(tmpFile, this.urlArchivesExploded.get(url)); + } + } + + return; + } catch (Exception e) { - throw new BuildException("Failed to deploy bundle '" + getProject().getBundleName() + "' version " - + getProject().getBundleVersion() + ": " + e, e); + // can't do anything with any files we did download - be nice and clean up + try { + for (File doomed : downloadedFiles) { + doomed.delete(); + } + } catch (Exception ignore) { + // ignore this, we just can't delete them - but we want to throw our original exception + } + throw e; } + }
- if (this.systemService != null) { - this.systemService.install(); - } + private void download(URL url, File tmpFile) throws Exception { + getProject().auditLog(AuditStatus.SUCCESS, "File Download Started", "Downloading file from URL", + "Downloading file from URL: " + url, null);
- if (this.postinstallTarget != null) { - Target target = (Target) getProject().getTargets().get(this.postinstallTarget); - if (target == null) { - throw new BuildException("Specified postinstall target (" + this.postinstallTarget - + ") does not exist."); - } - target.performTasks(); + long size; + try { + InputStream in = url.openStream(); + tmpFile.getParentFile().mkdirs(); // if this fails, our next line will throw a file-not-found error and we'll abort + OutputStream out = new FileOutputStream(tmpFile); + size = StreamUtil.copy(in, out); + } catch (Exception e) { + getProject().auditLog(AuditStatus.FAILURE, "File Download Failed", + "Failed to download content from a remote server", "Failed to download file from: " + url, + ThrowableUtil.getStackAsString(e)); + throw e; }
- return; + getProject().auditLog(AuditStatus.SUCCESS, "File Download Finished", "Successfully downloaded file from URL", + "Downloaded file of size [" + size + "] bytes from URL: " + url, null); }
public void start() throws BuildException { @@ -289,6 +515,28 @@ public class DeploymentUnitType extends AbstractBundleType { this.archivesExploded.put(archive.getSource(), exploded); }
+ public void addConfigured(UrlFileType file) { + File destFile = file.getDestinationFile(); + if (destFile == null) { + File destDir = file.getDestinationDir(); + destFile = new File(destDir, file.getBaseName()); + } + this.urlFiles.put(file.getSource(), destFile); // key=full absolute path, value=could be relative or absolute + if (file.isReplace()) { + this.rawUrlFilesToReplace.add(file.getSource()); + } + } + + public void addConfigured(UrlArchiveType archive) { + this.urlArchives.add(archive.getSource()); + Pattern replacePattern = archive.getReplacePattern(); + if (replacePattern != null) { + this.urlArchiveReplacePatterns.put(archive.getSource(), replacePattern); + } + Boolean exploded = Boolean.valueOf(archive.getExploded()); + this.urlArchivesExploded.put(archive.getSource(), exploded); + } + public void addConfigured(IgnoreType ignore) { List<FileSet> fileSets = ignore.getFileSets(); this.ignorePattern = getPattern(fileSets); diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlArchiveType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlArchiveType.java new file mode 100644 index 0000000..af664aa --- /dev/null +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlArchiveType.java @@ -0,0 +1,63 @@ +/* + * 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.bundle.ant.type; + +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.tools.ant.BuildException; + +/** + * An archive file to be exploded during the bundle deployment (it could remain compressed if exploded="false" is specified) + * Can optionally contain a rhq:replace child element that specifies the set of files that contain + * template variables (e.g. @@http.port@@) which need to be replaced with the value of the corresponding property. + * + * This archive file is located at a remote location specified by a URL. + * + * @author Ian Springer + * @author John Mazzitelli + */ +public class UrlArchiveType extends AbstractUrlFileType { + private Pattern replacePattern; + private String exploded = Boolean.TRUE.toString(); + + public void addConfigured(ReplaceType replace) { + List<FileSet> fileSets = replace.getFileSets(); + this.replacePattern = getPattern(fileSets); + } + + public Pattern getReplacePattern() { + return replacePattern; + } + + public String getExploded() { + return exploded; + } + + public void setExploded(String exploded) { + if (!Boolean.TRUE.toString().equalsIgnoreCase(exploded) && !Boolean.FALSE.toString().equalsIgnoreCase(exploded)) { + throw new BuildException("'exploded' attribute must be 'true' or 'false': " + exploded); + } + this.exploded = exploded; + } +} \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlFileType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlFileType.java new file mode 100644 index 0000000..b4c20b0 --- /dev/null +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/UrlFileType.java @@ -0,0 +1,78 @@ +/* + * 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.bundle.ant.type; + +import java.io.File; + +import org.apache.tools.ant.BuildException; + +/** + * A file to be copied during the bundle deployment. If the replace attribute is set to true, any template variables + * (e.g. @@http.port@@) inside the file will be replaced with the value of the corresponding property. + * + * This file is located at a remote location specified by a URL. + * + * @author Ian Springer + * @author John Mazzitelli + */ +public class UrlFileType extends AbstractUrlFileType { + private File destinationDir; + private File destinationFile; + private boolean replace; + + public File getDestinationDir() { + return this.destinationDir; + } + + // Pass in a String, rather than a File, since we don't want Ant to resolve the path relative to basedir if it's relative. + public void setDestinationDir(String destinationDir) { + if (this.destinationFile != null) { + throw new BuildException( + "Both 'destinationDir' and 'destinationFile' attributes are defined - only one or the other may be specified."); + } + this.destinationDir = new File(destinationDir); + } + + public File getDestinationFile() { + if (this.destinationDir == null && this.destinationFile == null) { + return new File(getBaseName()); // the default destination is the same relative path as that of its local name + } + return this.destinationFile; + } + + public void setDestinationFile(String destinationFile) { + if (this.destinationDir != null) { + throw new BuildException( + "Both 'destinationDir' and 'destinationFile' attributes are defined - only one or the other may be specified."); + } + this.destinationFile = new File(destinationFile); + } + + public boolean isReplace() { + return replace; + } + + public void setReplace(boolean replace) { + this.replace = replace; + } +} \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml b/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml index 010077e..d5cf418 100644 --- a/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml +++ b/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml @@ -13,6 +13,8 @@ <!-- deployment type's child types --> <typedef name="file" classname="org.rhq.bundle.ant.type.FileType"/> <typedef name="archive" classname="org.rhq.bundle.ant.type.ArchiveType"/> + <typedef name="url-file" classname="org.rhq.bundle.ant.type.UrlFileType"/> + <typedef name="url-archive" classname="org.rhq.bundle.ant.type.UrlArchiveType"/> <typedef name="replace" classname="org.rhq.bundle.ant.type.ReplaceType"/> <typedef name="ignore" classname="org.rhq.bundle.ant.type.IgnoreType"/> <typedef name="fileset" classname="org.rhq.bundle.ant.type.FileSet"/> diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index 4eb4369..92f43b4 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -78,7 +78,7 @@ public class AntLauncherTest {
AntLauncher ant = new AntLauncher();
- BundleAntProject project = ant.parseBundleDeployFile(getBuildXml("test-bundle-v1.xml")); + BundleAntProject project = ant.parseBundleDeployFile(getBuildXml("test-bundle-v1.xml"), null); assert project != null; Set<String> bundleFiles = project.getBundleFileNames(); assert bundleFiles != null; @@ -518,8 +518,8 @@ public class AntLauncherTest { assert new File(DEPLOY_DIR, "subdir/test0.txt").exists() : "missing raw file from default destination location"; assert new File(DEPLOY_DIR, "another/foo.txt").exists() : "missing raw file from the destinationFile"; assert new File(DEPLOY_DIR, "second.dir/test2.txt").exists() : "missing raw file from the destinationDir"; - assert !new File(DEPLOY_DIR, "subdir/test1.zip").exists() : "should not be here because destinationFile was specified"; - assert !new File(DEPLOY_DIR, "subdir/test2.zip").exists() : "should not be here because destinationFile was specified"; + assert !new File(DEPLOY_DIR, "subdir/test1.txt").exists() : "should not be here because destinationFile was specified"; + assert !new File(DEPLOY_DIR, "subdir/test2.txt").exists() : "should not be here because destinationFile was specified"; assert new File(DEPLOY_DIR, "subdir/test.zip").exists() : "missing unexploded zip file"; assert new File(DEPLOY_DIR, "subdir/test-replace.zip").exists() : "missing unexploded zip file"; assert !new File(DEPLOY_DIR, "subdir/test-explode.zip").exists() : "should have been exploded"; @@ -544,6 +544,98 @@ public class AntLauncherTest { } }
+ public void testUrlFilesAndArchives() throws Exception { + // We want to test a fresh install, so make sure the deploy dir doesn't pre-exist. + FileUtil.purge(DEPLOY_DIR, true); + + // we need to create our own directory structure so we can use file: URLs + File tmpUrlLocation = FileUtil.createTempDirectory("anttest", ".url", null); + Set<File> downloadedFiles = null; + + try { + File subdir = new File(tmpUrlLocation, "subdir"); // must match the name in the recipe + subdir.mkdirs(); + writeFile("file0", subdir, "test0.txt"); // filename must match recipe + writeFile("file1", subdir, "test1.txt"); // filename must match recipe + writeFile("X=@@X@@\n", subdir, "test2.txt"); // filename must match recipe + createZip(new String[] { "one", "two" }, subdir, "test.zip", new String[] { "one.txt", "two.txt" }); + createZip(new String[] { "3", "4" }, subdir, "test-explode.zip", new String[] { "three.txt", "four.txt" }); + createZip(new String[] { "X=@@X@@\n" }, subdir, "test-replace.zip", new String[] { "template.txt" }); // will be exploded then recompressed + + AntLauncher ant = new AntLauncher(); + Properties inputProps = createInputProperties("/test-bundle-url-input.properties"); + inputProps.setProperty("rhq.test.url.dir", tmpUrlLocation.toURI().toURL().toString()); // we use this so our recipe can use URLs + List<BuildListener> buildListeners = createBuildListeners(); + + BundleAntProject project = ant.executeBundleDeployFile(getBuildXml("test-bundle-url.xml"), inputProps, + buildListeners); + assert project != null; + + Set<String> bundleFiles = project.getBundleFileNames(); + assert bundleFiles != null; + assert bundleFiles.size() == 0 : "we don't have any bundle files - only downloaded files from URLs: " + + bundleFiles; + + downloadedFiles = project.getDownloadedFiles(); + assert downloadedFiles != null; + assert downloadedFiles.size() == 6 : downloadedFiles; + ArrayList<String> expectedDownloadedFileNames = new ArrayList<String>(); + // remember, we store url downloaded files under the names of their destination file/dir, not source location + expectedDownloadedFileNames.add("test0.txt"); + expectedDownloadedFileNames.add("foo.txt"); + expectedDownloadedFileNames.add("test2.txt"); + expectedDownloadedFileNames.add("test.zip"); + expectedDownloadedFileNames.add("test-explode.zip"); + expectedDownloadedFileNames.add("test-replace.zip"); + for (File downloadedFile : downloadedFiles) { + assert expectedDownloadedFileNames.contains(downloadedFile.getName()) : "We downloaded a file but its not in the project's list: " + + downloadedFile; + } + + assert new File(DEPLOY_DIR, "test0.txt").exists() : "missing raw file from default destination location"; + assert new File(DEPLOY_DIR, "another/foo.txt").exists() : "missing raw file from the destinationFile"; + assert new File(DEPLOY_DIR, "second.dir/test2.txt").exists() : "missing raw file from the destinationDir"; + assert !new File(DEPLOY_DIR, "test1.txt").exists() : "should not be here because destinationFile was specified"; + assert !new File(DEPLOY_DIR, "test2.txt").exists() : "should not be here because destinationFile was specified"; + assert new File(DEPLOY_DIR, "test.zip").exists() : "missing unexploded zip file"; + assert new File(DEPLOY_DIR, "test-replace.zip").exists() : "missing unexploded zip file"; + assert !new File(DEPLOY_DIR, "test-explode.zip").exists() : "should have been exploded"; + + // test that the file in the zip is realized + final String[] templateVarValue = new String[] { null }; + ZipUtil.walkZipFile(new File(DEPLOY_DIR, "test-replace.zip"), new ZipUtil.ZipEntryVisitor() { + @Override + public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception { + if (entry.getName().equals("template.txt")) { + Properties props = new Properties(); + props.load(stream); + templateVarValue[0] = props.getProperty("X"); + } + return true; + } + }); + assert templateVarValue[0] != null && templateVarValue[0].equals("9876") : templateVarValue[0]; + + // test that our raw file was realized + File realizedFile = new File(DEPLOY_DIR, "second.dir/test2.txt"); + Properties props = new Properties(); + FileInputStream inStream = new FileInputStream(realizedFile); + try { + props.load(inStream); + assert props.getProperty("X", "<unset>").equals("9876"); + } finally { + inStream.close(); + } + } finally { + FileUtil.purge(tmpUrlLocation, true); + if (downloadedFiles != null) { + for (File doomed : downloadedFiles) { + doomed.delete(); + } + } + } + } + private List<BuildListener> createBuildListeners() { List<BuildListener> buildListeners = new ArrayList<BuildListener>(); DefaultLogger logger = new DefaultLogger(); diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-url-input.properties b/modules/common/ant-bundle/src/test/resources/test-bundle-url-input.properties new file mode 100644 index 0000000..6f7b9ba --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-url-input.properties @@ -0,0 +1 @@ +X=9876 diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-url.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-url.xml new file mode 100644 index 0000000..ebfdd81 --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-url.xml @@ -0,0 +1,26 @@ +<?xml version="1.0"?> + +<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle"> + + <rhq:bundle name="test" version="1"> + + <rhq:input-property name="X" /> + + <rhq:deployment-unit name="appserver"> + <rhq:url-file url="${rhq.test.url.dir}/subdir/test0.txt" replace="false" /> + <rhq:url-file url="${rhq.test.url.dir}/subdir/test1.txt" destinationFile="another/foo.txt" replace="false" /> + <rhq:url-file url="${rhq.test.url.dir}/subdir/test2.txt" destinationDir="second.dir" replace="true" /> + <rhq:url-archive url="${rhq.test.url.dir}/subdir/test.zip" exploded="false" /> + <rhq:url-archive url="${rhq.test.url.dir}/subdir/test-explode.zip" exploded="true" /> + <rhq:url-archive url="${rhq.test.url.dir}/subdir/test-replace.zip" exploded="false"> + rhq:replace + <rhq:fileset includes="template.txt"/> + </rhq:replace> + </rhq:url-archive> + </rhq:deployment-unit> + + </rhq:bundle> + + <target name="main"/> + +</project> \ No newline at end of file diff --git a/modules/enterprise/server/plugins/ant-bundle/src/main/java/org/rhq/enterprise/server/plugins/ant/AntBundleServerPluginComponent.java b/modules/enterprise/server/plugins/ant-bundle/src/main/java/org/rhq/enterprise/server/plugins/ant/AntBundleServerPluginComponent.java index 07fcad5..82354b6 100644 --- a/modules/enterprise/server/plugins/ant-bundle/src/main/java/org/rhq/enterprise/server/plugins/ant/AntBundleServerPluginComponent.java +++ b/modules/enterprise/server/plugins/ant-bundle/src/main/java/org/rhq/enterprise/server/plugins/ant/AntBundleServerPluginComponent.java @@ -106,7 +106,7 @@ public class AntBundleServerPluginComponent implements ServerPluginComponent, Bu
// parse, but do not execute, the Ant script AntLauncher antLauncher = new AntLauncher(); - BundleAntProject project = antLauncher.parseBundleDeployFile(recipeFile); + BundleAntProject project = antLauncher.parseBundleDeployFile(recipeFile, null);
// obtain the parse results deploymentProps = new DeploymentProperties(0, project.getBundleName(), project.getBundleVersion(), project
commit 33f4acf7c1b1c118bc0e3996cb6f573ac0e636c2 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 14:40:47 2010 -0500
move the auditLog method over to the project so both our tasks and types can use it
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java index a80e61e..6fab4ba 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/BundleAntProject.java @@ -23,6 +23,7 @@ package org.rhq.bundle.ant;
import java.io.File; +import java.util.Date; import java.util.HashSet; import java.util.Set;
@@ -42,11 +43,18 @@ import org.rhq.core.util.updater.DeployDifferences; * This project object is to be used by either the bundle {@link AntLauncher} or custom * bundle Ant tasks. The launcher or tasks can inform this project object of things that * are happening as the Ant script is being parsed and/or executed. + * + * Also provides a common method for any task to invoke to send an audit message. * * @author John Mazzitelli * @author Ian Springer */ public class BundleAntProject extends Project { + // these statuses should match those of see BundleResourceDeploymentHistory.Status + public enum AuditStatus { + SUCCESS, FAILURE, WARN + }; + // Bundle-level attributes private boolean parseOnly;
@@ -153,4 +161,37 @@ public class BundleAntProject extends Project { public boolean isDryRun() { return dryRun; } + + /** + * Logs a message in a format that our audit task/agent-side audit log listener knows about. + * When running in the agent, this audit log will be sent to the server. + * It is always logged at part of the normal Ant logger mechanism. + * + * @param status SUCCESS, FAILURE or WARN + * @param action audit action, a short summary easily displayed (e.g "File Download") + * @param info information about the action target, easily displayed (e.g. "myfile.zip") + * @param message Optional, brief (one or two lines) information message + * @param details Optional, verbose data, such as full file text or long error messages/stack traces + */ + public void auditLog(AuditStatus status, String action, String info, String message, String details) { + if (status == null) { + status = AuditStatus.SUCCESS; + } + + // this will log a message with a very specific format that is understood + // by the agent-side build listener's messageLogged method: + // org.rhq.plugins.ant.DeploymentAuditorBuildListener.messageLogged(BuildEvent) + // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> + StringBuilder str = new StringBuilder("RHQ_AUDIT_MESSAGE___"); + str.append(status.name()); + str.append("___"); + str.append((action != null) ? action : "Audit Message"); + str.append("___"); + str.append((info != null) ? info : "Timestamp: " + new Date().toString()); + str.append("___"); + str.append((message != null) ? message : ""); + str.append("___"); + str.append((details != null) ? details : ""); + this.log(str.toString(), Project.MSG_INFO); + } } diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java index a95724a..f6d819a 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java @@ -18,9 +18,6 @@ */ package org.rhq.bundle.ant.task;
-import java.util.Date; - -import org.apache.tools.ant.Project; import org.apache.tools.ant.Task;
import org.rhq.bundle.ant.BundleAntProject; @@ -33,15 +30,9 @@ import org.rhq.bundle.ant.BundleAntProject; * As new tasks are created by extending this task object, developers must make sure * they add the new tasks to the bundle-ant-tasks.properties file. * - * Also provides a common method for any task to invoke to send an audit message. - * * @author John Mazzitelli */ public abstract class AbstractBundleTask extends Task { - // these statuses should match those of see BundleResourceDeploymentHistory.Status - enum AuditStatus { - SUCCESS, FAILURE, WARN - };
/** * Returns the specific {@link BundleAntProject} object that is invoking this task. @@ -54,37 +45,4 @@ public abstract class AbstractBundleTask extends Task { public BundleAntProject getProject() { return (BundleAntProject) super.getProject(); } - - /** - * Logs a message in a format that our audit task/agent-side audit log listener knows about. - * When running in the agent, this audit log will be sent to the server. - * It is always logged at part of the normal Ant logger mechanism. - * - * @param status SUCCESS, FAILURE or WARN - * @param action audit action, a short summary easily displayed (e.g "File Download") - * @param info information about the action target, easily displayed (e.g. "myfile.zip") - * @param message Optional, brief (one or two lines) information message - * @param details Optional, verbose data, such as full file text or long error messages/stack traces - */ - protected void auditLog(AuditStatus status, String action, String info, String message, String details) { - if (status == null) { - status = AuditStatus.SUCCESS; - } - - // this will log a message with a very specific format that is understood - // by the agent-side build listener's messageLogged method: - // org.rhq.plugins.ant.DeploymentAuditorBuildListener.messageLogged(BuildEvent) - // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> - StringBuilder str = new StringBuilder("RHQ_AUDIT_MESSAGE___"); - str.append(status.name()); - str.append("___"); - str.append((action != null) ? action : "Audit Message"); - str.append("___"); - str.append((info != null) ? info : "Timestamp: " + new Date().toString()); - str.append("___"); - str.append((message != null) ? message : ""); - str.append("___"); - str.append((details != null) ? details : ""); - getProject().log(str.toString(), Project.MSG_INFO); - } } \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java index a74b77c..19f284b 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java @@ -20,6 +20,8 @@ package org.rhq.bundle.ant.task;
import org.apache.tools.ant.BuildException;
+import org.rhq.bundle.ant.BundleAntProject.AuditStatus; + /** * The rhq:audit task is a way recipe authors can add their own audit messages to the stream * of audit messages that the server gets to see how the progress went with the provisioning of a bundle. @@ -44,7 +46,7 @@ public class AuditTask extends AbstractBundleTask {
@Override public void execute() throws BuildException { - auditLog(status, action, info, message, details); + getProject().auditLog(status, action, info, message, details); }
public AuditStatus getStatus() {
commit da2d86a9cc49ac57c5a0caa91b3339b8cb89d24c Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 14:25:47 2010 -0500
pull up the audit code so all tasks can emit audit messages (on the agent, this sends them to the server)
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java index eabad70..a95724a 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AbstractBundleTask.java @@ -18,6 +18,9 @@ */ package org.rhq.bundle.ant.task;
+import java.util.Date; + +import org.apache.tools.ant.Project; import org.apache.tools.ant.Task;
import org.rhq.bundle.ant.BundleAntProject; @@ -29,10 +32,17 @@ import org.rhq.bundle.ant.BundleAntProject; * * As new tasks are created by extending this task object, developers must make sure * they add the new tasks to the bundle-ant-tasks.properties file. - * + * + * Also provides a common method for any task to invoke to send an audit message. + * * @author John Mazzitelli */ public abstract class AbstractBundleTask extends Task { + // these statuses should match those of see BundleResourceDeploymentHistory.Status + enum AuditStatus { + SUCCESS, FAILURE, WARN + }; + /** * Returns the specific {@link BundleAntProject} object that is invoking this task. * This task can call methods on the returned project object to inform the project @@ -44,4 +54,37 @@ public abstract class AbstractBundleTask extends Task { public BundleAntProject getProject() { return (BundleAntProject) super.getProject(); } + + /** + * Logs a message in a format that our audit task/agent-side audit log listener knows about. + * When running in the agent, this audit log will be sent to the server. + * It is always logged at part of the normal Ant logger mechanism. + * + * @param status SUCCESS, FAILURE or WARN + * @param action audit action, a short summary easily displayed (e.g "File Download") + * @param info information about the action target, easily displayed (e.g. "myfile.zip") + * @param message Optional, brief (one or two lines) information message + * @param details Optional, verbose data, such as full file text or long error messages/stack traces + */ + protected void auditLog(AuditStatus status, String action, String info, String message, String details) { + if (status == null) { + status = AuditStatus.SUCCESS; + } + + // this will log a message with a very specific format that is understood + // by the agent-side build listener's messageLogged method: + // org.rhq.plugins.ant.DeploymentAuditorBuildListener.messageLogged(BuildEvent) + // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> + StringBuilder str = new StringBuilder("RHQ_AUDIT_MESSAGE___"); + str.append(status.name()); + str.append("___"); + str.append((action != null) ? action : "Audit Message"); + str.append("___"); + str.append((info != null) ? info : "Timestamp: " + new Date().toString()); + str.append("___"); + str.append((message != null) ? message : ""); + str.append("___"); + str.append((details != null) ? details : ""); + getProject().log(str.toString(), Project.MSG_INFO); + } } \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java index af0e60b..a74b77c 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java @@ -18,10 +18,7 @@ */ package org.rhq.bundle.ant.task;
-import java.util.Date; - import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project;
/** * The rhq:audit task is a way recipe authors can add their own audit messages to the stream @@ -34,7 +31,7 @@ import org.apache.tools.ant.Project; * @author John Mazzitelli */ public class AuditTask extends AbstractBundleTask { - private String status = "SUCCESS"; // must match one of SUCCESS, WARN, or FAILURE (see BundleResourceDeploymentHistory.Status) + private AuditStatus status = AuditStatus.SUCCESS; // see BundleResourceDeploymentHistory.Status private String action = null; private String info = null; private String message = ""; @@ -43,34 +40,27 @@ public class AuditTask extends AbstractBundleTask { @Override public void maybeConfigure() throws BuildException { super.maybeConfigure(); // inits the attribute fields - validateAttributes(); }
@Override public void execute() throws BuildException { - // this will log a message with a very specific format that is understood - // by the agent-side build listener's messageLogged method: - // org.rhq.plugins.ant.DeploymentAuditorBuildListener.messageLogged(BuildEvent) - // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> - StringBuilder str = new StringBuilder("RHQ_AUDIT_MESSAGE___"); - str.append(this.status); - str.append("___"); - str.append((this.action != null) ? this.action : "Audit Message"); - str.append("___"); - str.append((this.info != null) ? this.info : "Timestamp: " + new Date().toString()); - str.append("___"); - str.append(this.message); - str.append("___"); - str.append(this.details); - getProject().log(str.toString(), Project.MSG_INFO); + auditLog(status, action, info, message, details); }
- public String getStatus() { + public AuditStatus getStatus() { return status; }
public void setStatus(String status) { - this.status = status; + if (this.status == null) { + this.status = AuditStatus.SUCCESS; + } else { + try { + this.status = AuditStatus.valueOf(status.toUpperCase()); + } catch (Exception e) { + throw new BuildException("The 'status' attribute must be either 'SUCCESS', 'WARN' or 'FAILURE'"); + } + } }
public String getAction() { @@ -106,15 +96,4 @@ public class AuditTask extends AbstractBundleTask { this.details += getProject().replaceProperties(msg); } } - - protected void validateAttributes() throws BuildException { - if (this.status == null) { - this.status = "SUCCESS"; - } else if (!this.status.equalsIgnoreCase("SUCCESS") && !this.status.equalsIgnoreCase("FAILURE") - && !this.status.equalsIgnoreCase("WARN")) { - throw new BuildException("The 'result' attribute must be either 'SUCCESS', 'WARN' or 'FAILURE'"); - } - this.status = this.status.toUpperCase(); - } - } \ No newline at end of file
commit b89e87b60e77452da15d66459f9d752ee7c63e84 Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 13:42:38 2010 -0500
revert method signature
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 5858d84..3072708 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 @@ -37,7 +37,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert
private AlertManagerLocal alertManager = LookupUtil.getAlertManager();
- public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) throws Exception { + public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(this.alertManager.findAlertsByCriteria(getSessionSubject(), criteria), "AlertService.findAlertsByCriteria"); @@ -46,7 +46,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int deleteAlerts(int[] alertIds) throws Exception { + public int deleteAlerts(int[] alertIds) throws RuntimeException { try { return this.alertManager.deleteAlerts(getSessionSubject(), alertIds); } catch (Throwable t) { @@ -54,7 +54,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int deleteAlertsByContext(EntityContext context) throws Exception { + public int deleteAlertsByContext(EntityContext context) throws RuntimeException { try { return this.alertManager.deleteAlertsByContext(getSessionSubject(), context); } catch (Throwable t) { @@ -62,7 +62,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int acknowledgeAlerts(int[] alertIds) throws Exception { + public int acknowledgeAlerts(int[] alertIds) throws RuntimeException { try { return this.alertManager.acknowledgeAlerts(getSessionSubject(), alertIds); } catch (Throwable t) { @@ -70,7 +70,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int acknowledgeAlertsByContext(EntityContext context) throws Exception { + public int acknowledgeAlertsByContext(EntityContext context) throws RuntimeException { try { return this.alertManager.acknowledgeAlertsByContext(getSessionSubject(), context); } catch (Throwable t) {
commit 77e1b14f5f782fbd44e5a738d4581a26ec64513b Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 12:59:58 2010 -0500
test out suppression of table header for those with search bars
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 fcc5909..78fb5db 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 @@ -432,6 +432,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements }
public void setFilterFormItems(FormItem... formItems) { + setShowHeader(false); this.filterForm.setItems(formItems); }
commit 264e845a22ba36bdaa62f4d21f0237b15219dcaa Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 12:52:26 2010 -0500
declare services to throw exceptions so they are properly gwt-serialized
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 05b813f..f79fa9d 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 @@ -30,20 +30,20 @@ public interface AlertDefinitionGWTService extends RemoteService {
PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria);
- int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception; + int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws RuntimeException;
AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, - boolean updateInternals) throws Exception; + boolean updateInternals) throws RuntimeException;
- int enableAlertDefinitions(int[] alertDefinitionIds) throws Exception; + int enableAlertDefinitions(int[] alertDefinitionIds) throws RuntimeException;
- int disableAlertDefinitions(int[] alertDefinitionIds) throws Exception; + int disableAlertDefinitions(int[] alertDefinitionIds) throws RuntimeException;
- int removeAlertDefinitions(int[] alertDefinitionIds) throws Exception; + int removeAlertDefinitions(int[] alertDefinitionIds) throws RuntimeException;
- String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws Exception; + String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws RuntimeException;
- String[] getAllAlertSenders() throws Exception; + String[] getAllAlertSenders() throws RuntimeException;
- ConfigurationDefinition getConfigurationDefinitionForSender(String sender) throws Exception; + ConfigurationDefinition getConfigurationDefinitionForSender(String sender) throws RuntimeException; } \ No newline at end of file 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 a8fd51a..8cbd431 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 @@ -37,7 +37,7 @@ public interface AlertGWTService extends RemoteService { * * @return all alerts that match the specified criteria */ - PageList<Alert> findAlertsByCriteria(AlertCriteria criteria); + PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) throws RuntimeException;
/** * Delete the alerts with the specified ids if the current user has permission to do so (i.e. either @@ -50,7 +50,7 @@ public interface AlertGWTService extends RemoteService { * @param alertIds the ids of the alerts to be deleted * @return the number of alerts deleted */ - int deleteAlerts(int[] alertIds); + int deleteAlerts(int[] alertIds) throws RuntimeException;
/** * Deletes all alerts for the given context if the current user has permission to do so (i.e., either @@ -62,7 +62,7 @@ public interface AlertGWTService extends RemoteService { * the user * @return the number of alerts deleted */ - int deleteAlertsByContext(EntityContext context); + int deleteAlertsByContext(EntityContext context) throws RuntimeException;
/** * Acknowledges the alerts with the specified ids if the current user has permission to do so (i.e., either @@ -75,7 +75,7 @@ public interface AlertGWTService extends RemoteService { * @param alertIds the ids of the alerts to be acknowledged * @return the number of alerts acknowledged */ - int acknowledgeAlerts(int[] alertIds); + int acknowledgeAlerts(int[] alertIds) throws RuntimeException;
/** * Acknowledges all alerts for the given context if the current user has permission to do so (i.e., either @@ -87,5 +87,5 @@ public interface AlertGWTService extends RemoteService { * the user * @return the number of alerts acknowledged */ - int acknowledgeAlertsByContext(EntityContext context); + int acknowledgeAlertsByContext(EntityContext context) throws RuntimeException; } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertTemplateGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertTemplateGWTService.java index da8bf55..9f079cb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertTemplateGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AlertTemplateGWTService.java @@ -34,11 +34,12 @@ public interface AlertTemplateGWTService extends RemoteService { * @return the updated definition * @throws Exception */ - AlertDefinition updateAlertTemplate(AlertDefinition alertDefinition, boolean purgeInternals) throws Exception; + AlertDefinition updateAlertTemplate(AlertDefinition alertDefinition, boolean purgeInternals) + throws RuntimeException;
- void enableAlertTemplates(Integer[] alertDefinitionIds) throws Exception; + void enableAlertTemplates(Integer[] alertDefinitionIds) throws RuntimeException;
- void disableAlertTemplates(Integer[] alertDefinitionIds) throws Exception; + void disableAlertTemplates(Integer[] alertDefinitionIds) throws RuntimeException;
- void removeAlertTemplates(Integer[] alertDefinitionIds) throws Exception; + void removeAlertTemplates(Integer[] alertDefinitionIds) throws RuntimeException; } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AuthorizationGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AuthorizationGWTService.java index 13b5572..249a655 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AuthorizationGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AuthorizationGWTService.java @@ -36,7 +36,7 @@ public interface AuthorizationGWTService extends RemoteService { * * @return the set of permissions that the current user possesses for the specified {@link org.rhq.core.domain.resource.Resource} - never null */ - Set<Permission> getExplicitResourcePermissions(int resourceId); + Set<Permission> getExplicitResourcePermissions(int resourceId) throws RuntimeException;
/** * Gets the set of permissions that the current user implicitly possesses for the specified {@link org.rhq.core.domain.resource.Resource}. @@ -45,7 +45,7 @@ public interface AuthorizationGWTService extends RemoteService { * * @return the set of permissions that the current user implicitly possesses for the specified {@link org.rhq.core.domain.resource.Resource} - never null */ - Set<Permission> getImplicitResourcePermissions(int resourceId); + Set<Permission> getImplicitResourcePermissions(int resourceId) throws RuntimeException;
/** * Gets the set of permissions that the current user explicitly possesses for the specified {@link org.rhq.core.domain.resource.group.Group}. @@ -54,7 +54,7 @@ public interface AuthorizationGWTService extends RemoteService { * * @return the set of permissions that the current user explicitly possesses for the specified {@link org.rhq.core.domain.resource.group.Group} - never null */ - Set<Permission> getExplicitGroupPermissions(int groupId); + Set<Permission> getExplicitGroupPermissions(int groupId) throws RuntimeException;
/** * Gets the set of permissions that the current user implicitly possesses for the specified {@link org.rhq.core.domain.resource.group.Group}. @@ -63,13 +63,13 @@ public interface AuthorizationGWTService extends RemoteService { * * @return the set of permissions that the current user implicitly possesses for the specified {@link org.rhq.core.domain.resource.group.Group} */ - Set<Permission> getImplicitGroupPermissions(int groupId); + Set<Permission> getImplicitGroupPermissions(int groupId) throws RuntimeException;
/** * Gets the set of global permissions that the current user explicitly possesses. * * @return the set of global permissions that the current user possesses - never null */ - Set<Permission> getExplicitGlobalPermissions(); + Set<Permission> getExplicitGlobalPermissions() throws RuntimeException;
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AvailabilityGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AvailabilityGWTService.java index fcb5a29..f657b9d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AvailabilityGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/AvailabilityGWTService.java @@ -20,7 +20,6 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
import com.google.gwt.user.client.rpc.RemoteService;
-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; @@ -30,7 +29,6 @@ import org.rhq.core.domain.util.PageList; */ public interface AvailabilityGWTService extends RemoteService {
- - PageList<Availability> findAvailabilityForResource(int resourceId, PageControl pc); + PageList<Availability> findAvailabilityForResource(int resourceId, PageControl pc) throws RuntimeException;
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java index 0f58c44..4c7b209 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java @@ -42,53 +42,58 @@ import org.rhq.core.domain.util.PageList;
public interface BundleGWTService extends RemoteService {
- BundleVersion createBundleVersion(int bundleId, String name, String version, String recipe) throws Exception; + BundleVersion createBundleVersion(int bundleId, String name, String version, String recipe) throws RuntimeException;
- BundleVersion createBundleVersionViaURL(String url) throws Exception; + BundleVersion createBundleVersionViaURL(String url) throws RuntimeException;
- BundleVersion createBundleVersionViaRecipe(String recipe) throws Exception; + BundleVersion createBundleVersionViaRecipe(String recipe) throws RuntimeException;
BundleDeployment createBundleDeployment(int bundleVersionId, int bundleDestinationId, String description, Configuration configuration, boolean enforcePolicy, int enforcementInterval, boolean pinToBundle) - throws Exception; + throws RuntimeException;
BundleDestination createBundleDestination(int bundleId, String name, String description, String deployDir, - int groupId) throws Exception; + int groupId) throws RuntimeException;
- void deleteBundles(int[] bundleIds) throws Exception; + void deleteBundles(int[] bundleIds) throws RuntimeException;
- void deleteBundle(int bundleId) throws Exception; + void deleteBundle(int bundleId) throws RuntimeException;
- void deleteBundleDeployment(int bundleDeploymentId) throws Exception; + void deleteBundleDeployment(int bundleDeploymentId) throws RuntimeException;
- void deleteBundleDestination(int bundleDestinationId) throws Exception; + void deleteBundleDestination(int bundleDestinationId) throws RuntimeException;
- void deleteBundleVersion(int bundleVersionId, boolean deleteBundleIfEmpty) throws Exception; + void deleteBundleVersion(int bundleVersionId, boolean deleteBundleIfEmpty) throws RuntimeException;
- PageList<Bundle> findBundlesByCriteria(BundleCriteria criteria) throws Exception; + PageList<Bundle> findBundlesByCriteria(BundleCriteria criteria) throws RuntimeException;
- PageList<BundleDeployment> findBundleDeploymentsByCriteria(BundleDeploymentCriteria criteria); + PageList<BundleDeployment> findBundleDeploymentsByCriteria(BundleDeploymentCriteria criteria) + throws RuntimeException;
- PageList<BundleDestination> findBundleDestinationsByCriteria(BundleDestinationCriteria criteria); + PageList<BundleDestination> findBundleDestinationsByCriteria(BundleDestinationCriteria criteria) + throws RuntimeException;
- PageList<BundleFile> findBundleFilesByCriteria(BundleFileCriteria criteria); + PageList<BundleFile> findBundleFilesByCriteria(BundleFileCriteria criteria) throws RuntimeException;
- PageList<BundleResourceDeployment> findBundleResourceDeploymentsByCriteria(BundleResourceDeploymentCriteria criteria); + PageList<BundleResourceDeployment> findBundleResourceDeploymentsByCriteria(BundleResourceDeploymentCriteria criteria) + throws RuntimeException;
- PageList<BundleVersion> findBundleVersionsByCriteria(BundleVersionCriteria criteria) throws Exception; + PageList<BundleVersion> findBundleVersionsByCriteria(BundleVersionCriteria criteria) throws RuntimeException;
PageList<BundleWithLatestVersionComposite> findBundlesWithLatestVersionCompositesByCriteria(BundleCriteria criteria) - throws Exception; + throws RuntimeException;
- HashMap<String, Boolean> getAllBundleVersionFilenames(int bundleVersionId) throws Exception; + HashMap<String, Boolean> getAllBundleVersionFilenames(int bundleVersionId) throws RuntimeException;
- ArrayList<BundleType> getAllBundleTypes() throws Exception; + ArrayList<BundleType> getAllBundleTypes() throws RuntimeException;
- String getBundleDeploymentName(int bundleDestinationId, int bundleVersionId, int prevDeploymentId); + String getBundleDeploymentName(int bundleDestinationId, int bundleVersionId, int prevDeploymentId) + throws RuntimeException;
- BundleDeployment scheduleBundleDeployment(int bundleDeploymentId, boolean isCleanDeployment) throws Exception; + BundleDeployment scheduleBundleDeployment(int bundleDeploymentId, boolean isCleanDeployment) + throws RuntimeException;
BundleDeployment scheduleRevertBundleDeployment(int bundleDestinationId, String deploymentDescription, - boolean isCleanDeployment) throws Exception; + boolean isCleanDeployment) throws RuntimeException;
} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ClusterGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ClusterGWTService.java index 20d32d5..de16309 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ClusterGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ClusterGWTService.java @@ -36,7 +36,6 @@ import org.rhq.core.domain.resource.group.composite.ClusterFlyweight; */ public interface ClusterGWTService extends RemoteService {
- /** * Given a cluster key create a backing group. * @param clusterKey @@ -44,7 +43,7 @@ public interface ClusterGWTService extends RemoteService { * Otherwise no resources will be assigned to the new group. * @throws IllegalArgumentException if a backing group exists for this clusterKey */ - ResourceGroup createAutoClusterBackingGroup(ClusterKey clusterKey, boolean addResources); + ResourceGroup createAutoClusterBackingGroup(ClusterKey clusterKey, boolean addResources) throws RuntimeException;
/** * Return the backing group for the supplied cluster key. Resource membership will represent the resources @@ -52,17 +51,15 @@ public interface ClusterGWTService extends RemoteService { * @param clusterKey * @return The backing group, or null if the key does not have a backing group. */ - ResourceGroup getAutoClusterBackingGroup(ClusterKey clusterKey); + ResourceGroup getAutoClusterBackingGroup(ClusterKey clusterKey) throws RuntimeException;
/** * Given a cluster key get the auto cluster resource membership. The membership is always determined * at call time, regardless of whether a backing group exists. To get the backing group, if it exists, * for a cluster key then call {@link #getAutoClusterBackingGroup(String)}. */ - List<Resource> getAutoClusterResources(ClusterKey clusterKey); - - - ClusterFlyweight getClusterTree(int groupId); + List<Resource> getAutoClusterResources(ClusterKey clusterKey) throws RuntimeException;
+ ClusterFlyweight getClusterTree(int groupId) throws RuntimeException;
} 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 5b8c09f..b0ca09b 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 @@ -25,46 +25,55 @@ import org.rhq.core.domain.util.PageList; */ @RemoteServiceRelativePath("ConfigurationGWTService") public interface ConfigurationGWTService extends RemoteService { - Configuration getPluginConfiguration(int resourceId); + Configuration getPluginConfiguration(int resourceId) throws RuntimeException;
- ConfigurationDefinition getPluginConfigurationDefinition(int resourceTypeId); + ConfigurationDefinition getPluginConfigurationDefinition(int resourceTypeId) throws RuntimeException;
- Configuration getResourceConfiguration(int resourceId); + Configuration getResourceConfiguration(int resourceId) throws RuntimeException;
- ConfigurationDefinition getResourceConfigurationDefinition(int resourceTypeId); + ConfigurationDefinition getResourceConfigurationDefinition(int resourceTypeId) throws RuntimeException;
PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdates(Integer resourceId, Long beginDate, - Long endDate, boolean suppressOldest, PageControl pc); + Long endDate, boolean suppressOldest, PageControl pc) throws RuntimeException;
- ResourceConfigurationUpdate updateResourceConfiguration(int resourceId, Configuration configuration); + ResourceConfigurationUpdate updateResourceConfiguration(int resourceId, Configuration configuration) + throws RuntimeException;
- PluginConfigurationUpdate updatePluginConfiguration(int resourceId, Configuration configuration); + PluginConfigurationUpdate updatePluginConfiguration(int resourceId, Configuration configuration) + throws RuntimeException;
PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdatesByCriteria( - ResourceConfigurationUpdateCriteria criteria); + ResourceConfigurationUpdateCriteria criteria) throws RuntimeException;
PageList<PluginConfigurationUpdate> findPluginConfigurationUpdatesByCriteria( - PluginConfigurationUpdateCriteria criteria); + PluginConfigurationUpdateCriteria criteria) throws RuntimeException;
PageList<GroupResourceConfigurationUpdate> findGroupResourceConfigurationUpdatesByCriteria( - GroupResourceConfigurationUpdateCriteria criteria); + GroupResourceConfigurationUpdateCriteria criteria) throws RuntimeException;
PageList<GroupPluginConfigurationUpdate> findGroupPluginConfigurationUpdatesByCriteria( - GroupPluginConfigurationUpdateCriteria criteria); + GroupPluginConfigurationUpdateCriteria criteria) throws RuntimeException;
- List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup(int groupId); + List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup(int groupId) + throws RuntimeException;
- List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroup(int groupId); + List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroup(int groupId) + throws RuntimeException;
- List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroupUpdate(int groupUpdateId); + List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroupUpdate(int groupUpdateId) + throws RuntimeException;
- void updateResourceConfigurationsForGroup(int groupId, List<ResourceConfigurationComposite> resourceConfigurations); + void updateResourceConfigurationsForGroup(int groupId, List<ResourceConfigurationComposite> resourceConfigurations) + throws RuntimeException;
- void updatePluginConfigurationsForGroup(int groupId, List<ResourceConfigurationComposite> pluginConfigurations); + void updatePluginConfigurationsForGroup(int groupId, List<ResourceConfigurationComposite> pluginConfigurations) + throws RuntimeException;
- void deleteGroupPluginConfigurationUpdate(Integer groupId, Integer[] groupPluginConfigUpdateIds); + void deleteGroupPluginConfigurationUpdate(Integer groupId, Integer[] groupPluginConfigUpdateIds) + throws RuntimeException;
- void deleteGroupResourceConfigurationUpdate(Integer groupId, Integer[] groupResourceConfigUpdateIds); + void deleteGroupResourceConfigurationUpdate(Integer groupId, Integer[] groupResourceConfigUpdateIds) + throws RuntimeException;
- //RawConfiguration dummy(RawConfiguration config); + //RawConfiguration dummy(RawConfiguration config) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ContentGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ContentGWTService.java index 9ca5c51..a8da933 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ContentGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ContentGWTService.java @@ -37,11 +37,11 @@ import org.rhq.core.domain.util.PageList; */ public interface ContentGWTService extends RemoteService {
- void deletePackageVersion(int packageVersionId); + void deletePackageVersion(int packageVersionId) throws RuntimeException;
- PageList<PackageVersion> findPackageVersionsByCriteria(PackageVersionCriteria criteria); + PageList<PackageVersion> findPackageVersionsByCriteria(PackageVersionCriteria criteria) throws RuntimeException;
- List<Architecture> getArchitectures(); + List<Architecture> getArchitectures() throws RuntimeException;
- PackageType getResourceCreationPackageType(int resourceTypeId); + PackageType getResourceCreationPackageType(int resourceTypeId) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DashboardGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DashboardGWTService.java index da86756..f56b97a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DashboardGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DashboardGWTService.java @@ -26,7 +26,6 @@ import java.util.List;
import com.google.gwt.user.client.rpc.RemoteService;
-import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.dashboard.Dashboard;
/** @@ -34,14 +33,12 @@ import org.rhq.core.domain.dashboard.Dashboard; */ public interface DashboardGWTService extends RemoteService {
+ List<Dashboard> findDashboardsForSubject() throws RuntimeException;
- List<Dashboard> findDashboardsForSubject(); + List<Dashboard> findSharedDashboards() throws RuntimeException;
- List<Dashboard> findSharedDashboards(); - - Dashboard storeDashboard(Dashboard dashboard); - - void removeDashboard(int dashboardId); + Dashboard storeDashboard(Dashboard dashboard) throws RuntimeException;
+ void removeDashboard(int dashboardId) throws RuntimeException;
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/EventGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/EventGWTService.java index 5846d8d..ebe1326 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/EventGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/EventGWTService.java @@ -39,18 +39,19 @@ import org.rhq.core.domain.util.PageList; */ public interface EventGWTService extends RemoteService {
- EventSeverity[] getSeverityBuckets(int resourceId, long begin, long end, int numBuckets); + EventSeverity[] getSeverityBuckets(int resourceId, long begin, long end, int numBuckets) throws RuntimeException;
EventSeverity[] getSeverityBucketsForAutoGroup(int parentResourceId, int resourceTypeId, long begin, long end, - int numBuckets); + int numBuckets) throws RuntimeException;
- EventSeverity[] getSeverityBucketsForCompGroup(int resourceGroupId, long begin, long end, int numBuckets); + EventSeverity[] getSeverityBucketsForCompGroup(int resourceGroupId, long begin, long end, int numBuckets) + throws RuntimeException;
- PageList<Event> findEventsByCriteria(EventCriteria criteria); + PageList<Event> findEventsByCriteria(EventCriteria criteria) throws RuntimeException;
- PageList<EventComposite> findEventCompositesByCriteria(EventCriteria criteria); + PageList<EventComposite> findEventCompositesByCriteria(EventCriteria criteria) throws RuntimeException;
- int deleteEventsForContext(EntityContext context, List<Integer> eventIds); + int deleteEventsForContext(EntityContext context, List<Integer> eventIds) throws RuntimeException;
- int purgeEventsForContext(EntityContext context); + int purgeEventsForContext(EntityContext context) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GroupAlertDefinitionGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GroupAlertDefinitionGWTService.java index ff4299e..55e355d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GroupAlertDefinitionGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GroupAlertDefinitionGWTService.java @@ -24,7 +24,8 @@ import org.rhq.core.domain.alert.AlertDefinition;
public interface GroupAlertDefinitionGWTService extends RemoteService {
- int createGroupAlertDefinitions(AlertDefinition groupAlertDefinition, Integer resourceGroupId) throws Exception; + int createGroupAlertDefinitions(AlertDefinition groupAlertDefinition, Integer resourceGroupId) + throws RuntimeException;
/** * Updates a group alert definition. @@ -35,11 +36,11 @@ public interface GroupAlertDefinitionGWTService extends RemoteService { * @throws Exception */ AlertDefinition updateGroupAlertDefinitions(AlertDefinition groupAlertDefinition, boolean purgeInternals) - throws Exception; + throws RuntimeException;
- int enableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws Exception; + int enableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws RuntimeException;
- int disableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws Exception; + int disableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws RuntimeException;
- int removeGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws Exception; + int removeGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws RuntimeException; } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/LdapGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/LdapGWTService.java index 673f3c7..8356773 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/LdapGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/LdapGWTService.java @@ -39,12 +39,12 @@ public interface LdapGWTService extends RemoteService { /** * @return Map with all LDAP groups available */ - Set<Map<String, String>> findAvailableGroups(); + Set<Map<String, String>> findAvailableGroups() throws RuntimeException;
/** * @return Map with LDAP details for user passed. */ - Map<String, String> getLdapDetailsFor(String user); + Map<String, String> getLdapDetailsFor(String user) throws RuntimeException;
/** In setting the LDAP groups for this role, all previous group * assignments for this role are removed before most up to date @@ -53,19 +53,19 @@ public interface LdapGWTService extends RemoteService { * @param roleId * @param groupIds */ - void setLdapGroupsForRole(int roleId, List<String> groupIds); + void setLdapGroupsForRole(int roleId, List<String> groupIds) throws RuntimeException;
/** Finds ldap groups already assigned to this role. * * @param currentRoleId * @return */ - PageList<LdapGroup> findLdapGroupsAssignedToRole(int currentRoleId); + PageList<LdapGroup> findLdapGroupsAssignedToRole(int currentRoleId) throws RuntimeException;
/** Boolean response about whether ldap configured.. * * @return */ - Boolean checkLdapConfiguredStatus(); + Boolean checkLdapConfiguredStatus() throws RuntimeException;
} 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 4c145b7..0ecd8a4 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,7 +24,6 @@ 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; @@ -47,46 +46,55 @@ import org.rhq.core.domain.util.PageList; @RemoteServiceRelativePath("MeasurementDataGWTService") public interface MeasurementDataGWTService extends RemoteService {
- List<MeasurementDataTrait> findCurrentTraitsForResource(int resourceId, DisplayType displayType); + List<MeasurementDataTrait> findCurrentTraitsForResource(int resourceId, DisplayType displayType) + throws RuntimeException;
- Set<MeasurementData> findLiveData(int resourceId, int[] definitionIds); + Set<MeasurementData> findLiveData(int resourceId, int[] definitionIds) throws RuntimeException;
List<List<MeasurementDataNumericHighLowComposite>> findDataForResource(int resourceId, int[] definitionIds, - long beginTime, long endTime, int numPoints); + long beginTime, long endTime, int numPoints) throws RuntimeException;
PageList<CallTimeDataComposite> findCallTimeDataForResource(int scheduleId, long start, long end, - PageControl pageControl); + PageControl pageControl) throws RuntimeException;
- PageList<MeasurementDefinition> findMeasurementDefinitionsByCriteria(MeasurementDefinitionCriteria criteria); + PageList<MeasurementDefinition> findMeasurementDefinitionsByCriteria(MeasurementDefinitionCriteria criteria) + throws RuntimeException;
- PageList<MeasurementSchedule> findMeasurementSchedulesByCriteria(MeasurementScheduleCriteria criteria); + PageList<MeasurementSchedule> findMeasurementSchedulesByCriteria(MeasurementScheduleCriteria criteria) + throws RuntimeException;
- PageList<MeasurementScheduleComposite> getMeasurementScheduleCompositesByContext(EntityContext context); + PageList<MeasurementScheduleComposite> getMeasurementScheduleCompositesByContext(EntityContext context) + throws RuntimeException;
- PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, - String resourceNameFilter, String parentNameFilter, PageControl pc); + PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, String resourceNameFilter, + String parentNameFilter, PageControl pc) throws RuntimeException;
- PageList<MeasurementOOBComposite> getHighestNOOBsForResource(int resourceId, int n); + PageList<MeasurementOOBComposite> getHighestNOOBsForResource(int resourceId, int n) throws RuntimeException;
- void enableSchedulesForResource(int resourceId, int[] measurementDefinitionIds); + void enableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) throws RuntimeException;
- void disableSchedulesForResource(int resourceId, int[] measurementDefinitionIds); + void disableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) throws RuntimeException;
- void updateSchedulesForResource(int resourceId, int[] measurementDefinitionIds, long collectionInterval); + void updateSchedulesForResource(int resourceId, int[] measurementDefinitionIds, long collectionInterval) + throws RuntimeException;
- void enableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds); + void enableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) throws RuntimeException;
- void disableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds); + void disableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) + throws RuntimeException;
- void updateSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds, long collectionInterval); + void updateSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds, long collectionInterval) + throws RuntimeException;
- void enableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules); + void enableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules) + throws RuntimeException;
- void disableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules); + void disableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules) + throws RuntimeException;
void updateSchedulesForResourceType(int[] measurementDefinitionIds, long collectionInterval, - boolean updateExistingSchedules); + boolean updateExistingSchedules) throws RuntimeException; + + PageList<MeasurementDataTrait> findTraitsByCriteria(MeasurementDataTraitCriteria criteria) throws RuntimeException;
- PageList<MeasurementDataTrait> findTraitsByCriteria(MeasurementDataTraitCriteria criteria); - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java index badd227..dd52adc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java @@ -33,7 +33,6 @@ import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedCom import org.rhq.core.domain.operation.composite.ResourceOperationScheduleComposite; import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.util.PageList; -import org.rhq.core.util.exception.ThrowableUtil;
/** * @author Greg Hinkle @@ -41,22 +40,25 @@ import org.rhq.core.util.exception.ThrowableUtil; public interface OperationGWTService extends RemoteService {
PageList<ResourceOperationHistory> findResourceOperationHistoriesByCriteria( - ResourceOperationHistoryCriteria criteria); + ResourceOperationHistoryCriteria criteria) throws RuntimeException;
- PageList<GroupOperationHistory> findGroupOperationHistoriesByCriteria(GroupOperationHistoryCriteria criteria); + PageList<GroupOperationHistory> findGroupOperationHistoriesByCriteria(GroupOperationHistoryCriteria criteria) + throws RuntimeException;
- List<DisambiguationReport<ResourceOperationLastCompletedComposite>> findRecentCompletedOperations(int pageSize); + List<DisambiguationReport<ResourceOperationLastCompletedComposite>> findRecentCompletedOperations(int pageSize) + throws RuntimeException;
- List<DisambiguationReport<ResourceOperationScheduleComposite>> findScheduledOperations(int pageSize); + List<DisambiguationReport<ResourceOperationScheduleComposite>> findScheduledOperations(int pageSize) + throws RuntimeException;
- void invokeResourceOperation(int resourceId, String operationName, Configuration parameters, - String description, int timeout) throws RuntimeException; + void invokeResourceOperation(int resourceId, String operationName, Configuration parameters, String description, + int timeout) throws RuntimeException;
- void scheduleResourceOperation(int resourceId, String operationName, Configuration parameters, - String description, int timeout, String cronString) throws RuntimeException; + void scheduleResourceOperation(int resourceId, String operationName, Configuration parameters, String description, + int timeout, String cronString) throws RuntimeException;
List<ResourceOperationSchedule> findScheduledResourceOperations(int resourceId) throws RuntimeException;
List<GroupOperationSchedule> findScheduledGroupOperations(int groupId) throws RuntimeException; - + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RemoteInstallGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RemoteInstallGWTService.java index bd76bf9..6cd207b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RemoteInstallGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RemoteInstallGWTService.java @@ -36,17 +36,17 @@ import org.rhq.core.domain.install.remote.RemoteAccessInfo; public interface RemoteInstallGWTService extends RemoteService {
// --- RemoteInstallManagerRemote - boolean agentInstallCheck(RemoteAccessInfo remoteAccessInfo, String agentInstallPath); + boolean agentInstallCheck(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException;
- AgentInstallInfo installAgent(RemoteAccessInfo remoteAccessInfo, String parentPath); + AgentInstallInfo installAgent(RemoteAccessInfo remoteAccessInfo, String parentPath) throws RuntimeException;
- String startAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath); + String startAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException;
- String stopAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath); + String stopAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException;
- String agentStatus(RemoteAccessInfo remoteAccessInfo, String agentInstallPath); + String agentStatus(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException;
- String findAgentInstallPath(RemoteAccessInfo remoteAccessInfo, String parentPath); + String findAgentInstallPath(RemoteAccessInfo remoteAccessInfo, String parentPath) throws RuntimeException;
- String[] remotePathDiscover(RemoteAccessInfo remoteAccessInfo, String parentPath); + String[] remotePathDiscover(RemoteAccessInfo remoteAccessInfo, String parentPath) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java index b8a0a6e..1f52491 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java @@ -33,6 +33,6 @@ import org.rhq.core.domain.util.PageList; */ public interface RepoGWTService extends RemoteService {
- PageList<Repo> findReposByCriteria(RepoCriteria criteria) throws Exception; + PageList<Repo> findReposByCriteria(RepoCriteria criteria) throws RuntimeException;
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceBossGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceBossGWTService.java index a114335..30531ad 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceBossGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceBossGWTService.java @@ -24,6 +24,7 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
import com.google.gwt.user.client.rpc.RemoteService; + import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.resource.InventorySummary;
@@ -31,9 +32,9 @@ import org.rhq.core.domain.resource.InventorySummary; * @author John Sanda */ public interface ResourceBossGWTService extends RemoteService { - - InventorySummary getInventorySummaryForLoggedInUser();
- InventorySummary getInventorySummary(Subject user); + InventorySummary getInventorySummaryForLoggedInUser() throws RuntimeException; + + InventorySummary getInventorySummary(Subject user) throws RuntimeException;
} 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 f0daa9d..68e5342 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 @@ -44,39 +44,42 @@ import org.rhq.core.domain.util.PageList; public interface ResourceGWTService extends RemoteService {
void createResource(int parentResourceId, int newResourceTypeId, String newResourceName, - Configuration newResourceConfiguration); + Configuration newResourceConfiguration) throws RuntimeException;
void createResource(int parentResourceId, int newResourceTypeId, String newResourceName, - Configuration deploymentTimeConfiguration, int packageVersionId); + Configuration deploymentTimeConfiguration, int packageVersionId) throws RuntimeException;
- List<DeleteResourceHistory> deleteResources(int[] resourceIds); + List<DeleteResourceHistory> deleteResources(int[] resourceIds) throws RuntimeException;
- List<RecentlyAddedResourceComposite> findRecentlyAddedResources(long ctime, int maxItems); + List<RecentlyAddedResourceComposite> findRecentlyAddedResources(long ctime, int maxItems) throws RuntimeException;
- PageList<Resource> findResourcesByCriteria(ResourceCriteria criteria); + PageList<Resource> findResourcesByCriteria(ResourceCriteria criteria) throws RuntimeException;
- PageList<ResourceComposite> findResourceCompositesByCriteria(ResourceCriteria criteria); + PageList<ResourceComposite> findResourceCompositesByCriteria(ResourceCriteria criteria) throws RuntimeException;
- List<ResourceError> findResourceErrors(int resourceId); + List<ResourceError> findResourceErrors(int resourceId) throws RuntimeException;
- List<DisambiguationReport<ProblemResourceComposite>> findProblemResources(long ctime, int maxItems); + List<DisambiguationReport<ProblemResourceComposite>> findProblemResources(long ctime, int maxItems) + throws RuntimeException;
- Resource getPlatformForResource(int resourceId); + Resource getPlatformForResource(int resourceId) throws RuntimeException;
- Map<Resource, List<Resource>> getQueuedPlatformsAndServers(HashSet<InventoryStatus> statuses, PageControl pc); + Map<Resource, List<Resource>> getQueuedPlatformsAndServers(HashSet<InventoryStatus> statuses, PageControl pc) + throws RuntimeException;
- List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId); + List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId) throws RuntimeException;
- void ignoreResources(int[] resourceIds); + void ignoreResources(int[] resourceIds) throws RuntimeException;
- void importResources(int[] resourceIds); + void importResources(int[] resourceIds) throws RuntimeException;
- Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration); + Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration) + throws RuntimeException;
- void updateResource(Resource resource); + void updateResource(Resource resource) throws RuntimeException;
- void unignoreResources(int[] resourceIds); + void unignoreResources(int[] resourceIds) throws RuntimeException;
- List<Integer> uninventoryResources(int[] resourceIds); + List<Integer> uninventoryResources(int[] resourceIds) throws RuntimeException;
} 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 17c0f6c..bd196fc 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 @@ -35,7 +35,7 @@ import org.rhq.core.domain.util.PageList; @RemoteServiceRelativePath("ResourceGroupGWTService") public interface ResourceGroupGWTService extends RemoteService {
- GroupDefinition createGroupDefinition(GroupDefinition groupDefinition); + GroupDefinition createGroupDefinition(GroupDefinition groupDefinition) throws RuntimeException;
/** * The owner will be set to the session subject. @@ -43,31 +43,34 @@ public interface ResourceGroupGWTService extends RemoteService { * @param resourceIds initial members * @return */ - ResourceGroup createPrivateResourceGroup(ResourceGroup group, int[] resourceIds); + ResourceGroup createPrivateResourceGroup(ResourceGroup group, int[] resourceIds) throws RuntimeException;
- ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds); + ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds) throws RuntimeException;
- void deleteGroupDefinitions(int[] groupDefinitionIds); + void deleteGroupDefinitions(int[] groupDefinitionIds) throws RuntimeException;
- void deleteResourceGroups(int[] groupIds); + void deleteResourceGroups(int[] groupIds) throws RuntimeException;
- PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria); + PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria) + throws RuntimeException;
- PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria); + PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria) throws RuntimeException;
- PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria); + PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria) + throws RuntimeException;
- void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType); + void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType) + throws RuntimeException;
- void setAssignedResources(int groupId, int[] resourceIds, boolean setType); + void setAssignedResources(int groupId, int[] resourceIds, boolean setType) throws RuntimeException;
- void recalculateGroupDefinitions(int[] groupDefinitionIds); + void recalculateGroupDefinitions(int[] groupDefinitionIds) throws RuntimeException;
- void updateGroupDefinition(GroupDefinition groupDefinition); + void updateGroupDefinition(GroupDefinition groupDefinition) throws RuntimeException;
- void updateResourceGroup(ResourceGroup group); + void updateResourceGroup(ResourceGroup group) throws RuntimeException;
- void updateResourceGroup(ResourceGroup group, boolean updateMembership); + void updateResourceGroup(ResourceGroup group, boolean updateMembership) throws RuntimeException;
- void setRecursive(int groupId, boolean isRecursive) throws Exception; + void setRecursive(int groupId, boolean isRecursive) throws RuntimeException; } \ No newline at end of file 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 9d4e471..87a6dec 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 @@ -15,13 +15,13 @@ import org.rhq.core.domain.util.PageList; @RemoteServiceRelativePath("ResourceTypeGWTService") public interface ResourceTypeGWTService extends RemoteService {
- PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria); + PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria) throws RuntimeException;
- ArrayList<ResourceType> getResourceTypesForResourceAncestors(int resourceId); + ArrayList<ResourceType> getResourceTypesForResourceAncestors(int resourceId) throws RuntimeException;
- ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId); + ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId) throws RuntimeException;
- HashMap<Integer, String> getResourceTypeDescendantsWithOperations(int resourceTypeId); + HashMap<Integer, String> getResourceTypeDescendantsWithOperations(int resourceTypeId) throws RuntimeException;
- Map<Integer, ResourceTypeTemplateCountComposite> getTemplateCountCompositeMap(); + Map<Integer, ResourceTypeTemplateCountComposite> getTemplateCountCompositeMap() throws RuntimeException; } 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 1502c16..c2fdcc4 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 @@ -29,17 +29,17 @@ import org.rhq.core.domain.util.PageList; */ public interface RoleGWTService extends RemoteService {
- PageList<Role> findRolesByCriteria(RoleCriteria criteria); + PageList<Role> findRolesByCriteria(RoleCriteria criteria) throws RuntimeException;
- Role createRole(Role role); + Role createRole(Role role) throws RuntimeException;
- Role updateRole(Role role); + Role updateRole(Role role) throws RuntimeException;
- void removeRoles(int[] roleIds); + void removeRoles(int[] roleIds) throws RuntimeException;
- void setAssignedResourceGroups(int roleId, int[] resourceGroupIds); + void setAssignedResourceGroups(int roleId, int[] resourceGroupIds) throws RuntimeException;
- void setAssignedSubjects(int roleId, int[] subjectIds); + void setAssignedSubjects(int roleId, int[] subjectIds) throws RuntimeException;
- void setAssignedRolesForSubject(int subjectId, int[] roleIds); + void setAssignedRolesForSubject(int subjectId, int[] roleIds) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SearchGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SearchGWTService.java index 00b1d73..5ea5641 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SearchGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SearchGWTService.java @@ -36,18 +36,19 @@ public interface SearchGWTService extends RemoteService { * search suggestions */ List<SearchSuggestion> getTabAwareSuggestions(SearchSubsystem searchSubsystem, String expression, - int caretPosition, String tab); + int caretPosition, String tab) throws RuntimeException;
- List<SearchSuggestion> getSuggestions(SearchSubsystem searchSubsystem, String expression, int caretPosition); + List<SearchSuggestion> getSuggestions(SearchSubsystem searchSubsystem, String expression, int caretPosition) + throws RuntimeException;
/* * saved searches */ - int createSavedSearch(SavedSearch savedSearch); + int createSavedSearch(SavedSearch savedSearch) throws RuntimeException;
- void updateSavedSearch(SavedSearch savedSearch); + void updateSavedSearch(SavedSearch savedSearch) throws RuntimeException;
- void deleteSavedSearch(int savedSearchId); + void deleteSavedSearch(int savedSearchId) throws RuntimeException;
- List<SavedSearch> findSavedSearchesByCriteria(SavedSearchCriteria criteria); + List<SavedSearch> findSavedSearchesByCriteria(SavedSearchCriteria criteria) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SubjectGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SubjectGWTService.java index 67fd05a..a09cdc1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SubjectGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SubjectGWTService.java @@ -18,15 +18,12 @@ */ package org.rhq.enterprise.gui.coregui.client.gwt;
-import javax.persistence.EntityExistsException; - import com.google.gwt.user.client.rpc.RemoteService;
import org.rhq.core.domain.auth.Principal; 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.server.auth.SubjectException;
/** * @see org.rhq.enterprise.server.auth.SubjectManagerLocal @@ -41,7 +38,7 @@ public interface SubjectGWTService extends RemoteService { * @param password The password part ofthe principal * @throws Exception if the principal could not be added */ - void createPrincipal(String username, String password); + void createPrincipal(String username, String password) throws RuntimeException;
/** * Create a a new subject. This <b>ignores</b> the roles in <code>subject</code>. The created subject will not be @@ -50,7 +47,7 @@ public interface SubjectGWTService extends RemoteService { * @param subjectToCreate The subject to be created. * @return the newly persisted {@link Subject} */ - Subject createSubject(Subject subjectToCreate); + Subject createSubject(Subject subjectToCreate) throws RuntimeException;
/** * Creates a new subject, including their assigned roles, as well as an associated principal with the specified @@ -61,7 +58,7 @@ public interface SubjectGWTService extends RemoteService { * * @return the persisted subject */ - Subject createSubject(Subject subjectToCreate, String password) throws Exception; + Subject createSubject(Subject subjectToCreate, String password) throws RuntimeException;
/** * Deletes the given set of users, including both the {@link Subject} and {@link org.rhq.core.domain.auth.Principal} objects associated with @@ -70,7 +67,7 @@ public interface SubjectGWTService extends RemoteService { * @param subjectIds identifies the subject IDs for all the users that are to be deleted * @throws Exception if failed to delete one or more users */ - void deleteSubjects(int[] subjectIds); + void deleteSubjects(int[] subjectIds) throws RuntimeException;
/** * Logs a user into the system. This will authenticate the given user with the given password. If the user was @@ -82,14 +79,14 @@ public interface SubjectGWTService extends RemoteService { * @throws org.rhq.enterprise.server.exception.LoginException * if the login failed for some reason */ - Subject login(String username, String password); + Subject login(String username, String password) throws RuntimeException;
/** * Logs out a user. * * @param subject The username for the current user */ - void logout(Subject subject); + void logout(Subject subject) throws RuntimeException;
/** * Updates an existing subject with new data. This does <b>not</b> cascade any changes to the roles, but it will save @@ -99,7 +96,7 @@ public interface SubjectGWTService extends RemoteService { * * @return the merged subject, which may or may not be the same instance of <code>subjectToModify</code> */ - Subject updateSubject(Subject subjectToModify); + Subject updateSubject(Subject subjectToModify) throws RuntimeException;
/** * Updates an existing subject with new data. This cascades changes to roles and LDAP roles, so the passed-in @@ -110,7 +107,7 @@ public interface SubjectGWTService extends RemoteService { * * @return the merged subject, which may or may not be the same instance of <code>subjectToModify</code> */ - Subject updateSubject(Subject subjectToModify, String newPassword); + Subject updateSubject(Subject subjectToModify, String newPassword) throws RuntimeException;
/** * Queries subjects using current logged in user. @@ -118,7 +115,7 @@ public interface SubjectGWTService extends RemoteService { * @param criteria details for the search * @return PageList<Subject> matching criteria. */ - PageList<Subject> findSubjectsByCriteria(SubjectCriteria criteria); + PageList<Subject> findSubjectsByCriteria(SubjectCriteria criteria) throws RuntimeException;
/** * Checks the subject passed in for LDAP processing, to optionally: @@ -129,7 +126,7 @@ public interface SubjectGWTService extends RemoteService { * @param subjectToModify the subject * @param password the LDAP password */ - Subject processSubjectForLdap(Subject subjectToModify, String password); + Subject processSubjectForLdap(Subject subjectToModify, String password) throws RuntimeException;
/** * Checks that the user exists <b>and</b> has a {@link Principal} associated with it. This means that the user both @@ -140,5 +137,5 @@ public interface SubjectGWTService extends RemoteService { * * @return <code>true</code> if the user exists and has a {@link Principal}, <code>false</code> otherwise */ - boolean isUserWithPrincipal(String username); + boolean isUserWithPrincipal(String username) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SystemGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SystemGWTService.java index 03fb121..1da3e7f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SystemGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/SystemGWTService.java @@ -26,5 +26,5 @@ import org.rhq.core.domain.common.ProductInfo; * @author Ian Springer */ public interface SystemGWTService extends RemoteService { - ProductInfo getProductInfo(); + ProductInfo getProductInfo() throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/TagGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/TagGWTService.java index 849fbc6..2abfd4a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/TagGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/TagGWTService.java @@ -26,7 +26,6 @@ import java.util.Set;
import com.google.gwt.user.client.rpc.RemoteService;
-import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.TagCriteria; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.tagging.compsite.TagReportComposite; @@ -37,24 +36,23 @@ import org.rhq.core.domain.util.PageList; */ public interface TagGWTService extends RemoteService {
+ PageList<Tag> findTagsByCriteria(TagCriteria tagCriteria) throws RuntimeException;
- PageList<Tag> findTagsByCriteria(TagCriteria tagCriteria); + Set<Tag> addTags(Set<Tag> tags) throws RuntimeException;
- Set<Tag> addTags(Set<Tag> tags); + void removeTags(Set<Tag> tags) throws RuntimeException;
- void removeTags(Set<Tag> tags); + void updateResourceTags(int resourceId, Set<Tag> tags) throws RuntimeException;
- void updateResourceTags(int resourceId, Set<Tag> tags); + void updateResourceGroupTags(int resourceGroupId, Set<Tag> tags) throws RuntimeException;
- void updateResourceGroupTags(int resourceGroupId, Set<Tag> tags); + void updateBundleTags(int bundleId, Set<Tag> tags) throws RuntimeException;
- void updateBundleTags(int bundleId, Set<Tag> tags); + void updateBundleVersionTags(int bundleVersionId, Set<Tag> tags) throws RuntimeException;
- void updateBundleVersionTags(int bundleVersionId, Set<Tag> tags); + void updateBundleDeploymentTags(int bundleDeploymentId, Set<Tag> tags) throws RuntimeException;
- void updateBundleDeploymentTags(int bundleDeploymentId, Set<Tag> tags); + void updateBundleDestinationTags(int bundleDestinationId, Set<Tag> tags) throws RuntimeException;
- void updateBundleDestinationTags(int bundleDestinationId, Set<Tag> tags); - - PageList<TagReportComposite> findTagReportCompositesByCriteria(TagCriteria tagCriteria); + PageList<TagReportComposite> findTagReportCompositesByCriteria(TagCriteria tagCriteria) throws RuntimeException; } 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 3072708..5858d84 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 @@ -37,7 +37,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert
private AlertManagerLocal alertManager = LookupUtil.getAlertManager();
- public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) throws RuntimeException { + public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) throws Exception { try { return SerialUtility.prepare(this.alertManager.findAlertsByCriteria(getSessionSubject(), criteria), "AlertService.findAlertsByCriteria"); @@ -46,7 +46,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int deleteAlerts(int[] alertIds) throws RuntimeException { + public int deleteAlerts(int[] alertIds) throws Exception { try { return this.alertManager.deleteAlerts(getSessionSubject(), alertIds); } catch (Throwable t) { @@ -54,7 +54,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int deleteAlertsByContext(EntityContext context) throws RuntimeException { + public int deleteAlertsByContext(EntityContext context) throws Exception { try { return this.alertManager.deleteAlertsByContext(getSessionSubject(), context); } catch (Throwable t) { @@ -62,7 +62,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int acknowledgeAlerts(int[] alertIds) throws RuntimeException { + public int acknowledgeAlerts(int[] alertIds) throws Exception { try { return this.alertManager.acknowledgeAlerts(getSessionSubject(), alertIds); } catch (Throwable t) { @@ -70,7 +70,7 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert } }
- public int acknowledgeAlertsByContext(EntityContext context) throws RuntimeException { + public int acknowledgeAlertsByContext(EntityContext context) throws Exception { try { return this.alertManager.acknowledgeAlertsByContext(getSessionSubject(), context); } catch (Throwable t) {
commit ac2bd3ab11776fb8b564208ffc12db584efd985d Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 12:37:58 2010 -0500
replace global search with always visible message 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 dca51dc..4c74934 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 @@ -338,7 +338,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { // default view History.newItem(DEFAULT_VIEW_PATH); } else { - messageBar.clearMessage(); if (pendingMessage != null) { getMessageCenter().notify(pendingMessage); pendingMessage = null; 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 a4a1e40..99596e0 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 @@ -74,7 +74,7 @@ public class MenuBarView extends LocatableVLayout { topStrip.addMember(getActionsSection());
addMember(topStrip); - addMember(new SearchBarPane(this.extendLocatorId("Search"))); + //addMember(new SearchBarPane(this.extendLocatorId("Search")));
markForRedraw(); } 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 122f032..c03b508 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 @@ -38,6 +38,7 @@ public class Message {
// TODO: Add Debug severity? public enum Severity { + Blank("InfoBlank", "info/icn_info_blank.png"), // Info("InfoBlock", "info/icn_info_blue.png"), // Warning("WarnBlock", "info/icn_info_orange.png"), // Error("ErrorBlock", "info/icn_info_red.png"), // 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 f0c901d..9aecd39 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 @@ -35,11 +35,13 @@ 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 = 15000; // 15 seconds + private static final int AUTO_HIDE_DELAY_MILLIS = 30000;
- private Label label; + private Label label = new Label(); private Message stickyMessage;
+ private static final String NON_BREAKING_SPACE = " "; + public MessageBar() { super(LOCATOR_ID);
@@ -51,71 +53,63 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag super.onDraw();
setWidth100(); - setHeight(35); - setAlign(Alignment.CENTER);
+ label.setAlign(Alignment.CENTER); + label.setWidth("400px"); + label.setHeight("25px"); + + setLabelEmpty(); + addMember(label); + CoreGUI.getMessageCenter().addMessageListener(this); }
@Override public void onMessage(Message message) { if (!message.isBackgroundJobResult()) { - // First clear any previous message. - clearMessage(message.isSticky()); - displayMessage(message); + updateLabel(message);
- // Auto-clear the message after 15 seconds unless it's been designated as sticky. + // Auto-clear the message after some time unless it's been designated as sticky. if (message.isSticky()) { this.stickyMessage = message; } else { - Timer hideTimer = new Timer() { + new Timer() { @Override public void run() { clearMessage(false); if (stickyMessage != null) { - displayMessage(stickyMessage); + updateLabel(stickyMessage); } } - }; - hideTimer.schedule(AUTO_HIDE_DELAY_MILLIS); + }.schedule(AUTO_HIDE_DELAY_MILLIS); } } }
- public void clearMessage() { - clearMessage(true); - } - - private void displayMessage(Message message) { - this.label = createLabel(message); - addMember(this.label); + private void clearMessage(boolean clearSticky) { + setLabelEmpty(); markForRedraw(); - }
- private void clearMessage(boolean clearSticky) { - if (this.label != null) { - this.label.destroy(); - markForRedraw(); - } if (clearSticky) { this.stickyMessage = null; } }
- private Label createLabel(Message message) { - Label label = new Label(); + private void setLabelEmpty() { + label.setContents(NON_BREAKING_SPACE); + label.setIcon(Message.Severity.Blank.getIcon()); + label.setStyleName(Message.Severity.Blank.getStyle()); + }
+ private void updateLabel(Message message) { String contents = (message.getConciseMessage() != null) ? message.getConciseMessage() : message .getDetailedMessage(); label.setContents(contents); - label.setAlign(Alignment.CENTER);
String styleName = (contents != null) ? message.getSeverity().getStyle() : null; label.setStyleName(styleName);
- 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); @@ -123,6 +117,6 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag String icon = (contents != null) ? message.getSeverity().getIcon() : null; label.setIcon(icon);
- return label; + markForRedraw(); } } diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/info/icn_info_blank.png b/modules/enterprise/gui/coregui/src/main/webapp/images/info/icn_info_blank.png new file mode 100644 index 0000000..8198687 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/info/icn_info_blank.png differ
commit d67bdf0d39a3899b805c747890ae7180624847e6 Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 10:11:56 2010 -0500
enable search bar for all ResourceGroup{Composite} views
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java index 2418ec0..e81a82e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java @@ -128,6 +128,7 @@ public class ResourceGroupCompositeDataSource extends RPCDataSource<ResourceGrou criteria.addFilterDownMemberCount(getFilter(request, "downMemberCount", Long.class)); criteria.addFilterExplicitResourceIds(getFilter(request, "explicitResourceId", Integer.class)); criteria.addFilterGroupDefinitionId(getFilter(request, "groupDefinitionId", Integer.class)); + criteria.setSearchExpression(getFilter(request, "search", String.class));
return criteria; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java index 85625d6..f12d6a6 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 @@ -39,6 +39,7 @@ import com.smartgwt.client.widgets.grid.events.CellDoubleClickEvent; import com.smartgwt.client.widgets.grid.events.CellDoubleClickHandler;
import org.rhq.core.domain.resource.group.GroupCategory; +import org.rhq.core.domain.search.SearchSubsystem; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.components.table.AbstractTableAction; @@ -252,4 +253,9 @@ public class ResourceGroupListView extends Table<ResourceGroupCompositeDataSourc return view; }
+ @Override + protected SearchSubsystem getSearchSubsystem() { + return SearchSubsystem.GROUP; + } + } \ 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 7821ab7..617bffe 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 @@ -124,6 +124,7 @@ public class ResourceGroupsDataSource extends RPCDataSource<ResourceGroup> { criteria.addFilterDownMemberCount(getFilter(request, "downMemberCount", Long.class)); criteria.addFilterExplicitResourceIds(getFilter(request, "explicitResourceId", Integer.class)); criteria.addFilterGroupDefinitionId(getFilter(request, "groupDefinitionId", Integer.class)); + criteria.setSearchExpression(getFilter(request, "search", String.class));
return criteria; }
commit cb86da0d33b2f1e5e018d9f1a00d69d6fd552c1c Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 10:05:34 2010 -0500
enable search bar for all resource search views
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 c569234..fcc5909 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 @@ -73,6 +73,7 @@ import com.smartgwt.client.widgets.menu.MenuItem; import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent; import com.smartgwt.client.widgets.toolbar.ToolStrip;
+import org.rhq.core.domain.search.SearchSubsystem; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.components.form.SearchBarItem; @@ -181,7 +182,16 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements super.onInit();
filterForm = new TableFilter(this); - configureTableFilters(); + + /* + * table filters and search bar are currently mutually exclusive + */ + if (getSearchSubsystem() == null) { + configureTableFilters(); + } else { + final SearchBarItem searchFilter = new SearchBarItem("search", "Search", getSearchSubsystem()); + setFilterFormItems(searchFilter); + }
listGrid = new LocatableListGrid(getLocatorId()); listGrid.setAutoFetchData(autoFetchData); @@ -863,4 +873,12 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements public void setShowFilterForm(boolean showFilterForm) { this.showFilterForm = showFilterForm; } + + /* + * by default, no search bar is shown above this table. if this table represents a subsystem that is capable + * of search, return the specific object here. + */ + protected SearchSubsystem getSearchSubsystem() { + return null; + } } 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 07c1bcc..ff8d83c 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 @@ -38,6 +38,7 @@ import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.resource.ResourceCategory; +import org.rhq.core.domain.search.SearchSubsystem; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.components.table.AbstractTableAction; @@ -231,4 +232,9 @@ public class ResourceSearchView extends Table { selectListeners.add(listener); }
+ @Override + protected SearchSubsystem getSearchSubsystem() { + return SearchSubsystem.RESOURCE; + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java index eb519a9..91fccfc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java @@ -1,17 +1,9 @@ package org.rhq.enterprise.gui.coregui.client.test.inventory;
-import org.rhq.core.domain.search.SearchSubsystem; -import org.rhq.enterprise.gui.coregui.client.components.form.SearchBarItem; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchView;
public class TestSearchBarView extends ResourceSearchView { public TestSearchBarView(String locatorId) { super(locatorId); } - - @Override - protected void configureTableFilters() { - final SearchBarItem searchFilter = new SearchBarItem("search", "Search", SearchSubsystem.RESOURCE); - setFilterFormItems(searchFilter); - } }
commit 59567145c4c931d29961bf25de76b2dc4d960390 Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 00:42:11 2010 -0500
remove all filters except the SearchBar for the TestSearchBarView
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java index 234d775..eb519a9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java @@ -1,13 +1,6 @@ package org.rhq.enterprise.gui.coregui.client.test.inventory;
-import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.CATEGORY; -import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; - -import com.smartgwt.client.widgets.form.fields.TextItem; - -import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.search.SearchSubsystem; -import org.rhq.enterprise.gui.coregui.client.components.form.EnumSelectItem; import org.rhq.enterprise.gui.coregui.client.components.form.SearchBarItem; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchView;
@@ -18,11 +11,7 @@ public class TestSearchBarView extends ResourceSearchView {
@Override protected void configureTableFilters() { - final TextItem nameFilter = new TextItem(NAME.propertyName(), NAME.title()); - final EnumSelectItem categoryFilter = new EnumSelectItem(CATEGORY.propertyName(), CATEGORY.title(), - ResourceCategory.class); final SearchBarItem searchFilter = new SearchBarItem("search", "Search", SearchSubsystem.RESOURCE); - - setFilterFormItems(nameFilter, categoryFilter, searchFilter); + setFilterFormItems(searchFilter); } }
commit 44ebe352011837c815122fff43497149e5008e1a Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Dec 23 13:05:51 2010 -0500
Dashboard Work for Adding Portlets to a Dashboard - Add some more support to PortletFactory for better handling portlet keys *and* names. - Fix the 'add portlet' drop down menu to use names as opposed to keys. - make sure when adding a portlet we properly specify name and key, key was being passed incorrectly.
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 5843658..9631294 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 @@ -199,8 +199,11 @@ public class DashboardView extends LocatableVLayout { });
Menu addPortletMenu = new Menu(); - for (String portletName : PortletFactory.getRegisteredPortletKeys()) { - addPortletMenu.addItem(new MenuItem(portletName)); + HashMap<String, String> keyNameMap = PortletFactory.getRegisteredPortletNameMap(); + for (String portletKey : keyNameMap.keySet()) { + MenuItem menuItem = new MenuItem(keyNameMap.get(portletKey)); + menuItem.setAttribute("portletKey", portletKey); + addPortletMenu.addItem(menuItem); }
addPortlet = new LocatableIMenuButton(extendLocatorId("AddPortlet"), MSG.common_title_add_portlet(), @@ -211,8 +214,9 @@ public class DashboardView extends LocatableVLayout {
addPortletMenu.addItemClickHandler(new ItemClickHandler() { public void onItemClick(ItemClickEvent itemClickEvent) { - String portletTitle = itemClickEvent.getItem().getTitle(); - addPortlet(portletTitle, portletTitle); + String key = itemClickEvent.getItem().getAttribute("portletKey"); + String name = itemClickEvent.getItem().getTitle(); + addPortlet(key, name); } });
@@ -407,12 +411,12 @@ public class DashboardView extends LocatableVLayout { if (portletMap == null) { portletMap = new HashMap<String, PortletViewFactory>(); for (String key : PortletFactory.getRegisteredPortletKeys()) { - portletMap.put(key, PortletFactory.getRegisteredPortlet(key)); + portletMap.put(key, PortletFactory.getRegisteredPortletFactory(key)); } } for (PortletWindow portletWindow : portlets) { for (DashboardPortlet portlet : result.getPortlets()) { - if (portletWindow.getDashboardPortlet().getId() == portlet.getId()) { + if (portletWindow.getDashboardPortlet().equals(portlet)) { portletWindow.getDashboardPortlet().setConfiguration(portlet.getConfiguration());
//restarting port auto-refresh with newest settings 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 4e1ac46..aaa2229 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 @@ -19,10 +19,8 @@ package org.rhq.enterprise.gui.coregui.client.dashboard;
import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; -import java.util.Map;
import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.queue.AutodiscoveryPortlet; @@ -44,39 +42,44 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; */ public class PortletFactory {
- private static Map<String, PortletViewFactory> registeredPortlets; + private static HashMap<String, PortletViewFactory> registeredPortletFactoryMap; + private static HashMap<String, String> registeredPortletNameMap;
static { - registeredPortlets = new HashMap<String, PortletViewFactory>(); - - registeredPortlets.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.Factory.INSTANCE); - - registeredPortlets.put(RecentlyAddedResourcesPortlet.KEY, RecentlyAddedResourcesPortlet.Factory.INSTANCE); - - registeredPortlets.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.Factory.INSTANCE); - - registeredPortlets.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.Factory.INSTANCE); - - registeredPortlets.put(RecentAlertsPortlet.KEY, RecentAlertsPortlet.Factory.INSTANCE); - - registeredPortlets.put(GraphPortlet.KEY, GraphPortlet.Factory.INSTANCE); - - registeredPortlets.put(TagCloudPortlet.KEY, TagCloudPortlet.Factory.INSTANCE); - - registeredPortlets.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.Factory.INSTANCE); - - registeredPortlets.put(MashupPortlet.KEY, MashupPortlet.Factory.INSTANCE); - - registeredPortlets.put(MessagePortlet.KEY, MessagePortlet.Factory.INSTANCE); - - registeredPortlets.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.Factory.INSTANCE); - - registeredPortlets.put(OperationsPortlet.KEY, OperationsPortlet.Factory.INSTANCE); + registeredPortletFactoryMap = new HashMap<String, PortletViewFactory>(); + registeredPortletFactoryMap.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(RecentlyAddedResourcesPortlet.KEY, + RecentlyAddedResourcesPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(RecentAlertsPortlet.KEY, RecentAlertsPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(GraphPortlet.KEY, GraphPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(TagCloudPortlet.KEY, TagCloudPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(MashupPortlet.KEY, MashupPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(MessagePortlet.KEY, MessagePortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.Factory.INSTANCE); + registeredPortletFactoryMap.put(OperationsPortlet.KEY, OperationsPortlet.Factory.INSTANCE); + + registeredPortletNameMap = new HashMap<String, String>(registeredPortletFactoryMap.size()); + registeredPortletNameMap.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.NAME); + registeredPortletNameMap.put(RecentlyAddedResourcesPortlet.KEY, RecentlyAddedResourcesPortlet.NAME); + registeredPortletNameMap.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.NAME); + registeredPortletNameMap.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.NAME); + registeredPortletNameMap.put(RecentAlertsPortlet.KEY, RecentAlertsPortlet.NAME); + registeredPortletNameMap.put(GraphPortlet.KEY, GraphPortlet.NAME); + registeredPortletNameMap.put(TagCloudPortlet.KEY, TagCloudPortlet.NAME); + registeredPortletNameMap.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.NAME); + registeredPortletNameMap.put(MashupPortlet.KEY, MashupPortlet.NAME); + registeredPortletNameMap.put(MessagePortlet.KEY, MessagePortlet.NAME); + registeredPortletNameMap.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.NAME); + registeredPortletNameMap.put(OperationsPortlet.KEY, OperationsPortlet.NAME); + //registeredPortletNameMap = Collections.unmodifiableMap(registeredPortletNameMap); }
public static Portlet buildPortlet(PortletWindow portletWindow, DashboardPortlet storedPortlet) {
- PortletViewFactory viewFactory = registeredPortlets.get(storedPortlet.getPortletKey()); + PortletViewFactory viewFactory = registeredPortletFactoryMap.get(storedPortlet.getPortletKey());
// 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 @@ -93,18 +96,29 @@ public class PortletFactory { return view; }
- @SuppressWarnings("unchecked") public static List<String> getRegisteredPortletKeys() {
- ArrayList portlets = new ArrayList(registeredPortlets.keySet()); - Collections.sort(portlets); - return portlets; + ArrayList<String> portletKeys = new ArrayList<String>(registeredPortletFactoryMap.keySet()); + return portletKeys; + } + + /** + * @return Unmodifiable Map of registered portlet keys to names + */ + public static HashMap<String, String> getRegisteredPortletNameMap() { + + return registeredPortletNameMap; + } + + public static String getRegisteredPortletName(String key) { + + return registeredPortletNameMap.get(key); }
- public static PortletViewFactory getRegisteredPortlet(String key) { + public static PortletViewFactory getRegisteredPortletFactory(String key) { PortletViewFactory portletFactory = null; if ((key != null) & (!key.trim().isEmpty())) { - portletFactory = registeredPortlets.get(key); + portletFactory = registeredPortletFactoryMap.get(key); } return portletFactory; }
commit b0c15054d7c0fc2d72bf350c5b0957d11a7711ec Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 12:58:52 2010 -0500
if you are looking at a live deployment, provide a revert button so you can revert right there
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index 870988e..78651a0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -70,6 +70,7 @@ import org.rhq.enterprise.gui.coregui.client.ImageManager; 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.bundle.revert.BundleRevertWizard; import org.rhq.enterprise.gui.coregui.client.components.HeaderLabel; import org.rhq.enterprise.gui.coregui.client.components.buttons.BackButton; import org.rhq.enterprise.gui.coregui.client.components.table.Table; @@ -209,6 +210,23 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab
private Canvas getActionLayout(String locatorId) { LocatableVLayout actionLayout = new LocatableVLayout(locatorId, 10); + + // we can only revert the live deployments, only show revert button when appropriate + if (deployment.isLive()) { + IButton revertButton = new LocatableIButton(actionLayout.extendLocatorId("Revert"), MSG + .view_bundle_revert()); + revertButton.setIcon("subsystems/bundle/BundleAction_Revert_16.png"); + revertButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) { + new BundleRevertWizard(deployment.getDestination()).startWizard(); + } + }); + actionLayout.addMember(revertButton); + if (!canManageBundles) { + revertButton.setDisabled(true); + } + } + IButton deleteButton = new LocatableIButton(actionLayout.extendLocatorId("Delete"), MSG.common_button_delete()); deleteButton.setIcon("subsystems/bundle/BundleDeploymentAction_Delete_16.png"); deleteButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
commit 1a41bcb2e0ada1b50c1c5beaf0c82a9bf74cc5cd Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 12:41:22 2010 -0500
let the textarea grow to the width of the popup window so the user can see large amounts of large messages
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java index 89eec9d..60f5007 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java @@ -164,6 +164,7 @@ public class BundleResourceDeploymentHistoryListView extends LocatableVLayout {
AutoFitTextAreaItem detail = new AutoFitTextAreaItem("attachment", MSG.common_title_details()); detail.setTitleVAlign(VerticalAlignment.TOP); + detail.setWidth("100%");
form.setItems(timestamp, action, category, user, status, info, message, detail); form.editRecord(record);
commit 45656ceb9d368f0549e02aef560e476c2491d276 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 11:24:39 2010 -0500
support a default location for <file>s so you don't have to specify a destination if its the same as its name
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/FileType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/FileType.java index 2e55c0e..b968ced 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/FileType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/FileType.java @@ -22,10 +22,10 @@ */ package org.rhq.bundle.ant.type;
-import org.apache.tools.ant.BuildException; - import java.io.File;
+import org.apache.tools.ant.BuildException; + /** * A file to be copied during the bundle deployment. If the replace attribute is set to true, any template variables * (e.g. @@http.port@@) inside the file will be replaced with the value of the corresponding property. @@ -43,19 +43,24 @@ public class FileType extends AbstractFileType {
// Pass in a String, rather than a File, since we don't want Ant to resolve the path relative to basedir if it's relative. public void setDestinationDir(String destinationDir) { - if (getDestinationFile() != null) { - throw new BuildException("Both 'destinationDir' and 'destinationFile' attributes are defined - only one or the other may be specified."); + if (this.destinationFile != null) { + throw new BuildException( + "Both 'destinationDir' and 'destinationFile' attributes are defined - only one or the other may be specified."); } this.destinationDir = new File(destinationDir); }
public File getDestinationFile() { + if (this.destinationDir == null && this.destinationFile == null) { + return new File(getName()); // the default destination is the same relative path as that of its local name + } return this.destinationFile; }
public void setDestinationFile(String destinationFile) { - if (getDestinationDir() != null) { - throw new BuildException("Both 'destinationDir' and 'destinationFile' attributes are defined - only one or the other may be specified."); + if (this.destinationDir != null) { + throw new BuildException( + "Both 'destinationDir' and 'destinationFile' attributes are defined - only one or the other may be specified."); } this.destinationFile = new File(destinationFile); } diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index 956ea93..4eb4369 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -486,6 +486,7 @@ public class AntLauncherTest { try { File subdir = new File(antBasedir, "subdir"); // must match the name in the recipe subdir.mkdirs(); + writeFile("file0", subdir, "test0.txt"); // filename must match recipe writeFile("file1", subdir, "test1.txt"); // filename must match recipe writeFile("file2", subdir, "test2.txt"); // filename must match recipe createZip(new String[] { "one", "two" }, subdir, "test.zip", new String[] { "one.txt", "two.txt" }); @@ -506,13 +507,15 @@ public class AntLauncherTest { assert project != null; Set<String> bundleFiles = project.getBundleFileNames(); assert bundleFiles != null; - assert bundleFiles.size() == 5 : bundleFiles; + assert bundleFiles.size() == 6 : bundleFiles; + assert bundleFiles.contains("subdir/test0.txt") : bundleFiles; assert bundleFiles.contains("subdir/test1.txt") : bundleFiles; assert bundleFiles.contains("subdir/test2.txt") : bundleFiles; assert bundleFiles.contains("subdir/test.zip") : bundleFiles; assert bundleFiles.contains("subdir/test-explode.zip") : bundleFiles; assert bundleFiles.contains("subdir/test-replace.zip") : bundleFiles;
+ assert new File(DEPLOY_DIR, "subdir/test0.txt").exists() : "missing raw file from default destination location"; assert new File(DEPLOY_DIR, "another/foo.txt").exists() : "missing raw file from the destinationFile"; assert new File(DEPLOY_DIR, "second.dir/test2.txt").exists() : "missing raw file from the destinationDir"; assert !new File(DEPLOY_DIR, "subdir/test1.zip").exists() : "should not be here because destinationFile was specified"; diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml index 940ecf1..af3dbd2 100644 --- a/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml @@ -7,6 +7,7 @@ <rhq:input-property name="X" />
<rhq:deployment-unit name="appserver"> + <rhq:file name="subdir/test0.txt" replace="false" /> <rhq:file name="subdir/test1.txt" destinationFile="another/foo.txt" replace="false"/> <rhq:file name="subdir/test2.txt" destinationDir="second.dir" replace="false"/> <rhq:archive name="subdir/test.zip" exploded="false" />
commit 9f1a09b854b0f21b66819f2906e7b6659347d2e7 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 11:09:49 2010 -0500
BZ 610879 - make sure the ant parser knows the true location of the local raw files and archive files so the UI can ask for them when appropriate
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java index 86fd666..f5d32eb 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java @@ -238,13 +238,13 @@ public class AntLauncher { "The bundle task must contain exactly one rhq:deploymentUnit child element."); } DeploymentUnitType deployment = deployments.iterator().next(); - Map<File, File> files = deployment.getFiles(); - for (File file : files.keySet()) { - project.getBundleFileNames().add(file.getName()); + Map<File, String> files = deployment.getLocalFileNames(); + for (String file : files.values()) { + project.getBundleFileNames().add(file); } - Set<File> archives = deployment.getArchives(); - for (File archive : archives) { - project.getBundleFileNames().add(archive.getName()); + Map<File, String> archives = deployment.getLocalArchiveNames(); + for (String archive : archives.values()) { + project.getBundleFileNames().add(archive); } }
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractFileType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractFileType.java index 29b9d92..f5bbe92 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractFileType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractFileType.java @@ -25,7 +25,6 @@ package org.rhq.bundle.ant.type; import java.io.File;
import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.types.DataType;
/** * A base class for the functionality shared by {@link FileType} and {@link ArchiveType}. @@ -33,6 +32,7 @@ import org.apache.tools.ant.types.DataType; * @author Ian Springer */ public abstract class AbstractFileType extends AbstractBundleType { + private String name; private File source;
// TODO: We currently do not call this method. Do we want to or should we just let the Deployer utility handle @@ -43,7 +43,7 @@ public abstract class AbstractFileType extends AbstractBundleType { } if (this.source.isDirectory()) { throw new BuildException("File path specified by 'name' attribute (" + this.source - + ") is a directory - it must be a regular file."); + + ") is a directory - it must be a regular file."); } }
@@ -51,7 +51,12 @@ public abstract class AbstractFileType extends AbstractBundleType { return this.source; }
+ public String getName() { + return this.name; + } + public void setName(String name) { + this.name = name; File file = new File(name); if (file.isAbsolute()) { throw new BuildException("Path specified by 'name' attribute (" + name diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java index 31a52bc..8d00a96 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java @@ -49,8 +49,10 @@ public class DeploymentUnitType extends AbstractBundleType { private String name; private String manageRootDir = Boolean.TRUE.toString(); private Map<File, File> files = new LinkedHashMap<File, File>(); + private Map<File, String> localFileNames = new LinkedHashMap<File, String>(); private Set<File> rawFilesToReplace = new LinkedHashSet<File>(); private Set<File> archives = new LinkedHashSet<File>(); + private Map<File, String> localArchiveNames = new LinkedHashMap<File, String>(); private Map<File, Boolean> archivesExploded = new HashMap<File, Boolean>(); private Map<File, Pattern> archiveReplacePatterns = new HashMap<File, Pattern>(); private SystemServiceType systemService; @@ -175,15 +177,50 @@ public class DeploymentUnitType extends AbstractBundleType { this.manageRootDir = booleanString; }
+ /** + * Returns a map of all raw files. The key is the full absolute path + * to the file as it does or would appear on the file system. The value + * is a path that is either absolute or relative - it is the destination + * where the file is to be placed when being deployed on the destination file system; + * if the value is relative, then it is relative to the root destination directory. + * + * @return map of raw files + */ public Map<File, File> getFiles() { return files; }
+ /** + * Returns a map of all raw files. The key is the full absolute path + * to the file as it does or would appear on the file system (the same key + * as the keys in map {@link #getFiles()}). + * The value is a path relative to the file as it is found in the bundle distro (this + * is the "name" attribute of the "file" type tag). + * + * @return map of local file names + */ + public Map<File, String> getLocalFileNames() { + return localFileNames; + } + public Set<File> getArchives() { return archives; }
/** + * Returns a map of all archive files. The key is the full absolute path + * to the archive as it does or would appear on the file system (the same key + * as the keys in map {@link #getArchives()}). + * The value is a path relative to the file as it is found in the bundle distro (this + * is the "name" attribute of the "archive" type tag). + * + * @return map of local file names + */ + public Map<File, String> getLocalArchiveNames() { + return localArchiveNames; + } + + /** * Returns a map keyed on {@link #getArchives() archive names} whose values * are either true or false, where true means the archive is to be deployed exploded * and false means the archive should be deployed in compressed form. @@ -220,8 +257,10 @@ public class DeploymentUnitType extends AbstractBundleType {
// Add the init script and its config file to the list of bundle files. this.files.put(this.systemService.getScriptFile(), this.systemService.getScriptDestFile()); + this.localFileNames.put(this.systemService.getScriptFile(), this.systemService.getScriptFileName()); if (this.systemService.getConfigFile() != null) { this.files.put(this.systemService.getConfigFile(), this.systemService.getConfigDestFile()); + this.localFileNames.put(this.systemService.getConfigFile(), this.systemService.getConfigFileName()); this.rawFilesToReplace.add(this.systemService.getConfigFile()); } } @@ -232,7 +271,8 @@ public class DeploymentUnitType extends AbstractBundleType { File destDir = file.getDestinationDir(); destFile = new File(destDir, file.getSource().getName()); } - this.files.put(file.getSource(), destFile); + this.files.put(file.getSource(), destFile); // key=full absolute path, value=could be relative or absolute + this.localFileNames.put(file.getSource(), file.getName()); if (file.isReplace()) { this.rawFilesToReplace.add(file.getSource()); } @@ -240,6 +280,7 @@ public class DeploymentUnitType extends AbstractBundleType {
public void addConfigured(ArchiveType archive) { this.archives.add(archive.getSource()); + this.localArchiveNames.put(archive.getSource(), archive.getName()); Pattern replacePattern = archive.getReplacePattern(); if (replacePattern != null) { this.archiveReplacePatterns.put(archive.getSource(), replacePattern); diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/SystemServiceType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/SystemServiceType.java index fd1fd93..6521d2e 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/SystemServiceType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/SystemServiceType.java @@ -18,12 +18,6 @@ */ package org.rhq.bundle.ant.type;
-import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.Chmod; -import org.apache.tools.ant.taskdefs.Copy; -import org.apache.tools.ant.taskdefs.Execute; -import org.apache.tools.ant.taskdefs.optional.unix.Symlink; - import java.io.File; import java.io.IOException; import java.util.Arrays; @@ -31,6 +25,12 @@ import java.util.HashSet; import java.util.Set; import java.util.TreeSet;
+import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.Chmod; +import org.apache.tools.ant.taskdefs.Copy; +import org.apache.tools.ant.taskdefs.Execute; +import org.apache.tools.ant.taskdefs.optional.unix.Symlink; + /** * An Ant task that installs a system startup/shutdown service. Currently only Red Hat Linux versions are supported. * @@ -53,6 +53,8 @@ public class SystemServiceType extends AbstractBundleType { private String name; private File scriptFile; private File configFile; + private String scriptFileName; + private String configFileName; private boolean overwriteScript; private boolean overwriteConfig; private boolean overwriteLinks = true; @@ -64,7 +66,7 @@ public class SystemServiceType extends AbstractBundleType { * before services with a higher priority number. */ private Byte startPriority; - + /** * An integer from 0-99 indicating the service's stop order - services with a lower priority number are stopped * before services with a higher priority number. @@ -79,13 +81,13 @@ public class SystemServiceType extends AbstractBundleType {
public void validate() throws BuildException { validateAttributes(); - + this.scriptDestFile = new File(getInitDir(), this.name); this.configDestFile = new File(getSysConfigDir(), this.name); }
public void init() throws BuildException { - if (!OS_NAME.equals("Linux") || !REDHAT_RELEASE_FILE.exists() ) { + if (!OS_NAME.equals("Linux") || !REDHAT_RELEASE_FILE.exists()) { throw new BuildException("The system-service element is only supported on Red Hat Linux systems."); }
@@ -116,7 +118,7 @@ public class SystemServiceType extends AbstractBundleType { // Install the script itself (e.g. /etc/init.d/named). File initDir = getInitDir(); if (!initDir.exists()) { - initDir.mkdirs(); + initDir.mkdirs(); } if (!initDir.canWrite()) { throw new BuildException(initDir + " directory is not writeable."); @@ -150,23 +152,23 @@ public class SystemServiceType extends AbstractBundleType {
public void start() throws BuildException { File scriptFile = getScriptDestFile(); - String[] commandLine = {scriptFile.getAbsolutePath(), "start"}; + String[] commandLine = { scriptFile.getAbsolutePath(), "start" }; try { executeCommand(commandLine); } catch (IOException e) { - throw new BuildException("Failed to start " + this.name + " system service via command [" + Arrays.toString(commandLine) - + "].", e); + throw new BuildException("Failed to start " + this.name + " system service via command [" + + Arrays.toString(commandLine) + "].", e); } }
public void stop() throws BuildException { File scriptFile = getScriptDestFile(); - String[] commandLine = {scriptFile.getAbsolutePath(), "stop"}; + String[] commandLine = { scriptFile.getAbsolutePath(), "stop" }; try { executeCommand(commandLine); } catch (IOException e) { - throw new BuildException("Failed to stop " + this.name + " system service via command [" + Arrays.toString(commandLine) - + "].", e); + throw new BuildException("Failed to stop " + this.name + " system service via command [" + + Arrays.toString(commandLine) + "].", e); } }
@@ -182,6 +184,10 @@ public class SystemServiceType extends AbstractBundleType { this.name = name; }
+ public String getScriptFileName() { + return scriptFileName; + } + public File getScriptFile() { return scriptFile; } @@ -192,9 +198,14 @@ public class SystemServiceType extends AbstractBundleType { throw new BuildException("Path specified by 'scriptFile' attribute (" + scriptFile + ") is not relative - it must be a relative path, relative to the Ant basedir."); } + this.scriptFileName = scriptFile; this.scriptFile = getProject().resolveFile(scriptFile); }
+ public String getConfigFileName() { + return configFileName; + } + public File getConfigFile() { return configFile; } @@ -205,6 +216,7 @@ public class SystemServiceType extends AbstractBundleType { throw new BuildException("Path specified by 'configFile' attribute (" + configFile + ") is not relative - it must be a relative path, relative to the Ant basedir."); } + this.configFileName = configFile; this.configFile = getProject().resolveFile(configFile); }
@@ -290,7 +302,7 @@ public class SystemServiceType extends AbstractBundleType { throw new BuildException("The 'startLevels' attribute must have a non-empty value."); } this.startLevelChars = parseLevels(this.startLevels); - this.stopLevelChars = new TreeSet<Character>(); + this.stopLevelChars = new TreeSet<Character>(); for (char level : REDHAT_RUN_LEVELS) { if (!this.startLevelChars.contains(level)) { this.stopLevelChars.add(level); @@ -314,7 +326,7 @@ public class SystemServiceType extends AbstractBundleType { this.root.mkdirs(); if (!this.root.exists()) { throw new BuildException("Failed to create root directory " + this.root - + " as specified by 'root' attribute."); + + " as specified by 'root' attribute."); } } if (!this.root.isDirectory()) { @@ -341,12 +353,15 @@ public class SystemServiceType extends AbstractBundleType { }
} catch (Exception e) { - throw new BuildException("Invalid run level: " + token + throw new BuildException( + "Invalid run level: " + + token + " - the 'startLevels' attribute must be a comma-separated list of run levels - the valid levels are " + REDHAT_RUN_LEVELS + "."); } if (levelChars.contains(level)) { - throw new BuildException("The 'startLevels' attribute defines run level " + level + " more than once."); + throw new BuildException("The 'startLevels' attribute defines run level " + level + + " more than once."); } levelChars.add(level); } @@ -399,7 +414,7 @@ public class SystemServiceType extends AbstractBundleType {
private int executeCommand(String[] commandLine) throws IOException { Execute executeTask = new Execute(); - executeTask.setCommandline(commandLine); + executeTask.setCommandline(commandLine); return executeTask.execute(); }
diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index 772c3e5..956ea93 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -476,6 +476,71 @@ public class AntLauncherTest { "777"); }
+ public void testSubdirectoriesInRecipe() throws Exception { + // We want to test a fresh install, so make sure the deploy dir doesn't pre-exist. + FileUtil.purge(DEPLOY_DIR, true); + + // we need to create our own directory structure - let's build a temporary ant basedir + // and put our recipe in there as well as a subdirectory with a test raw file and test zip file + File antBasedir = FileUtil.createTempDirectory("anttest", ".test", null); + try { + File subdir = new File(antBasedir, "subdir"); // must match the name in the recipe + subdir.mkdirs(); + writeFile("file1", subdir, "test1.txt"); // filename must match recipe + writeFile("file2", subdir, "test2.txt"); // filename must match recipe + createZip(new String[] { "one", "two" }, subdir, "test.zip", new String[] { "one.txt", "two.txt" }); + createZip(new String[] { "3", "4" }, subdir, "test-explode.zip", new String[] { "three.txt", "four.txt" }); + createZip(new String[] { "X=@@X@@\n" }, subdir, "test-replace.zip", new String[] { "template.txt" }); // will be exploded then recompressed + File recipeFile = new File(antBasedir, "deploy.xml"); + FileUtil.copyFile(new File(ANT_BASEDIR, "test-bundle-subdir.xml"), recipeFile); + + AntLauncher ant = new AntLauncher(); + Properties inputProps = new Properties(); + inputProps.setProperty(DeployPropertyNames.DEPLOY_DIR, DEPLOY_DIR.getPath()); + inputProps.setProperty(DeployPropertyNames.DEPLOY_ID, String.valueOf(++this.deploymentId)); + inputProps.setProperty(DeployPropertyNames.DEPLOY_PHASE, DeploymentPhase.INSTALL.name()); + inputProps.setProperty("X", "alpha-omega"); + List<BuildListener> buildListeners = createBuildListeners(); + + BundleAntProject project = ant.executeBundleDeployFile(recipeFile, inputProps, buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); + assert bundleFiles != null; + assert bundleFiles.size() == 5 : bundleFiles; + assert bundleFiles.contains("subdir/test1.txt") : bundleFiles; + assert bundleFiles.contains("subdir/test2.txt") : bundleFiles; + assert bundleFiles.contains("subdir/test.zip") : bundleFiles; + assert bundleFiles.contains("subdir/test-explode.zip") : bundleFiles; + assert bundleFiles.contains("subdir/test-replace.zip") : bundleFiles; + + assert new File(DEPLOY_DIR, "another/foo.txt").exists() : "missing raw file from the destinationFile"; + assert new File(DEPLOY_DIR, "second.dir/test2.txt").exists() : "missing raw file from the destinationDir"; + assert !new File(DEPLOY_DIR, "subdir/test1.zip").exists() : "should not be here because destinationFile was specified"; + assert !new File(DEPLOY_DIR, "subdir/test2.zip").exists() : "should not be here because destinationFile was specified"; + assert new File(DEPLOY_DIR, "subdir/test.zip").exists() : "missing unexploded zip file"; + assert new File(DEPLOY_DIR, "subdir/test-replace.zip").exists() : "missing unexploded zip file"; + assert !new File(DEPLOY_DIR, "subdir/test-explode.zip").exists() : "should have been exploded"; + + // test that the file in the zip is realized + final String[] templateVarValue = new String[] { null }; + ZipUtil.walkZipFile(new File(DEPLOY_DIR, "subdir/test-replace.zip"), new ZipUtil.ZipEntryVisitor() { + @Override + public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception { + if (entry.getName().equals("template.txt")) { + Properties props = new Properties(); + props.load(stream); + templateVarValue[0] = props.getProperty("X"); + } + return true; + } + }); + assert templateVarValue[0] != null && templateVarValue[0].equals("alpha-omega") : templateVarValue[0]; + + } finally { + FileUtil.purge(antBasedir, true); + } + } + private List<BuildListener> createBuildListeners() { List<BuildListener> buildListeners = new ArrayList<BuildListener>(); DefaultLogger logger = new DefaultLogger(); diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml new file mode 100644 index 0000000..940ecf1 --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-subdir.xml @@ -0,0 +1,25 @@ +<?xml version="1.0"?> + +<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle"> + + <rhq:bundle name="test" version="1"> + + <rhq:input-property name="X" /> + + <rhq:deployment-unit name="appserver"> + <rhq:file name="subdir/test1.txt" destinationFile="another/foo.txt" replace="false"/> + <rhq:file name="subdir/test2.txt" destinationDir="second.dir" replace="false"/> + <rhq:archive name="subdir/test.zip" exploded="false" /> + <rhq:archive name="subdir/test-explode.zip" exploded="true" /> + <rhq:archive name="subdir/test-replace.zip" exploded="false"> + rhq:replace + <rhq:fileset includes="template.txt"/> + </rhq:replace> + </rhq:archive> + </rhq:deployment-unit> + + </rhq:bundle> + + <target name="main"/> + +</project> \ No newline at end of file
commit 2d80a4ce1b73a6e799dc34893647e8cd746ed1bd Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Dec 23 10:31:28 2010 -0500
Dashboard Work - Always use persisted dashboards. So, when using the default dashbaord, persist it as opposed to just displaying it. This is trivial db overhead and allows us to assume we're working with persisted entities (with assigned ids). This simplifies some logic, especially since portlets unique key is the id. (note, this was recommended by ghinkle and I agreed it was a good idea.) - Implemented hashcode/equals for DashboardPortlet. The dash portlets are managed in a Set, which uses equals() comparisons. On persisted dash updates the portlet objects for a dash are replaced and so object comparisons were failing. Now using the overrides we perform "id" comparisons. - Now disable the Dash while persisting a dash update asynchronously. This prevents the user from losing modifications made during that async window. For example, rapid portlet removal could be imcomplete. (This replaces the faulty "synchronized" logic I had put in earlier. synchronized methods are not (cannot be) honored in smartgwts generated javascript. That code has been reverted) - note, [BZ 661808 Removing portlets from the dashboard is not working] resulted from both the bad equals logic *and* the async update window problem, yeesh... - reenabled the ability to delete the last dashboard tab. We had prevented this so that the user would not have a blank dashboards view. Instead, now if the user kills his last dashboard we immediately assign and display a new default dash for the user. This allows a user to delete a dash he doesn't like/need and basically start over, instead of trying to edit the current one back into shape. - replaced some homegrown locatorId logic with SeleniumUtility.getSafeId() - trivial: fix a few typos in method and variable names
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 95e920d..4521f36 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 @@ -183,7 +183,7 @@ public class Dashboard implements Serializable { portlets.add(storedPortlet); }
- public Dashboard deepCoopy(boolean keepIds) { + public Dashboard deepCopy(boolean keepIds) {
Dashboard newDashboard = new Dashboard(); if (keepIds) { 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 19debd6..a83b061 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 @@ -174,4 +174,35 @@ public class DashboardPortlet implements Serializable { public String toString() { return "DashboardPortlet[id=" + id + ",key=" + portletKey + ",name=" + name + "]"; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof DashboardPortlet)) { + return false; + } + + final DashboardPortlet other = (DashboardPortlet) obj; + + // id test is only valid for entities. if not persisted entities then fail. + if (id <= 0 || other.id <= 0) { + return false; + } else if (id != other.id) { + return false; + } + + return true; + } + } 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 9feaffd..5843658 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 @@ -59,6 +59,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIMenuButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** * @author Greg Hinkle @@ -197,19 +198,18 @@ public class DashboardView extends LocatableVLayout { } });
- Menu addPorletMenu = new Menu(); + Menu addPortletMenu = new Menu(); for (String portletName : PortletFactory.getRegisteredPortletKeys()) { - addPorletMenu.addItem(new MenuItem(portletName)); + addPortletMenu.addItem(new MenuItem(portletName)); }
- addPortlet = new LocatableIMenuButton(extendLocatorId("AddPortal"), MSG.common_title_add_portlet(), - addPorletMenu); + addPortlet = new LocatableIMenuButton(extendLocatorId("AddPortlet"), MSG.common_title_add_portlet(), + addPortletMenu);
- // addPortlet = new ButtonItem("addPortlet", "Add Portlet"); addPortlet.setIcon("[skin]/images/actions/add.png"); addPortlet.setAutoFit(true);
- addPorletMenu.addItemClickHandler(new ItemClickHandler() { + addPortletMenu.addItemClickHandler(new ItemClickHandler() { public void onItemClick(ItemClickEvent itemClickEvent) { String portletTitle = itemClickEvent.getItem().getTitle(); addPortlet(portletTitle, portletTitle); @@ -325,11 +325,7 @@ public class DashboardView extends LocatableVLayout { } }
- /** - * A synchronized call to ensure add/remove/save are exclusive. - * - */ - synchronized private void addPortlet(String portletKey, String portletName) { + private void addPortlet(String portletKey, String portletName) { DashboardPortlet storedPortlet = new DashboardPortlet(portletName, portletKey, 250);
final PortletWindow newPortlet = new PortletWindow(extendLocatorId(portletKey), this, storedPortlet); @@ -369,46 +365,39 @@ public class DashboardView extends LocatableVLayout { newPortlet.show(); } }, 750); - save(storedDashboard); + save(); }
- /** - * A synchronized call to ensure the remove and save are atomic. - * - * @param portlet - */ - synchronized public void removePortlet(DashboardPortlet portlet) { + public void removePortlet(DashboardPortlet portlet) { storedDashboard.removePortlet(portlet); - save(storedDashboard); + save(); }
- /** - * A synchronized call to ensure add/remove/save are exclusive. - */ - synchronized private void setDashboard(Dashboard dashboard) { - storedDashboard = dashboard; + public void save(Dashboard dashboard) { + if (null != dashboard) { + storedDashboard = dashboard; + save(); + } }
public void save() { - save(storedDashboard); - } + // since we reset storedDashboard after the async update completes, block modification of the dashboard + // during that interval. + DashboardView.this.disable();
- private void save(Dashboard dashboard) { - GWTServiceLookup.getDashboardService().storeDashboard(dashboard, new AsyncCallback<Dashboard>() { + GWTServiceLookup.getDashboardService().storeDashboard(storedDashboard, new AsyncCallback<Dashboard>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.view_dashboardManager_error(), caught); + DashboardView.this.enable(); }
public void onSuccess(Dashboard result) { CoreGUI.getMessageCenter().notify( new Message(MSG.view_dashboardManager_saved(result.getName()), Message.Severity.Info)); - // use the synchronized call to ensure add/delete portlet doesn't get interrupted. This is really - // just limited protection for add/remove portlet. Since this now sets storedDashboard, - // anything using the old version could lose edits. If we want to make this more robust we'll probably - // need a locking mechanism for editing the dashboard. - setDashboard(storedDashboard);
updateConfigs(result); + storedDashboard = result; + DashboardView.this.enable(); } }); } @@ -432,8 +421,8 @@ public class DashboardView extends LocatableVLayout { // 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(PortletFactory.replaceSpaces(portlet.getPortletKey()) - + "-" + Integer.toString(portlet.getId())); + Portlet view = viewFactory.getInstance(SeleniumUtility.getSafeId(portlet.getPortletKey() + "-" + + Integer.toString(portlet.getId())));
//add code to re-initialize refresh cycle for portlets if (view instanceof AutoRefreshPortlet) { 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 1b837bf..e9df895 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 @@ -76,7 +76,7 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView // Each NamedTab is a Dashboard, name=Dashboard.id, title=Dashboard.name private NamedTabSet tabSet;
- // The ID (0 for default dash) + // The ID private String selectedTabName;
private IButton editButton; @@ -109,12 +109,31 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView CoreGUI.getErrorHandler().handleError(MSG.view_dashboardsManager_error1(), caught); }
- public void onSuccess(List<Dashboard> result) { + public void onSuccess(final List<Dashboard> result) { initialized = true; + if (result.isEmpty()) { - result.add(getDefaultDashboard()); + // if the user has no dashboards persist a default dashboard for him to work with. In + // this way we're always working with a persisted dashboard and real entities. + addDefaultDashboard(); + + } else { + updateDashboards(result); } - updateDashboards(result); + } + }); + } + + private void addDefaultDashboard() { + dashboardService.storeDashboard(getDefaultDashboard(), new AsyncCallback<Dashboard>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_dashboardsManager_error1(), caught); + } + + public void onSuccess(Dashboard defaultDashboard) { + List<Dashboard> dashboards = new ArrayList<Dashboard>(1); + dashboards.add(defaultDashboard); + updateDashboards(dashboards); } }); } @@ -190,8 +209,6 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView
}
- //updateFirstTabCanCloseState("update dashboards"); - tabSet.addCloseClickHandler(new CloseClickHandler() { public void onCloseClick(final TabCloseClickEvent tabCloseClickEvent) { tabCloseClickEvent.cancel(); @@ -203,12 +220,11 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView dashboardsByName.remove(tabCloseClickEvent.getTab().getTitle()); tabSet.removeTab(tabCloseClickEvent.getTab()); dashboardView.delete(); - // if ( 0 == tabSet.getTabs().length) { - // - // } - History.newItem(VIEW_ID.getName());
- //updateFirstTabCanCloseState("close handler"); + // if it's the last tab go back to a default tab + if (0 == tabSet.getTabs().length) { + addDefaultDashboard(); + } } } }); @@ -311,8 +327,6 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView tabSet.selectTab(tab); editMode = true; editButton.setTitle(editMode ? MSG.common_title_view_mode() : MSG.common_title_edit_mode()); - - //updateFirstTabCanCloseState("store dashboard"); } }); } @@ -325,16 +339,13 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView }
public void renderView(ViewPath viewPath) { - NamedTab[] tabs = tabSet.getTabs(); - // make sure we have at least a default dashboard tab - if (0 == tabs.length) { - List<Dashboard> defaultTabs = new ArrayList<Dashboard>(1); - defaultTabs.add(getDefaultDashboard()); - updateDashboards(defaultTabs); - tabs = tabSet.getTabs(); + if (null == tabSet || 0 == tabSet.getTabs().length) { + return; }
+ NamedTab[] tabs = tabSet.getTabs(); + // if nothing selected or pathtab does not exist, default to the first tab NamedTab selectedTab = tabs[0]; selectedTabName = selectedTab.getName(); @@ -351,8 +362,6 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView } }
- //updateFirstTabCanCloseState("render view"); - tabSet.selectTab(selectedTab); }
@@ -364,13 +373,4 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView public boolean isInitialized() { return initialized; } - - // must be called when the tabset is first loaded (onInit), on each subsequent load, and whenever it changes - //public void updateFirstTabCanCloseState(String comingFrom) { - // do not allow closing if there is only one dashboard tab remaining - // boolean canClose = tabSet.getTabs().length > 1; - // NamedTab firstTab = tabSet.getTabs()[0]; - // firstTab.setCanClose(canClose); - //} - }
commit 248c9ab7ade22850f2e39f32433cc8b9bbeb5504 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Dec 22 18:41:21 2010 -0500
Dashboard Work - Add some doc to DashboardPortlet for name and portletKey semantics - Remove improper I18N of portlet keys and use static keys - Add explicit I18Nd default names for all portlets - Make sure name and key are used properly
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 5562dbe..19debd6 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 @@ -53,14 +53,17 @@ public class DashboardPortlet implements Serializable {
private static final long serialVersionUID = 1L;
+ // This is the only unique key. dashboard+portletKey+name does not have to be unique @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "RHQ_DASHBOARD_PORTLET_ID_SEQ") @Id private int id;
+ // A non-displayed, persisted identifier for the portlet. @Column(name = "PORTLET_KEY") private String portletKey;
+ // A displayed, persisted, editable name for the portlet. @Column(name = "NAME") private String name;
@@ -167,4 +170,8 @@ public class DashboardPortlet implements Serializable { newPortlet.configuration = this.configuration != null ? this.configuration.deepCopy(keepIds) : null; return newPortlet; } + + public String toString() { + return "DashboardPortlet[id=" + id + ",key=" + portletKey + ",name=" + name + "]"; + } } 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 61bd111..1b837bf 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 @@ -190,7 +190,7 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView
}
- updateFirstTabCanCloseState("update dashboards"); + //updateFirstTabCanCloseState("update dashboards");
tabSet.addCloseClickHandler(new CloseClickHandler() { public void onCloseClick(final TabCloseClickEvent tabCloseClickEvent) { @@ -203,9 +203,12 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView dashboardsByName.remove(tabCloseClickEvent.getTab().getTitle()); tabSet.removeTab(tabCloseClickEvent.getTab()); dashboardView.delete(); + // if ( 0 == tabSet.getTabs().length) { + // + // } History.newItem(VIEW_ID.getName());
- updateFirstTabCanCloseState("close handler"); + //updateFirstTabCanCloseState("close handler"); } } }); @@ -223,44 +226,40 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView dashboard.setColumnWidths("32%", "68%"); dashboard.getConfiguration().put(new PropertySimple(Dashboard.CFG_BACKGROUND, "#F1F2F3"));
- DashboardPortlet summary = new DashboardPortlet(MSG.view_dashboardsManager_inventory_title(), - InventorySummaryPortlet.KEY, 230); + DashboardPortlet summary = new DashboardPortlet(InventorySummaryPortlet.NAME, InventorySummaryPortlet.KEY, 230); dashboard.addPortlet(summary, 0, 0);
- DashboardPortlet tagCloud = new DashboardPortlet(MSG.view_dashboardsManager_tagcloud_title(), - TagCloudPortlet.KEY, 200); + DashboardPortlet tagCloud = new DashboardPortlet(TagCloudPortlet.NAME, TagCloudPortlet.KEY, 200); dashboard.addPortlet(tagCloud, 0, 1);
// Experimental // StoredPortlet platformSummary = new StoredPortlet("Platform Summary", PlatformPortletView.KEY, 300); // col2.add(platformSummary);
- DashboardPortlet welcome = new DashboardPortlet(MSG.view_dashboardsManager_message_title(), MessagePortlet.KEY, - 180); + DashboardPortlet welcome = new DashboardPortlet(MessagePortlet.NAME, MessagePortlet.KEY, 180); welcome.getConfiguration().put( new PropertySimple("message", MSG.view_dashboardsManager_message_title_details())); dashboard.addPortlet(welcome, 1, 0);
- DashboardPortlet news = new DashboardPortlet(MSG.view_dashboardsManager_mashup_title(), MashupPortlet.KEY, 320); + DashboardPortlet news = new DashboardPortlet(MashupPortlet.NAME, MashupPortlet.KEY, 320); news.getConfiguration().put( new PropertySimple("address", "http://rhq-project.org/display/RHQ/RHQ+News?decorator=popup")); dashboard.addPortlet(news, 1, 1); // - DashboardPortlet discoveryQueue = new DashboardPortlet(MSG.view_portlet_autodiscovery_title(), - AutodiscoveryPortlet.KEY, 250); + DashboardPortlet discoveryQueue = new DashboardPortlet(AutodiscoveryPortlet.NAME, AutodiscoveryPortlet.KEY, 250); dashboard.addPortlet(discoveryQueue, 1, 2);
- DashboardPortlet recentAlerts = new DashboardPortlet(RecentAlertsPortlet.KEY, RecentAlertsPortlet.KEY, 250); + DashboardPortlet recentAlerts = new DashboardPortlet(RecentAlertsPortlet.NAME, RecentAlertsPortlet.KEY, 250); dashboard.addPortlet(recentAlerts, 1, 3);
- DashboardPortlet recentlyAdded = new DashboardPortlet(MSG.common_title_recently_added(), + DashboardPortlet recentlyAdded = new DashboardPortlet(RecentlyAddedResourcesPortlet.NAME, RecentlyAddedResourcesPortlet.KEY, 250); dashboard.addPortlet(recentlyAdded, 1, 4);
- DashboardPortlet operations = new DashboardPortlet(MSG.common_title_operations(), OperationsPortlet.KEY, 500); + DashboardPortlet operations = new DashboardPortlet(OperationsPortlet.NAME, OperationsPortlet.KEY, 500); dashboard.addPortlet(operations, 1, 5);
- DashboardPortlet problemResources = new DashboardPortlet(MSG.view_portlet_problem_resources_title(), + DashboardPortlet problemResources = new DashboardPortlet(ProblemResourcesPortlet.NAME, ProblemResourcesPortlet.KEY, 250); //initialize config for the problemResources portlet. problemResources.getConfiguration() @@ -313,7 +312,7 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView editMode = true; editButton.setTitle(editMode ? MSG.common_title_view_mode() : MSG.common_title_edit_mode());
- updateFirstTabCanCloseState("store dashboard"); + //updateFirstTabCanCloseState("store dashboard"); } }); } @@ -352,7 +351,7 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView } }
- updateFirstTabCanCloseState("render view"); + //updateFirstTabCanCloseState("render view");
tabSet.selectTab(selectedTab); } @@ -367,11 +366,11 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView }
// must be called when the tabset is first loaded (onInit), on each subsequent load, and whenever it changes - public void updateFirstTabCanCloseState(String comingFrom) { - // do not allow closing if there is only one dashboard tab remaining - boolean canClose = tabSet.getTabs().length > 1; - NamedTab firstTab = tabSet.getTabs()[0]; - firstTab.setCanClose(canClose); - } + //public void updateFirstTabCanCloseState(String comingFrom) { + // do not allow closing if there is only one dashboard tab remaining + // boolean canClose = tabSet.getTabs().length > 1; + // NamedTab firstTab = tabSet.getTabs()[0]; + // firstTab.setCanClose(canClose); + //}
} 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 857f893..4e1ac46 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 @@ -37,6 +37,7 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.summary.Inventor import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.summary.TagCloudPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.util.MashupPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.util.MessagePortlet; +import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** * @author Greg Hinkle @@ -49,7 +50,9 @@ public class PortletFactory { registeredPortlets = new HashMap<String, PortletViewFactory>();
registeredPortlets.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.Factory.INSTANCE); + registeredPortlets.put(RecentlyAddedResourcesPortlet.KEY, RecentlyAddedResourcesPortlet.Factory.INSTANCE); + registeredPortlets.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.Factory.INSTANCE);
registeredPortlets.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.Factory.INSTANCE); @@ -63,8 +66,11 @@ public class PortletFactory { registeredPortlets.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.Factory.INSTANCE);
registeredPortlets.put(MashupPortlet.KEY, MashupPortlet.Factory.INSTANCE); + registeredPortlets.put(MessagePortlet.KEY, MessagePortlet.Factory.INSTANCE); + registeredPortlets.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.Factory.INSTANCE); + registeredPortlets.put(OperationsPortlet.KEY, OperationsPortlet.Factory.INSTANCE); }
@@ -75,7 +81,7 @@ 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(replaceSpaces(storedPortlet.getPortletKey()) + "-" + Portlet view = viewFactory.getInstance(SeleniumUtility.getSafeId(storedPortlet.getPortletKey()) + "-" + Integer.toString(storedPortlet.getId())); view.configure(portletWindow, storedPortlet);
@@ -87,19 +93,6 @@ public class PortletFactory { return view; }
- /** Translated spaces to underscore. Spaces not allowed in locator ids. - * - * @param portletKey - * @return - */ - public static String replaceSpaces(String portletKey) { - String translated = portletKey; - if (portletKey != null) { - translated = portletKey.replaceAll(" ", "_"); - } - return translated; - } - @SuppressWarnings("unchecked") public static List<String> getRegisteredPortletKeys() {
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 e31ea1d..e92d367 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 @@ -50,8 +50,13 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; */ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements CustomSettingsPortlet, AutoRefreshPortlet { + + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "Autodiscovery"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_autodiscovery(); + //ui attributes/properties/indentifiers - public static final String KEY = MSG.view_portlet_autodiscovery_title(); private static final String AUTODISCOVERY_PLATFORM_MAX = "auto-discovery-platform-max"; private String unlimited = MSG.common_label_unlimited(); private String defaultValue = unlimited; 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 1681d58..b41778b 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 @@ -47,7 +47,10 @@ import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; */ public class FavoriteResourcesPortlet extends ResourceSearchView implements AutoRefreshPortlet {
- public static final String KEY = MSG.view_portlet_favoriteResources_title(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "FavoriteResources"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_favoriteResources();
public static final String CFG_TABLE_PREFS = "tablePreferences";
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/GraphPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/GraphPortlet.java index 0175f28..85a34ff 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/GraphPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/GraphPortlet.java @@ -47,7 +47,10 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitorin */ public class GraphPortlet extends SmallGraphView implements CustomSettingsPortlet {
- public static final String KEY = MSG.view_portlet_graph_title(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "Graph"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_graph();
private PortletWindow portletWindow; private DashboardPortlet storedPortlet; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java index 3540d9b..12bbce7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java @@ -62,11 +62,15 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableListGrid; public class PlatformSummaryPortlet extends LocatableListGrid implements Portlet { public static final ViewName VIEW_ID = new ViewName("CpuAndMemoryUtilization", MSG.view_reports_platforms());
+ // A non-displayed, persisted identifier for the portlet + public static final String KEY = "PlatformSummary"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_platformSummary(); + private MeasurementDataGWTServiceAsync measurementService = GWTServiceLookup.getMeasurementDataService(); private ResourceTypeGWTServiceAsync typeService = GWTServiceLookup.getResourceTypeGWTService();
private HashMap<Integer, PlatformMetricDefinitions> platformMetricDefinitionsHashMap = new HashMap<Integer, PlatformMetricDefinitions>(); - public static final String KEY = MSG.view_portlet_platform_title();
public PlatformSummaryPortlet(String locatorId) { super(locatorId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index a9a801d..df8e479 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 @@ -57,7 +57,11 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSettingsPortlet, AutoRefreshPortlet {
- public static final String KEY = MSG.view_portlet_recentAlerts_title(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "RecentAlerts"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_recentAlerts(); + //widget keys also used in form population 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"; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java index b80f0d3..f925bde 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java @@ -50,7 +50,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements CustomSettingsPortlet, AutoRefreshPortlet {
- public static final String KEY = MSG.view_portlet_recentlyAdded_title(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "RecentlyAddedResources"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_recentlyAddedResources();
private boolean simple = true; private DashboardPortlet storedPortlet; @@ -75,7 +78,7 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C treeGrid = new TreeGrid(); treeGrid.setDataSource(getDataSource()); treeGrid.setAutoFetchData(true); - treeGrid.setTitle(MSG.common_title_recently_added()); + treeGrid.setTitle(MSG.view_portlet_defaultName_recentlyAddedResources()); treeGrid.setResizeFieldsInRealTime(true); treeGrid.setTreeFieldTitle("Resource Name");
@@ -92,7 +95,7 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C treeGrid.setFields(resourceNameField, timestampField);
if (!simple) { - addMember(new HeaderLabel(MSG.common_title_recently_added())); + addMember(new HeaderLabel(MSG.view_portlet_defaultName_recentlyAddedResources())); }
addMember(treeGrid); 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 8ae6ee3..c884170 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 @@ -59,14 +59,16 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class OperationsPortlet extends LocatableVLayout implements CustomSettingsPortlet, AutoRefreshPortlet {
+ // A non-displayed, persisted identifier for the portlet + public static final String KEY = "Operations"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_operations(); + //unique field/form identifiers public static final String OPERATIONS_RANGE_COMPLETED_ENABLED = "operations-completed-enabled"; public static final String OPERATIONS_RANGE_SCHEDULED_ENABLED = "operations-scheduled-enabled"; public static final String OPERATIONS_RANGE_COMPLETED = "operations-range-completed"; public static final String OPERATIONS_RANGE_SCHEDULED = "operations-range-scheduled"; - //portlet key - public static final String KEY = MSG.common_title_operations(); - private static final String TITLE = KEY; private static String recentOperations = MSG.common_title_recent_operations(); private static String scheduledOperations = MSG.common_title_scheduled_operations(); public static String RANGE_DISABLED_MESSAGE = MSG.view_portlet_operations_disabled(); @@ -98,7 +100,7 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting protected void onInit() { super.onInit(); //set title for larger container - setTitle(TITLE); + //setTitle(TITLE);
this.recentOperationsGrid = new LocatableListGrid(recentOperations); recentOperationsGrid.setDataSource(getDataSourceCompleted()); 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 8c6f106..d040f7c 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 @@ -60,11 +60,14 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel; */ public class ProblemResourcesPortlet extends Table implements CustomSettingsPortlet, AutoRefreshPortlet {
+ // A non-displayed, persisted identifier for the portlet + public static final String KEY = "ProblemResources"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_problemResources(); + //keys for smart gwt elements. should be unique public static final String PROBLEM_RESOURCE_SHOW_HRS = "max-problems-query-span"; public static final String PROBLEM_RESOURCE_SHOW_MAX = "max-problems-shown"; - public static final String KEY = MSG.view_portlet_problem_resources_title(); - private static final String TITLE = KEY; private DashboardPortlet storedPortlet; //reference to datasource private ProblemResourcesDataSource dataSource; @@ -75,7 +78,7 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort private Timer defaultReloader;
public ProblemResourcesPortlet(String locatorId) { - super(locatorId, TITLE, true); + super(locatorId, NAME, true);
setShowHeader(false); setShowFooter(true); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java index adb7911..b5e11ec 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java @@ -50,11 +50,17 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
public class InventorySummaryPortlet extends LocatableVLayout implements AutoRefreshPortlet { + + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "InventorySummary"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_inventorySummary(); + private ResourceBossGWTServiceAsync resourceBossService = GWTServiceLookup.getResourceBossService();
private LocatableDynamicForm form; - public static final String KEY = MSG.common_title_summary_counts(); private Timer defaultReloader; + private Timer reloader;
public InventorySummaryPortlet(String locatorId) { super(locatorId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java index 1ca4b1f..716f66f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java @@ -36,7 +36,10 @@ import org.rhq.enterprise.gui.coregui.client.report.tag.TagCloudView; */ public class TagCloudPortlet extends TagCloudView implements Portlet {
- public static final String KEY = MSG.view_portlet_tagCloud_title(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "TagCloud"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_tagCloud();
public TagCloudPortlet(String locatorId) { super(locatorId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java index 8d6af1c..3cff303 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java @@ -41,7 +41,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHTMLPane; */ public class MashupPortlet extends LocatableHTMLPane implements ConfigurablePortlet {
- public static final String KEY = MSG.common_title_mashup(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "Mashup"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_mashup();
public MashupPortlet(String locatorId) { super(locatorId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java index bb37906..2a463aa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java @@ -41,7 +41,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHTMLPane; */ public class MessagePortlet extends LocatableHTMLPane implements ConfigurablePortlet {
- public static final String KEY = MSG.view_portlet_message_title(); + // A non-displayed, persisted identifier for the portlet + public static final String KEY = "Message"; + // A default displayed, persisted name for the portlet + public static final String NAME = MSG.view_portlet_defaultName_message();
public MessagePortlet(String locatorId) { super(locatorId); diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 0263cc9..548d86b 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -133,14 +133,14 @@ common_title_plugin = Plugin common_title_port = Port common_title_portlet_auto_refresh=Portlet Auto-refresh Interval common_title_providers = Providers -common_title_recently_added = Recently Added Resources common_title_recent_alerts = Recent Alerts -common_title_recent_configuration_updates=Recent Configuration Updates -common_title_recent_event_counts=Recent Event Counts -common_title_recent_measurements=Recent Measurements -common_title_recent_oob_metrics=Recent Out of Bound metrics +common_title_recent_configuration_updates = Recent Configuration Updates +common_title_recent_event_counts = Recent Event Counts +common_title_recent_measurements = Recent Measurements +common_title_recent_oob_metrics = Recent Out of Bound metrics common_title_recent_operations = Recent Operations -common_title_recent_pkg_history=Recent Package History +common_title_recent_pkg_history = Recent Package History +common_title_recently_added = Recently Added common_title_remove_column = Remove Column common_title_repositories = Repositories common_title_resource = Resource @@ -168,7 +168,6 @@ common_title_stop= Stop common_title_summary = Summary common_title_tag_cloud = Tag Cloud common_title_the = The -common_title_summary_counts = Summary Counts common_title_timestamp = Date/Time common_title_total = Total common_title_type = Type @@ -1178,17 +1177,25 @@ view_dashboards_portlets_refresh_one_min = Refresh every 1 minute view_dashboards_portlets_refresh_success1=Updated interval for portlets that auto-refresh view_dashboards_portlets_refresh_success2=Stopping reload for portlets that auto-refresh view_dashboardsManager_error1 = Failed to add new dashboard -# // dup in common -view_dashboardsManager_inventory_title = Inventory Summary -view_dashboardsManager_mashup_title = RHQ News -view_dashboardsManager_message_title = Welcome To RHQ view_dashboardsManager_message_title_details = <h1>Welcome to RHQ</h1>\n<p>The RHQ project is an abstraction and plug-in based systems management suite that provides extensible and integrated systems management for multiple products and platforms across a set of core features. The project is designed with layered modules that provide a flexible architecture for deployment. It delivers a core user interface that delivers audited and historical management across an entire enterprise. A Server/Agent architecture provides remote management and plugins implement all specific support for managed products.</p>\n <p>This default dashboard can be edited by clicking the (edit mode) button above.</p> -view_dashboardsManager_tagcloud_title = Tag Cloud + +view_portlet_defaultName_autodiscovery = Discovery Queue +view_portlet_defaultName_favoriteResources = Favorite Resources +view_portlet_defaultName_graph = Resource Graph +view_portlet_defaultName_inventorySummary = Inventory Summary +view_portlet_defaultName_mashup = RHQ News +view_portlet_defaultName_message = Welcome To RHQ +view_portlet_defaultName_operations = Operations +view_portlet_defaultName_platformSummary = Platforms Summary +view_portlet_defaultName_problemResources = Alerted or Unavailable Resources +view_portlet_defaultName_recentAlerts = Recent Alerts +view_portlet_defaultName_recentlyAddedResources = Recently Added Resources +view_portlet_defaultName_tagCloud = Tag Cloud + + view_portlet_autodiscovery_config_platform_selection = Number of platforms to display view_portlet_autodiscovery_help_msg = This portlet offers the ability to import newly discovered resources into the inventory for monitoring and management or to ignore them from further action. -view_portlet_autodiscovery_title = Discovery Queue view_portlet_favoriteResources_msg = This portlet displays your favorite resources -view_portlet_favoriteResources_title = Favorite Resources view_portlet_generic_help = No help available for this portlet view_portlet_generic_unconfigured = No settings available for this portlet view_portlet_graph_configure_resource_graph = The resource to graph @@ -1198,7 +1205,6 @@ view_portlet_graph_configure_title_desc = Configuration of the graph portlet view_portlet_graph_help_msg = This Portlet supports the graphing of a resource metric. view_portlet_graph_help_title = Graph Portlet view_portlet_graph_help_unconfigured = This graph is unconfigured, click the settings button to configure. -view_portlet_graph_title = Resource Graph view_portlet_inventory_error1 = Failed to retrieve inventory summary view_portlet_inventory_tooltip_expand = Click to show more details for this resource. view_portlet_inventory_tooltip_collapse = Click to hide details for this resource. @@ -1224,7 +1230,6 @@ view_portlet_operations_disabled = (Results currently disabled. Change settings view_portlet_operations_help_msg = This portlet displays both operations that have occurred and are scheduled to occur. view_portlet_platform_help_msg = This portlet displays information about platforms in inventory. view_portlet_platform_platform_error_1 = Failed to load platform metrics -view_portlet_platform_title = Platforms Summary view_portlet_platform_type_error_1 = Could not load type data view_portlet_problem_resources_config_display_maximum = Maximum number of Problem resources to display. view_portlet_problem_resources_config_display_range = Show problem resources going back this many hours. @@ -1233,20 +1238,15 @@ view_portlet_problem_resources_config_problem_label = problem resources on dashb view_portlet_problem_resources_config_title = ProblemResourcesPortlet Configuration view_portlet_problem_resources_config_title_desc = The configuration settings for the Problem resources portlet. view_portlet_problem_resources_help = This portlet displays resources that have reported alerts or Down availability. -view_portlet_problem_resources_title = Has Alerts or Currently Unavailable view_portlet_recentAlerts_config_members = Select Members view_portlet_recentAlerts_config_priority_label = priority Alerts, view_portlet_recentAlerts_config_when = within the past view_portlet_recentAlerts_help_msg = Displays recent alerts fired on resources visible to the current user login. view_portlet_recentAlerts_fail_msg = Failed to load resources assigned for alert filtering. -# // dup in common -view_portlet_recentAlerts_title = Recent Alerts view_portlet_recentlyAdded_approved_platforms = recently approved platforms on dashboard. view_portlet_recentlyAdded_error1 = Failed to load recently added resources view_portlet_recentlyAdded_help_msg = This portlet displays resources that have recently been imported into the inventory. -view_portlet_recentlyAdded_title =Recently Added Portlet view_portlet_tagCloud_help = portlet displays the relative tag counts in the system visible to the current user. -view_portlet_tagCloud_title = TagCloud
# =================== Inventory =====================
commit 41332964f7e4ce702f11bb87e0b4db8301c01cdf Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 08:31:57 2010 -0500
only send the message to the server if its a real audit message
diff --git a/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java b/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java index b8476b9..b0a7d84 100644 --- a/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java +++ b/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java @@ -75,22 +75,19 @@ public class DeploymentAuditorBuildListener implements BuildListener { }
public void messageLogged(BuildEvent event) { - // this will see if this is an audit message (e.g. rhq:audit) and if so, send it up to the server - // see org.rhq.bundle.ant.task.AuditTask.execute() - // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> - try { - Status status = Status.SUCCESS; - String action = "Audit Message"; - String info = "Recipe Audit Message"; - String message = new Date().toString(); - String details = null; - BundleResourceDeployment deployment = this.bundleResourceDeployment; - Category category = Category.AUDIT_MESSAGE; - + // this will see if this is an audit message (e.g. rhq:audit) and if so, send it up to the server + // see org.rhq.bundle.ant.task.AuditTask.execute() + // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> String[] eventStrings = event.getMessage().split("___"); int index = 0; if (eventStrings[index++].equals("RHQ_AUDIT_MESSAGE")) { + Status status = Status.SUCCESS; + String action = "Audit Message"; + String info = "Recipe Audit Message"; + String message = new Date().toString(); + String details = null; + try { String statusStr = eventStrings[index++]; status = Status.valueOf(statusStr.toUpperCase()); @@ -101,9 +98,9 @@ public class DeploymentAuditorBuildListener implements BuildListener { } catch (ArrayIndexOutOfBoundsException e) { // the message didn't have all the info, just skip looking for the rest and log what we have } + this.bundleManagerProvider.auditDeployment(this.bundleResourceDeployment, action, info, + Category.AUDIT_MESSAGE, status, message, details); } - - this.bundleManagerProvider.auditDeployment(deployment, action, info, category, status, message, details); } catch (Exception e) { throw new RuntimeException(e); }
commit 65c741a60042218f7ab290b4795b563c9be2c77e Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 06:03:04 2010 -0500
BZ 649318 add new rhq:audit task that lets the recipe author be able to send up custom audit trail entries
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java new file mode 100644 index 0000000..af0e60b --- /dev/null +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/task/AuditTask.java @@ -0,0 +1,120 @@ +/* + * 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.bundle.ant.task; + +import java.util.Date; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; + +/** + * The rhq:audit task is a way recipe authors can add their own audit messages to the stream + * of audit messages that the server gets to see how the progress went with the provisioning of a bundle. + * + * <rhq:audit status='SUCCESS|WARN|FAILURE' action="My Step" info="summary info" message="intermediate details"> + * long details here + * </rhq:audit> + * + * @author John Mazzitelli + */ +public class AuditTask extends AbstractBundleTask { + private String status = "SUCCESS"; // must match one of SUCCESS, WARN, or FAILURE (see BundleResourceDeploymentHistory.Status) + private String action = null; + private String info = null; + private String message = ""; + private String details = ""; + + @Override + public void maybeConfigure() throws BuildException { + super.maybeConfigure(); // inits the attribute fields + validateAttributes(); + } + + @Override + public void execute() throws BuildException { + // this will log a message with a very specific format that is understood + // by the agent-side build listener's messageLogged method: + // org.rhq.plugins.ant.DeploymentAuditorBuildListener.messageLogged(BuildEvent) + // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> + StringBuilder str = new StringBuilder("RHQ_AUDIT_MESSAGE___"); + str.append(this.status); + str.append("___"); + str.append((this.action != null) ? this.action : "Audit Message"); + str.append("___"); + str.append((this.info != null) ? this.info : "Timestamp: " + new Date().toString()); + str.append("___"); + str.append(this.message); + str.append("___"); + str.append(this.details); + getProject().log(str.toString(), Project.MSG_INFO); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = (message != null) ? message : ""; + } + + /** + * Set a multiline message. + * @param msg the CDATA text to append to the message text + */ + public void addText(String msg) { + if (msg != null) { + this.details += getProject().replaceProperties(msg); + } + } + + protected void validateAttributes() throws BuildException { + if (this.status == null) { + this.status = "SUCCESS"; + } else if (!this.status.equalsIgnoreCase("SUCCESS") && !this.status.equalsIgnoreCase("FAILURE") + && !this.status.equalsIgnoreCase("WARN")) { + throw new BuildException("The 'result' attribute must be either 'SUCCESS', 'WARN' or 'FAILURE'"); + } + this.status = this.status.toUpperCase(); + } + +} \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml b/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml index fee46ef..010077e 100644 --- a/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml +++ b/modules/common/ant-bundle/src/main/resources/org/rhq/bundle/antlib.xml @@ -17,5 +17,7 @@ <typedef name="ignore" classname="org.rhq.bundle.ant.type.IgnoreType"/> <typedef name="fileset" classname="org.rhq.bundle.ant.type.FileSet"/> <typedef name="system-service" classname="org.rhq.bundle.ant.type.SystemServiceType"/> - + + <!-- audit task used to send custom audit messages to server --> + <taskdef name="audit" classname="org.rhq.bundle.ant.task.AuditTask"/> </antlib> diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index 2c41874..772c3e5 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -140,6 +140,7 @@ public class AntLauncherTest { assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); assert propDef.isRequired();
+ // make sure our test infrastruction setup the input properties correctly Configuration config = project.getConfiguration(); assert config.getProperties().size() == 1 : config.getProperties(); assert "10000".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); @@ -193,6 +194,7 @@ public class AntLauncherTest { assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); assert propDef.isRequired();
+ // make sure our test infrastruction setup the input properties correctly Configuration config = project.getConfiguration(); assert config.getProperties().size() == 1; assert "20000".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); @@ -249,6 +251,7 @@ public class AntLauncherTest { assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); assert propDef.isRequired();
+ // make sure our test infrastruction setup the input properties correctly Configuration config = project.getConfiguration(); assert config.getProperties().size() == 1; assert "20000".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); @@ -431,6 +434,48 @@ public class AntLauncherTest { } }
+ // this doesn't verify the audit messages getting emitted are correct + // but it does verify the audit tag getting processed correctly. + // you have to look at the test logs to see the audit messages + // TODO: write a ant build listener to listen for this messages, parse them and verify they are correct + // this test should then ask the listener at the end if everything was OK and assert false if not + public void testAuditMessages() throws Exception { + // We want to test a fresh install, so make sure the deploy dir doesn't pre-exist. + FileUtil.purge(DEPLOY_DIR, true); + + AntLauncher ant = new AntLauncher(); + Properties inputProps = createInputProperties("/test-audit-input.properties"); + List<BuildListener> buildListeners = createBuildListeners(); + + BundleAntProject project = ant.executeBundleDeployFile(getBuildXml("test-bundle-audit.xml"), inputProps, + buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); + assert bundleFiles != null; + assert bundleFiles.size() == 1 : bundleFiles; + assert bundleFiles.contains("test-audit.properties") : bundleFiles; + + // sanity check - make sure our recipe defined this property + ConfigurationDefinition configDef = project.getConfigurationDefinition(); + assert configDef.getPropertyDefinitions().size() == 1 : configDef.getPropertyDefinitions(); + PropertyDefinitionSimple propDef = configDef.getPropertyDefinitionSimple("listener.port"); + assert propDef != null; + + // make sure our test infrastruction setup the input properties correctly + Configuration config = project.getConfiguration(); + assert config.getProperties().size() == 1 : config.getProperties(); + assert "777".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); + + String preinstallTargetExecuted = (String) project.getProperties().get("preinstallTargetExecuted"); + assert preinstallTargetExecuted.equals("1a"); + String postinstallTargetExecuted = (String) project.getProperties().get("postinstallTargetExecuted"); + assert postinstallTargetExecuted.equals("1b"); + + assert new File(DEPLOY_DIR, "test-audit.properties").exists() : "missing file"; + assert readPropsFile(new File(DEPLOY_DIR, "test-audit.properties")).getProperty("my.listener.port").equals( + "777"); + } + private List<BuildListener> createBuildListeners() { List<BuildListener> buildListeners = new ArrayList<BuildListener>(); DefaultLogger logger = new DefaultLogger(); diff --git a/modules/common/ant-bundle/src/test/resources/test-audit-input.properties b/modules/common/ant-bundle/src/test/resources/test-audit-input.properties new file mode 100644 index 0000000..aaa7499 --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-audit-input.properties @@ -0,0 +1 @@ +listener.port=777 diff --git a/modules/common/ant-bundle/src/test/resources/test-audit.properties b/modules/common/ant-bundle/src/test/resources/test-audit.properties new file mode 100644 index 0000000..4dc4374 --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-audit.properties @@ -0,0 +1,3 @@ +my.listener.port=@@listener.port@@ +one.property=wot +two.property=gorilla? diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-audit.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-audit.xml new file mode 100644 index 0000000..687c4ba --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-audit.xml @@ -0,0 +1,39 @@ +<?xml version="1.0"?> + +<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle"> + + <rhq:bundle name="audit-test" version="1"> + + <rhq:input-property name="listener.port" type="integer"/> + + <rhq:deployment-unit name="test" preinstallTarget="preinstall" postinstallTarget="postinstall"> + <rhq:file name="test-audit.properties" destinationFile="test-audit.properties" replace="true"/> + </rhq:deployment-unit> + + </rhq:bundle> + + <target name="main"/> + + <target name="preinstall"> + <property name="preinstallTargetExecuted" value="1a"/> + <rhq:audit status="success" action="action1" info="info1" message="message1"> + preinstall successful message with port "${listener.port}" ! + </rhq:audit> + <rhq:audit status="failure" action="action2" info="info2" message="message2"> + preinstall failure message here! + </rhq:audit> + <rhq:audit status="warn" action="action3" info="info3" message="message3"> + preinstall warn message here! + </rhq:audit> + </target> + + <target name="postinstall"> + <property name="postinstallTargetExecuted" value="1b"/> + <rhq:audit /> + <rhq:audit status="SUCCESS" /> + <rhq:audit status="WARN" action="actionA" /> + <rhq:audit status="FAILURE" action="actionB" info="infoB" /> + <rhq:audit status="SUCCESS" action="actionC" info="infoC" message="messageC" /> + </target> + +</project> \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeploymentHistory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeploymentHistory.java index eb00b26..b7f28fc 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeploymentHistory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeploymentHistory.java @@ -228,7 +228,8 @@ public class BundleResourceDeploymentHistory implements Serializable { FILE_ADD("File Add"), // FILE_CHANGE("File Change"), // FILE_DOWNLOAD("File Download"), // - FILE_REMOVE("File Remove"); + FILE_REMOVE("File Remove"), // + AUDIT_MESSAGE("Audit Message");
private String displayName;
diff --git a/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java b/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java index 7f41de8..b8476b9 100644 --- a/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java +++ b/modules/plugins/ant-bundle/src/main/java/org/rhq/plugins/ant/DeploymentAuditorBuildListener.java @@ -22,12 +22,16 @@ */ package org.rhq.plugins.ant;
+import java.util.Date; + import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.util.StringUtils;
import org.rhq.core.domain.bundle.BundleResourceDeployment; import org.rhq.core.domain.bundle.BundleResourceDeploymentHistory; +import org.rhq.core.domain.bundle.BundleResourceDeploymentHistory.Category; +import org.rhq.core.domain.bundle.BundleResourceDeploymentHistory.Status; import org.rhq.core.pluginapi.bundle.BundleManagerProvider;
/** @@ -71,6 +75,38 @@ public class DeploymentAuditorBuildListener implements BuildListener { }
public void messageLogged(BuildEvent event) { + // this will see if this is an audit message (e.g. rhq:audit) and if so, send it up to the server + // see org.rhq.bundle.ant.task.AuditTask.execute() + // RHQ_AUDIT_MESSAGE___<status>___<action>___<info>___<message>___<details> + + try { + Status status = Status.SUCCESS; + String action = "Audit Message"; + String info = "Recipe Audit Message"; + String message = new Date().toString(); + String details = null; + BundleResourceDeployment deployment = this.bundleResourceDeployment; + Category category = Category.AUDIT_MESSAGE; + + String[] eventStrings = event.getMessage().split("___"); + int index = 0; + if (eventStrings[index++].equals("RHQ_AUDIT_MESSAGE")) { + try { + String statusStr = eventStrings[index++]; + status = Status.valueOf(statusStr.toUpperCase()); + action = eventStrings[index++]; + info = eventStrings[index++]; + message = eventStrings[index++]; + details = eventStrings[index++]; + } catch (ArrayIndexOutOfBoundsException e) { + // the message didn't have all the info, just skip looking for the rest and log what we have + } + } + + this.bundleManagerProvider.auditDeployment(deployment, action, info, category, status, message, details); + } catch (Exception e) { + throw new RuntimeException(e); + } return; }
@@ -101,7 +137,6 @@ public class DeploymentAuditorBuildListener implements BuildListener { return msg.toString(); }
- @SuppressWarnings( { "ThrowableResultOfMethodCallIgnored" }) private static String createMessage(String action, BuildEvent event) { StringBuilder msg = new StringBuilder(action);
commit d31fc63f7d6ea1116ef1884941ed869213fe3600 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 23 03:59:41 2010 -0500
BZ 638730 - ant bundle deployment now supports provisioning archive files in exploded or compressed form
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/DeployPropertyNames.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/DeployPropertyNames.java index 4e7d3bf..b7705e1 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/DeployPropertyNames.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/DeployPropertyNames.java @@ -6,7 +6,7 @@ package org.rhq.bundle.ant; public class DeployPropertyNames { /** System property that should always be available to Ant scripts - it's the location where the deployment should be installed */ public static final String DEPLOY_DIR = "rhq.deploy.dir"; - + /** System property that should always be available to Ant scripts - it's the ID of the bundle deployment */ public static final String DEPLOY_ID = "rhq.deploy.id";
@@ -32,7 +32,7 @@ public class DeployPropertyNames { * Optional deploy property - if true, this is a dry run or preview (that is, it should log what steps would occur * but not actually perform any of the steps); if not specified, the default is false */ - public static final Object DEPLOY_DRY_RUN = "rhq.deploy.dryRun"; + public static final String DEPLOY_DRY_RUN = "rhq.deploy.dryRun";
private DeployPropertyNames() { } diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractBundleType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractBundleType.java index cea5df4..44daf4c 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractBundleType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/AbstractBundleType.java @@ -1,21 +1,22 @@ package org.rhq.bundle.ant.type;
-import org.apache.tools.ant.types.DataType; -import org.rhq.bundle.ant.BundleAntProject; - import java.io.File; import java.util.List; import java.util.regex.Pattern;
+import org.apache.tools.ant.types.DataType; + +import org.rhq.bundle.ant.BundleAntProject; + /** * */ public abstract class AbstractBundleType extends DataType { @Override public BundleAntProject getProject() { - return (BundleAntProject)super.getProject(); + return (BundleAntProject) super.getProject(); } - + protected static Pattern getPattern(List<FileSet> fileSets) { if (fileSets == null || fileSets.isEmpty()) { return null; @@ -45,25 +46,7 @@ public abstract class AbstractBundleType extends DataType { firstIncludePattern = false; } regex.append("("); - for (int i = 0; i < includePattern.length(); i++) { - char c = includePattern.charAt(i); - if (c == '?') { - regex.append('.'); - } else if (c == '*') { - if (i + 1 < includePattern.length()) { - char c2 = includePattern.charAt(++i); - if (c2 == '*') { - regex.append(".*"); - i++; - continue; - } - } - regex.append("[^/]*"); - } else { - regex.append(c); - } - // TODO: Escape backslashes. - } + buildIncludePatternRegex(includePattern, regex); regex.append(")"); } } @@ -71,4 +54,34 @@ public abstract class AbstractBundleType extends DataType { } return Pattern.compile(regex.toString()); } + + /** + * Builds a regex expression for a single include pattern. + * + * @param includePattern the single include pattern to build a regex for + * @param regex appends all regex characters to this regex string + */ + protected static void buildIncludePatternRegex(String includePattern, StringBuilder regex) { + for (int i = 0; i < includePattern.length(); i++) { + char c = includePattern.charAt(i); + if (c == '?') { + regex.append('.'); + } else if (c == '*') { + if (i + 1 < includePattern.length()) { + char c2 = includePattern.charAt(i + 1); + if (c2 == '*') { + regex.append(".*"); + i += 2; + continue; + } + } + regex.append("[^/]*"); + } else if (c == '.') { + regex.append("\."); + } else { + regex.append(c); + } + // TODO: Escape backslashes. + } + } } diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/ArchiveType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/ArchiveType.java index 19aaaf6..d531801 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/ArchiveType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/ArchiveType.java @@ -25,15 +25,18 @@ package org.rhq.bundle.ant.type; import java.util.List; import java.util.regex.Pattern;
+import org.apache.tools.ant.BuildException; + /** - * An archive file to be exploded during the bundle deployment. Can optionally contain a rhq:replace child element - * that specifies the set of files that contain template variables (e.g. @@http.port@@) which need to be replaced with - * the value of the corresponding property. + * An archive file to be exploded during the bundle deployment (it could remain compressed if exploded="false" is specified) + * Can optionally contain a rhq:replace child element that specifies the set of files that contain + * template variables (e.g. @@http.port@@) which need to be replaced with the value of the corresponding property. * * @author Ian Springer */ public class ArchiveType extends AbstractFileType { private Pattern replacePattern; + private String exploded = Boolean.TRUE.toString();
public void addConfigured(ReplaceType replace) { List<FileSet> fileSets = replace.getFileSets(); @@ -43,4 +46,15 @@ public class ArchiveType extends AbstractFileType { public Pattern getReplacePattern() { return replacePattern; } + + public String getExploded() { + return exploded; + } + + public void setExploded(String exploded) { + if (!Boolean.TRUE.toString().equalsIgnoreCase(exploded) && !Boolean.FALSE.toString().equalsIgnoreCase(exploded)) { + throw new BuildException("'exploded' attribute must be 'true' or 'false': " + exploded); + } + this.exploded = exploded; + } } \ No newline at end of file diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java index 3727adb..31a52bc 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java @@ -51,6 +51,7 @@ public class DeploymentUnitType extends AbstractBundleType { private Map<File, File> files = new LinkedHashMap<File, File>(); private Set<File> rawFilesToReplace = new LinkedHashSet<File>(); private Set<File> archives = new LinkedHashSet<File>(); + private Map<File, Boolean> archivesExploded = new HashMap<File, Boolean>(); private Map<File, Pattern> archiveReplacePatterns = new HashMap<File, Pattern>(); private SystemServiceType systemService; private Pattern ignorePattern; @@ -98,8 +99,9 @@ public class DeploymentUnitType extends AbstractBundleType { Project.MSG_VERBOSE); }
- DeploymentData deploymentData = new DeploymentData(deploymentProps, this.archives, this.files, deployDir, - this.archiveReplacePatterns, this.rawFilesToReplace, templateEngine, this.ignorePattern, willManageRootDir); + DeploymentData deploymentData = new DeploymentData(deploymentProps, this.archives, this.files, getProject() + .getBaseDir(), deployDir, this.archiveReplacePatterns, this.rawFilesToReplace, templateEngine, + this.ignorePattern, willManageRootDir, this.archivesExploded); Deployer deployer = new Deployer(deploymentData); try { DeployDifferences diffs = getProject().getDeployDifferences(); @@ -181,6 +183,17 @@ public class DeploymentUnitType extends AbstractBundleType { return archives; }
+ /** + * Returns a map keyed on {@link #getArchives() archive names} whose values + * are either true or false, where true means the archive is to be deployed exploded + * and false means the archive should be deployed in compressed form. + * + * @return map showing how an archive should be deployed in its final form + */ + public Map<File, Boolean> getArchivesExploded() { + return archivesExploded; + } + public String getPreinstallTarget() { return preinstallTarget; } @@ -231,6 +244,8 @@ public class DeploymentUnitType extends AbstractBundleType { if (replacePattern != null) { this.archiveReplacePatterns.put(archive.getSource(), replacePattern); } + Boolean exploded = Boolean.valueOf(archive.getExploded()); + this.archivesExploded.put(archive.getSource(), exploded); }
public void addConfigured(IgnoreType ignore) { diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index a9edfc1..2c41874 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -23,6 +23,7 @@ package org.rhq.bundle.ant;
import java.io.File; +import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -30,18 +31,25 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream;
import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; +import org.rhq.core.util.ZipUtil; import org.rhq.core.util.file.FileUtil; +import org.rhq.core.util.updater.DeploymentsMetadata; +import org.rhq.core.util.updater.FileHashcodeMap;
/** * @author John Mazzitelli @@ -50,6 +58,14 @@ import org.rhq.core.util.file.FileUtil; @Test public class AntLauncherTest { private static final File DEPLOY_DIR = new File("target/test-ant-bundle").getAbsoluteFile(); + private static final String ANT_BASEDIR = "target/test-classes"; + + private int deploymentId; + + @BeforeClass + public void beforeClass() { + deploymentId = 0; + }
@AfterClass public void afterClass() { @@ -135,17 +151,12 @@ public class AntLauncherTest {
assert new File(DEPLOY_DIR, "subdir/test.properties").exists() : "missing file"; assert new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "missing archived bundle file"; + assert new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties").exists() : "missing subdir archive file"; assert unrelatedFile.exists() : "unrelated file was removed during the install"; - } - - private List<BuildListener> createBuildListeners() { - List<BuildListener> buildListeners = new ArrayList<BuildListener>(); - DefaultLogger logger = new DefaultLogger(); - logger.setMessageOutputLevel(Project.MSG_DEBUG); - logger.setOutputPrintStream(System.out); - logger.setErrorPrintStream(System.err); - buildListeners.add(logger); - return buildListeners; + assert readPropsFile(new File(DEPLOY_DIR, "subdir/test.properties")).getProperty("junk.listener.port").equals( + "10000"); + assert readPropsFile(new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties")).getProperty( + "templatized.variable").equals("10000"); }
@Test(dependsOnMethods = "testInstall") @@ -193,7 +204,12 @@ public class AntLauncherTest {
assert new File(DEPLOY_DIR, "subdir/test.properties").exists() : "missing file"; assert new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "missing archived bundle file"; + assert new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties").exists() : "missing subdir archive file"; assert !unrelatedFile.exists() : "we are managing root dir so unrelated file should be removed during upgrade"; + assert readPropsFile(new File(DEPLOY_DIR, "subdir/test.properties")).getProperty("junk.listener.port").equals( + "20000"); + assert readPropsFile(new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties")).getProperty( + "templatized.variable").equals("20000"); }
public void testUpgradeNoManageRootDir() throws Exception { @@ -244,25 +260,223 @@ public class AntLauncherTest {
assert new File(DEPLOY_DIR, "subdir/test.properties").exists() : "missing file"; assert new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "missing archived bundle file"; + assert new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties").exists() : "missing subdir archive file"; assert unrelatedFile.exists() : "we are NOT managing root dir so unrelated file should NOT be removed during upgrade"; + assert readPropsFile(new File(DEPLOY_DIR, "subdir/test.properties")).getProperty("junk.listener.port").equals( + "20000"); + assert readPropsFile(new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties")).getProperty( + "templatized.variable").equals("20000"); + } + + public void testInstallCompressedZipNoDryRun() throws Exception { + testInstallCompressedZip(false); + } + + public void testInstallCompressedZipDryRun() throws Exception { + testInstallCompressedZip(true); + } + + private void testInstallCompressedZip(boolean dryRun) throws Exception { + // We want to test a fresh install, so make sure the deploy dir doesn't pre-exist. + FileUtil.purge(DEPLOY_DIR, true); + + AntLauncher ant = new AntLauncher(); + Properties inputProps = createInputProperties("/test-bundle-compressed-archives-input.properties", dryRun); + List<BuildListener> buildListeners = createBuildListeners(); + + BundleAntProject project = ant.executeBundleDeployFile(getBuildXml("test-bundle-compressed-archives.xml"), + inputProps, buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); + assert bundleFiles != null; + assert bundleFiles.size() == 1 : bundleFiles; + assert bundleFiles.contains("file.zip") : bundleFiles; + + assert project.getBundleName().equals("test compressed archive files"); + assert project.getBundleVersion().equals("1.0"); + assert project.getBundleDescription() == null; + + // while we are here, let's see that we have 0 config props + ConfigurationDefinition configDef = project.getConfigurationDefinition(); + assert configDef.getPropertyDefinitions().size() == 0 : configDef.getPropertyDefinitions(); + Configuration config = project.getConfiguration(); + assert config.getProperties().size() == 0 : config.getProperties(); + + if (!dryRun) { + assert new File(DEPLOY_DIR, "file.zip").exists() : "should be here, we told it to stay compressed"; + } else { + assert !new File(DEPLOY_DIR, "file.zip").exists() : "dry run - should not be here"; + } + + assert !new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "should not have exploded this"; + assert !new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties").exists() : "should not have exploded this"; + assert !new File(DEPLOY_DIR, "archived-subdir").isDirectory() : "should not still have the exploded dir"; + + DeploymentsMetadata dm = new DeploymentsMetadata(DEPLOY_DIR); + if (!dryRun) { + FileHashcodeMap fhm = dm.getCurrentDeploymentFileHashcodes(); + assert !fhm.containsKey("archived-bundle-file.txt") : "should not have metadata - this is inside the compressed zip"; + assert !fhm.containsKey("archived-subdir/archived-file-in-subdir.properties") : "should not have metadata - this is inside the compressed zip"; + assert fhm.containsKey("file.zip") : "should have metadata for this - we didn't explode it, we just have this compressed file"; + + // test that we created the zip OK. Note that our test did not do any file replacing/realization of templates + final String[] templateVarValue = new String[] { null }; + final Integer[] entries = new Integer[] { 0 }; + ZipUtil.walkZipFile(new File(DEPLOY_DIR, "file.zip"), new ZipUtil.ZipEntryVisitor() { + @Override + public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception { + if (entry.getName().equals("archived-subdir/archived-file-in-subdir.properties")) { + Properties props = new Properties(); + props.load(stream); + templateVarValue[0] = props.getProperty("templatized.variable"); + } + if (!entry.isDirectory()) { + entries[0] = Integer.valueOf(entries[0].intValue() + 1); + } + return true; + } + }); + assert templateVarValue[0] != null && templateVarValue[0].equals("@@listener.port@@") : templateVarValue[0]; + assert entries[0].intValue() == 2 : entries[0]; // we only counted the file entries + } else { + try { + dm.getCurrentDeploymentFileHashcodes(); + assert false : "this was a dry run, we should not have written our metadata to the filesystem"; + } catch (Exception e) { + // expected + } + } + } + + public void testInstallCompressedZipWithTemplatizedFilesNoDryRun() throws Exception { + testInstallCompressedZipWithTemplatizedFiles(false); + } + + public void testInstallCompressedZipWithTemplatizedFilesDryRun() throws Exception { + testInstallCompressedZipWithTemplatizedFiles(true); + } + + private void testInstallCompressedZipWithTemplatizedFiles(boolean dryRun) throws Exception { + // We want to test a fresh install, so make sure the deploy dir doesn't pre-exist. + FileUtil.purge(DEPLOY_DIR, true); + + AntLauncher ant = new AntLauncher(); + Properties inputProps = createInputProperties("/test-bundle-compressed-archives-input.properties", dryRun); + List<BuildListener> buildListeners = createBuildListeners(); + + BundleAntProject project = ant.executeBundleDeployFile( + getBuildXml("test-bundle-compressed-archives-with-replace.xml"), inputProps, buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); + assert bundleFiles != null; + assert bundleFiles.size() == 1 : bundleFiles; + assert bundleFiles.contains("file.zip") : bundleFiles; + + assert project.getBundleName().equals("test compressed archive files"); + assert project.getBundleVersion().equals("1.0"); + assert project.getBundleDescription() == null; + + // we have one property that we use to realize our content + ConfigurationDefinition configDef = project.getConfigurationDefinition(); + assert configDef.getPropertyDefinitions().size() == 1 : configDef.getPropertyDefinitions(); + PropertyDefinitionSimple propDef = configDef.getPropertyDefinitionSimple("listener.port"); + assert propDef != null; + assert propDef.getType() == PropertySimpleType.INTEGER; + assert propDef.getDefaultValue() == null : "recipe didn't define a default for our property"; + assert propDef.getDescription() == null : "recipe didn't define a description for our property"; + assert propDef.isRequired() : "recipe didn't make the property required, but the default should be required"; + + if (!dryRun) { + assert new File(DEPLOY_DIR, "file.zip").exists() : "should be here, we told it to stay compressed"; + } else { + assert !new File(DEPLOY_DIR, "file.zip").exists() : "this was a dry run, should not be here"; + } + assert !new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "should not have exploded this"; + assert !new File(DEPLOY_DIR, "archived-subdir/archived-file-in-subdir.properties").exists() : "should not have exploded this"; + assert !new File(DEPLOY_DIR, "archived-subdir").isDirectory() : "should not still have the exploded dir"; + + DeploymentsMetadata dm = new DeploymentsMetadata(DEPLOY_DIR); + if (!dryRun) { + FileHashcodeMap fhm = dm.getCurrentDeploymentFileHashcodes(); + assert !fhm.containsKey("archived-bundle-file.txt") : "should not have metadata - this is inside the compressed zip"; + assert !fhm.containsKey("archived-subdir/archived-file-in-subdir.properties") : "should not have metadata - this is inside the compressed zip"; + assert fhm.containsKey("file.zip") : "should have metadata for this - we didn't explode it, we just have this compressed file"; + + // test that the file in the zip is realized + final String[] templateVarValue = new String[] { null }; + final Integer[] entries = new Integer[] { 0 }; + ZipUtil.walkZipFile(new File(DEPLOY_DIR, "file.zip"), new ZipUtil.ZipEntryVisitor() { + @Override + public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception { + if (entry.getName().equals("archived-subdir/archived-file-in-subdir.properties")) { + Properties props = new Properties(); + props.load(stream); + templateVarValue[0] = props.getProperty("templatized.variable"); + } + if (!entry.isDirectory()) { + entries[0] = Integer.valueOf(entries[0].intValue() + 1); + } + return true; + } + }); + assert templateVarValue[0] != null && templateVarValue[0].equals("12345") : templateVarValue[0]; + assert entries[0].intValue() == 2 : entries[0]; // we only counted the file entries + } else { + try { + dm.getCurrentDeploymentFileHashcodes(); + assert false : "this was a dry run, we should not have written our metadata to the filesystem"; + } catch (Exception e) { + // expected + } + } + } + + private List<BuildListener> createBuildListeners() { + List<BuildListener> buildListeners = new ArrayList<BuildListener>(); + DefaultLogger logger = new DefaultLogger(); + logger.setMessageOutputLevel(Project.MSG_DEBUG); + logger.setOutputPrintStream(System.out); + logger.setErrorPrintStream(System.err); + buildListeners.add(logger); + return buildListeners; }
private Properties createInputProperties(String resourcePath) throws IOException { + return createInputProperties(resourcePath, false); + } + + private Properties createInputProperties(String resourcePath, boolean dryRun) throws IOException { Properties inputProps = new Properties(); inputProps.setProperty(DeployPropertyNames.DEPLOY_DIR, DEPLOY_DIR.getPath()); - inputProps.setProperty(DeployPropertyNames.DEPLOY_ID, "100"); + inputProps.setProperty(DeployPropertyNames.DEPLOY_ID, String.valueOf(++this.deploymentId)); inputProps.setProperty(DeployPropertyNames.DEPLOY_PHASE, DeploymentPhase.INSTALL.name()); - InputStream inputStream = this.getClass().getResourceAsStream(resourcePath); + if (dryRun) { + inputProps.setProperty(DeployPropertyNames.DEPLOY_DRY_RUN, Boolean.TRUE.toString()); + } + if (resourcePath != null) { + InputStream inputStream = this.getClass().getResourceAsStream(resourcePath); + try { + inputProps.load(inputStream); + } finally { + inputStream.close(); + } + } + return inputProps; + } + + private Properties readPropsFile(File propFile) throws Exception { + Properties props = new Properties(); + InputStream inputStream = new FileInputStream(propFile); try { - inputProps.load(inputStream); + props.load(inputStream); } finally { inputStream.close(); } - return inputProps; + return props; }
private File getBuildXml(String name) throws Exception { - File file = new File("target/test-classes", name); + File file = new File(ANT_BASEDIR, name); assert file.exists() : "The test Ant build script doesn't exist: " + file.getAbsolutePath(); return file; } @@ -286,4 +500,32 @@ public class AntLauncherTest { File destFile = new File(destDir, fileName); return writeFile(content, destFile); } + + private File createZip(String[] content, File destDir, String zipName, String[] entryName) throws Exception { + FileOutputStream stream = null; + ZipOutputStream out = null; + + try { + destDir.mkdirs(); + File zipFile = new File(destDir, zipName); + stream = new FileOutputStream(zipFile); + out = new ZipOutputStream(stream); + + assert content.length == entryName.length; + for (int i = 0; i < content.length; i++) { + ZipEntry zipAdd = new ZipEntry(entryName[i]); + zipAdd.setTime(System.currentTimeMillis()); + out.putNextEntry(zipAdd); + out.write(content[i].getBytes()); + } + return zipFile; + } finally { + if (out != null) { + out.close(); + } + if (stream != null) { + stream.close(); + } + } + } } diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java new file mode 100644 index 0000000..8757540 --- /dev/null +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java @@ -0,0 +1,156 @@ +/* + * 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.bundle.ant.type; + +import java.util.regex.Pattern; + +import org.testng.annotations.Test; + +@Test +public class AbstractBundleTypeTest { + public void testGetPattern() { + Pattern regex; + + regex = assertIncludePatternRegex("easy.txt", "easy\.txt", "easy.txt"); + assert !regex.matcher("easyXtxt").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("Xeasy.txt").matches(); + assert !regex.matcher("easy.txtX").matches(); + assert !regex.matcher("/easy.txt").matches(); + assert !regex.matcher("easy.txt/").matches(); + + regex = assertIncludePatternRegex("another.one/easy.txt", "another\.one/easy\.txt", "another.one/easy.txt"); + assert !regex.matcher("anotherXone/easyXtxt").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("another.one/easy.txtX").matches(); + assert !regex.matcher("another.one/easy.txt/X").matches(); + assert !regex.matcher("Xanother.one/easy.txt").matches(); + assert !regex.matcher("X/another.one/easy.txt").matches(); + assert !regex.matcher("/another.one/easy.txt").matches(); + assert !regex.matcher("another.one/easy.txt/").matches(); + + regex = assertIncludePatternRegex("*.properties", "[^/]*\.properties", "any.properties"); + assert !regex.matcher("anyXproperties").matches() : "should not have matched, is the . escaped?"; + assert regex.matcher("with space.properties").matches(); + assert !regex.matcher("subdir/any.properties").matches(); + assert !regex.matcher("any.properties/foo").matches(); + + regex = assertIncludePatternRegex("a*b.properties", "a[^/]*b\.properties", "a123b.properties"); + assert !regex.matcher("a123bXproperties").matches() : "should not have matched, is the . escaped?"; + assert regex.matcher("a b.properties").matches(); + assert regex.matcher("ab.properties").matches(); + assert !regex.matcher("subdir/a123b.properties").matches(); + assert !regex.matcher("a123b.properties/foo").matches(); + + regex = assertIncludePatternRegex("/*.properties", "/[^/]*\.properties", "/any.properties"); + assert !regex.matcher("/anyXproperties").matches() : "should not have matched, is the . escaped?"; + assert regex.matcher("/with space.properties").matches(); + assert !regex.matcher("subdir/any.properties").matches(); + assert !regex.matcher("/any.properties/foo").matches(); + + regex = assertIncludePatternRegex("?.properties", ".\.properties", "a.properties"); + assert !regex.matcher("aXproperties").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("ab.properties").matches(); + assert regex.matcher(" .properties").matches(); + assert !regex.matcher(".properties").matches(); + assert !regex.matcher("subdir/a.properties").matches(); + assert !regex.matcher("a.properties/foo").matches(); + + regex = assertIncludePatternRegex("a?b.properties", "a.b\.properties", "aNb.properties"); + assert !regex.matcher("aNbXproperties").matches() : "should not have matched, is the . escaped?"; + assert regex.matcher("a b.properties").matches(); + assert !regex.matcher("ab.properties").matches(); + assert !regex.matcher("subdir/aNb.properties").matches(); + assert !regex.matcher("aNb.properties/foo").matches(); + + regex = assertIncludePatternRegex("/?.properties", "/.\.properties", "/a.properties"); + assert !regex.matcher("/aXproperties").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("/ab.properties").matches(); + assert regex.matcher("/ .properties").matches(); + assert !regex.matcher("/.properties").matches(); + assert !regex.matcher("subdir/a.properties").matches(); + assert !regex.matcher("/a.properties/foo").matches(); + + regex = assertIncludePatternRegex("file*.xml", "file[^/]*\.xml", "fileANY.xml"); + assert !regex.matcher("fileANYXxml").matches() : "should not have matched, is the . escaped?"; + assert regex.matcher("fileWITH SPACE.xml").matches(); + assert !regex.matcher("subdir/fileANY.xml").matches(); + assert !regex.matcher("fileANY.xml/foo").matches(); + assert regex.matcher("file.xml").matches(); + + regex = assertIncludePatternRegex("*/*.properties", "[^/]*/[^/]*\.properties", "aaa/bbb.properties"); + assert !regex.matcher("aaa/bbbXproperties").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("bbb.properties").matches(); + assert regex.matcher("subdir1/abc.properties").matches(); + assert !regex.matcher("subdir2/subdir1/abc.properties").matches(); + assert !regex.matcher("subdir1/abc.properties/foo").matches(); + + regex = assertIncludePatternRegex("*/*/*.properties", "[^/]*/[^/]*/[^/]*\.properties", + "aaa/bbb/ccc.properties"); + assert !regex.matcher("aaa/bbb/cccXproperties").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("ccc.properties").matches(); + assert !regex.matcher("bbb/ccc.properties").matches(); + assert !regex.matcher("toomany/aaa/bbb/ccc.properties").matches(); + assert !regex.matcher("aaa/bbb/ccc.properties/foo").matches(); + + // ** = any level, including root level + regex = assertIncludePatternRegex("**/*.properties", ".*[^/]*\.properties", "aaa/bbb/ccc.properties"); + assert !regex.matcher("aaa/bbb/cccXproperties").matches() : "should not have matched, is the . escaped?"; + assert regex.matcher("bbb.properties").matches(); + assert regex.matcher("subdir1/abc.properties").matches(); + assert regex.matcher("subdir2/subdir1/abc.properties").matches(); + assert !regex.matcher("subdir1/abc.properties/foo").matches(); + + regex = assertIncludePatternRegex("abc/**/*.properties", "abc/.*[^/]*\.properties", "abc/aaa/bbb.properties"); + assert !regex.matcher("abc/aaa/bbbXproperties").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("bbb.properties").matches(); + assert regex.matcher("abc/aaa.properties").matches(); + assert regex.matcher("abc/aaa/bbb/ccc.properties").matches(); + assert !regex.matcher("abc/aaa/bbb/ccc.properties/foo").matches(); + + regex = assertIncludePatternRegex("abc/**/xyz/*.properties", "abc/.*xyz/[^/]*\.properties", + "abc/aaa/xyz/bbb.properties"); + assert !regex.matcher("abc/aaa/xyz/bbbXproperties").matches() : "should not have matched, is the . escaped?"; + assert !regex.matcher("bbb.properties").matches(); + assert regex.matcher("abc/xyz/ccc.properties").matches(); + assert regex.matcher("abc/aaa/bbb/xyz/ccc.properties").matches(); + assert !regex.matcher("abc/aaa/bbb/xyz/ccc.properties/foo").matches(); + } + + /** + * @param patternToTest the include pattern to test - this is the string in the ant script like "*.properties" + * @param expectedRegex this is the regex pattern that we expect to result from the patternToTest + * @param valueToTest this is a value that should match the expectedRegex + * @return the compiled Pattern, for further testing by the caller + */ + private Pattern assertIncludePatternRegex(String patternToTest, String expectedRegex, String valueToTest) { + StringBuilder regex = new StringBuilder(); + AbstractBundleType.buildIncludePatternRegex(patternToTest, regex); + assert regex.toString().equals(expectedRegex) : "Tested={" + patternToTest + "}; Expected={" + expectedRegex + + "}; Actual={" + regex + "}"; + + assert Pattern.compile(regex.toString()).matcher(valueToTest).matches() : "The ExpectedRegex {" + expectedRegex + + "} did not match the ValueToTest {" + valueToTest + "} - this unit test does not appear valid"; + + return Pattern.compile(regex.toString()); + } +} diff --git a/modules/common/ant-bundle/src/test/resources/file.zip b/modules/common/ant-bundle/src/test/resources/file.zip index 922658a..969a6c1 100644 Binary files a/modules/common/ant-bundle/src/test/resources/file.zip and b/modules/common/ant-bundle/src/test/resources/file.zip differ diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-input.properties b/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-input.properties new file mode 100644 index 0000000..b66ba1d --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-input.properties @@ -0,0 +1 @@ +listener.port = 12345 diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-with-replace.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-with-replace.xml new file mode 100644 index 0000000..ea4255a --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives-with-replace.xml @@ -0,0 +1,21 @@ +<?xml version="1.0"?> + +<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle"> + + <rhq:bundle name="test compressed archive files" version="1.0"> + + <rhq:input-property name="listener.port" type="integer"/> + + <rhq:deployment-unit name="appserver"> + <rhq:archive name="file.zip" exploded="false"> + rhq:replace + <rhq:fileset includes="**/*.foo"/> + <rhq:fileset includes="**/*.properties"/> + </rhq:replace> + </rhq:archive> + </rhq:deployment-unit> + + </rhq:bundle> + + <target name="main"/> +</project> \ No newline at end of file diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives.xml new file mode 100644 index 0000000..a35b6ac --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-compressed-archives.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> + +<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle"> + + <rhq:bundle name="test compressed archive files" version="1.0"> + + <rhq:deployment-unit name="appserver"> + <rhq:archive name="file.zip" exploded="false"/> + </rhq:deployment-unit> + + </rhq:bundle> + + <target name="main"/> +</project> \ No newline at end of file diff --git a/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java b/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java index 5116631..652bcda 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java @@ -35,6 +35,7 @@ import java.util.Set; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -566,22 +567,76 @@ public class Deployer { boolean dryRun) throws Exception {
// NOTE: right now, this only adds to the "realized" set of files is diff, no need to track "added" or "changed" here - FileHashcodeMap newFileHashCodeMap = new FileHashcodeMap();
+ // get information about the source dir - will be needed if we were told to not explode a zip + String sourceDirAbsPath = this.deploymentData.getSourceDir().getAbsolutePath(); + int sourceDirLength = sourceDirAbsPath.length(); + // extract all zip files ExtractorZipFileVisitor visitor; for (File zipFile : this.deploymentData.getZipFiles()) { - debug("Extracting zip [", zipFile, "] entries. dryRun=", dryRun); + Boolean exploded = this.deploymentData.getZipsExploded().get(zipFile); + if (exploded == null) { + exploded = Boolean.TRUE; // the default is to explode the archive + } + + debug("Extracting zip [", zipFile, "] entries. exploded=", exploded, ", dryRun=", dryRun);
Pattern realizeRegex = null; if (this.deploymentData.getZipEntriesToRealizeRegex() != null) { realizeRegex = this.deploymentData.getZipEntriesToRealizeRegex().get(zipFile); } - visitor = new ExtractorZipFileVisitor(this.deploymentData.getDestinationDir(), realizeRegex, - this.deploymentData.getTemplateEngine(), currentFilesToLeaveAlone.keySet(), diff, dryRun); - ZipUtil.walkZipFile(zipFile, visitor); - newFileHashCodeMap.putAll(visitor.getFileHashcodeMap()); + + if (exploded.booleanValue()) { + // EXPLODED + visitor = new ExtractorZipFileVisitor(this.deploymentData.getDestinationDir(), realizeRegex, + this.deploymentData.getTemplateEngine(), currentFilesToLeaveAlone.keySet(), diff, dryRun); + ZipUtil.walkZipFile(zipFile, visitor); + newFileHashCodeMap.putAll(visitor.getFileHashcodeMap()); // exploded into individual files + } else { + // COMPRESSED + + // Note: there is a requirement that all zip files must be located in the sourceDir - this is why. We need + // the path of the zip relative to the source dir so we can copy it to the same relative location + // under the destination dir. Without doing this, if the zip is in a subdirectory, we won't know where to + // put it under the destination dir. + String zipRelativePath = zipFile.getAbsolutePath().substring(sourceDirLength); + if (zipRelativePath.startsWith("/") || zipRelativePath.startsWith("\")) { + zipRelativePath = zipRelativePath.substring(1); + } + File compressedFile = new File(this.deploymentData.getDestinationDir(), zipRelativePath); + + if (this.deploymentData.getTemplateEngine() != null && realizeRegex != null) { + // we need to explode it to perform the realization of templatized variables + // TODO: can we do this in another tmp location and build the zip in the dest dir? + visitor = new ExtractorZipFileVisitor(this.deploymentData.getDestinationDir(), realizeRegex, + this.deploymentData.getTemplateEngine(), currentFilesToLeaveAlone.keySet(), diff, dryRun); + ZipUtil.walkZipFile(zipFile, visitor); + // we have to compress the file again - our new compressed file will have the new realized files in them + if (!dryRun) { + createZipFile(compressedFile, this.deploymentData.getDestinationDir(), visitor + .getFileHashcodeMap()); + } + } + + // Copy the archive to the destination dir if we need to. Generate its hashcode and add it to the new file hashcode map + MessageDigestGenerator hashcodeGenerator = new MessageDigestGenerator(); + String compressedFileHashcode; + if (!dryRun) { + if (!compressedFile.exists()) { + if (compressedFile.getParentFile() != null) { + compressedFile.getParentFile().mkdirs(); + } + FileUtil.copyFile(zipFile, compressedFile); + } + compressedFileHashcode = hashcodeGenerator.calcDigestString(compressedFile); + } else { + // use source zip for hash - should be the same as the would-be compressed file since we aren't realizing files in it + compressedFileHashcode = hashcodeGenerator.calcDigestString(zipFile); + } + newFileHashCodeMap.put(zipRelativePath, compressedFileHashcode); + } }
// copy all raw files @@ -681,6 +736,73 @@ public class Deployer { }
/** + * Create a zip file by adding all the files found in the file hashcode map. The + * relative paths found in the map's key set are relative to the rootDir directory. + * The files are stored in the given zipFile. + * + * @param zipFile where to zip up all the files + * @param rootDir all relative file paths are relative to this root directory + * @param fileHashcodeMap the key set tells us all the files that need to be zipped up + * + * @throws Exception + */ + private void createZipFile(File zipFile, File rootDir, FileHashcodeMap fileHashcodeMap) throws Exception { + if (zipFile.getParentFile() != null) { + zipFile.getParentFile().mkdirs(); + } + + Set<File> childrenOfRootToDelete = new HashSet<File>(); + + ZipOutputStream zos = null; + try { + zos = new ZipOutputStream(new FileOutputStream(zipFile)); + + for (String relativeFileToZip : fileHashcodeMap.keySet()) { + File fileToZip = new File(rootDir, relativeFileToZip); + FileInputStream fis = null; + try { + fis = new FileInputStream(fileToZip); + ZipEntry zipEntry = new ZipEntry(relativeFileToZip); + zos.putNextEntry(zipEntry); + StreamUtil.copy(fis, zos, false); + } finally { + if (fis != null) { + fis.close(); + } + + // Remember the location to delete it later. To speed up the deletes, we only remember + // the locations of the direct children under the rootDir. Since we know all zip content + // is located under those locations, we'll recursively delete everything under those + // rootDir children. We obviously can't delete everything under rootDir because there + // could be files in there not related to our zip file. + File childOfRoot = fileToZip; + while (childOfRoot != null) { + File parent = childOfRoot.getParentFile(); + if (parent.equals(rootDir)) { + childrenOfRootToDelete.add(childOfRoot); + break; + } else { + childOfRoot = parent; + } + } + } + } + + } finally { + if (zos != null) { + zos.close(); + } + } + + // we are done zipping up all files, delete all the individual files that are exploded that are now in the zip + for (File childOfRootToDelete : childrenOfRootToDelete) { + FileUtil.purge(childOfRootToDelete, true); + } + + return; + } + + /** * Performs in-memory-only calculations to determine where new files would go and what * their new hashcodes would be. * diff --git a/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java b/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java index b1fac47..e81fbaa 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java @@ -43,11 +43,13 @@ public class DeploymentData { private final Set<File> zipFiles; private final Map<File, File> rawFiles; private final File destinationDir; + private final File sourceDir; private final Map<File, Pattern> zipEntriesToRealizeRegex; private final Set<File> rawFilesToRealize; private final TemplateEngine templateEngine; private final Pattern ignoreRegex; private final boolean manageRootDir; + private final Map<File, Boolean> zipsExploded;
/** * Constructors that prepares this object with the data that is necessary in order to deploy archive/file content @@ -60,6 +62,7 @@ public class DeploymentData { * in which case they are relative to destDir and can have subdirectories and/or a different filename * than what the file is named currently) * @param destinationDir the root directory where the content is to be deployed + * @param sourceDir the root directory where the source files (zips and raw files) are located * @param zipEntriesToRealizeRegex the patterns of files (whose paths are relative to destDir) that * must have replacement variables within them replaced with values * obtained via the given template engine. The key is the name of the zip file @@ -77,34 +80,45 @@ public class DeploymentData { * The purpose of this is to be able to write files to an existing directory that has other * unrelated files in it that need to remain intact. e.g. the deploy/ directory of JBossAS. * Note: regardless of this setting, all subdirectories under the root dir will be managed. + * @param zipsExploded if not <code>null</code>, this is a map keyed on zip files whose values indicate + * if the zips should be exploded (true) or remain compressed after the deployment + * is finished (false). If a zip file is not found in this map, true is the default. */ public DeploymentData(DeploymentProperties deploymentProps, Set<File> zipFiles, Map<File, File> rawFiles, - File destinationDir, Map<File, Pattern> zipEntriesToRealizeRegex, Set<File> rawFilesToRealize, - TemplateEngine templateEngine, Pattern ignoreRegex, boolean manageRootDir) { + File sourceDir, File destinationDir, Map<File, Pattern> zipEntriesToRealizeRegex, Set<File> rawFilesToRealize, + TemplateEngine templateEngine, Pattern ignoreRegex, boolean manageRootDir, Map<File, Boolean> zipsExploded) {
if (deploymentProps == null) { throw new IllegalArgumentException("deploymentProps == null"); } if (destinationDir == null) { - throw new IllegalArgumentException("destDir == null"); + throw new IllegalArgumentException("destinationDir == null"); + } + if (sourceDir == null) { + throw new IllegalArgumentException("sourceDir == null"); }
if (zipFiles == null) { - zipFiles = new HashSet<File>(); + zipFiles = new HashSet<File>(0); } if (rawFiles == null) { - rawFiles = new HashMap<File, File>(); + rawFiles = new HashMap<File, File>(0); } if ((zipFiles.size() == 0) && (rawFiles.size() == 0)) { throw new IllegalArgumentException("zipFiles/rawFiles are empty - nothing to do"); } + if (zipsExploded == null) { + zipsExploded = new HashMap<File, Boolean>(0); + }
this.deploymentProps = deploymentProps; this.zipFiles = zipFiles; this.rawFiles = rawFiles; this.destinationDir = destinationDir; + this.sourceDir = sourceDir; this.ignoreRegex = ignoreRegex; this.manageRootDir = manageRootDir; + this.zipsExploded = zipsExploded;
// if there is nothing to realize or we have no template engine to obtain replacement values, then we null things out if (templateEngine == null || (zipEntriesToRealizeRegex == null && rawFilesToRealize == null)) { @@ -136,6 +150,10 @@ public class DeploymentData { return destinationDir; }
+ public File getSourceDir() { + return sourceDir; + } + public Map<File, Pattern> getZipEntriesToRealizeRegex() { return zipEntriesToRealizeRegex; } @@ -155,4 +173,8 @@ public class DeploymentData { public boolean isManageRootDir() { return manageRootDir; } + + public Map<File, Boolean> getZipsExploded() { + return zipsExploded; + } } diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java index 5f0fca6..69d6d53 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java @@ -255,8 +255,8 @@ public class DeployerTest { File destDir = tmpDir; Map<File, Pattern> filesToRealizeRegex1 = new HashMap<File, Pattern>(1); filesToRealizeRegex1.put(testZipFile1, realizeRegex); - DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex1, - null, templateEngine, ignoreRegex, true); + DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, + filesToRealizeRegex1, null, templateEngine, ignoreRegex, true, null); Deployer deployer = new Deployer(dd); diff = new DeployDifferences();
@@ -291,8 +291,8 @@ public class DeployerTest { rawFiles.put(testRawFileB, updaterBabsolute); // raw file to absolute path Map<File, Pattern> filesToRealizeRegex2 = new HashMap<File, Pattern>(1); filesToRealizeRegex2.put(testZipFile2, realizeRegex); - dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex2, null, - templateEngine, ignoreRegex, true); + dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, filesToRealizeRegex2, null, + templateEngine, ignoreRegex, true, null); deployer = new Deployer(dd); diff = new DeployDifferences(); deployer.deploy(diff); @@ -419,8 +419,8 @@ public class DeployerTest { rawFiles = new HashMap<File, File>(2); rawFiles.put(testRawFileA, updaterAabsolute); // source raw file to absolute path rawFiles.put(testRawFileBChange1, updaterBabsolute); // source raw file to absolute path - dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex2, null, - templateEngine, ignoreRegex, true); + dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, filesToRealizeRegex2, null, + templateEngine, ignoreRegex, true, null); deployer = new Deployer(dd); diff = new DeployDifferences(); deployer.deploy(diff); @@ -459,8 +459,8 @@ public class DeployerTest { rawFiles = new HashMap<File, File>(2); rawFiles.put(testRawFileAChange, updaterAabsolute); // source raw file to absolute path rawFiles.put(testRawFileBChange2, updaterBabsolute); // source raw file to absolute path - dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex2, null, - templateEngine, ignoreRegex, true); + dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, filesToRealizeRegex2, null, + templateEngine, ignoreRegex, true, null); deployer = new Deployer(dd); diff = new DeployDifferences(); deployer.deploy(diff); @@ -525,8 +525,8 @@ public class DeployerTest { Pattern ignoreRegex = null; Set<File> realizeRawFiles1 = new HashSet<File>(1); realizeRawFiles1.add(testRawFileB); - DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, null, - realizeRawFiles1, templateEngine, ignoreRegex, true); + DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, null, + realizeRawFiles1, templateEngine, ignoreRegex, true, null); Deployer deployer = new Deployer(dd); DeployDifferences diff = new DeployDifferences(); FileHashcodeMap map = deployer.deploy(diff); @@ -579,8 +579,8 @@ public class DeployerTest { realizeRawFiles1.add(testZipFile1); realizeRawFiles1.add(testZipFile2); realizeRawFiles1.add(testRawFileB); - DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, null, - realizeRawFiles1, templateEngine, ignoreRegex, true); + DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, null, + realizeRawFiles1, templateEngine, ignoreRegex, true, null); Deployer deployer = new Deployer(dd); DeployDifferences listener = new DeployDifferences(); deployer.deploy(listener); @@ -677,8 +677,8 @@ public class DeployerTest { Map<File, Pattern> realizeRegex1 = new HashMap<File, Pattern>(1); realizeRegex1.put(testZipFile1, filesToRealizeRegex);
- DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, realizeRegex1, null, - templateEngine, ignoreRegex, true); + DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, tmpDir, destDir, realizeRegex1, + null, templateEngine, ignoreRegex, true, null); Deployer deployer = new Deployer(dd); DeployDifferences listener = new DeployDifferences(); deployer.deploy(listener); diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java index 88d2731..4ef558b 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java @@ -101,8 +101,8 @@ public class ManageRootDirTest { this.originalZipFiles = new HashSet<File>(1); this.originalZipFiles.add(originalZipFile); this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); - DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, - null, null, false); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, tmpDir, deployDir, null, + null, null, null, false, null); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = new File(deployDir, originalFileName); @@ -241,8 +241,8 @@ public class ManageRootDirTest { this.originalZipFiles = new HashSet<File>(1); this.originalZipFiles.add(originalZipFile); this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); - DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, - null, null, false); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, tmpDir, deployDir, null, + null, null, null, false, null); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); assert new File(this.deployDir, origFileName1).exists(); @@ -261,7 +261,8 @@ public class ManageRootDirTest { new String[] { newFileName1, newFileName2 }); HashSet<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile); - dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, false); + dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, null, false, + null); deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap = deployer.deploy(this.diff); assert new File(this.deployDir, newFileName1).exists(); @@ -275,8 +276,8 @@ public class ManageRootDirTest { }
private void baseX_X_X(boolean dryRun) throws Exception { - DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null, false); + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, tmpDir, deployDir, null, null, + null, null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -319,8 +320,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -367,8 +368,8 @@ public class ManageRootDirTest { String newHashcode = MessageDigestGenerator.getDigestString(newContent); writeFile(newContent, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null, false); + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, tmpDir, deployDir, null, null, + null, null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -417,8 +418,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -467,8 +468,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -531,8 +532,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -594,8 +595,8 @@ public class ManageRootDirTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -650,8 +651,8 @@ public class ManageRootDirTest { private void baseNoCurrent(boolean dryRun) throws Exception { assert this.currentFile.delete() : "Failed to delete the current file, cannot prepare the test";
- DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null, false); + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, tmpDir, deployDir, null, null, + null, null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -702,8 +703,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -767,8 +768,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -842,8 +843,8 @@ public class ManageRootDirTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -883,7 +884,8 @@ public class ManageRootDirTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, originalZipFiles, null, deployDir, null, null, null, null, false); + dd = new DeploymentData(v1Duplicate, originalZipFiles, null, tmpDir, deployDir, null, null, null, null, false, + null); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; @@ -933,8 +935,8 @@ public class ManageRootDirTest { Pattern iRegex = Pattern.compile(".*ignoreSubdir.*"); // this matches the subdirectory name, thus everything under it is ignored assert ignoredFile.exists() : "for some reason we couldn't create our test file; cannot know if clean worked";
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, iRegex, - false); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + iRegex, false, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff, true, dryRun); // note: clean is true diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java index 16275ef..6b6bcdf 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java @@ -92,8 +92,8 @@ public class SimpleDeployerRawFileTest { this.sourceRawFiles = new HashMap<File, File>(1); this.sourceRawFiles.put(sourceRawFile, new File(extDir, originalFileName)); // note we name it different than the source file this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); - DeploymentData dd = new DeploymentData(originalDeployProps, null, sourceRawFiles, deployDir, null, null, null, - null, true); + DeploymentData dd = new DeploymentData(originalDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, + null, null, null, true, null); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = sourceRawFiles.get(sourceRawFile); @@ -206,8 +206,8 @@ public class SimpleDeployerRawFileTest { }
private void baseX_X_X(boolean dryRun) throws Exception { - DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -249,8 +249,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -296,8 +296,8 @@ public class SimpleDeployerRawFileTest { String newHashcode = MessageDigestGenerator.getDigestString(newContent); writeFile(newContent, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -345,8 +345,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -394,8 +394,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -458,8 +458,8 @@ public class SimpleDeployerRawFileTest { File newDestRawFile = new File(extDir, newFileName); newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -521,8 +521,8 @@ public class SimpleDeployerRawFileTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -582,8 +582,8 @@ public class SimpleDeployerRawFileTest { private void baseNoCurrent(boolean dryRun) throws Exception { assert this.currentFile.delete() : "Failed to delete the current file, cannot prepare the test";
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -634,8 +634,8 @@ public class SimpleDeployerRawFileTest { File newDestRawFile = new File(extDir, newFileName); newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -699,8 +699,8 @@ public class SimpleDeployerRawFileTest { File newDestRawFile = new File(extDir, newFileName); newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -773,8 +773,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -813,7 +813,8 @@ public class SimpleDeployerRawFileTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, deployDir, null, null, null, null, true); + dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, tmpDir, deployDir, null, null, null, null, true, + null); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java index 5a0f842..148aa08 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java @@ -90,8 +90,8 @@ public class SimpleDeployerRawRelativeFileTest { this.sourceRawFiles = new HashMap<File, File>(1); this.sourceRawFiles.put(sourceRawFile, new File(originalFileName)); // RELATIVE! note we name it different than the source file this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); - DeploymentData dd = new DeploymentData(originalDeployProps, null, sourceRawFiles, deployDir, null, null, null, - null, true); + DeploymentData dd = new DeploymentData(originalDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, + null, null, null, true, null); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = sourceRawFiles.get(sourceRawFile); @@ -205,8 +205,8 @@ public class SimpleDeployerRawRelativeFileTest { }
private void baseX_X_X(boolean dryRun) throws Exception { - DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -248,8 +248,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -295,8 +295,8 @@ public class SimpleDeployerRawRelativeFileTest { String newHashcode = MessageDigestGenerator.getDigestString(newContent); writeFile(newContent, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -344,8 +344,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -393,8 +393,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -457,8 +457,8 @@ public class SimpleDeployerRawRelativeFileTest { File newDestRawFile = new File(newFileName); // RELATIVE! newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -520,8 +520,8 @@ public class SimpleDeployerRawRelativeFileTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -580,8 +580,8 @@ public class SimpleDeployerRawRelativeFileTest { private void baseNoCurrent(boolean dryRun) throws Exception { assert this.currentFileWithAbsolutePath.delete() : "Failed to delete the current file, cannot prepare the test";
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -632,8 +632,8 @@ public class SimpleDeployerRawRelativeFileTest { File newDestRawFile = new File(newFileName); // RELATIVE! newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -697,8 +697,8 @@ public class SimpleDeployerRawRelativeFileTest { File newDestRawFile = new File(newFileName); // RELATIVE! newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -771,8 +771,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -811,7 +811,8 @@ public class SimpleDeployerRawRelativeFileTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, deployDir, null, null, null, null, true); + dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, tmpDir, deployDir, null, null, null, null, true, + null); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java index 712a984..f875576 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java @@ -86,8 +86,8 @@ public class SimpleDeployerTest { this.originalZipFiles = new HashSet<File>(1); this.originalZipFiles.add(originalZipFile); this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); - DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, - null, null, true); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, tmpDir, deployDir, null, + null, null, null, true, null); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = new File(deployDir, originalFileName); @@ -226,8 +226,8 @@ public class SimpleDeployerTest { this.originalZipFiles = new HashSet<File>(1); this.originalZipFiles.add(originalZipFile); this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); - DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, - null, null, true); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, tmpDir, deployDir, null, + null, null, null, true, null); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); assert new File(this.deployDir, origFileName1).exists(); @@ -246,7 +246,8 @@ public class SimpleDeployerTest { new String[] { newFileName1, newFileName2 }); HashSet<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile); - dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, true); + dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, null, true, + null); deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap = deployer.deploy(this.diff); assert new File(this.deployDir, newFileName1).exists(); @@ -261,8 +262,8 @@ public class SimpleDeployerTest { }
private void baseX_X_X(boolean dryRun) throws Exception { - DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null, true); + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -304,8 +305,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -351,8 +352,8 @@ public class SimpleDeployerTest { String newHashcode = MessageDigestGenerator.getDigestString(newContent); writeFile(newContent, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null, true); + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -400,8 +401,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -449,8 +450,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -512,8 +513,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -574,8 +575,8 @@ public class SimpleDeployerTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -634,8 +635,8 @@ public class SimpleDeployerTest { private void baseNoCurrent(boolean dryRun) throws Exception { assert this.currentFile.delete() : "Failed to delete the current file, cannot prepare the test";
- DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null, true); + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, tmpDir, deployDir, null, null, + null, null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -685,8 +686,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -749,8 +750,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -823,8 +824,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + null, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -863,7 +864,8 @@ public class SimpleDeployerTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, originalZipFiles, null, deployDir, null, null, null, null, true); + dd = new DeploymentData(v1Duplicate, originalZipFiles, null, tmpDir, deployDir, null, null, null, null, true, + null); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; @@ -912,8 +914,8 @@ public class SimpleDeployerTest { Pattern iRegex = Pattern.compile(".*ignoreSubdir.*"); // this matches the subdirectory name, thus everything under it is ignored assert ignoredFile.exists() : "for some reason we couldn't create our test file; cannot know if clean worked";
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, iRegex, - true); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, tmpDir, deployDir, null, null, null, + iRegex, true, null); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff, true, dryRun); // note: clean is true
commit 35b1680ff655706712cf4feecc016b05a5f0c4bf Author: Simeon Pinder spinder@redhat.com Date: Thu Dec 23 01:04:38 2010 -0500
i)fix build compilation problem ii)update portlets to return same instance iii)fix refresh issue with default page refresh value.
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 14e4d4f..e31ea1d 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 @@ -180,9 +180,13 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private static Portlet reference = null;
public final Portlet getInstance(String locatorId) { - return new AutodiscoveryPortlet(locatorId); + if (reference == null) { + reference = new AutodiscoveryPortlet(locatorId); + } + return reference; } }
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 40311ff..1681d58 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 @@ -107,10 +107,14 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private static Portlet reference;
public final Portlet getInstance(String locatorId) { //return GWT.create(FavoriteResourcesPortlet.class); - return new FavoriteResourcesPortlet(locatorId); + if (reference == null) { + reference = new FavoriteResourcesPortlet(locatorId); + } + return reference; } }
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 1ebf65e..a9a801d 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 @@ -531,9 +531,13 @@ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSetti
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private static Portlet reference;
public final Portlet getInstance(String locatorId) { - return new RecentAlertsPortlet(locatorId); + if (reference == null) { + reference = new RecentAlertsPortlet(locatorId); + } + return reference; } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java index 46d376a..b80f0d3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java @@ -208,9 +208,13 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private Portlet reference;
public final Portlet getInstance(String locatorId) { - return new RecentlyAddedResourcesPortlet(locatorId); + if (reference == null) { + reference = new RecentlyAddedResourcesPortlet(locatorId); + } + return reference; } }
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 4c46860..8ae6ee3 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 @@ -366,9 +366,13 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private Portlet reference;
public final Portlet getInstance(String locatorId) { - return new OperationsPortlet(locatorId); + if (reference == null) { + reference = new OperationsPortlet(locatorId); + } + return reference; } }
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 658257f..8c6f106 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 @@ -239,9 +239,13 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private Portlet reference;
public final Portlet getInstance(String locatorId) { - return new ProblemResourcesPortlet(locatorId); + if (reference == null) { + reference = new ProblemResourcesPortlet(locatorId); + } + return reference; } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java index 62bcf15..adb7911 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java @@ -163,10 +163,14 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); + private Portlet reference;
public final Portlet getInstance(String locatorId) { // return GWT.create(InventorySummaryView.class); - return new InventorySummaryPortlet(locatorId); + if (reference == null) { + reference = new InventorySummaryPortlet(locatorId); + } + return reference; } }
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 7fde8e7..f5c936d 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 @@ -75,19 +75,14 @@ public class UserPreferences {
public int getPageRefreshInterval() { if ((getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD) == null) - || (Long.valueOf(getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD)) < MeasurementUtility.MINUTES)) { - //default to 60 seconds + || (Integer.valueOf(getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD)) == 60)) {//default to 60 seconds setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(MeasurementUtility.MINUTES)); } return getPreferenceAsInteger(UserPreferenceNames.PAGE_REFRESH_PERIOD); }
public void setPageRefreshInterval(int refreshInterval, AsyncCallback<Subject> callback) { - if (refreshInterval >= MeasurementUtility.MINUTES) { - setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval)); - } else { - setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(MeasurementUtility.MINUTES)); - } + setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval)); store(callback); }
commit 864d54670483b27c4f5d7d6996117c26c877efbf Author: Joseph Marques joseph@redhat.com Date: Thu Dec 23 00:29:41 2010 -0500
fix compile error
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java index 8080f30..0adfdc3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java @@ -64,11 +64,11 @@ public class ResourceOperationScheduleDataSource extends OperationScheduleDataSo throw new RuntimeException("Failed to find scheduled operations for " + resourceComposite.getResource() + ".", caught); } - }); + }); }
@Override protected void executeAdd(Record recordToAdd, DSRequest request, DSResponse response) { - operationService.scheduleResourceOperation(); + //operationService.scheduleResourceOperation(); } }
commit dca49573ece14274b2184a1046420e217784fa9a Author: Joseph Marques joseph@redhat.com Date: Wed Dec 22 23:04:01 2010 -0500
initial integration of search bar contained within a smartgwt form
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/SearchBarItem.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/SearchBarItem.java index abc0958..83793e4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/SearchBarItem.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/SearchBarItem.java @@ -32,8 +32,8 @@ public class SearchBarItem extends CanvasItem { private Canvas canvas = new Canvas(); private FlexSearchBar searchBar;
- public SearchBarItem(SearchSubsystem subsystem) { - super("Search"); + public SearchBarItem(String name, String title, SearchSubsystem subsystem) { + super(name, title);
searchBar = new FlexSearchBar(); searchBar.setSearchSubsystem(subsystem); @@ -50,4 +50,8 @@ public class SearchBarItem extends CanvasItem { return canvas; }
+ public FlexSearchBar getSearchBar() { + return searchBar; + } + } 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 a99ff5a..c569234 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 @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.Set;
+import com.google.gwt.event.dom.client.KeyCodes; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSRequest; @@ -51,6 +52,7 @@ 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.HiddenItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; @@ -715,9 +717,12 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements * * @author Joseph Marques */ - private static class TableFilter extends DynamicForm implements KeyPressHandler, ChangedHandler { + private static class TableFilter extends DynamicForm implements KeyPressHandler, ChangedHandler, + com.google.gwt.event.dom.client.KeyPressHandler {
private Table table; + private SearchBarItem searchBarItem; + private HiddenItem hiddenItem;
public TableFilter(Table table) { super(); @@ -728,12 +733,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements
@Override public void setItems(FormItem... items) { - super.setItems(items); - setupFormItems(items); - } - - private void setupFormItems(FormItem... formItems) { - for (FormItem nextFormItem : formItems) { + for (FormItem nextFormItem : items) { nextFormItem.setWrapTitle(false); nextFormItem.setWidth(300); // wider than default if (nextFormItem instanceof TextItem) { @@ -741,9 +741,22 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements } else if (nextFormItem instanceof SelectItem) { nextFormItem.addChangedHandler(this); } else if (nextFormItem instanceof SearchBarItem) { - nextFormItem.addKeyPressHandler(this); + searchBarItem = (SearchBarItem) nextFormItem; + searchBarItem.getSearchBar().addKeyPressHandler(this); + String name = searchBarItem.getName(); + searchBarItem.setName(name + "_hidden"); + hiddenItem = new HiddenItem(name); } } + + if (hiddenItem != null) { + FormItem[] tmpItems = new FormItem[items.length + 1]; + System.arraycopy(items, 0, tmpItems, 0, items.length); + tmpItems[items.length] = hiddenItem; + items = tmpItems; + } + + super.setItems(items); }
private void fetchFilteredTableData() { @@ -765,6 +778,15 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements return super.getFields().length != 0; }
+ @Override + public void onKeyPress(com.google.gwt.event.dom.client.KeyPressEvent event) { + if (event.getCharCode() != KeyCodes.KEY_ENTER) { + return; + } + // TODO: figure out why this event is being sent twice + hiddenItem.setValue(searchBarItem.getSearchBar().getValue()); + fetchFilteredTableData(); + } }
public static class TableActionInfo { 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 8d0ac24..2590ea3 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 @@ -164,7 +164,7 @@ public class ResourceDatasource extends RPCDataSource<Resource> { protected ResourceCriteria getFetchCriteria(final DSRequest request) { ResourceCriteria criteria = new ResourceCriteria(); criteria.setPageControl(getPageControl(request)); - + //printRequestCriteria(request); criteria.addFilterId(getFilter(request, "id", Integer.class)); criteria.addFilterParentResourceId(getFilter(request, "parentId", Integer.class)); criteria.addFilterCurrentAvailability(getFilter(request, AVAILABILITY.propertyName(), AvailabilityType.class)); @@ -177,6 +177,7 @@ public class ResourceDatasource extends RPCDataSource<Resource> { criteria.addFilterTagNamespace(getFilter(request, "tagNamespace", String.class)); criteria.addFilterTagSemantic(getFilter(request, "tagSemantic", String.class)); criteria.addFilterTagName(getFilter(request, "tagName", String.class)); + criteria.setSearchExpression(getFilter(request, "search", String.class));
return criteria; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java index 9e3e6eb..2284b78 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java @@ -34,11 +34,6 @@ import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; -import com.google.gwt.user.client.DOM; -import com.google.gwt.user.client.Element; -import com.google.gwt.user.client.Event; -import com.google.gwt.user.client.Event.NativePreviewEvent; -import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; @@ -94,23 +89,6 @@ public class FlexSearchBar extends AbstractSearchBar { private String defaultSearchText; private String defaultSavedSearchPatternId;
- private Element searchButton; - - public void setupButton() { - searchButton = DOM.createButton(); - Event.addNativePreviewHandler(new NativePreviewHandler() { - public void onPreviewNativeEvent(NativePreviewEvent event) { - if (event.getNativeEvent() != null && event.getNativeEvent().getEventTarget() != null) { - - if (event.getNativeEvent().getEventTarget().equals(searchButton) - && event.getTypeInt() == Event.ONMOUSEDOWN) { - //prepareSearchExecution(); - } - } - } - }); - } - HorizontalPanel sbc; HorizontalPanel sbc_sbbgc; HorizontalPanel sbc_sbbgc_sbcc; @@ -143,6 +121,14 @@ public class FlexSearchBar extends AbstractSearchBar { sbc_sbbc = createHPanel(sbc, "searchBarButtonContainer", "searchButtonContainer"); sbc_pfsc = createHPanel(sbc, null, "patternFieldSuggestionsContainer"); sbc_ssc = createHPanel(sbc, null, "savedSearchesContainer"); + + sbc_sbbgc_sbcc_sbclhs_pfc.add(autoCompletePatternField); + sbc_sbbgc_sbcc_sbcrhs_pnfc.add(patternNameField); + sbc_sbbgc_sbcc_sbcrhs_pnlc.add(patternNameLabel); + sbc_sbbgc_sbcc_sbcrhs_sic.add(starImage); + sbc_sbbgc_sbcc_sbcrhs_aic.add(arrowImage); + sbc_ssc.add(savedSearchesPanel); + initWidget(sbc);
savedSearchManager = new SavedSearchManager(this); @@ -163,13 +149,6 @@ public class FlexSearchBar extends AbstractSearchBar { }
public void onSavedSearchManagerLoaded() { - sbc_sbbgc_sbcc_sbclhs_pfc.add(autoCompletePatternField); - sbc_sbbgc_sbcc_sbcrhs_pnfc.add(patternNameField); - sbc_sbbgc_sbcc_sbcrhs_pnlc.add(patternNameLabel); - sbc_sbbgc_sbcc_sbcrhs_sic.add(starImage); - sbc_sbbgc_sbcc_sbcrhs_aic.add(arrowImage); - sbc_ssc.add(savedSearchesPanel); - setupAutoCompletingPatternField(); setupPatternNameField(); setupPatternNameLabel(); @@ -179,14 +158,12 @@ public class FlexSearchBar extends AbstractSearchBar {
if (defaultSearchText != null) { this.autoCompletePatternField.setText(defaultSearchText); - click(searchButton); // execute the search with this default search expression } else if (defaultSavedSearchPatternId != null) { try { Integer savedSearchId = Integer.valueOf(defaultSavedSearchPatternId); activateSavedSearch(savedSearchId); } catch (Exception e) { this.autoCompletePatternField.setText(MSG.view_searchBar_error_selectSavedSearch()); - click(searchButton); // execute the search, which will help to further highlight the error } }
@@ -475,11 +452,6 @@ public class FlexSearchBar extends AbstractSearchBar { } }
- private static native void click(Element button) - /*-{ - button.click(); - }-*/; - public void activateSavedSearch(Integer savedSearchId) { SavedSearch savedSearch = savedSearchManager.getSavedSearchById(savedSearchId); if (savedSearch == null) { @@ -505,11 +477,18 @@ public class FlexSearchBar extends AbstractSearchBar { Log.debug("search results change: [" + savedSearch.getName() + "," + savedSearch.getPattern() + "]"); turnNameFieldIntoLabel(); savedSearchesPanel.hide(); - click(searchButton); }
public String getSelectedTab() { return null; }
+ public void addKeyPressHandler(KeyPressHandler handler) { + autoCompletePatternField.addKeyPressHandler(handler); + } + + public String getValue() { + return autoCompletePatternField.getValue(); + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java index d58197d..234d775 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/inventory/TestSearchBarView.java @@ -21,7 +21,7 @@ public class TestSearchBarView extends ResourceSearchView { final TextItem nameFilter = new TextItem(NAME.propertyName(), NAME.title()); final EnumSelectItem categoryFilter = new EnumSelectItem(CATEGORY.propertyName(), CATEGORY.title(), ResourceCategory.class); - final SearchBarItem searchFilter = new SearchBarItem(SearchSubsystem.RESOURCE); + final SearchBarItem searchFilter = new SearchBarItem("search", "Search", SearchSubsystem.RESOURCE);
setFilterFormItems(nameFilter, categoryFilter, searchFilter); }
commit d897f1dbb0d5744c64b22c828f8f449e385b6597 Author: Joseph Marques joseph@redhat.com Date: Wed Dec 22 22:55:24 2010 -0500
more robust handling around filter parameters with multiple values
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 a7bd459..f43417f 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 @@ -29,6 +29,7 @@ import java.util.Set;
import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.core.client.JavaScriptObject; +import com.google.gwt.user.client.Window; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@ -425,7 +426,7 @@ public abstract class RPCDataSource<T> extends DataSource { // nothing to do, result is already null } else if (type == Integer.class) { int[] intermediates; - if (type.getClass().isArray()) { + if (isArray(value)) { intermediates = criteria.getAttributeAsIntArray(paramName); } else { // want array return, but only single instance of the type in the request intermediates = new int[] { criteria.getAttributeAsInt(paramName) }; @@ -437,7 +438,7 @@ public abstract class RPCDataSource<T> extends DataSource { } } else if (type == String.class) { String[] intermediates; - if (type.getClass().isArray()) { + if (isArray(value)) { intermediates = criteria.getAttributeAsStringArray(paramName); } else { // want array return, but only single instance of the type in the request intermediates = new String[] { criteria.getAttributeAsString(paramName) }; @@ -449,7 +450,7 @@ public abstract class RPCDataSource<T> extends DataSource { } } else if (type.isEnum()) { String[] intermediates; - if (type.getClass().isArray()) { + if (isArray(value)) { intermediates = criteria.getAttributeAsStringArray(paramName); } else { // want array return, but only single instance of the type in the request intermediates = new String[] { criteria.getAttributeAsString(paramName) }; @@ -468,6 +469,10 @@ public abstract class RPCDataSource<T> extends DataSource { return resultArray; }
+ private static boolean isArray(Object value) { + return value.getClass().isArray() || value.getClass().equals(ArrayList.class); + } + @SuppressWarnings("unchecked") private static <S> S[] getEnumArray(Class<S> genericEnumType, int size) { // workaround until GWT implements reflection APIs, so we can do: @@ -484,8 +489,17 @@ public abstract class RPCDataSource<T> extends DataSource { }
@SuppressWarnings("unchecked") + public static void printRequestCriteria(DSRequest request) { + Criteria criteria = request.getCriteria(); + Map<String, Object> criteriaMap = criteria.getValues(); + + for (Map.Entry<String, Object> nextEntry : criteriaMap.entrySet()) { + Window.alert(nextEntry.getKey() + ":" + nextEntry.getValue()); + } + } + + @SuppressWarnings("unchecked") public static <S> S getFilter(DSRequest request, String paramName, Class<S> type) { - Log.debug("Fetching " + paramName + " (" + type + ")"); Criteria criteria = request.getCriteria(); Map<String, Object> criteriaMap = criteria.getValues();
commit 682db9a8bd03ebedab669fc02147c2bc46e7ff23 Author: Simeon Pinder spinder@redhat.com Date: Wed Dec 22 17:06:00 2010 -0500
fix refresh issue.
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 74ce25c..14e4d4f 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 @@ -40,6 +40,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.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
@@ -197,13 +198,15 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } } 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 f7cbcdc..40311ff 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 @@ -40,6 +40,7 @@ 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.resource.ResourceSearchView; +import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility;
/** * @author Greg Hinkle @@ -121,13 +122,15 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } } 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 024adb3..1ebf65e 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 @@ -545,14 +545,16 @@ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSetti if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - refresh(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + refresh(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java index 30c9b4e..46d376a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java @@ -44,6 +44,7 @@ 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.LocatableVLayout;
public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements CustomSettingsPortlet, @@ -236,13 +237,15 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } } 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 507c8ed..4c46860 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 @@ -45,6 +45,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.operation.RecentOperationsDataSource; import org.rhq.enterprise.gui.coregui.client.operation.ScheduledOperationsDataSource; +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; @@ -424,13 +425,15 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } } 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 fddbfa1..658257f 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 @@ -298,14 +298,16 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - refresh(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + refresh(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java index 6b70298..62bcf15 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java @@ -45,6 +45,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.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceBossGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
@@ -177,13 +178,15 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef if (defaultReloader != null) { defaultReloader.cancel(); } - defaultReloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - defaultReloader.schedule(retrievedRefreshInterval); - } - }; - defaultReloader.schedule(retrievedRefreshInterval); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); + } } } 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 1c311b0..7fde8e7 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 @@ -74,14 +74,20 @@ public class UserPreferences { }
public int getPageRefreshInterval() { - if (getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD) == null) {//default to 60 seconds + if ((getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD) == null) + || (Long.valueOf(getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD)) < MeasurementUtility.MINUTES)) { + //default to 60 seconds setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(MeasurementUtility.MINUTES)); } return getPreferenceAsInteger(UserPreferenceNames.PAGE_REFRESH_PERIOD); }
public void setPageRefreshInterval(int refreshInterval, AsyncCallback<Subject> callback) { - setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval)); + if (refreshInterval >= MeasurementUtility.MINUTES) { + setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval)); + } else { + setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(MeasurementUtility.MINUTES)); + } store(callback); }
commit 51864e3db11b09ee8fb6bed6d16dd1322e3f6c25 Author: Ian Springer ian.springer@redhat.com Date: Wed Dec 22 16:27:01 2010 -0500
finish up calendar mode of schedule editor widget functionality-wise; start on new SLSB method for scheduling an operation that takes a ResourceOperationSchedule as a param
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 c2e2626..45bf782 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 @@ -24,7 +24,6 @@ import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumSet; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; @@ -87,7 +86,6 @@ 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.layout.HLayout; -import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.layout.SectionStack; import com.smartgwt.client.widgets.layout.SectionStackSection; import com.smartgwt.client.widgets.layout.VLayout; @@ -123,7 +121,6 @@ import org.rhq.enterprise.gui.coregui.client.ImageManager; 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.LocatableIButton; @@ -166,7 +163,6 @@ public class ConfigurationEditor extends LocatableVLayout { private int resourceId; private int resourceTypeId; private ConfigType configType; - private IButton saveButton;
private boolean readOnly = false; private Set<String> invalidPropertyNames = new HashSet<String>(); @@ -361,61 +357,50 @@ public class ConfigurationEditor extends LocatableVLayout { sectionStack.addSection(buildGroupSection(layout.extendLocatorId(definition.getName()), definition)); }
- toolStrip = new LocatableToolStrip(layout.extendLocatorId("Tools")); - toolStrip.setBackgroundImage(null); - toolStrip.setWidth100(); + this.toolStrip = buildToolStrip(layout, sectionStack); + layout.addMember(toolStrip); + layout.addMember(sectionStack); + }
- toolStrip.addMember(new LayoutSpacer()); - saveButton = new LocatableIButton(toolStrip.extendLocatorId("Save"), MSG.common_button_save()); - saveButton.setAlign(Alignment.CENTER); - saveButton.setDisabled(true); - //toolStrip.addMember(saveButton); + return layout; + }
- IButton resetButton = new LocatableIButton(toolStrip.extendLocatorId("Reset"), MSG.common_button_reset()); - resetButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { - public void onClick(ClickEvent clickEvent) { - reload(); - } - }); - //toolStrip.addMember(resetButton); - - toolStrip.addMember(new LayoutSpacer()); - - Menu menu = new LocatableMenu(toolStrip.extendLocatorId("JumpMenu")); - for (SectionStackSection section : sectionStack.getSections()) { - MenuItem item = new MenuItem(section.getTitle()); - item.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - int x = event.getMenu().getItemNum(event.getItem()); - sectionStack.expandSection(x); - sectionStack.showSection(x); - } - }); - menu.addItem(item); - } - menu.addItem(new MenuItemSeparator()); + private LocatableToolStrip buildToolStrip(LocatableVLayout layout, final SectionStack sectionStack) { + LocatableToolStrip toolStrip = new LocatableToolStrip(layout.extendLocatorId("Tools")); + toolStrip.setBackgroundImage(null); + toolStrip.setWidth100();
- MenuItem hideAllItem = new MenuItem(MSG.view_configEdit_hideAll()); - hideAllItem.addClickHandler(new ClickHandler() { + Menu menu = new LocatableMenu(toolStrip.extendLocatorId("JumpMenu")); + for (SectionStackSection section : sectionStack.getSections()) { + MenuItem item = new MenuItem(section.getTitle()); + item.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { - for (int i = 0; i < sectionStack.getSections().length; i++) { - sectionStack.collapseSection(i); - } + int x = event.getMenu().getItemNum(event.getItem()); + sectionStack.expandSection(x); + sectionStack.showSection(x); } }); - menu.addItem(hideAllItem); + menu.addItem(item); + } + menu.addItem(new MenuItemSeparator());
- // TODO GH: Save button as saveListener() or remove the buttons from this form and have - // the container provide them? + MenuItem hideAllItem = new MenuItem(MSG.view_configEdit_hideAll()); + hideAllItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + for (int i = 0; i < sectionStack.getSections().length; i++) { + sectionStack.collapseSection(i); + } + } + }); + menu.addItem(hideAllItem);
- toolStrip.addMember(new LocatableIMenuButton(toolStrip.extendLocatorId("Jump"), MSG - .view_configEdit_jumpToSection(), menu)); + // TODO GH: Save button as saveListener() or remove the buttons from this form and have + // the container provide them?
- layout.addMember(toolStrip); - layout.addMember(sectionStack); - } + toolStrip.addMember(new LocatableIMenuButton(toolStrip.extendLocatorId("Jump"), MSG + .view_configEdit_jumpToSection(), menu));
- return layout; + return toolStrip; }
public SectionStackSection buildGroupSection(String locatorId, PropertyGroupDefinition group) { @@ -451,17 +436,6 @@ public class ConfigurationEditor extends LocatableVLayout { form.setValuesManager(valuesManager); form.setValidateOnExit(true); form.setHiliteRequiredFields(true); - - form.addItemChangedHandler(new ItemChangedHandler() { - public void onItemChanged(ItemChangedEvent itemChangedEvent) { - if (!changed) { - changed = true; - CanvasUtility.blink(saveButton); - saveButton.setDisabled(false); - } - } - }); - form.setNumCols(4); form.setCellPadding(5); form.setColWidths(190, 28, 210); @@ -1123,7 +1097,6 @@ public class ConfigurationEditor extends LocatableVLayout {
final IButton okButton = new LocatableIButton(extendLocatorId("OK"), MSG.common_button_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); @@ -1469,7 +1442,6 @@ public class ConfigurationEditor extends LocatableVLayout {
final IButton okButton = new LocatableIButton(extendLocatorId("OK"), MSG.common_button_ok()); okButton.disable(); - // saveButton.setID("config_structured_button_save"); okButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { if (newRow) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java index 5684067..fc9aef4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java @@ -20,8 +20,11 @@ package org.rhq.enterprise.gui.coregui.client.components.trigger;
import java.util.Date; +import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map;
+import com.smartgwt.client.types.Visibility; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.DateTimeItem; import com.smartgwt.client.widgets.form.fields.FormItem; @@ -47,8 +50,47 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class JobTriggerEditor extends LocatableVLayout {
+ private static final String FIELD_REPEAT_INTERVAL = "repeatInterval"; + private static final String FIELD_REPEAT_DURATION = "repeatDuration"; + private static final String FIELD_END_TIME = "endTime"; + + private static final Map<String, Long> UNITS_TO_MILLIS_MULTIPLIER_MAP = new HashMap(); + static { + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("seconds", 1000L); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("s", 1000L); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("minutes", 1000L * 60); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("m", 1000L * 60); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("hours", 1000L * 60 * 60); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("h", 1000L * 60 * 60); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("days", 1000L * 60 * 60 * 24); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("d", 1000L * 60 * 60 * 24); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("weeks", 1000L * 60 * 60 * 24 * 7); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("w", 1000L * 60 * 60 * 24 * 7); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("months", 1000L * 60 * 60 * 24 * 7 * 30); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("M", 1000L * 60 * 60 * 24 * 7 * 30); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("quarters", 1000L * 60 * 60 * 24 * 7 * 90); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("q", 1000L * 60 * 60 * 24 * 7 * 90); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("years", 1000L * 60 * 60 * 24 * 7 * 30 * 365); + UNITS_TO_MILLIS_MULTIPLIER_MAP.put("y", 1000L * 60 * 60 * 24 * 7 * 30 * 365); + } + private boolean isReadOnly; - private boolean isValid; + + private DynamicForm laterForm; + private DynamicForm repeatForm; + + // These flags allow us to determine the trigger type. + private boolean isCronMode; + private boolean isStartLater; + private boolean isRecurring; + private boolean isRepeatDuration; + private boolean isEndTime; + private boolean isStartDelay; + private boolean isStartTime; + private static final String FIELD_START_TYPE = "startType"; + private static final String FIELD_START_TIME = "startTime"; + private static final String FIELD_START_DELAY = "startDelay"; + private static final String FIELD_RECURRENCE_TYPE = "recurrenceType";
/** * Create a new job trigger. @@ -111,70 +153,81 @@ public class JobTriggerEditor extends LocatableVLayout { modeItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { if (event.getValue().equals("calendar")) { - calendarTypeForm.show(); + JobTriggerEditor.this.isCronMode = false; + calendarTypeForm.show(); } } });
- final DynamicForm laterForm = createLaterForm(); - addMember(laterForm); + this.laterForm = createLaterForm(); + addMember(this.laterForm);
- final DynamicForm repeatForm = createRepeatForm(); - addMember(repeatForm); + this.repeatForm = createRepeatForm(); + addMember(this.repeatForm);
calendarTypeItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { String value = (String)event.getValue(); if (value.equals("now")) { - isValid = true; + JobTriggerEditor.this.isStartLater = false; + JobTriggerEditor.this.isRecurring = false; } else if (value.equals("nowAndRepeat")) { - laterForm.hide(); - FormItem repeatIntervalItem = repeatForm.getItem("repeatInterval"); + JobTriggerEditor.this.isStartLater = false; + JobTriggerEditor.this.isRecurring = true; + + FormItem repeatIntervalItem = repeatForm.getItem(FIELD_REPEAT_INTERVAL); repeatIntervalItem.setTitle("Run now and every"); repeatIntervalItem.redraw(); - repeatForm.show(); } else if (value.equals("later")) { - repeatForm.hide(); - laterForm.show(); + JobTriggerEditor.this.isStartLater = true; + JobTriggerEditor.this.isRecurring = false; } else { - // later and repeat - laterForm.show(); - FormItem repeatIntervalItem = repeatForm.getItem("repeatInterval"); + // value.equals("laterAndRepeat") + JobTriggerEditor.this.isStartLater = true; + JobTriggerEditor.this.isRecurring = true; + + FormItem repeatIntervalItem = repeatForm.getItem(FIELD_REPEAT_INTERVAL); repeatIntervalItem.setTitle("Repeat every"); repeatIntervalItem.redraw(); - repeatForm.show(); } + laterForm.setVisibility(JobTriggerEditor.this.isStartLater ? Visibility.VISIBLE : Visibility.HIDDEN); + repeatForm.setVisibility(JobTriggerEditor.this.isRecurring ? Visibility.VISIBLE : Visibility.HIDDEN); } }); }
private DynamicForm createRepeatForm() { - final DynamicForm nowAndRepeatForm = new DynamicForm(); - nowAndRepeatForm.setNumCols(6); - nowAndRepeatForm.setColWidths(130, 130, 130, 130, 130); + final DynamicForm repeatForm = new DynamicForm(); + repeatForm.setNumCols(6); + repeatForm.setColWidths(130, 130, 130, 130, 130);
- TextItem repeatIntervalItem = new TextItem("repeatInterval", "Run now and every"); + TextItem repeatIntervalItem = new TextItem(FIELD_REPEAT_INTERVAL, "Run now and every"); + repeatIntervalItem.setRequired(true);
// Configure hint. - repeatIntervalItem.setHint("[1-9][0-9]* (seconds|minutes|hours|days|weeks|months|quarters|years)"); + repeatIntervalItem.setHint("N UNITS (where N is a positive integer and UNITS is "seconds", "minutes", "hours", "days", "weeks", "months", "quarters", or "years", e.g. "30 seconds" or "6 weeks")"); repeatIntervalItem.setShowHint(false); repeatIntervalItem.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { + repeatForm.setColWidths(130, 400, 130, 130, 130); event.getItem().setShowHint(true); + repeatForm.markForRedraw(); } }); repeatIntervalItem.addBlurHandler(new BlurHandler() { public void onBlur(BlurEvent event) { - event.getItem().setShowHint(false); + repeatForm.setColWidths(130, 130, 130, 130, 130); + event.getItem().setShowHint(false); + repeatForm.markForRedraw(); } });
// Configure validation. - RegExpValidator repeatIntervalValidator = new RegExpValidator("[1-9][0-9]*[ ]+(seconds|minutes|hours|days|weeks|months|quarters|years)"); + RegExpValidator repeatIntervalValidator = new RegExpValidator("[1-9][0-9]*[ ]*(seconds|s|minutes|m|hours|h|days|d|weeks|w|months|M|quarters|q|years|y)"); repeatIntervalItem.setValidators(repeatIntervalValidator); repeatIntervalItem.setValidateOnExit(true);
- RadioGroupItem recurrenceTypeItem = new RadioGroupItem("recurrenceType"); + RadioGroupItem recurrenceTypeItem = new RadioGroupItem(FIELD_RECURRENCE_TYPE); recurrenceTypeItem.setShowTitle(false); LinkedHashMap<String, String> recurrenceTypeValueMap = new LinkedHashMap<String, String>(); recurrenceTypeValueMap.put("for", "For"); @@ -182,31 +235,34 @@ public class JobTriggerEditor extends LocatableVLayout { recurrenceTypeValueMap.put("indefinitely", "Indefinitely"); recurrenceTypeItem.setValueMap(recurrenceTypeValueMap);
- final TextItem repeatDurationItem = new TextItem("repeatDuration"); + final TextItem repeatDurationItem = new TextItem(FIELD_REPEAT_DURATION); repeatDurationItem.setShowTitle(false); repeatDurationItem.setVisible(false);
// Configure hint. - repeatDurationItem.setHint("[1-9][0-9]* (repetitions|seconds|minutes|hours|days|weeks|months|quarters|years)"); + repeatDurationItem.setHint("N UNITS (where N is a positive integer and UNITS is "times", "seconds", "minutes", "hours", "days", "weeks", "months", "quarters", or "years", e.g. "30 seconds" or "5 repetitions")"); repeatDurationItem.setShowHint(false); repeatDurationItem.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { + repeatForm.setColWidths(130, 130, 400, 130, 130); event.getItem().setShowHint(true); + repeatForm.markForRedraw(); } }); repeatDurationItem.addBlurHandler(new BlurHandler() { public void onBlur(BlurEvent event) { + repeatForm.setColWidths(130, 130, 130, 130, 130); event.getItem().setShowHint(false); + repeatForm.markForRedraw(); } });
// Configure validation. - RegExpValidator repeatDurationValidator = new RegExpValidator("[1-9][0-9]*[ ]+(repetitions|seconds|minutes|hours|days|weeks|months|quarters|years)"); + RegExpValidator repeatDurationValidator = new RegExpValidator("[1-9][0-9]*[ ]*(times|repetitions|seconds|s|minutes|m|hours|h|days|d|weeks|w|months|M|quarters|q|years|y)"); repeatDurationItem.setValidators(repeatDurationValidator); repeatDurationItem.setValidateOnExit(true);
- - final DateTimeItem endTimeItem = createDateTimeItem("endTime"); + final DateTimeItem endTimeItem = createDateTimeItem(FIELD_END_TIME); endTimeItem.setShowTitle(false); endTimeItem.setVisible(false);
@@ -216,22 +272,36 @@ public class JobTriggerEditor extends LocatableVLayout { public void onChanged(ChangedEvent event) { String value = (String)event.getValue(); if (value.equals("for")) { - endTimeItem.hide(); - repeatDurationItem.show(); + JobTriggerEditor.this.isEndTime = false; + JobTriggerEditor.this.isRepeatDuration = true; } else if (value.equals("until")) { - repeatDurationItem.hide(); + JobTriggerEditor.this.isEndTime = true; + JobTriggerEditor.this.isRepeatDuration = false; + } else { + // indefinite + JobTriggerEditor.this.isEndTime = false; + JobTriggerEditor.this.isRepeatDuration = false; + } + + endTimeItem.setRequired(JobTriggerEditor.this.isEndTime); + if (JobTriggerEditor.this.isEndTime) { endTimeItem.show(); } else { - repeatDurationItem.hide(); endTimeItem.hide(); } + repeatDurationItem.setRequired(JobTriggerEditor.this.isRepeatDuration); + if (JobTriggerEditor.this.isRepeatDuration) { + repeatDurationItem.show(); + } else { + repeatDurationItem.hide(); + } } });
- nowAndRepeatForm.setFields(repeatIntervalItem, recurrenceTypeItem, repeatDurationItem, endTimeItem, spacerItem); - nowAndRepeatForm.setVisible(false); + repeatForm.setFields(repeatIntervalItem, recurrenceTypeItem, repeatDurationItem, endTimeItem, spacerItem); + repeatForm.setVisible(false);
- return nowAndRepeatForm; + return repeatForm; }
private DynamicForm createLaterForm() { @@ -239,34 +309,38 @@ public class JobTriggerEditor extends LocatableVLayout { laterForm.setNumCols(4); laterForm.setColWidths(130, 130, 130);
- RadioGroupItem startTypeItem = new RadioGroupItem("startType", "Run"); + RadioGroupItem startTypeItem = new RadioGroupItem(FIELD_START_TYPE, "Run"); LinkedHashMap<String, String> startTypeValueMap = new LinkedHashMap<String, String>(); startTypeValueMap.put("on", "on"); startTypeValueMap.put("in", "in"); startTypeItem.setValueMap(startTypeValueMap);
- final DateTimeItem startTimeItem = createDateTimeItem("startTime"); + final DateTimeItem startTimeItem = createDateTimeItem(FIELD_START_TIME);
- final TextItem startDelayItem = new TextItem("startDelay"); + final TextItem startDelayItem = new TextItem(FIELD_START_DELAY); startDelayItem.setShowTitle(false); startDelayItem.setVisible(false);
// Configure hint. - startDelayItem.setHint("[1-9][0-9]* (seconds|minutes|hours|days|weeks|months|quarters|years)"); + startDelayItem.setHint("N UNITS (where N is a positive integer and UNITS is "seconds", "minutes", "hours", "days", "weeks", "months", "quarters", or "years", e.g. "30 seconds" or "6 weeks")"); startDelayItem.setShowHint(false); startDelayItem.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { + laterForm.setColWidths(130, 130, 400); event.getItem().setShowHint(true); + laterForm.markForRedraw(); } }); startDelayItem.addBlurHandler(new BlurHandler() { public void onBlur(BlurEvent event) { + laterForm.setColWidths(130, 130, 130); event.getItem().setShowHint(false); + laterForm.markForRedraw(); } });
// Configure validation. - RegExpValidator startDelayValidator = new RegExpValidator("[1-9][0-9]*[ ]+(seconds|minutes|hours|days|weeks|months|quarters|years)"); + RegExpValidator startDelayValidator = new RegExpValidator("[1-9][0-9]*([ ]+(seconds|minutes|hours|days|weeks|months|quarters|years)|(s|m|h|d|w|M|q|y))"); startDelayItem.setValidators(startDelayValidator); startDelayItem.setValidateOnExit(true);
@@ -276,11 +350,24 @@ public class JobTriggerEditor extends LocatableVLayout { public void onChanged(ChangedEvent event) { String value = (String)event.getValue(); if (value.equals("on")) { + JobTriggerEditor.this.isStartDelay = false; + JobTriggerEditor.this.isStartTime = true; + } else { + // value.equals("in") + JobTriggerEditor.this.isStartDelay = true; + JobTriggerEditor.this.isStartTime = false; + } + startDelayItem.setRequired(JobTriggerEditor.this.isStartDelay); + if (JobTriggerEditor.this.isStartDelay) { + startDelayItem.show(); + } else { startDelayItem.hide(); + } + startTimeItem.setRequired(JobTriggerEditor.this.isStartTime); + if (JobTriggerEditor.this.isStartTime) { startTimeItem.show(); } else { startTimeItem.hide(); - startDelayItem.show(); } } }); @@ -291,6 +378,139 @@ public class JobTriggerEditor extends LocatableVLayout { return laterForm; }
+ public JobTrigger getJobTrigger() throws Exception { + JobTrigger jobTrigger = null; + + if (this.isCronMode) { + // TODO + } else { + // calendar mode + + // Validate first. + boolean isValid = true; + if (this.isStartLater) { + isValid = isValid && this.laterForm.validate(); + } + if (this.isRecurring) { + isValid = isValid && this.repeatForm.validate(); + } + if (!isValid) { + throw new Exception("The specified schedule is not valid."); + } + + if (this.isStartLater) { + Date startDate; + if (this.isStartDelay) { + // start delay - computer start time + String startDelay = this.laterForm.getValueAsString(FIELD_START_DELAY); + Duration startDelayDuration = parseDurationString(startDelay); + long delay = startDelayDuration.count * startDelayDuration.multiplier; + long startTime = System.currentTimeMillis() + delay; + startDate = new Date(startTime); + } else { + // start time + DateTimeItem startTimeItem = (DateTimeItem)this.laterForm.getField(FIELD_START_TIME); + startDate = startTimeItem.getValueAsDate(); + } + + if (this.isRecurring) { + // LATER AND REPEAT + + String repeatInterval = this.repeatForm.getValueAsString(FIELD_REPEAT_INTERVAL); + Duration intervalDuration = parseDurationString(repeatInterval); + long intervalMillis = intervalDuration.count * intervalDuration.multiplier; + + if (this.isRepeatDuration) { + String repeatDurationString = this.repeatForm.getValueAsString(FIELD_REPEAT_DURATION); + Duration repeatDuration = parseDurationString(repeatDurationString); + if (repeatDuration.multiplier == null) { + // n repetitions + int repetitions = repeatDuration.count; + jobTrigger = JobTrigger.createLaterAndRepeatTrigger(startDate, intervalMillis, repetitions); + } else { + // n units of time - compute end time + long delay = repeatDuration.count * repeatDuration.multiplier; + long endTime = System.currentTimeMillis() + delay; + Date endDate = new Date(endTime); + jobTrigger = JobTrigger.createLaterAndRepeatTrigger(startDate, intervalMillis, endDate); + } + } else if (this.isEndTime) { + DateTimeItem endTimeItem = (DateTimeItem)this.repeatForm.getField(FIELD_END_TIME); + Date endDate = endTimeItem.getValueAsDate(); + jobTrigger = JobTrigger.createLaterAndRepeatTrigger(startDate, intervalMillis, endDate); + } + } else { + // LATER + + jobTrigger = JobTrigger.createLaterTrigger(startDate); + } + } else { + if (this.isRecurring) { + // NOW AND REPEAT + + String repeatInterval = this.repeatForm.getValueAsString(FIELD_REPEAT_INTERVAL); + Duration intervalDuration = parseDurationString(repeatInterval); + long intervalMillis = intervalDuration.count * intervalDuration.multiplier; + + if (this.isRepeatDuration) { + String repeatDurationString = this.repeatForm.getValueAsString(FIELD_REPEAT_DURATION); + Duration repeatDuration = parseDurationString(repeatDurationString); + if (repeatDuration.multiplier == null) { + // n repetitions + int repetitions = repeatDuration.count; + jobTrigger = JobTrigger.createNowAndRepeatTrigger(intervalMillis, repetitions); + } else { + // n units of time - compute end time + long delay = repeatDuration.count * repeatDuration.multiplier; + long endTime = System.currentTimeMillis() + delay; + Date endDate = new Date(endTime); + jobTrigger = JobTrigger.createNowAndRepeatTrigger(intervalMillis, endDate); + } + } else if (this.isEndTime) { + DateTimeItem endTimeItem = (DateTimeItem)this.repeatForm.getField(FIELD_END_TIME); + Date endDate = endTimeItem.getValueAsDate(); + jobTrigger = JobTrigger.createNowAndRepeatTrigger(intervalMillis, endDate); + } + } else { + // NOW + + jobTrigger = JobTrigger.createNowTrigger(); + } + } + } + + return jobTrigger; + } + + private static Duration parseDurationString(String durationString) { + String countString = ""; + int index; + for (index = 0; index < durationString.length(); index++) { + char c = durationString.charAt(index); + if (Character.isDigit(c)) { + countString += c; + } else { + break; + } + } + int count = Integer.valueOf(countString); + + // Skip optional whitespace. + while (index < durationString.length()) { + char c = durationString.charAt(index); + if (c != ' ') { + break; + } + index++; + } + + String units = durationString.substring(index); + Long multiplier = UNITS_TO_MILLIS_MULTIPLIER_MAP.get(units.toLowerCase()); + + return new Duration(count, multiplier); + } + + private static DateTimeItem createDateTimeItem(String name) { final DateTimeItem dateTimeItem = new DateTimeItem(name); dateTimeItem.setEnforceDate(true); @@ -307,8 +527,14 @@ public class JobTriggerEditor extends LocatableVLayout { return isReadOnly; }
- public boolean isValid() { - return isValid; + private static class Duration { + public int count; + // a null multiplier means the count refers repetitions, rather than units of time + public Long multiplier; + + private Duration(int count, Long multiplier) { + this.count = count; + this.multiplier = multiplier; + } } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java index 6da2ec5..1a87bd3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java @@ -33,17 +33,20 @@ import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
+import org.rhq.core.domain.common.JobTrigger; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.operation.OperationDefinition; 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.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.form.AbstractRecordEditor; import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; import org.rhq.enterprise.gui.coregui.client.components.trigger.JobTriggerEditor; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleDataSource; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
@@ -63,6 +66,7 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { private StaticTextItem operationDescriptionItem; private StaticTextItem operationParametersItem; private LocatableHLayout operationParametersConfigurationHolder; + private JobTriggerEditor triggerEditor;
public ResourceOperationScheduleDetailsView(String locatorId, ResourceComposite resourceComposite, int scheduleId) { super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite), scheduleId, "Scheduled Operation", null); @@ -117,8 +121,8 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { contentPane.addMember(this.operationParametersConfigurationHolder);
if (isNewRecord()) { - JobTriggerEditor triggerEditor = new JobTriggerEditor(extendLocatorId("TriggerEditor")); - contentPane.addMember(triggerEditor); + this.triggerEditor = new JobTriggerEditor(extendLocatorId("TriggerEditor")); + contentPane.addMember(this.triggerEditor); }
EnhancedDynamicForm notesForm = new EnhancedDynamicForm(extendLocatorId("NotesForm"), isReadOnly(), @@ -144,6 +148,21 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { return ResourceOperationScheduleDataSource.Field.OPERATION_DISPLAY_NAME; }
+ @Override + protected void save() { + try { + JobTrigger trigger = this.triggerEditor.getJobTrigger(); + System.out.println(trigger); + } + catch (Exception e) { + e.printStackTrace(); + CoreGUI.getMessageCenter().notify(new Message(e.getMessage(), Message.Severity.Warning)); + return; + } + + super.save(); + } + private void refreshOperationDescriptionItem() { String operationName = this.operationNameItem.getValueAsString(); String value; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java index 6e9c744..8080f30 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java @@ -67,4 +67,8 @@ public class ResourceOperationScheduleDataSource extends OperationScheduleDataSo }); }
+ @Override + protected void executeAdd(Record recordToAdd, DSRequest request, DSResponse response) { + operationService.scheduleResourceOperation(); + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/CanvasUtility.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/CanvasUtility.java index ef37367..5e1e6c0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/CanvasUtility.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/CanvasUtility.java @@ -27,7 +27,9 @@ import com.smartgwt.client.widgets.Canvas; public class CanvasUtility {
public static void blink(Canvas canvas) { - canvas.animateFade(10, new FadeAnimationCallback(3,canvas,false)); + if (canvas != null) { + canvas.animateFade(10, new FadeAnimationCallback(3, canvas, false)); + } }
private static class FadeAnimationCallback implements AnimationCallback { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java index b54dc27..3c71dd4 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.server.operation;
+import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -165,6 +166,18 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan } }
+ public ResourceOperationSchedule scheduleResourceOperation(Subject subject, ResourceOperationSchedule schedule) + throws ScheduleException { + JobTrigger jobTrigger = schedule.getJobTrigger(); + Trigger trigger = convertToTrigger(jobTrigger); + try { + return scheduleResourceOperation(subject, schedule.getResource().getId(), schedule.getOperationName(), schedule.getParameters(), trigger, schedule.getDescription()); + } + catch (SchedulerException e) { + throw new ScheduleException(e); + } + } + public ResourceOperationSchedule scheduleResourceOperation(Subject subject, int resourceId, String operationName, Configuration parameters, Trigger trigger, String notes) throws SchedulerException { Resource resource = getResourceIfAuthorized(subject, resourceId); @@ -1943,4 +1956,36 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan return schedule; }
+ private static Trigger convertToTrigger(JobTrigger jobTrigger) { + Trigger trigger; + if (jobTrigger.getRecurrenceType() == JobTrigger.RecurrenceType.CRON_EXPRESSION) { + CronTrigger cronTrigger = new CronTrigger(); + try { + cronTrigger.setCronExpression(jobTrigger.getCronExpression()); + } + catch (ParseException e) { + throw new RuntimeException(e); + } + trigger = cronTrigger; + } else { + SimpleTrigger simpleTrigger = new SimpleTrigger(); + Date startTime = null; + switch (jobTrigger.getStartType()) { + case NOW: + startTime = new Date(); + break; + case DATETIME: + startTime = jobTrigger.getStartDate(); + break; + } + simpleTrigger.setStartTime(startTime); + + // TODO (ips): Finish implementing this. + + trigger= simpleTrigger; + } + + return trigger; + } + } \ No newline at end of file
commit 7c3612eeeb3f43c84544811b61e9b89c3cfc37c2 Author: Simeon Pinder spinder@redhat.com Date: Wed Dec 22 15:36:47 2010 -0500
revert use of shared component as introduced a regression in portlet refresh.
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 e7c2265..74ce25c 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,7 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.queue;
+import com.google.gwt.user.client.Timer; import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -31,12 +32,12 @@ import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -56,8 +57,7 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C //portlet settings and datasource elements private DashboardPortlet storedPortlet; private AutodiscoveryQueueDataSource dataSource; - private static TableOrCanvasAutoRefresh defaultReloader; - private static Canvas componentToReload; + private Timer defaultReloader;
public AutodiscoveryPortlet(String locatorId) { super(locatorId, true); @@ -191,14 +191,19 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } } 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 3b860b8..f7cbcdc 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 @@ -24,6 +24,7 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.resou
import java.util.Set;
+import com.google.gwt.user.client.Timer; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; @@ -38,7 +39,6 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchView;
/** @@ -52,9 +52,7 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto
private DashboardPortlet storedPortlet; private PortletWindow portletWindow; - - private static Canvas componentToReload; - private static TableOrCanvasAutoRefresh defaultReloader; + private Timer defaultReloader;
public FavoriteResourcesPortlet(String locatorId) { super(locatorId); @@ -117,14 +115,19 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } } 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 7cfcdb8..024adb3 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,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts;
+import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.DynamicForm; @@ -36,6 +37,7 @@ import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.Messages; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.alert.AlertHistoryView; import org.rhq.enterprise.gui.coregui.client.alert.AlertPortletDataSource; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; @@ -43,7 +45,6 @@ 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -93,8 +94,7 @@ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSetti private AlertPortletDataSource dataSource; //instance ui widgets private Canvas containerCanvas; - private static Canvas componentToReload; - private static TableOrCanvasAutoRefresh defaultReloader; + private Timer defaultReloader;
public RecentAlertsPortlet(String locatorId) { super(locatorId); @@ -539,15 +539,20 @@ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSetti
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + refresh(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java index 5a3a0b2..30c9b4e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java @@ -23,6 +23,7 @@
package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.imported;
+import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.DynamicForm; @@ -36,13 +37,13 @@ import com.smartgwt.client.widgets.tree.TreeGrid;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.components.HeaderLabel; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements CustomSettingsPortlet, @@ -59,8 +60,7 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C
private static final String RECENTLY_ADDED_SHOW_MAX = "recently-added-show-amount"; private static final String RECENTLY_ADDED_SHOW_HRS = "recently-added-time-range"; - private static Canvas componentToReload; - private static TableOrCanvasAutoRefresh defaultReloader; + private Timer defaultReloader;
public RecentlyAddedResourcesPortlet(String locatorId) { super(locatorId); @@ -230,14 +230,19 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } } 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 76f61be..507c8ed 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 @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.operatio * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
+import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.DynamicForm; @@ -36,12 +37,12 @@ import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -79,8 +80,7 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting public static String unlimited = MSG.common_label_unlimited(); public static String defaultValue = unlimited; public static boolean defaultEnabled = true; - private static Canvas componentToReload; - private static TableOrCanvasAutoRefresh defaultReloader; + private Timer defaultReloader;
//default no-args constructor for serialization. private OperationsPortlet() { @@ -418,14 +418,19 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } } 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 296d92d..fddbfa1 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 @@ -38,6 +38,7 @@ import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableWidget; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; @@ -45,7 +46,6 @@ 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -72,8 +72,7 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort //constants public static final String unlimited = MSG.common_label_unlimited(); public static final String defaultValue = unlimited; - private static Canvas componentToReload; - private static TableOrCanvasAutoRefresh defaultReloader; + private Timer defaultReloader;
public ProblemResourcesPortlet(String locatorId) { super(locatorId, TITLE, true); @@ -293,15 +292,20 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + refresh(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java index 9a569aa..6b70298 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.summary; import java.util.ArrayList; import java.util.List;
+import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; @@ -37,11 +38,11 @@ import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.resource.InventorySummary; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; 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.util.selenium.LocatableDynamicForm; @@ -52,8 +53,7 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef
private LocatableDynamicForm form; public static final String KEY = MSG.common_title_summary_counts(); - private static Canvas componentToReload; - private static TableOrCanvasAutoRefresh defaultReloader; + private Timer defaultReloader;
public InventorySummaryPortlet(String locatorId) { super(locatorId); @@ -171,14 +171,19 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef
@Override public void startRefreshCycle() { - //lazy load - if (componentToReload == null) { - componentToReload = this; - } - //cancel the previous timer run + //current setting + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + //cancel previous operation if (defaultReloader != null) { - defaultReloader.stopTimer(); + defaultReloader.cancel(); } - defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); + defaultReloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + defaultReloader.schedule(retrievedRefreshInterval); + } + }; + defaultReloader.schedule(retrievedRefreshInterval); } }
commit d05803785b4fc6f381aca71b8a41b43013a8faa1 Author: Simeon Pinder spinder@redhat.com Date: Fri Dec 17 08:41:57 2010 -0500
attempt to fix initial menu load missing icons.
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 02f942b..9feaffd 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 @@ -269,10 +269,14 @@ public class DashboardView extends LocatableVLayout { Integer[] refreshValues = { STOP_VALUE, REFRESH1_VALUE, REFRESH5_VALUE, REFRESH10_VALUE }; refreshMenuMappings = new HashMap<Integer, String>(); refreshMenuItems = new MenuItem[refreshIntervals.length]; + int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); for (int i = 0; i < refreshIntervals.length; i++) { MenuItem item = new MenuItem(refreshIntervals[i], ""); item.addClickHandler(menuClick); refreshMenuMappings.put(refreshValues[i], refreshIntervals[i]); + if (retrievedRefreshInterval == refreshValues[i]) { + item.setIcon(ImageManager.getAvailabilityIcon(true)); + } refreshMenuItems[i] = item; }
@@ -280,6 +284,7 @@ public class DashboardView extends LocatableVLayout { refreshMenuButton = new LocatableIMenuButton(extendLocatorId("AutoRefreshButton"), MSG .common_title_change_refresh_time(), refreshMenu); refreshMenu.setAutoHeight(); + refreshMenuButton.getMenu().setItems(refreshMenuItems); refreshMenuButton.setWidth(170); refreshMenuButton.setShowTitle(true); refreshMenuButton.setTop(0); @@ -294,6 +299,8 @@ public class DashboardView extends LocatableVLayout {
editForm.setItems(nameItem, numColItem, addCanvas, picker, addColumn, removeColumn, refreshCanvas); updateRefreshMenu(); + this.refreshMenuButton.markForRedraw(); + markForRedraw(); return editForm; }
commit 5cccd335fac28b498cabf4269d655bbd4eb0ff12 Author: Simeon Pinder spinder@redhat.com Date: Thu Dec 16 19:01:42 2010 -0500
set default value for refresh interval.
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 bbb05bd..02f942b 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 @@ -62,6 +62,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle + * @author Simeon Pinder */ public class DashboardView extends LocatableVLayout { private DashboardsView dashboardsView; @@ -78,6 +79,11 @@ public class DashboardView extends LocatableVLayout { private static String REFRESH1 = MSG.view_dashboards_portlets_refresh_one_min(); private static String REFRESH5 = MSG.view_dashboards_portlets_refresh_multiple_min(String.valueOf(5)); private static String REFRESH10 = MSG.view_dashboards_portlets_refresh_multiple_min(String.valueOf(10)); + private static Integer STOP_VALUE = 0; + private static Integer REFRESH1_VALUE = 1 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + private static Integer REFRESH5_VALUE = 5 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + private static Integer REFRESH10_VALUE = 10 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + private HashMap<Integer, String> refreshMenuMappings; private MenuItem[] refreshMenuItems; private int refreshInterval = 0; @@ -243,15 +249,15 @@ public class DashboardView extends LocatableVLayout { refreshInterval = 0; if (selection != null) { if (selection.equals(STOP)) { - refreshInterval = 0; + refreshInterval = STOP_VALUE; } else if (selection.equals(REFRESH1)) { - refreshInterval = Long.valueOf(MeasurementUtility.MINUTES).intValue(); + refreshInterval = REFRESH1_VALUE; } else if (selection.equals(REFRESH5)) { - refreshInterval = 5 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + refreshInterval = REFRESH5_VALUE; } else if (selection.equals(REFRESH10)) { - refreshInterval = 10 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + refreshInterval = REFRESH10_VALUE; } else {//unable to locate value disable refresh - refreshInterval = 0;// + refreshInterval = STOP_VALUE;// } UserSessionManager.getUserPreferences().setPageRefreshInterval(refreshInterval, new UpdatePortletRefreshCallback()); @@ -260,9 +266,7 @@ public class DashboardView extends LocatableVLayout { };
String[] refreshIntervals = { STOP, REFRESH1, REFRESH5, REFRESH10 }; - Integer[] refreshValues = { 0, 1 * Long.valueOf(MeasurementUtility.MINUTES).intValue(), - 5 * Long.valueOf(MeasurementUtility.MINUTES).intValue(), - 10 * Long.valueOf(MeasurementUtility.MINUTES).intValue() }; + Integer[] refreshValues = { STOP_VALUE, REFRESH1_VALUE, REFRESH5_VALUE, REFRESH10_VALUE }; refreshMenuMappings = new HashMap<Integer, String>(); refreshMenuItems = new MenuItem[refreshIntervals.length]; for (int i = 0; i < refreshIntervals.length; i++) { 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 97e6314..1c311b0 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 @@ -33,6 +33,7 @@ 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 org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility;
/** * @author Greg Hinkle @@ -73,6 +74,9 @@ public class UserPreferences { }
public int getPageRefreshInterval() { + if (getPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD) == null) {//default to 60 seconds + setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(MeasurementUtility.MINUTES)); + } return getPreferenceAsInteger(UserPreferenceNames.PAGE_REFRESH_PERIOD); }
commit dedf4e96b1ce355cc2d3df01f397e3be006ad62d Author: Simeon Pinder spinder@redhat.com Date: Thu Dec 16 18:38:31 2010 -0500
i)modify dashboard to allow portlet refresh interval configuration with other dashboard settings ii)refactored portlet refresh logic into shared utility iii)refactor portlets to use shared utilty for refresh
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java index 2453272..2dca467 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java @@ -29,6 +29,8 @@ public interface AutoRefreshPortlet extends Portlet {
int refreshCycle = 60000;//ms
+ /** Each portlet implements to define the refresh cycle. See + * TableOrCanvasAutoRefresh for sample implementation. + */ void startRefreshCycle(); - } 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 c276e09..bbb05bd 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 @@ -74,10 +74,10 @@ public class DashboardView extends LocatableVLayout { IMenuButton addPortlet;
Set<PortletWindow> portlets = new HashSet<PortletWindow>(); - private static String STOP = "Stop"; - private static String REFRESH1 = "Refresh every 1 minute"; - private static String REFRESH5 = "Refresh every 5 minutes"; - private static String REFRESH10 = "Refresh every 10 minutes"; + private static String STOP = MSG.common_title_stop(); + private static String REFRESH1 = MSG.view_dashboards_portlets_refresh_one_min(); + private static String REFRESH5 = MSG.view_dashboards_portlets_refresh_multiple_min(String.valueOf(5)); + private static String REFRESH10 = MSG.view_dashboards_portlets_refresh_multiple_min(String.valueOf(10)); private HashMap<Integer, String> refreshMenuMappings; private MenuItem[] refreshMenuItems; private int refreshInterval = 0; @@ -273,8 +273,8 @@ public class DashboardView extends LocatableVLayout { }
refreshMenu.setItems(refreshMenuItems); - refreshMenuButton = new LocatableIMenuButton(extendLocatorId("AutoRefreshButton"), "Change Refresh Time", - refreshMenu); + refreshMenuButton = new LocatableIMenuButton(extendLocatorId("AutoRefreshButton"), MSG + .common_title_change_refresh_time(), refreshMenu); refreshMenu.setAutoHeight(); refreshMenuButton.setWidth(170); refreshMenuButton.setShowTitle(true); @@ -282,7 +282,7 @@ public class DashboardView extends LocatableVLayout { refreshMenuButton.setIconOrientation("left");
CanvasItem refreshCanvas = new CanvasItem(); - refreshCanvas.setTitle("Portlets auto-refresh interval"); + refreshCanvas.setTitle(MSG.common_title_portlet_auto_refresh()); refreshCanvas.setWrapTitle(false); refreshCanvas.setCanvas(refreshMenuButton); refreshCanvas.setStartRow(false); @@ -415,6 +415,7 @@ public class DashboardView extends LocatableVLayout { if (portletWindow.getDashboardPortlet().getId() == portlet.getId()) { portletWindow.getDashboardPortlet().setConfiguration(portlet.getConfiguration());
+ //restarting port auto-refresh with newest settings PortletViewFactory viewFactory = portletMap.get(portlet.getPortletKey());
// TODO: Note, we're using a sequence generated ID here as a locatorId. This is not optimal for repeatable @@ -424,7 +425,7 @@ public class DashboardView extends LocatableVLayout { + "-" + Integer.toString(portlet.getId()));
//add code to re-initialize refresh cycle for portlets - if (portlet instanceof AutoRefreshPortlet) { + if (view instanceof AutoRefreshPortlet) { ((AutoRefreshPortlet) view).startRefreshCycle(); } } @@ -472,9 +473,9 @@ public class DashboardView extends LocatableVLayout { public void onSuccess(Subject subject) { String m; if (refreshInterval > 0) { - m = "Updated interval for portlets that auto-refresh"; + m = MSG.view_dashboards_portlets_refresh_success1(); } else { - m = "Stopping reload for portlets that auto-refresh"; + m = MSG.view_dashboards_portlets_refresh_success2(); } CoreGUI.getMessageCenter().notify(new Message(m, Message.Severity.Info)); updateRefreshMenu(); @@ -484,9 +485,9 @@ public class DashboardView extends LocatableVLayout { public void onFailure(Throwable throwable) { String m; if (refreshInterval > 0) { - m = "Failed to updated interval for portlets that auto-refresh"; + m = MSG.view_dashboards_portlets_refresh_fail1(); } else { - m = "Failed to disable reload for portlets that auto-refresh"; + m = MSG.view_dashboards_portlets_refresh_fail2(); } CoreGUI.getMessageCenter().notify(new Message(m, Message.Severity.Error)); // Revert back to our original favorite status, since the server update failed. @@ -498,7 +499,7 @@ public class DashboardView extends LocatableVLayout { if (refreshMenuItems != null) { int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); String currentSelection = refreshMenuMappings.get(retrievedRefreshInterval); - if (currentSelection != null) { + if (currentSelection != null) {//iterate over menu items and update icon details for (int i = 0; i < refreshMenuItems.length; i++) { MenuItem menu = refreshMenuItems[i]; if (currentSelection.equals(menu.getTitle())) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java index 2c9c217..75f15c0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java @@ -25,18 +25,25 @@ import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility;
-/** +/**An implementation of a shared portet refresh utility. * @author Simeon Pinder */ public class TableOrCanvasAutoRefresh {
private Timer reloader;
+ /** reloads the Table or Canvas page based on the pageRefreshInterval saved to the + * current user's settings. + */ public TableOrCanvasAutoRefresh(final Canvas toBeReloaded) { if (toBeReloaded != null) { + //current setting final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + if (this.reloader != null) { + this.reloader.cancel(); + } if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { - reloader = new Timer() { + this.reloader = new Timer() { public void run() { if (toBeReloaded instanceof Table) { ((Table) toBeReloaded).refresh(); @@ -44,14 +51,19 @@ public class TableOrCanvasAutoRefresh { ((Canvas) toBeReloaded).redraw(); }
- //launch again until portlet reference and child references GC. + //launch again until shedule stopped or GC. reloader.schedule(retrievedRefreshInterval); } }; - reloader.schedule(retrievedRefreshInterval); - } else {//disable timer - reloader = null; + this.reloader.schedule(retrievedRefreshInterval); } } } + + //stops the timer from previous run. + public void stopTimer() { + if (this.reloader != null) { + this.reloader.cancel(); + } + } } 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 c837294..e7c2265 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,7 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.queue;
-import com.google.gwt.user.client.Timer; import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; @@ -32,19 +31,19 @@ import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; -import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; 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.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** + * @author Simeon Pinder * @author Greg Hinkle */ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements CustomSettingsPortlet, @@ -57,7 +56,8 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C //portlet settings and datasource elements private DashboardPortlet storedPortlet; private AutodiscoveryQueueDataSource dataSource; - private Timer reloader; + private static TableOrCanvasAutoRefresh defaultReloader; + private static Canvas componentToReload;
public AutodiscoveryPortlet(String locatorId) { super(locatorId, true); @@ -71,21 +71,23 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C if (getTreeGrid() != null) { getTreeGrid().setDataSource(getDataSource()); } - //loads/retrieves initial portlet settings for datasource - String retrieved = null; - //if settings already exist for this portlet - if (storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX) != null) { - //retrieve and translate to int - retrieved = storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX).getStringValue(); - } else {//create setting - storedPortlet.getConfiguration().put(new PropertySimple(AUTODISCOVERY_PLATFORM_MAX, defaultValue)); - retrieved = defaultValue; - } + if ((storedPortlet != null) && (storedPortlet.getConfiguration() != null)) { + //loads/retrieves initial portlet settings for datasource + String retrieved = null; + //if settings already exist for this portlet + if (storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX) != null) { + //retrieve and translate to int + retrieved = storedPortlet.getConfiguration().getSimple(AUTODISCOVERY_PLATFORM_MAX).getStringValue(); + } else {//create setting + storedPortlet.getConfiguration().put(new PropertySimple(AUTODISCOVERY_PLATFORM_MAX, defaultValue)); + retrieved = defaultValue; + }
- if (retrieved.equals(unlimited)) { - getDataSource().setMaximumPlatformsToDisplay(-1); - } else { - getDataSource().setMaximumPlatformsToDisplay(Integer.parseInt(retrieved)); + if (retrieved.equals(unlimited)) { + getDataSource().setMaximumPlatformsToDisplay(-1); + } else { + getDataSource().setMaximumPlatformsToDisplay(Integer.parseInt(retrieved)); + } } }
@@ -189,19 +191,14 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C
@Override public void startRefreshCycle() { - final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); - if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { - reloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - reloader.schedule(retrievedRefreshInterval); - } - }; - reloader.schedule(retrievedRefreshInterval); - } else {//disable timer - reloader = null; + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); } - // new TableOrCanvasAutoRefresh(this); + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } } 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 f1a3876..3b860b8 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 @@ -24,7 +24,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.resou
import java.util.Set;
-import com.google.gwt.user.client.Timer; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; @@ -39,6 +38,7 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSearchView;
/** @@ -53,7 +53,8 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto private DashboardPortlet storedPortlet; private PortletWindow portletWindow;
- private Timer reloader; + private static Canvas componentToReload; + private static TableOrCanvasAutoRefresh defaultReloader;
public FavoriteResourcesPortlet(String locatorId) { super(locatorId); @@ -116,14 +117,14 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); + } + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } - } 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 ad26a09..7cfcdb8 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,7 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.alerts;
-import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.DynamicForm; @@ -44,6 +43,7 @@ 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -93,7 +93,8 @@ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSetti private AlertPortletDataSource dataSource; //instance ui widgets private Canvas containerCanvas; - private Timer reloader; + private static Canvas componentToReload; + private static TableOrCanvasAutoRefresh defaultReloader;
public RecentAlertsPortlet(String locatorId) { super(locatorId); @@ -538,14 +539,15 @@ public class RecentAlertsPortlet extends AlertHistoryView implements CustomSetti
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - refresh(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); + } + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java index abc9e6b..5a3a0b2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java @@ -23,7 +23,6 @@
package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.imported;
-import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.DynamicForm; @@ -43,6 +42,7 @@ 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.dashboard.TableOrCanvasAutoRefresh; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements CustomSettingsPortlet, @@ -59,7 +59,8 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C
private static final String RECENTLY_ADDED_SHOW_MAX = "recently-added-show-amount"; private static final String RECENTLY_ADDED_SHOW_HRS = "recently-added-time-range"; - private Timer reloader; + private static Canvas componentToReload; + private static TableOrCanvasAutoRefresh defaultReloader;
public RecentlyAddedResourcesPortlet(String locatorId) { super(locatorId); @@ -229,13 +230,14 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); + } + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } } 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 adc9706..76f61be 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 @@ -19,7 +19,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.recent.operatio * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
-import com.google.gwt.user.client.Timer; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.DynamicForm; @@ -42,6 +41,7 @@ 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -76,10 +76,11 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting private DashboardPortlet storedPortlet = null; private RecentOperationsDataSource dataSourceCompleted; private ScheduledOperationsDataSource dataSourceScheduled; - private Timer reloader; public static String unlimited = MSG.common_label_unlimited(); public static String defaultValue = unlimited; public static boolean defaultEnabled = true; + private static Canvas componentToReload; + private static TableOrCanvasAutoRefresh defaultReloader;
//default no-args constructor for serialization. private OperationsPortlet() { @@ -417,13 +418,14 @@ public class OperationsPortlet extends LocatableVLayout implements CustomSetting
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); + } + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } } 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 81fc756..296d92d 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 @@ -45,6 +45,7 @@ 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.dashboard.TableOrCanvasAutoRefresh; 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; @@ -71,6 +72,8 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort //constants public static final String unlimited = MSG.common_label_unlimited(); public static final String defaultValue = unlimited; + private static Canvas componentToReload; + private static TableOrCanvasAutoRefresh defaultReloader;
public ProblemResourcesPortlet(String locatorId) { super(locatorId, TITLE, true); @@ -290,14 +293,15 @@ public class ProblemResourcesPortlet extends Table implements CustomSettingsPort
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - refresh(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); + } + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java index 2bc852c..9a569aa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java @@ -25,7 +25,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.summary; import java.util.ArrayList; import java.util.List;
-import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; @@ -42,6 +41,7 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; 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.dashboard.TableOrCanvasAutoRefresh; 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.util.selenium.LocatableDynamicForm; @@ -52,7 +52,8 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef
private LocatableDynamicForm form; public static final String KEY = MSG.common_title_summary_counts(); - private Timer reloader; + private static Canvas componentToReload; + private static TableOrCanvasAutoRefresh defaultReloader;
public InventorySummaryPortlet(String locatorId) { super(locatorId); @@ -170,13 +171,14 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + //lazy load + if (componentToReload == null) { + componentToReload = this; + } + //cancel the previous timer run + if (defaultReloader != null) { + defaultReloader.stopTimer(); + } + defaultReloader = new TableOrCanvasAutoRefresh(componentToReload); } } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 8f06b15..0263cc9 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -79,6 +79,7 @@ common_title_background = Background common_title_bundle = Bundle common_title_bundles = Bundles common_title_category = Category +common_title_change_refresh_time=Change Refresh Time common_title_columns = Columns common_title_configuration = Configuration common_title_compatibleGroups = Compatible Groups @@ -130,6 +131,7 @@ common_title_platform = Platform common_title_platform_total = Platform Total common_title_plugin = Plugin common_title_port = Port +common_title_portlet_auto_refresh=Portlet Auto-refresh Interval common_title_providers = Providers common_title_recently_added = Recently Added Resources common_title_recent_alerts = Recent Alerts @@ -162,6 +164,7 @@ common_title_show = Show common_title_show_more = Show more... common_title_start = Start common_title_status = Status +common_title_stop= Stop common_title_summary = Summary common_title_tag_cloud = Tag Cloud common_title_the = The @@ -1168,6 +1171,12 @@ view_dashboardManager_deleteFail = Failed to delete dashboard. view_dashboardManager_deleted = Successfully deleted dashboard {0} view_dashboards_title = Dashboard view_dashboards_confirm1 = Are you sure you want to delete +view_dashboards_portlets_refresh_fail1=Failed to update interval for portlets that auto-refresh +view_dashboards_portlets_refresh_fail2=Failed to disable reload for portlets that auto-refresh +view_dashboards_portlets_refresh_multiple_min = Refresh every {0} minutes +view_dashboards_portlets_refresh_one_min = Refresh every 1 minute +view_dashboards_portlets_refresh_success1=Updated interval for portlets that auto-refresh +view_dashboards_portlets_refresh_success2=Stopping reload for portlets that auto-refresh view_dashboardsManager_error1 = Failed to add new dashboard # // dup in common view_dashboardsManager_inventory_title = Inventory Summary
commit 6fc936a2a16732c2a6e1699ba48c18d0ad21f810 Author: Simeon Pinder spinder@redhat.com Date: Wed Dec 15 19:37:15 2010 -0500
dashboard portlet refresh configuration logic.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java index 2aedc24..2453272 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/AutoRefreshPortlet.java @@ -27,7 +27,7 @@ package org.rhq.enterprise.gui.coregui.client.dashboard; */ public interface AutoRefreshPortlet extends Portlet {
- int refreshCycle = 40000;//ms + int refreshCycle = 60000;//ms
void startRefreshCycle();
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 81d3bb2..c276e09 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard;
+import java.util.HashMap; import java.util.HashSet; import java.util.Set;
@@ -39,17 +40,24 @@ import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.menu.IMenuButton; import com.smartgwt.client.widgets.menu.Menu; import com.smartgwt.client.widgets.menu.MenuItem; +import com.smartgwt.client.widgets.menu.events.ClickHandler; import com.smartgwt.client.widgets.menu.events.ItemClickEvent; import com.smartgwt.client.widgets.menu.events.ItemClickHandler; +import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
+import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.Dashboard; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.ImageManager; +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.MeasurementUtility; 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.LocatableIMenuButton; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -66,6 +74,15 @@ public class DashboardView extends LocatableVLayout { IMenuButton addPortlet;
Set<PortletWindow> portlets = new HashSet<PortletWindow>(); + private static String STOP = "Stop"; + private static String REFRESH1 = "Refresh every 1 minute"; + private static String REFRESH5 = "Refresh every 5 minutes"; + private static String REFRESH10 = "Refresh every 10 minutes"; + private HashMap<Integer, String> refreshMenuMappings; + private MenuItem[] refreshMenuItems; + private int refreshInterval = 0; + private LocatableIMenuButton refreshMenuButton; + private HashMap<String, PortletViewFactory> portletMap = null;
public DashboardView(String locatorId, DashboardsView dashboardsView, Dashboard storedDashboard) { super(locatorId); @@ -117,10 +134,11 @@ public class DashboardView extends LocatableVLayout { private DynamicForm buildEditForm() { editForm = new LocatableDynamicForm(extendLocatorId("Editor")); editForm.setAutoWidth(); - editForm.setNumCols(9); + editForm.setNumCols(12);
TextItem nameItem = new TextItem("name", MSG.common_title_dashboard_name()); nameItem.setValue(storedDashboard.getName()); + nameItem.setWrapTitle(false); nameItem.addBlurHandler(new BlurHandler() { public void onBlur(BlurEvent blurEvent) { String val = (String) blurEvent.getItem().getValue(); @@ -153,7 +171,6 @@ public class DashboardView extends LocatableVLayout { });
ButtonItem removeColumn = new ButtonItem("removeColumn", MSG.common_title_remove_column()); - // removeColumn.setIcon("silk/application_side_contract.png"); removeColumn.setAutoFit(true); removeColumn.setStartRow(false); removeColumn.setEndRow(false); @@ -175,7 +192,7 @@ public class DashboardView extends LocatableVLayout { });
Menu addPorletMenu = new Menu(); - for (String portletName : PortletFactory.getRegisteredPortlets()) { + for (String portletName : PortletFactory.getRegisteredPortletKeys()) { addPorletMenu.addItem(new MenuItem(portletName)); }
@@ -213,7 +230,66 @@ public class DashboardView extends LocatableVLayout { }); picker.setValue(storedDashboard.getConfiguration().getSimpleValue(Dashboard.CFG_BACKGROUND, "white"));
- editForm.setItems(nameItem, numColItem, addCanvas, picker, addColumn, removeColumn); + //refresh interval + LocatableMenu refreshMenu = new LocatableMenu(extendLocatorId("AutoRefreshMenu")); + refreshMenu.setShowShadow(true); + refreshMenu.setShadowDepth(10); + refreshMenu.setAutoWidth(); + refreshMenu.setHeight(15); + ClickHandler menuClick = new ClickHandler() { + @Override + public void onClick(MenuItemClickEvent event) { + String selection = event.getItem().getTitle(); + refreshInterval = 0; + if (selection != null) { + if (selection.equals(STOP)) { + refreshInterval = 0; + } else if (selection.equals(REFRESH1)) { + refreshInterval = Long.valueOf(MeasurementUtility.MINUTES).intValue(); + } else if (selection.equals(REFRESH5)) { + refreshInterval = 5 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + } else if (selection.equals(REFRESH10)) { + refreshInterval = 10 * Long.valueOf(MeasurementUtility.MINUTES).intValue(); + } else {//unable to locate value disable refresh + refreshInterval = 0;// + } + UserSessionManager.getUserPreferences().setPageRefreshInterval(refreshInterval, + new UpdatePortletRefreshCallback()); + } + } + }; + + String[] refreshIntervals = { STOP, REFRESH1, REFRESH5, REFRESH10 }; + Integer[] refreshValues = { 0, 1 * Long.valueOf(MeasurementUtility.MINUTES).intValue(), + 5 * Long.valueOf(MeasurementUtility.MINUTES).intValue(), + 10 * Long.valueOf(MeasurementUtility.MINUTES).intValue() }; + refreshMenuMappings = new HashMap<Integer, String>(); + refreshMenuItems = new MenuItem[refreshIntervals.length]; + for (int i = 0; i < refreshIntervals.length; i++) { + MenuItem item = new MenuItem(refreshIntervals[i], ""); + item.addClickHandler(menuClick); + refreshMenuMappings.put(refreshValues[i], refreshIntervals[i]); + refreshMenuItems[i] = item; + } + + refreshMenu.setItems(refreshMenuItems); + refreshMenuButton = new LocatableIMenuButton(extendLocatorId("AutoRefreshButton"), "Change Refresh Time", + refreshMenu); + refreshMenu.setAutoHeight(); + refreshMenuButton.setWidth(170); + refreshMenuButton.setShowTitle(true); + refreshMenuButton.setTop(0); + refreshMenuButton.setIconOrientation("left"); + + CanvasItem refreshCanvas = new CanvasItem(); + refreshCanvas.setTitle("Portlets auto-refresh interval"); + refreshCanvas.setWrapTitle(false); + refreshCanvas.setCanvas(refreshMenuButton); + refreshCanvas.setStartRow(false); + refreshCanvas.setEndRow(false); + + editForm.setItems(nameItem, numColItem, addCanvas, picker, addColumn, removeColumn, refreshCanvas); + updateRefreshMenu(); return editForm; }
@@ -327,10 +403,31 @@ public class DashboardView extends LocatableVLayout { }
private void updateConfigs(Dashboard result) { - for (PortletWindow portletWindow : portlets) { - for (DashboardPortlet portlet : result.getPortlets()) { - if (portletWindow.getDashboardPortlet().getId() == portlet.getId()) { - portletWindow.getDashboardPortlet().setConfiguration(portlet.getConfiguration()); + if (result != null) { + if (portletMap == null) { + portletMap = new HashMap<String, PortletViewFactory>(); + for (String key : PortletFactory.getRegisteredPortletKeys()) { + portletMap.put(key, PortletFactory.getRegisteredPortlet(key)); + } + } + for (PortletWindow portletWindow : portlets) { + for (DashboardPortlet portlet : result.getPortlets()) { + if (portletWindow.getDashboardPortlet().getId() == portlet.getId()) { + portletWindow.getDashboardPortlet().setConfiguration(portlet.getConfiguration()); + + PortletViewFactory viewFactory = portletMap.get(portlet.getPortletKey()); + + // 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(PortletFactory.replaceSpaces(portlet.getPortletKey()) + + "-" + Integer.toString(portlet.getId())); + + //add code to re-initialize refresh cycle for portlets + if (portlet instanceof AutoRefreshPortlet) { + ((AutoRefreshPortlet) view).startRefreshCycle(); + } + } } } } @@ -370,4 +467,53 @@ public class DashboardView extends LocatableVLayout { } markForRedraw(); } + + public class UpdatePortletRefreshCallback implements AsyncCallback<Subject> { + public void onSuccess(Subject subject) { + String m; + if (refreshInterval > 0) { + m = "Updated interval for portlets that auto-refresh"; + } else { + m = "Stopping reload for portlets that auto-refresh"; + } + CoreGUI.getMessageCenter().notify(new Message(m, Message.Severity.Info)); + updateRefreshMenu(); + save(); + } + + public void onFailure(Throwable throwable) { + String m; + if (refreshInterval > 0) { + m = "Failed to updated interval for portlets that auto-refresh"; + } else { + m = "Failed to disable reload for portlets that auto-refresh"; + } + CoreGUI.getMessageCenter().notify(new Message(m, Message.Severity.Error)); + // Revert back to our original favorite status, since the server update failed. + updateRefreshMenu(); + } + } + + public void updateRefreshMenu() { + if (refreshMenuItems != null) { + int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + String currentSelection = refreshMenuMappings.get(retrievedRefreshInterval); + if (currentSelection != null) { + for (int i = 0; i < refreshMenuItems.length; i++) { + MenuItem menu = refreshMenuItems[i]; + if (currentSelection.equals(menu.getTitle())) { + menu.setIcon(ImageManager.getAvailabilityIcon(true)); + } else { + menu.setIcon(""); + } + refreshMenuItems[i] = menu; + } + //update the menu + refreshMenuButton.getMenu().setItems(refreshMenuItems); + } + } + if (this.refreshMenuButton != null) { + this.refreshMenuButton.markForRedraw(); + } + } } 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 f3c3246..61bd111 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 @@ -253,8 +253,8 @@ public class DashboardsView extends LocatableVLayout implements BookmarkableView DashboardPortlet recentAlerts = new DashboardPortlet(RecentAlertsPortlet.KEY, RecentAlertsPortlet.KEY, 250); dashboard.addPortlet(recentAlerts, 1, 3);
- DashboardPortlet recentlyAdded = new DashboardPortlet(MSG.common_title_recently_added(), RecentlyAddedResourcesPortlet.KEY, - 250); + DashboardPortlet recentlyAdded = new DashboardPortlet(MSG.common_title_recently_added(), + RecentlyAddedResourcesPortlet.KEY, 250); dashboard.addPortlet(recentlyAdded, 1, 4);
DashboardPortlet operations = new DashboardPortlet(MSG.common_title_operations(), OperationsPortlet.KEY, 500); 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 07dd73f..857f893 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 @@ -92,7 +92,7 @@ public class PortletFactory { * @param portletKey * @return */ - private static String replaceSpaces(String portletKey) { + public static String replaceSpaces(String portletKey) { String translated = portletKey; if (portletKey != null) { translated = portletKey.replaceAll(" ", "_"); @@ -101,11 +101,19 @@ public class PortletFactory { }
@SuppressWarnings("unchecked") - public static List<String> getRegisteredPortlets() { + public static List<String> getRegisteredPortletKeys() {
ArrayList portlets = new ArrayList(registeredPortlets.keySet()); Collections.sort(portlets); return portlets; }
+ public static PortletViewFactory getRegisteredPortlet(String key) { + PortletViewFactory portletFactory = null; + if ((key != null) & (!key.trim().isEmpty())) { + portletFactory = registeredPortlets.get(key); + } + return portletFactory; + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.java new file mode 100644 index 0000000..2c9c217 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/TableOrCanvasAutoRefresh.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.dashboard; + +import com.google.gwt.user.client.Timer; +import com.smartgwt.client.widgets.Canvas; + +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; +import org.rhq.enterprise.gui.coregui.client.components.table.Table; +import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; + +/** + * @author Simeon Pinder + */ +public class TableOrCanvasAutoRefresh { + + private Timer reloader; + + public TableOrCanvasAutoRefresh(final Canvas toBeReloaded) { + if (toBeReloaded != null) { + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + reloader = new Timer() { + public void run() { + if (toBeReloaded instanceof Table) { + ((Table) toBeReloaded).refresh(); + } else { + ((Canvas) toBeReloaded).redraw(); + } + + //launch again until portlet reference and child references GC. + reloader.schedule(retrievedRefreshInterval); + } + }; + reloader.schedule(retrievedRefreshInterval); + } else {//disable timer + reloader = null; + } + } + } +} 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 87d2911..c837294 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 @@ -32,6 +32,7 @@ import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; +import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; @@ -39,6 +40,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.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
@@ -187,13 +189,19 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C
@Override public void startRefreshCycle() { - reloader = new Timer() { - public void run() { - redraw(); - //launch again until portlet reference and child references GC. - reloader.schedule(refreshCycle); - } - }; - reloader.schedule(refreshCycle); + final int retrievedRefreshInterval = UserSessionManager.getUserPreferences().getPageRefreshInterval(); + if (retrievedRefreshInterval >= MeasurementUtility.MINUTES) { + reloader = new Timer() { + public void run() { + redraw(); + //launch again until portlet reference and child references GC. + reloader.schedule(retrievedRefreshInterval); + } + }; + reloader.schedule(retrievedRefreshInterval); + } else {//disable timer + reloader = null; + } + // new TableOrCanvasAutoRefresh(this); } } 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 d0913fc..97e6314 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 @@ -72,6 +72,15 @@ public class UserPreferences { store(callback); }
+ public int getPageRefreshInterval() { + return getPreferenceAsInteger(UserPreferenceNames.PAGE_REFRESH_PERIOD); + } + + public void setPageRefreshInterval(int refreshInterval, AsyncCallback<Subject> callback) { + setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval)); + store(callback); + } + protected String getPreference(String name) { return userConfiguration.getSimpleValue(name, null); } @@ -144,6 +153,17 @@ public class UserPreferences { } }
+ public Integer getPreferenceAsInteger(String key) { + String pref = null; + try { + pref = getPreference(key); + } catch (IllegalArgumentException e) { + + // log.debug("A user preference named '" + key + "' does not exist."); + } + return (pref != null) ? Integer.valueOf(pref) : Integer.valueOf(0); + } + public void addChangeListener(UserPreferenceChangeListener listener) { changeListeners.add(listener); }
commit d2a766a39f4e3cf9b6e823d53dd356f8d42c5b1c Author: John Mazzitelli mazz@redhat.com Date: Wed Dec 22 11:39:22 2010 -0500
BZ 659142 - ant unit test shows the manageRootDir=false working
diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index 8a12139..a9edfc1 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -23,6 +23,7 @@ package org.rhq.bundle.ant;
import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -33,6 +34,7 @@ import java.util.Set; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; +import org.testng.annotations.AfterClass; import org.testng.annotations.Test;
import org.rhq.core.domain.configuration.Configuration; @@ -49,7 +51,15 @@ import org.rhq.core.util.file.FileUtil; public class AntLauncherTest { private static final File DEPLOY_DIR = new File("target/test-ant-bundle").getAbsoluteFile();
+ @AfterClass + public void afterClass() { + FileUtil.purge(DEPLOY_DIR, true); + } + public void testParse() throws Exception { + // We want to test with an empty deploy dir to ensure nothing gets installed there after a parse + FileUtil.purge(DEPLOY_DIR, true); + AntLauncher ant = new AntLauncher();
BundleAntProject project = ant.parseBundleDeployFile(getBuildXml("test-bundle-v1.xml")); @@ -74,12 +84,18 @@ public class AntLauncherTest { assert propDef.getDefaultValue().equals("8080"); assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); assert propDef.isRequired(); + + // all we did was parse, nothing should really have been extracted or installed + assert !DEPLOY_DIR.exists() : "Nothing should have been installed to the deploy dir"; }
public void testInstall() throws Exception { // We want to test a fresh install, so make sure the deploy dir doesn't pre-exist. FileUtil.purge(DEPLOY_DIR, true);
+ // but we do want to add an unrelated file to see that it remains untouched - the install just "goes around" it + File unrelatedFile = writeFile("unrelated content", DEPLOY_DIR, "unrelated-file.txt"); + AntLauncher ant = new AntLauncher(); Properties inputProps = createInputProperties("/test-bundle-v1-input.properties"); List<BuildListener> buildListeners = createBuildListeners(); @@ -116,6 +132,10 @@ public class AntLauncherTest { assert preinstallTargetExecuted.equals("1a"); String postinstallTargetExecuted = (String) project.getProperties().get("postinstallTargetExecuted"); assert postinstallTargetExecuted.equals("1b"); + + assert new File(DEPLOY_DIR, "subdir/test.properties").exists() : "missing file"; + assert new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "missing archived bundle file"; + assert unrelatedFile.exists() : "unrelated file was removed during the install"; }
private List<BuildListener> createBuildListeners() { @@ -130,7 +150,9 @@ public class AntLauncherTest {
@Test(dependsOnMethods = "testInstall") public void testUpgrade() throws Exception { - // We want to test an upgrade, so do *not* wipe out the deploy dir. + // We want to test an upgrade, so do *not* wipe out the deploy dir - our test method @dependsOnMethods testInstall + // but we do want to add an unrelated file to see that it gets deleted as part of the upgrade + File unrelatedFile = writeFile("unrelated content", DEPLOY_DIR, "unrelated-file.txt");
AntLauncher ant = new AntLauncher(); Properties inputProps = createInputProperties("/test-bundle-v2-input.properties"); @@ -168,6 +190,61 @@ public class AntLauncherTest { assert preinstallTargetExecuted.equals("2a"); String postinstallTargetExecuted = (String) project.getProperties().get("postinstallTargetExecuted"); assert postinstallTargetExecuted.equals("2b"); + + assert new File(DEPLOY_DIR, "subdir/test.properties").exists() : "missing file"; + assert new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "missing archived bundle file"; + assert !unrelatedFile.exists() : "we are managing root dir so unrelated file should be removed during upgrade"; + } + + public void testUpgradeNoManageRootDir() throws Exception { + // We want to test an upgrade, so do *not* wipe out the deploy dir - let's re-invoke testInstall + // to get us to an initial state of the v1 bundle installed + testInstall(); + + // we still want the unrelated file - we want to see that manageRootDir=false works (unrelated files should not be deleted) + File unrelatedFile = new File(DEPLOY_DIR, "unrelated-file.txt"); + assert unrelatedFile.exists() : "our initial install test method should have prepared an unmanaged file"; + + AntLauncher ant = new AntLauncher(); + Properties inputProps = createInputProperties("/test-bundle-v2-input.properties"); + List<BuildListener> buildListeners = createBuildListeners(); + + BundleAntProject project = ant.executeBundleDeployFile(getBuildXml("test-bundle-v2-noManageRootDir.xml"), + inputProps, buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); + assert bundleFiles != null; + assert bundleFiles.size() == 4 : bundleFiles; + assert bundleFiles.contains("test-v2.properties") : bundleFiles; + assert bundleFiles.contains("file.zip") : bundleFiles; + assert bundleFiles.contains("foo-script") : bundleFiles; // from install-system-service + assert bundleFiles.contains("foo-config") : bundleFiles; // from install-system-service + + assert project.getBundleName().equals("example.com (JBoss EAP 4.3)"); + assert project.getBundleVersion().equals("2.5"); + assert project.getBundleDescription().equals("updated bundle"); + + ConfigurationDefinition configDef = project.getConfigurationDefinition(); + assert configDef.getPropertyDefinitions().size() == 1 : configDef.getPropertyDefinitions(); + PropertyDefinitionSimple propDef = configDef.getPropertyDefinitionSimple("listener.port"); + assert propDef != null; + assert propDef.getType() == PropertySimpleType.INTEGER; + assert propDef.getDefaultValue().equals("9090"); + assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); + assert propDef.isRequired(); + + Configuration config = project.getConfiguration(); + assert config.getProperties().size() == 1; + assert "20000".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); + + String preinstallTargetExecuted = (String) project.getProperties().get("preinstallTargetExecuted"); + assert preinstallTargetExecuted.equals("2a"); + String postinstallTargetExecuted = (String) project.getProperties().get("postinstallTargetExecuted"); + assert postinstallTargetExecuted.equals("2b"); + + assert new File(DEPLOY_DIR, "subdir/test.properties").exists() : "missing file"; + assert new File(DEPLOY_DIR, "archived-bundle-file.txt").exists() : "missing archived bundle file"; + assert unrelatedFile.exists() : "we are NOT managing root dir so unrelated file should NOT be removed during upgrade"; }
private Properties createInputProperties(String resourcePath) throws IOException { @@ -189,4 +266,24 @@ public class AntLauncherTest { assert file.exists() : "The test Ant build script doesn't exist: " + file.getAbsolutePath(); return file; } + + private File writeFile(String content, File fileToOverwrite) throws Exception { + FileOutputStream out = null; + + try { + fileToOverwrite.getParentFile().mkdirs(); + out = new FileOutputStream(fileToOverwrite); + out.write(content.getBytes()); + return fileToOverwrite; + } finally { + if (out != null) { + out.close(); + } + } + } + + private File writeFile(String content, File destDir, String fileName) throws Exception { + File destFile = new File(destDir, fileName); + return writeFile(content, destFile); + } } diff --git a/modules/common/ant-bundle/src/test/resources/file.zip b/modules/common/ant-bundle/src/test/resources/file.zip index ea45ad7..922658a 100644 Binary files a/modules/common/ant-bundle/src/test/resources/file.zip and b/modules/common/ant-bundle/src/test/resources/file.zip differ diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-v2-noManageRootDir.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-v2-noManageRootDir.xml new file mode 100644 index 0000000..0b07e9e --- /dev/null +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-v2-noManageRootDir.xml @@ -0,0 +1,46 @@ +<?xml version="1.0"?> + +<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle"> + + <rhq:bundle name="example.com (JBoss EAP 4.3)" version="2.5" + description="updated bundle"> + + <rhq:input-property + name="listener.port" + description="This is where the product will listen for incoming messages" + required="true" + defaultValue="9090" + type="integer"/> + + <rhq:deployment-unit name="appserver" preinstallTarget="preinstall" postinstallTarget="postinstall" + manageRootDir="false"> <!-- this is the only difference with test-bundle-v2.xml --> + <rhq:system-service name="foo" scriptFile="foo-script" + configFile="foo-config" overwriteScript="true" + startLevels="3,4,5" startPriority="80" stopPriority="20" root="root"/> + <rhq:file name="test-v2.properties" destinationFile="subdir/test.properties" replace="true"/> + <rhq:archive name="file.zip"> + rhq:replace + <rhq:fileset includes="**/*.properties"/> + </rhq:replace> + </rhq:archive> + <!-- the files that should be ignored during upgrades --> + rhq:ignore + <rhq:fileset includes="*.log"/> + </rhq:ignore> + </rhq:deployment-unit> + + </rhq:bundle> + + <target name="main"/> + + <target name="preinstall"> + <echo>Deploying Test Bundle v2.5 to ${rhq.deploy.dir}...</echo> + <property name="preinstallTargetExecuted" value="2a"/> + </target> + + <target name="postinstall"> + <echo>Done deploying Test Bundle v2.5 to ${rhq.deploy.dir}.</echo> + <property name="postinstallTargetExecuted" value="2b"/> + </target> + +</project> \ No newline at end of file
commit 64407320dc3715ce09caf4c6f1f8c067602bddbd Author: John Mazzitelli mazz@redhat.com Date: Wed Dec 22 10:38:24 2010 -0500
put test more things in the ant launcher unit test
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java index bfc8d2e..86fd666 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/AntLauncher.java @@ -83,13 +83,18 @@ public class AntLauncher { * @throws InvalidBuildFileException if the build file is invalid */ public BundleAntProject executeBundleDeployFile(File buildFile, Properties buildProperties, - List<BuildListener> buildListeners) - throws InvalidBuildFileException { + List<BuildListener> buildListeners) throws InvalidBuildFileException { // Parse and validate the build file before even attempting to execute it. - parseBundleDeployFile(buildFile); + BundleAntProject parsedProject = parseBundleDeployFile(buildFile);
BundleAntProject project = createProject(buildFile, false);
+ // The parse above got us all the bundle files names. The rest of this method + // will be able to re-determine everything else for 'project' but these filenames. + // Therefore, we need to copy those filenames from the parsedProject to project. + // The rest of project will be filled in later. + project.getBundleFileNames().addAll(parsedProject.getBundleFileNames()); + try { if (buildProperties != null) { for (Map.Entry<Object, Object> property : buildProperties.entrySet()) { @@ -133,10 +138,9 @@ public class AntLauncher { try { // Use the 3-param version of parse(), rather than the 2-param version, or ProjectHelper.configureProject(), // to avoid actually executing the implicit target (which would cause the rhq:bundle task to be executed). - AntXMLContext context = (AntXMLContext) project.getReference(REFID_CONTEXT); - projectHelper.parse(project, buildFile, - new ProjectHelper2.RootHandler(context, - new ProjectHelper2.MainHandler())); + AntXMLContext context = (AntXMLContext) project.getReference(REFID_CONTEXT); + projectHelper.parse(project, buildFile, new ProjectHelper2.RootHandler(context, + new ProjectHelper2.MainHandler())); } catch (BuildException e) { throw new InvalidBuildFileException("Failed to parse bundle Ant build file.", e); } @@ -210,7 +214,7 @@ public class AntLauncher { for (Object targetObj : targets) { Target target = (Target) targetObj; Task[] tasks = target.getTasks(); - for (Task task : tasks) { + for (Task task : tasks) { if (task.getTaskName().equals(BUNDLE_TASK_NAME)) { abortIfTaskWithinTarget(target, task); bundleTaskCount++; @@ -230,7 +234,8 @@ public class AntLauncher { BundleTask bundleTask = (BundleTask) preconfigureTask(unconfiguredBundleTask); Collection<DeploymentUnitType> deployments = bundleTask.getDeploymentUnits().values(); if (deployments.isEmpty()) { - throw new InvalidBuildFileException("The bundle task must contain exactly one rhq:deploymentUnit child element."); + throw new InvalidBuildFileException( + "The bundle task must contain exactly one rhq:deploymentUnit child element."); } DeploymentUnitType deployment = deployments.iterator().next(); Map<File, File> files = deployment.getFiles(); diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java index 831bdf9..8a12139 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/AntLauncherTest.java @@ -28,6 +28,7 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; +import java.util.Set;
import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.DefaultLogger; @@ -53,17 +54,26 @@ public class AntLauncherTest {
BundleAntProject project = ant.parseBundleDeployFile(getBuildXml("test-bundle-v1.xml")); assert project != null; - /*Map<String, String> bundleFiles = project.getBundleFiles(); + Set<String> bundleFiles = project.getBundleFileNames(); assert bundleFiles != null; - assert bundleFiles.size() == 2 : bundleFiles; - assert bundleFiles.get("f").equals("test-v2.properties") : bundleFiles; - assert bundleFiles.get("pkg").equals("package.zip") : bundleFiles;*/ + assert bundleFiles.size() == 4 : bundleFiles; + assert bundleFiles.contains("test-v1.properties") : bundleFiles; + assert bundleFiles.contains("file.zip") : bundleFiles; + assert bundleFiles.contains("foo-script") : bundleFiles; // from install-system-service + assert bundleFiles.contains("foo-config") : bundleFiles; // from install-system-service + + assert project.getBundleName().equals("example.com (JBoss EAP 4.3)"); + assert project.getBundleVersion().equals("1.0"); + assert project.getBundleDescription().equals("example.com corporate website hosted on JBoss EAP 4.3");
ConfigurationDefinition configDef = project.getConfigurationDefinition(); assert configDef.getPropertyDefinitions().size() == 1 : configDef.getPropertyDefinitions(); PropertyDefinitionSimple propDef = configDef.getPropertyDefinitionSimple("listener.port"); assert propDef != null; assert propDef.getType() == PropertySimpleType.INTEGER; + assert propDef.getDefaultValue().equals("8080"); + assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); + assert propDef.isRequired(); }
public void testInstall() throws Exception { @@ -75,27 +85,37 @@ public class AntLauncherTest { List<BuildListener> buildListeners = createBuildListeners();
BundleAntProject project = ant.executeBundleDeployFile(getBuildXml("test-bundle-v1.xml"), inputProps, - buildListeners); - /*Map<String, String> bundleFiles = project.getBundleFiles(); + buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); assert bundleFiles != null; - assert bundleFiles.size() == 2 : bundleFiles; - assert bundleFiles.get("f").equals("test-v2.properties") : bundleFiles; - assert bundleFiles.get("pkg").equals("package.zip") : bundleFiles;*/ + assert bundleFiles.size() == 4 : bundleFiles; + assert bundleFiles.contains("test-v1.properties") : bundleFiles; + assert bundleFiles.contains("file.zip") : bundleFiles; + assert bundleFiles.contains("foo-script") : bundleFiles; // from install-system-service + assert bundleFiles.contains("foo-config") : bundleFiles; // from install-system-service + + assert project.getBundleName().equals("example.com (JBoss EAP 4.3)"); + assert project.getBundleVersion().equals("1.0"); + assert project.getBundleDescription().equals("example.com corporate website hosted on JBoss EAP 4.3");
ConfigurationDefinition configDef = project.getConfigurationDefinition(); assert configDef.getPropertyDefinitions().size() == 1 : configDef.getPropertyDefinitions(); PropertyDefinitionSimple propDef = configDef.getPropertyDefinitionSimple("listener.port"); assert propDef != null; assert propDef.getType() == PropertySimpleType.INTEGER; + assert propDef.getDefaultValue().equals("8080"); + assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); + assert propDef.isRequired();
Configuration config = project.getConfiguration(); assert config.getProperties().size() == 1 : config.getProperties(); assert "10000".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); - + String preinstallTargetExecuted = (String) project.getProperties().get("preinstallTargetExecuted"); - assert preinstallTargetExecuted.equals("true"); + assert preinstallTargetExecuted.equals("1a"); String postinstallTargetExecuted = (String) project.getProperties().get("postinstallTargetExecuted"); - assert postinstallTargetExecuted.equals("true"); + assert postinstallTargetExecuted.equals("1b"); }
private List<BuildListener> createBuildListeners() { @@ -117,28 +137,43 @@ public class AntLauncherTest { List<BuildListener> buildListeners = createBuildListeners();
BundleAntProject project = ant.executeBundleDeployFile(getBuildXml("test-bundle-v2.xml"), inputProps, - buildListeners); - /*Map<String, String> bundleFiles = project.getBundleFiles(); + buildListeners); + assert project != null; + Set<String> bundleFiles = project.getBundleFileNames(); assert bundleFiles != null; - assert bundleFiles.size() == 2 : bundleFiles; - assert bundleFiles.get("f").equals("test-v2.properties") : bundleFiles; - assert bundleFiles.get("pkg").equals("package.zip") : bundleFiles;*/ + assert bundleFiles.size() == 4 : bundleFiles; + assert bundleFiles.contains("test-v2.properties") : bundleFiles; + assert bundleFiles.contains("file.zip") : bundleFiles; + assert bundleFiles.contains("foo-script") : bundleFiles; // from install-system-service + assert bundleFiles.contains("foo-config") : bundleFiles; // from install-system-service + + assert project.getBundleName().equals("example.com (JBoss EAP 4.3)"); + assert project.getBundleVersion().equals("2.5"); + assert project.getBundleDescription().equals("updated bundle");
ConfigurationDefinition configDef = project.getConfigurationDefinition(); - assert configDef.getPropertyDefinitions().size() == 1; + assert configDef.getPropertyDefinitions().size() == 1 : configDef.getPropertyDefinitions(); PropertyDefinitionSimple propDef = configDef.getPropertyDefinitionSimple("listener.port"); assert propDef != null; assert propDef.getType() == PropertySimpleType.INTEGER; + assert propDef.getDefaultValue().equals("9090"); + assert propDef.getDescription().equals("This is where the product will listen for incoming messages"); + assert propDef.isRequired();
Configuration config = project.getConfiguration(); assert config.getProperties().size() == 1; assert "20000".equals(config.getSimpleValue("listener.port", null)) : config.getProperties(); + + String preinstallTargetExecuted = (String) project.getProperties().get("preinstallTargetExecuted"); + assert preinstallTargetExecuted.equals("2a"); + String postinstallTargetExecuted = (String) project.getProperties().get("postinstallTargetExecuted"); + assert postinstallTargetExecuted.equals("2b"); }
private Properties createInputProperties(String resourcePath) throws IOException { Properties inputProps = new Properties(); inputProps.setProperty(DeployPropertyNames.DEPLOY_DIR, DEPLOY_DIR.getPath()); - inputProps.setProperty(DeployPropertyNames.DEPLOY_ID, "100"); + inputProps.setProperty(DeployPropertyNames.DEPLOY_ID, "100"); inputProps.setProperty(DeployPropertyNames.DEPLOY_PHASE, DeploymentPhase.INSTALL.name()); InputStream inputStream = this.getClass().getResourceAsStream(resourcePath); try { diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-v1.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-v1.xml index 76820bf..a6dcfec 100644 --- a/modules/common/ant-bundle/src/test/resources/test-bundle-v1.xml +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-v1.xml @@ -34,12 +34,12 @@
<target name="preinstall"> <echo>Deploying Test Bundle v1.0 to ${rhq.deploy.dir}...</echo> - <property name="preinstallTargetExecuted" value="true"/> + <property name="preinstallTargetExecuted" value="1a"/> </target>
<target name="postinstall"> <echo>Done deploying Test Bundle v1.0 to ${rhq.deploy.dir}.</echo> - <property name="postinstallTargetExecuted" value="true"/> + <property name="postinstallTargetExecuted" value="1b"/> </target>
</project> \ No newline at end of file diff --git a/modules/common/ant-bundle/src/test/resources/test-bundle-v2.xml b/modules/common/ant-bundle/src/test/resources/test-bundle-v2.xml index 6764c13..1bbe0d1 100644 --- a/modules/common/ant-bundle/src/test/resources/test-bundle-v2.xml +++ b/modules/common/ant-bundle/src/test/resources/test-bundle-v2.xml @@ -2,14 +2,14 @@
<project name="test-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle">
- <rhq:bundle name="example.com (JBoss EAP 4.3)" version="1.0" - description="example.com corporate website hosted on JBoss EAP 4.3"> + <rhq:bundle name="example.com (JBoss EAP 4.3)" version="2.5" + description="updated bundle">
<rhq:input-property name="listener.port" description="This is where the product will listen for incoming messages" required="true" - defaultValue="8080" + defaultValue="9090" type="integer"/>
<rhq:deployment-unit name="appserver" preinstallTarget="preinstall" postinstallTarget="postinstall"> @@ -33,13 +33,13 @@ <target name="main"/>
<target name="preinstall"> - <echo>Deploying Test Bundle v1.0 to ${rhq.deploy.dir}...</echo> - <property name="preinstallTargetExecuted" value="true"/> + <echo>Deploying Test Bundle v2.5 to ${rhq.deploy.dir}...</echo> + <property name="preinstallTargetExecuted" value="2a"/> </target>
<target name="postinstall"> - <echo>Done deploying Test Bundle v1.0 to ${rhq.deploy.dir}.</echo> - <property name="postinstallTargetExecuted" value="true"/> + <echo>Done deploying Test Bundle v2.5 to ${rhq.deploy.dir}.</echo> + <property name="postinstallTargetExecuted" value="2b"/> </target>
</project> \ No newline at end of file
commit 067f66c0c2e4f1e9f544158f9d356f0ca70f2479 Author: John Mazzitelli mazz@redhat.com Date: Wed Dec 22 03:25:03 2010 -0500
BZ 659142 - Add support for deploying bundles into a folder in which the bundle doesn't have exclusive usage. this is to support being able to deploy a bundle in a JBossAS deploy/ directory. All unit tests pass with this commit, with a new set of unit tests being added to test this feature. however, more testing needs to be done on the ant recipe side to make sure the ant recipe is passing this flag correctly to the Deployer utility.
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java index dda489c..3727adb 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/DeploymentUnitType.java @@ -17,9 +17,19 @@ */ package org.rhq.bundle.ant.type;
+import java.io.File; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Target; + import org.rhq.bundle.ant.DeployPropertyNames; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; @@ -30,15 +40,6 @@ import org.rhq.core.util.updater.Deployer; import org.rhq.core.util.updater.DeploymentData; import org.rhq.core.util.updater.DeploymentProperties;
-import java.io.File; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - /** * An Ant task for deploying a bundle or previewing the deployment. * @@ -46,13 +47,13 @@ import java.util.regex.Pattern; */ public class DeploymentUnitType extends AbstractBundleType { private String name; + private String manageRootDir = Boolean.TRUE.toString(); private Map<File, File> files = new LinkedHashMap<File, File>(); private Set<File> rawFilesToReplace = new LinkedHashSet<File>(); private Set<File> archives = new LinkedHashSet<File>(); private Map<File, Pattern> archiveReplacePatterns = new HashMap<File, Pattern>(); private SystemServiceType systemService; private Pattern ignorePattern; - private boolean preview; private String preinstallTarget; private String postinstallTarget;
@@ -78,7 +79,8 @@ public class DeploymentUnitType extends AbstractBundleType { TemplateEngine templateEngine = createTemplateEngine();
if (this.files.isEmpty() && this.archives.isEmpty()) { - throw new BuildException("You must specify at least one file to deploy via nested rhq:file, rhq:archive, and/or rhq:system-service elements."); + throw new BuildException( + "You must specify at least one file to deploy via nested rhq:file, rhq:archive, and/or rhq:system-service elements."); } if (!this.files.isEmpty()) { log("Deploying files " + this.files + "...", Project.MSG_VERBOSE); @@ -87,8 +89,17 @@ public class DeploymentUnitType extends AbstractBundleType { log("Deploying archives " + this.archives + "...", Project.MSG_VERBOSE); }
+ boolean willManageRootDir = Boolean.parseBoolean(this.manageRootDir); + if (willManageRootDir) { + log("Managing the root directory of this deployment unit - unrelated files found will be removed", + Project.MSG_VERBOSE); + } else { + log("Not managing the root directory of this deployment unit - unrelated files will remain intact", + Project.MSG_VERBOSE); + } + DeploymentData deploymentData = new DeploymentData(deploymentProps, this.archives, this.files, deployDir, - this.archiveReplacePatterns, this.rawFilesToReplace, templateEngine, this.ignorePattern); + this.archiveReplacePatterns, this.rawFilesToReplace, templateEngine, this.ignorePattern, willManageRootDir); Deployer deployer = new Deployer(deploymentData); try { DeployDifferences diffs = getProject().getDeployDifferences(); @@ -98,7 +109,7 @@ public class DeploymentUnitType extends AbstractBundleType { } else { deployer.deploy(diffs, clean, dryRun); } - getProject().log("Results:\n" + diffs + "\n"); + getProject().log("Results:\n" + diffs + "\n"); } catch (Exception e) { throw new BuildException("Failed to deploy bundle '" + getProject().getBundleName() + "' version " + getProject().getBundleVersion() + ": " + e, e); @@ -111,7 +122,8 @@ public class DeploymentUnitType extends AbstractBundleType { if (this.postinstallTarget != null) { Target target = (Target) getProject().getTargets().get(this.postinstallTarget); if (target == null) { - throw new BuildException("Specified postinstall target (" + this.postinstallTarget + ") does not exist."); + throw new BuildException("Specified postinstall target (" + this.postinstallTarget + + ") does not exist."); } target.performTasks(); } @@ -140,7 +152,7 @@ public class DeploymentUnitType extends AbstractBundleType { this.systemService.uninstall(); } } - + public String getName() { return name; } @@ -149,20 +161,24 @@ public class DeploymentUnitType extends AbstractBundleType { this.name = name; }
- public Map<File, File> getFiles() { - return files; + public String getManageRootDir() { + return manageRootDir; }
- public Set<File> getArchives() { - return archives; + public void setManageRootDir(String booleanString) { + if (!Boolean.TRUE.toString().equalsIgnoreCase(booleanString) + && !Boolean.FALSE.toString().equalsIgnoreCase(booleanString)) { + throw new BuildException("manageRootDir attribute must be 'true' or 'false': " + booleanString); + } + this.manageRootDir = booleanString; }
- public boolean isPreview() { - return this.preview; + public Map<File, File> getFiles() { + return files; }
- public void setPreview(boolean preview) { - this.preview = preview; + public Set<File> getArchives() { + return archives; }
public String getPreinstallTarget() { @@ -183,7 +199,8 @@ public class DeploymentUnitType extends AbstractBundleType {
public void addConfigured(SystemServiceType systemService) { if (this.systemService != null) { - throw new IllegalStateException("A rhq:deploymentUnit element can only have one rhq:system-service child element."); + throw new IllegalStateException( + "A rhq:deployment-unit element can only have one rhq:system-service child element."); } this.systemService = systemService; this.systemService.validate(); @@ -230,7 +247,7 @@ public class DeploymentUnitType extends AbstractBundleType { } // And add the special rhq.deploy.dir prop. templateEngine.getTokens().put(DeployPropertyNames.DEPLOY_DIR, - getProject().getProperty(DeployPropertyNames.DEPLOY_DIR)); + getProject().getProperty(DeployPropertyNames.DEPLOY_DIR)); return templateEngine; } } \ No newline at end of file diff --git a/modules/core/util/src/main/java/org/rhq/core/util/updater/ChangesFileHashcodeMap.java b/modules/core/util/src/main/java/org/rhq/core/util/updater/ChangesFileHashcodeMap.java index 9fc824e..3f0c364 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/updater/ChangesFileHashcodeMap.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/updater/ChangesFileHashcodeMap.java @@ -41,6 +41,7 @@ public class ChangesFileHashcodeMap extends FileHashcodeMap { private final Map<String, String> additions = new HashMap<String, String>(); private final Map<String, String> changes = new HashMap<String, String>(); private final Set<String> ignored = new HashSet<String>(); + private final Set<String> skipped = new HashSet<String>();
/** * Creates an file/hashcode map populated with a map of original file data. @@ -87,4 +88,12 @@ public class ChangesFileHashcodeMap extends FileHashcodeMap { public Set<String> getIgnored() { return ignored; } + + /** + * @return the files and directories located directly under the root deploy dir that were skipped. + * These are files/directories that are considered unrelated to the deployment and should be left alone. + */ + public Set<String> getSkipped() { + return skipped; + } } diff --git a/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java b/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java index 2a4e99d..5116631 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/updater/Deployer.java @@ -340,7 +340,7 @@ public class Deployer {
FileHashcodeMap original = this.deploymentsMetadata.getCurrentDeploymentFileHashcodes(); ChangesFileHashcodeMap current = original.rescan(this.deploymentData.getDestinationDir(), this.deploymentData - .getIgnoreRegex()); + .getIgnoreRegex(), this.deploymentData.isManageRootDir()); FileHashcodeMap newFiles = getNewDeploymentFileHashcodeMap();
if (current.getUnknownContent() != null) { @@ -439,6 +439,9 @@ public class Deployer { currentFilesToDelete.removeAll(newFiles.keySet()); currentFilesToDelete.removeAll(current.getDeletions().keySet()); // these are already deleted, no sense trying to delete them again
+ // remember what files were skipped so we don't delete them during our purge below (only care about this if we are going to 'clean') + Set<String> skippedFiles = (clean) ? current.getSkipped() : null; + // don't use this anymore - its underlying key set has been altered and this no longer is the full current files current = null;
@@ -487,7 +490,7 @@ public class Deployer { if (clean) { debug("Cleaning the existing deployment's files found in the destination directory. dryRun=", dryRun); if (!dryRun) { - purgeFileOrDirectory(this.deploymentData.getDestinationDir(), false); + purgeFileOrDirectory(this.deploymentData.getDestinationDir(), skippedFiles, 0, false); } } diff.setCleaned(clean); @@ -816,8 +819,9 @@ public class Deployer { restoreBackupFilesRecursive(child, base, destDir, map, diff, dryRun); } else { String childRelativePath = child.getAbsolutePath().substring(base.length()); + //if (this.deploymentData.isManageRootDir() || new File(childRelativePath).getParent() != null) { File restoredFile = new File(destDir, childRelativePath); - debug("Restoring backup file [" + child + "] to [" + restoredFile + "]. dryRun=" + dryRun); + debug("Restoring backup file [", child, "] to [", restoredFile, "]. dryRun=", dryRun); if (!dryRun) { restoredFile.getParentFile().mkdirs(); String hashcode = copyFileAndCalcHashcode(child, restoredFile); @@ -826,6 +830,10 @@ public class Deployer { map.put(childRelativePath, MessageDigestGenerator.getDigestString(child)); } diff.addRestoredFile(childRelativePath, child.getAbsolutePath()); + //} else { + // debug("Skipping the restoration of the backed up file [", childRelativePath, + // "] since this deployment was told to not manage the root directory"); + //} } } } @@ -843,7 +851,7 @@ public class Deployer { } else { String childRelativePath = child.getAbsolutePath().substring(base.length()); File restoredFile = new File(rootDir, childRelativePath); - debug("Restoring backup file [" + child + "] to external location [" + restoredFile + "]. dryRun=" + debug("Restoring backup file [", child, "] to external location [", restoredFile, "]. dryRun=" + dryRun); if (!dryRun) { restoredFile.getParentFile().mkdirs(); @@ -882,14 +890,20 @@ public class Deployer { } }
- private void purgeFileOrDirectory(File fileOrDir, boolean deleteIt) { + private void purgeFileOrDirectory(File fileOrDir, Set<String> skippedFiles, int level, boolean deleteIt) { // make sure we only purge deployment files, never the metadata directory or its files + // we also want to leave all skipped files alone - don't delete those since they are unrelated to our deployment if (fileOrDir != null && !fileOrDir.getName().equals(DeploymentsMetadata.METADATA_DIR)) { if (fileOrDir.isDirectory()) { File[] doomedFiles = fileOrDir.listFiles(); if (doomedFiles != null) { for (File doomedFile : doomedFiles) { - purgeFileOrDirectory(doomedFile, true); // call this method recursively + // Do not purge any skipped files - we want to skip them. + // All our skipped files are always at the top root dir (level 0), + // so we can ignore the skipped set if we are at levels 1 or below since there are no skipped files down there + if (level != 0 || !skippedFiles.contains(doomedFile.getName())) { + purgeFileOrDirectory(doomedFile, skippedFiles, level + 1, true); // call this method recursively + } } } } diff --git a/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java b/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java index 32c1a26..b1fac47 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/updater/DeploymentData.java @@ -47,6 +47,7 @@ public class DeploymentData { private final Set<File> rawFilesToRealize; private final TemplateEngine templateEngine; private final Pattern ignoreRegex; + private final boolean manageRootDir;
/** * Constructors that prepares this object with the data that is necessary in order to deploy archive/file content @@ -69,10 +70,17 @@ public class DeploymentData { * @param templateEngine if one or more filesToRealize are specified, this template engine is used to determine * the values that should replace all replacement variables found in those files * @param ignoreRegex the files/directories to ignore when updating an existing deployment + * @param manageRootDir if false, the top directory where the files will be deployed (i.e. the destinationDir) + * will be left alone. That is, if files already exist there, they will not be removed or + * otherwise merged with this deployment's root files. If true, this top root directory + * will be managed just as any subdirectory within the deployment will be managed. + * The purpose of this is to be able to write files to an existing directory that has other + * unrelated files in it that need to remain intact. e.g. the deploy/ directory of JBossAS. + * Note: regardless of this setting, all subdirectories under the root dir will be managed. */ public DeploymentData(DeploymentProperties deploymentProps, Set<File> zipFiles, Map<File, File> rawFiles, File destinationDir, Map<File, Pattern> zipEntriesToRealizeRegex, Set<File> rawFilesToRealize, - TemplateEngine templateEngine, Pattern ignoreRegex) { + TemplateEngine templateEngine, Pattern ignoreRegex, boolean manageRootDir) {
if (deploymentProps == null) { throw new IllegalArgumentException("deploymentProps == null"); @@ -96,6 +104,7 @@ public class DeploymentData { this.rawFiles = rawFiles; this.destinationDir = destinationDir; this.ignoreRegex = ignoreRegex; + this.manageRootDir = manageRootDir;
// if there is nothing to realize or we have no template engine to obtain replacement values, then we null things out if (templateEngine == null || (zipEntriesToRealizeRegex == null && rawFilesToRealize == null)) { @@ -143,4 +152,7 @@ public class DeploymentData { return ignoreRegex; }
+ public boolean isManageRootDir() { + return manageRootDir; + } } diff --git a/modules/core/util/src/main/java/org/rhq/core/util/updater/FileHashcodeMap.java b/modules/core/util/src/main/java/org/rhq/core/util/updater/FileHashcodeMap.java index 5945abe..2a68f5d 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/updater/FileHashcodeMap.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/updater/FileHashcodeMap.java @@ -204,18 +204,22 @@ public class FileHashcodeMap extends TreeMap<String, String> { * * The root directory is also scanned for new files that are not in this original * map - if new files are found (and they do not match the ignoreRegex), they are added to the - * returned map. + * returned map. Note that if <code>reportNewRootFilesAsNew</code> is false, and if new files + * are found in the top root directory and they are not related to the deployment fileset, + * they will not be added to the returned map. * * @param rootDir directory where the relative paths are expected to be * @param ignoreRegex if relative paths of files under rootDir match this, they will be ignored. * This will eliminate files/directories from being considered "new" because * they aren't in original. + * @param reportNewRootFilesAsNew do not report as new any unrelated files found in the root dir * @return a map with current files/hashcodes, including files that were not found in original. * the returned object also has additional info such as those files that were added, * deleted, changed from this original. It also indicates what was ignored during the rescan. * @throws Exception */ - public ChangesFileHashcodeMap rescan(File rootDir, Pattern ignoreRegex) throws Exception { + public ChangesFileHashcodeMap rescan(File rootDir, Pattern ignoreRegex, boolean reportNewRootFilesAsNew) + throws Exception { ChangesFileHashcodeMap current = new ChangesFileHashcodeMap(this);
// go through our original files and recalculate their hashcodes @@ -253,9 +257,12 @@ public class FileHashcodeMap extends TreeMap<String, String> { // now recursively traverse the root directory and look for new files that aren't in our original map // files that have been added need to be put into our returned map and also marked as added FileHashcodeMap newFiles = new FileHashcodeMap(); - lookForNewFilesRecursive(newFiles, rootDir.getAbsolutePath(), 0, rootDir, ignoreRegex, current.getIgnored()); + Set<String> skippedFiles = new HashSet<String>(); + lookForNewFilesRecursive(newFiles, skippedFiles, rootDir.getAbsolutePath(), 0, rootDir, ignoreRegex, current + .getIgnored(), reportNewRootFilesAsNew); current.putAll(newFiles); current.getAdditions().putAll(newFiles); + current.getSkipped().addAll(skippedFiles);
return current; } @@ -264,16 +271,24 @@ public class FileHashcodeMap extends TreeMap<String, String> { * This looks for new files under the given fileOrDir and adds them to <code>newFiles</code>. * * @param newFiles the map where the new, current file/hashcode data will be stored - * @param rootPath the top root directory that is being scanned - * @param level the level deep in the file hierarchy currently being processed (0==at top root dir) - * @param fileOrDir existing directory/file to rescan + * @param skippedFiles a set where names of unrelated files/directories are stored. The names + * found here after this method returns are those files/dirs that were found + * in the top level root dir, but were skipped over and not processed. This will not + * contain paths with subdirectories - they will only be a filename with no paths + * because they are located directly under the root dir. + * @param rootPath the top root directory that is being scanned + * @param level the level deep in the file hierarchy currently being processed (0==at top root dir) + * @param fileOrDir existing directory/file to rescan * @param ignoreRegex a regular expression that indicates which files/directories should be ignored. * If a relative file/directory path matches this regex, it will be skipped. - * @param ignored a set that will contain those files/directories that were ignored while scanning the root dir + * @param ignored a set that will contain those files/directories that were ignored while scanning the root dir + * @param reportNewRootFilesAsNew if false, ignore unrelated files at the root dir location (level=0) + * * @throws Exception */ - private void lookForNewFilesRecursive(FileHashcodeMap newFiles, String rootPath, int level, File fileOrDir, - Pattern ignoreRegex, Set<String> ignored) throws Exception { + private void lookForNewFilesRecursive(FileHashcodeMap newFiles, Set<String> skippedFiles, String rootPath, + int level, File fileOrDir, Pattern ignoreRegex, Set<String> ignored, boolean reportNewRootFilesAsNew) + throws Exception {
if (fileOrDir == null || !fileOrDir.exists()) { throw new Exception("Non-existent file/directory provided: " + fileOrDir); @@ -301,10 +316,41 @@ public class FileHashcodeMap extends TreeMap<String, String> { return; }
+ // If we are currently at the top level and we are not to report unrelated files as new + // then we need to find out which files ARE related first. Related files are those files + // already in our Map at the root level (i.e. they are just a filename, no parent paths) + // plus those in our Map with a top parent dir name that match a child directory of + // fileOrDir (which is the root dir if we are at level=0). + // Note that we use File API to manipulate filenames/parents to ensure we do this right + // on Windows (taking care of relative paths with drive letters, e.g. C:subdir/file.txt). + HashSet<String> relatedTopLevelFiles = null; + if (level == 0 && !reportNewRootFilesAsNew) { + relatedTopLevelFiles = new HashSet<String>(); + for (String relatedFilePath : keySet()) { // loop through our Map key entries, these are the "related" files + File relatedFile = new File(relatedFilePath); + if (!relatedFile.isAbsolute()) { + String topLevelName = relatedFile.getName(); // prime the pump; if we have no parent, this is our file already at the top root dir + File parent = relatedFile.getParentFile(); + // walk up the file hierarchy until we hit the top parent - this is the related dir found in our top root + while (parent != null) { + topLevelName = parent.getName(); + parent = parent.getParentFile(); + } + relatedTopLevelFiles.add(topLevelName); // this is a file or dir at the top root dir + } + } + } + File[] children = fileOrDir.listFiles(); if (children != null) { for (File child : children) { - lookForNewFilesRecursive(newFiles, rootPath, level + 1, child, ignoreRegex, ignored); + // skip this child if we are at the top root dir and it is not related to our fileset + if (relatedTopLevelFiles == null || relatedTopLevelFiles.contains(child.getName())) { + lookForNewFilesRecursive(newFiles, skippedFiles, rootPath, level + 1, child, ignoreRegex, + ignored, reportNewRootFilesAsNew); + } else { + skippedFiles.add(child.getName()); + } } } } else { diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java index 50709cc..5f0fca6 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/DeployerTest.java @@ -256,7 +256,7 @@ public class DeployerTest { Map<File, Pattern> filesToRealizeRegex1 = new HashMap<File, Pattern>(1); filesToRealizeRegex1.put(testZipFile1, realizeRegex); DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex1, - null, templateEngine, ignoreRegex); + null, templateEngine, ignoreRegex, true); Deployer deployer = new Deployer(dd); diff = new DeployDifferences();
@@ -292,7 +292,7 @@ public class DeployerTest { Map<File, Pattern> filesToRealizeRegex2 = new HashMap<File, Pattern>(1); filesToRealizeRegex2.put(testZipFile2, realizeRegex); dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex2, null, - templateEngine, ignoreRegex); + templateEngine, ignoreRegex, true); deployer = new Deployer(dd); diff = new DeployDifferences(); deployer.deploy(diff); @@ -420,7 +420,7 @@ public class DeployerTest { rawFiles.put(testRawFileA, updaterAabsolute); // source raw file to absolute path rawFiles.put(testRawFileBChange1, updaterBabsolute); // source raw file to absolute path dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex2, null, - templateEngine, ignoreRegex); + templateEngine, ignoreRegex, true); deployer = new Deployer(dd); diff = new DeployDifferences(); deployer.deploy(diff); @@ -460,7 +460,7 @@ public class DeployerTest { rawFiles.put(testRawFileAChange, updaterAabsolute); // source raw file to absolute path rawFiles.put(testRawFileBChange2, updaterBabsolute); // source raw file to absolute path dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, filesToRealizeRegex2, null, - templateEngine, ignoreRegex); + templateEngine, ignoreRegex, true); deployer = new Deployer(dd); diff = new DeployDifferences(); deployer.deploy(diff); @@ -526,7 +526,7 @@ public class DeployerTest { Set<File> realizeRawFiles1 = new HashSet<File>(1); realizeRawFiles1.add(testRawFileB); DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, null, - realizeRawFiles1, templateEngine, ignoreRegex); + realizeRawFiles1, templateEngine, ignoreRegex, true); Deployer deployer = new Deployer(dd); DeployDifferences diff = new DeployDifferences(); FileHashcodeMap map = deployer.deploy(diff); @@ -580,7 +580,7 @@ public class DeployerTest { realizeRawFiles1.add(testZipFile2); realizeRawFiles1.add(testRawFileB); DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, null, - realizeRawFiles1, templateEngine, ignoreRegex); + realizeRawFiles1, templateEngine, ignoreRegex, true); Deployer deployer = new Deployer(dd); DeployDifferences listener = new DeployDifferences(); deployer.deploy(listener); @@ -678,7 +678,7 @@ public class DeployerTest { realizeRegex1.put(testZipFile1, filesToRealizeRegex);
DeploymentData dd = new DeploymentData(deploymentProps, zipFiles, rawFiles, destDir, realizeRegex1, null, - templateEngine, ignoreRegex); + templateEngine, ignoreRegex, true); Deployer deployer = new Deployer(dd); DeployDifferences listener = new DeployDifferences(); deployer.deploy(listener); diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/FileHashcodeMapTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/FileHashcodeMapTest.java index 2fce1e4..034f1e8 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/FileHashcodeMapTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/FileHashcodeMapTest.java @@ -77,17 +77,18 @@ public class FileHashcodeMapTest { assert ignored.contains("ignoreme1.txt") : ignored;
// first test - see that no changes can be detected - ChangesFileHashcodeMap currentMap = originalMap.rescan(tmpDir, ignoreRegex); + ChangesFileHashcodeMap currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assertSameMap(originalMap, currentMap); assert currentMap.getAdditions().isEmpty(); assert currentMap.getDeletions().isEmpty(); assert currentMap.getChanges().isEmpty(); assert currentMap.getIgnored().size() == 1 : currentMap; assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap; + assert currentMap.getSkipped().size() == 0;
// second test - change an original file StreamUtil.copy(new ByteArrayInputStream("test1-change".getBytes()), new FileOutputStream(testFile1)); - currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 2 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -99,10 +100,11 @@ public class FileHashcodeMapTest { assert currentMap.getChanges().get("test1.txt").equals(currentMap.get("test1.txt")); assert currentMap.getIgnored().size() == 1 : currentMap; assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap; + assert currentMap.getSkipped().size() == 0;
// third test - delete an original file assert testFile1.delete() : "could not delete file in order to test delete-detection"; - currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 2 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -114,12 +116,13 @@ public class FileHashcodeMapTest { assert currentMap.getChanges().isEmpty(); assert currentMap.getIgnored().size() == 1 : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap.getIgnored(); + assert currentMap.getSkipped().size() == 0;
// fourth test - add a new file StreamUtil.copy(new ByteArrayInputStream("test1".getBytes()), new FileOutputStream(testFile1)); File testFile3 = new File(tmpDir, "test3.txt"); StreamUtil.copy(new ByteArrayInputStream("test3".getBytes()), new FileOutputStream(testFile3)); - currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 3 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -133,6 +136,7 @@ public class FileHashcodeMapTest { assert currentMap.getChanges().isEmpty(); assert currentMap.getIgnored().size() == 1 : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap.getIgnored(); + assert currentMap.getSkipped().size() == 0;
// fifth test - concurrently change a file, delete a file add new file and add new file in new directory // changed file: testFile1 @@ -149,7 +153,7 @@ public class FileHashcodeMapTest { assert ignoreFile2.getParentFile().mkdirs() : "could not create new subdirectory for test"; StreamUtil.copy(new ByteArrayInputStream("ignore2".getBytes()), new FileOutputStream(ignoreFile2));
- currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 4 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -171,6 +175,7 @@ public class FileHashcodeMapTest { assert currentMap.getIgnored().size() == 2 : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme") : currentMap.getIgnored(); + assert currentMap.getSkipped().size() == 0;
// sixth test - starting from 5th test above, add an absolute path file absPathFile = File.createTempFile("fileHashcodeMapTestFile", ".test"); @@ -178,7 +183,7 @@ public class FileHashcodeMapTest { StreamUtil.copy(new ByteArrayInputStream("abs".getBytes()), new FileOutputStream(absPathFile)); originalMap.put(absPathFile.getAbsolutePath(), MessageDigestGenerator.getDigestString(absPathFile));
- currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 5 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -203,10 +208,11 @@ public class FileHashcodeMapTest { assert currentMap.getIgnored().size() == 2 : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme") : currentMap.getIgnored(); + assert currentMap.getSkipped().size() == 0;
// seventh test - detect that the absolute path file has changed StreamUtil.copy(new ByteArrayInputStream("abs-changed".getBytes()), new FileOutputStream(absPathFile)); - currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 5 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -233,10 +239,11 @@ public class FileHashcodeMapTest { assert currentMap.getIgnored().size() == 2 : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme") : currentMap.getIgnored(); + assert currentMap.getSkipped().size() == 0;
// eighth test - detect absolute path file has been deleted assert absPathFile.delete() : "could not delete the absolute path file for testing"; - currentMap = originalMap.rescan(tmpDir, ignoreRegex); + currentMap = originalMap.rescan(tmpDir, ignoreRegex, true); assert currentMap.size() == 5 : currentMap; assert currentMap.containsKey("test1.txt") : currentMap; assert currentMap.containsKey("test2.txt") : currentMap; @@ -262,6 +269,92 @@ public class FileHashcodeMapTest { assert currentMap.getIgnored().size() == 2 : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme1.txt") : currentMap.getIgnored(); assert currentMap.getIgnored().contains("ignoreme") : currentMap.getIgnored(); + assert currentMap.getSkipped().size() == 0; + + } finally { + FileUtil.purge(tmpDir, true); + if (absPathFile != null) { + absPathFile.delete(); + } + } + } + + public void testRescanSkipNewRootDirFiles() throws Exception { + File absPathFile = null; + File tmpDir = FileUtil.createTempDirectory("fileHashcodeMapTest", ".dir", null); + try { + File testFile1 = new File(tmpDir, "test1.txt"); + File testFile2 = new File(tmpDir, "testsubdir/test2.txt"); + File ignoreFile1 = new File(tmpDir, "ignoreme1.txt"); + Pattern ignoreRegex = Pattern.compile("ignoreme.*"); + + assert testFile2.getParentFile().mkdirs() : "could not create testsubdir"; + + StreamUtil.copy(new ByteArrayInputStream("test1".getBytes()), new FileOutputStream(testFile1)); + StreamUtil.copy(new ByteArrayInputStream("test2".getBytes()), new FileOutputStream(testFile2)); + StreamUtil.copy(new ByteArrayInputStream("ignore1".getBytes()), new FileOutputStream(ignoreFile1)); + + Set<String> ignored = new HashSet<String>(); + FileHashcodeMap originalMap = FileHashcodeMap.generateFileHashcodeMap(tmpDir, ignoreRegex, ignored); + assert originalMap.size() == 2 : originalMap; + assert originalMap.containsKey("test1.txt") : originalMap; + assert originalMap.containsKey("testsubdir/test2.txt") : originalMap; + assert ignored.size() == 1 : ignored; + assert ignored.contains("ignoreme1.txt") : ignored; + + // concurrently change a file, delete a file add new file and add new file in new directory + // changed file: testFile1 + // deleted file: testFile2 + // added file: testFile3 (should not be reported as new, its unrelated) + // added file in original directory: testsubdir/testFile4 (should be reported, its in related dir "testsubdir") + // I'll add an "ignoreme" directory just to see that it still gets ignored (technically it will get skipped) + StreamUtil.copy(new ByteArrayInputStream("test1-change".getBytes()), new FileOutputStream(testFile1)); + assert testFile2.delete() : "could not delete file in order to test delete-detection"; + File testFile3 = new File(tmpDir, "test3.txt"); + StreamUtil.copy(new ByteArrayInputStream("test3".getBytes()), new FileOutputStream(testFile3)); + File testFile4 = new File(tmpDir, "testsubdir/test4.txt"); + StreamUtil.copy(new ByteArrayInputStream("test4".getBytes()), new FileOutputStream(testFile4)); + File ignoreFile2 = new File(tmpDir, "ignoreme/ignore2.txt"); + assert ignoreFile2.getParentFile().mkdirs() : "could not create new subdirectory for test"; + StreamUtil.copy(new ByteArrayInputStream("ignore2".getBytes()), new FileOutputStream(ignoreFile2)); + + // now add some more unrelated files/dirs - these should not be reported as new + File unrelatedFile1 = new File(tmpDir, "unrelated1.txt"); + File unrelatedFile2 = new File(tmpDir, "unrelatedsubdir/unrelated2.txt"); + assert unrelatedFile2.getParentFile().mkdirs() : "could not create unrelated subdir"; + StreamUtil.copy(new ByteArrayInputStream("unrelated1".getBytes()), new FileOutputStream(unrelatedFile1)); + StreamUtil.copy(new ByteArrayInputStream("unrelated2".getBytes()), new FileOutputStream(unrelatedFile2)); + assert unrelatedFile1.exists(); // sanity check + assert unrelatedFile2.exists(); // sanity check + + ChangesFileHashcodeMap currentMap = originalMap.rescan(tmpDir, ignoreRegex, false); + assert currentMap.size() == 3 : currentMap; + assert currentMap.containsKey("test1.txt") : currentMap; + assert currentMap.containsKey("testsubdir/test2.txt") : currentMap; + assert !currentMap.containsKey("test3.txt") : currentMap; + assert currentMap.containsKey("testsubdir" + fileSeparator + "test4.txt") : currentMap; + assert !currentMap.get("test1.txt").equals(originalMap.get("test1.txt")) : currentMap + ":" + originalMap; + assert currentMap.get("testsubdir/test2.txt").equals(FileHashcodeMap.DELETED_FILE_HASHCODE) : currentMap; + assert currentMap.get("testsubdir" + fileSeparator + "test4.txt").equals( + MessageDigestGenerator.getDigestString(testFile4)) : currentMap; + assert currentMap.getAdditions().size() == 1; + assert currentMap.getAdditions().get("testsubdir" + fileSeparator + "test4.txt").equals( + currentMap.get("testsubdir" + fileSeparator + "test4.txt")); + assert currentMap.getDeletions().size() == 1; + assert currentMap.getDeletions().get("testsubdir/test2.txt").equals(currentMap.get("testsubdir/test2.txt")); + assert currentMap.getChanges().size() == 1; + assert currentMap.getChanges().get("test1.txt").equals(currentMap.get("test1.txt")); + // because we are not managing the root dir, those ignore dirs are totally skipped since they are in the root dir + // therefore, they aren't ignored due to the regex, they are skipped due to reportNewRootFilesAsNew=false + assert currentMap.getIgnored().size() == 0 : currentMap.getIgnored(); + // now we can look at what was really skipped which were: + // test3.txt, unrelatedsubdir, ignoreme, unrelated1.txt, ignoreme1.txt + assert currentMap.getSkipped().size() == 5 : currentMap.getSkipped(); + assert currentMap.getSkipped().contains("test3.txt") : currentMap.getSkipped(); + assert currentMap.getSkipped().contains("ignoreme1.txt") : currentMap.getSkipped(); + assert currentMap.getSkipped().contains("ignoreme") : currentMap.getSkipped(); + assert currentMap.getSkipped().contains("unrelatedsubdir") : currentMap.getSkipped(); + assert currentMap.getSkipped().contains("unrelated1.txt") : currentMap.getSkipped();
} finally { FileUtil.purge(tmpDir, true); diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java new file mode 100644 index 0000000..88d2731 --- /dev/null +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/ManageRootDirTest.java @@ -0,0 +1,1101 @@ +/* + * 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.util.updater; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import org.rhq.core.util.MessageDigestGenerator; +import org.rhq.core.util.file.FileUtil; +import org.rhq.core.util.stream.StreamUtil; + +/** + * Individually tests these situations but with the "manageRootDir" flag off so we should not + * remove files not involved in the deployment that are found in the root destination dir: + * + * (X, Y, Z, ? represent hashcodes; none means file doesn't exist): + * + * ORIGINAL CURRENT NEW What To Do... + * a. X X X New file is installed over current* + * b. X X Y New file is installed over current + * c. X Y X Current file is left as-is + * d. X Y Y New file is installed over current* + * e. X Y Z New file is installed over current, current is backed up + * f. none ? ? New file is installed over current, current is backed up + * g. X none ? New file is installed + * h. ? ? none Current file deleted, backed up if different than original + * + * (*) means the new and current files will actually be the same content + * + * @author John Mazzitelli + */ +@Test +public class ManageRootDirTest { + + private final String originalContent = "original content"; + private final String originalFileName = "original_file_name.txt"; + private final String unrelatedContent = "unrelated file content"; + private final String unrelatedFileName = "unrelated_file_name.txt"; + private final String unrelatedDirName = "unrelated_dir"; + private File tmpDir; + private File deployDir; + private File originalZipFile; + private Set<File> originalZipFiles; + private DeploymentProperties originalDeployProps; + private FileHashcodeMap originalFileHashcodeMap; + private String originalHashcode; + private File currentFile; + private DeploymentProperties newDeployProps; + private DeployDifferences diff; + private DeploymentsMetadata metadata; + private File unrelatedFile; + private String unrelatedFileHashcode; + private File unrelatedDir; + private File unrelatedDirFile; + private String unrelatedDirFileHashcode; + + @BeforeMethod + public void beforeMethod() throws Exception { + this.tmpDir = FileUtil.createTempDirectory("simpleDeployer_TMP", ".test", null); + this.deployDir = FileUtil.createTempDirectory("simpleDeployer", ".test", null); + this.unrelatedFile = writeFile(unrelatedContent, deployDir, unrelatedFileName); + this.unrelatedFileHashcode = MessageDigestGenerator.getDigestString(unrelatedContent); + this.unrelatedDir = new File(this.deployDir, this.unrelatedDirName); + assert this.unrelatedDir.mkdirs() : "Failed to create a test dir"; + this.unrelatedDirFile = writeFile(unrelatedContent, this.unrelatedDir, unrelatedFileName); + this.unrelatedDirFileHashcode = MessageDigestGenerator.getDigestString(unrelatedContent); + this.originalHashcode = MessageDigestGenerator.getDigestString(originalContent); + this.originalZipFile = createZip(originalContent, tmpDir, "original.zip", originalFileName); + this.originalZipFiles = new HashSet<File>(1); + this.originalZipFiles.add(originalZipFile); + this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, + null, null, false); + Deployer deployer = new Deployer(dd); + this.originalFileHashcodeMap = deployer.deploy(null); + this.currentFile = new File(deployDir, originalFileName); + + this.newDeployProps = new DeploymentProperties(2, "simple", "2.0", "new test deployment"); + this.diff = new DeployDifferences(); + this.metadata = new DeploymentsMetadata(this.deployDir); + + // sanity check due to my paranoia + assert this.currentFile.exists(); + assert this.originalHashcode.equals(MessageDigestGenerator.getDigestString(currentFile)); + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + assert this.unrelatedFile.exists(); + assert this.unrelatedDirFile.exists(); + } + + @AfterMethod(alwaysRun = true) + public void afterMethod() throws Exception { + FileUtil.purge(this.tmpDir, true); + FileUtil.purge(this.deployDir, true); + } + + public void testX_X_X() throws Exception { + baseX_X_X(false); + } + + public void testX_X_Y() throws Exception { + baseX_X_Y(false); + } + + public void testX_Y_X() throws Exception { + baseX_Y_X(false); + } + + public void testX_Y_Y() throws Exception { + baseX_Y_Y(false); + } + + public void testX_Y_Z() throws Exception { + baseX_Y_Z(false); + } + + public void testX_Y_Z_Restore() throws Exception { + baseX_Y_Z_Restore(false); + } + + public void testX_Y_Z_Clean() throws Exception { + baseX_Y_Z_Clean(false); + } + + public void testNoOriginalNoCurrentWithNew() throws Exception { + baseNoOriginalNoCurrentWithNew(false); + } + + public void testNoOriginalWithCurrentWithNew() throws Exception { + baseNoOriginalWithCurrentWithNew(false); + } + + public void testNoCurrent() throws Exception { + baseNoCurrent(false); + } + + public void testNoNew() throws Exception { + baseNoNew(false); + } + + public void testNoNewWithCurrentDifferentThanOriginal() throws Exception { + baseNoNewWithCurrentDifferentThanOriginal(false); + } + + public void testX_X_X_DryRun() throws Exception { + baseX_X_X(true); + } + + public void testX_X_Y_DryRun() throws Exception { + baseX_X_Y(true); + } + + public void testX_Y_X_DryRun() throws Exception { + baseX_Y_X(true); + } + + public void testX_Y_Y_DryRun() throws Exception { + baseX_Y_Y(true); + } + + public void testX_Y_Z_DryRun() throws Exception { + baseX_Y_Z(true); + } + + public void testX_Y_Z_Restore_DryRun() throws Exception { + baseX_Y_Z_Restore(true); + } + + public void testX_Y_Z_Clean_DryRun() throws Exception { + baseX_Y_Z_Clean(true); + } + + public void testNoOriginalNoCurrentWithNew_DryRun() throws Exception { + baseNoOriginalNoCurrentWithNew(true); + } + + public void testNoOriginalWithCurrentWithNew_DryRun() throws Exception { + baseNoOriginalWithCurrentWithNew(true); + } + + public void testNoCurrent_DryRun() throws Exception { + baseNoCurrent(true); + } + + public void testNoNew_DryRun() throws Exception { + baseNoNew(true); + } + + public void testNoNewWithCurrentDifferentThanOriginal_DryRun() throws Exception { + baseNoNewWithCurrentDifferentThanOriginal(true); + } + + public void testWithSubdirectories() throws Exception { + // this test is different than all the rest, start with clean tmp/dest dirs with no beforeMethod buildup + FileUtil.purge(this.tmpDir, false); + FileUtil.purge(this.deployDir, false); + + // fill the deployDir with some unrelated content + File unrelated1 = writeFile("unrelated1", this.deployDir, "unrelated.txt"); + File unrelated2 = writeFile("unrelated2", this.deployDir, "unrelateddir/unrelated.txt"); + assert unrelated1.exists(); + assert unrelated2.exists(); + + // deploy initial content + String origFileName1 = "original-file1.txt"; + String origFileName2 = "subdir/original-file2.txt"; + this.originalZipFile = createZip(new String[] { "content1", "content2" }, this.tmpDir, "original.zip", + new String[] { origFileName1, origFileName2 }); + this.originalZipFiles = new HashSet<File>(1); + this.originalZipFiles.add(originalZipFile); + this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, + null, null, false); + Deployer deployer = new Deployer(dd); + this.originalFileHashcodeMap = deployer.deploy(null); + assert new File(this.deployDir, origFileName1).exists(); + assert new File(this.deployDir, origFileName2).exists(); + assert unrelated1.exists() : "the deployment removed unrelated file1"; + assert unrelated2.getParentFile().isDirectory() : "the deployment removed an unrelated dir"; + assert unrelated2.exists() : "the deployment removed unrelated file2"; + + // deploy new content + this.newDeployProps = new DeploymentProperties(2, "simple", "2.0", "new test deployment"); + this.diff = new DeployDifferences(); + this.metadata = new DeploymentsMetadata(this.deployDir); + String newFileName1 = "new-file1.txt"; + String newFileName2 = "newsubdir/new-file2.txt"; + File newZipFile = createZip(new String[] { "newcontent1", "newcontent2" }, this.tmpDir, "new.zip", + new String[] { newFileName1, newFileName2 }); + HashSet<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, false); + deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap = deployer.deploy(this.diff); + assert new File(this.deployDir, newFileName1).exists(); + assert new File(this.deployDir, newFileName2).exists(); + assert !new File(this.deployDir, origFileName1).exists(); + assert !new File(this.deployDir, origFileName2).exists(); + assert unrelated1.exists() : "the deployment removed unrelated file1"; + assert unrelated2.getParentFile().isDirectory() : "the deployment removed an unrelated dir"; + assert unrelated2.exists() : "the deployment removed unrelated file2"; + assert this.diff.getBackedUpFiles().size() == 0 : this.diff; + } + + private void baseX_X_X(boolean dryRun) throws Exception { + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, + null, false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // nothing changed! + + assert newFileHashcodeMap.equals(this.originalFileHashcodeMap); + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(this.originalContent); + assert contentHash[1].equals(this.originalHashcode); + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getRestoredFiles().isEmpty() : this.diff; + assert !this.diff.wasCleaned() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseX_X_Y(boolean dryRun) throws Exception { + String newContent = "testX_X_Y"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + File newZipFile = createZip(newContent, tmpDir, "new-content.zip", originalFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // The new file changed the original file. The current file was never touched, so this is a simple upgrade + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(originalFileName).equals(newHashcode); + String[] contentHash = getOriginalFilenameContentHashcode(); + if (dryRun) { + assert contentHash[0].equals(originalContent); + assert contentHash[1].equals(originalHashcode); + } else { + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().size() == 1 : this.diff; + assert this.diff.getChangedFiles().contains(originalFileName) : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseX_Y_X(boolean dryRun) throws Exception { + String newContent = "testX_Y_X"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + writeFile(newContent, this.currentFile); + + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, + null, false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // very important to understand this - even though the current file is changed, the hashcode + // stored in the map and the metadata directory is the ORIGINAL hashcode. This is to make it + // known that the new deployment itself is the same as the original deployment. It is just + // that we allow the user's manual changes to continue to live on in the filesystem. However, + // if a newer deployment comes along in the future and changes the new file, this current file + // must be updated/backed up as appropriate and the only way to know when that happens is if + // the metadata retains the original/new hashcode and not the current one. + + assert newFileHashcodeMap.equals(this.originalFileHashcodeMap); + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + + assertUnrelatedFiles(); + // note nothing changed - our current file remains as is + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseX_Y_Y(boolean dryRun) throws Exception { + String newContent = "testX_Y_Y"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + writeFile(newContent, this.currentFile); + File newZipFile = createZip(newContent, tmpDir, "new-content.zip", originalFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // The new file changed the original, but our current file has already been manually updated + // to match the new file. Therefore, the current file doesn't have to change its content. + // Technically, the file could be overwritten, but the content will still be the same. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(originalFileName).equals(newHashcode); + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseX_Y_Z(boolean dryRun) throws Exception { + String newContentY = "testX_Y_Z_YYY"; + writeFile(newContentY, this.currentFile); + String newHashcodeY = MessageDigestGenerator.getDigestString(newContentY); + + String newContentZ = "testX_Y_Z_ZZZ"; + String newHashcodeZ = MessageDigestGenerator.getDigestString(newContentZ); + File newZipFile = createZip(newContentZ, tmpDir, "new-content.zip", originalFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // The new file changed the original, and our current file has been manually updated + // but that current file's change does not match the new file. Therefore, the current file + // is out of date. The safest thing to do is backup the current and copy the new file + // to become the current file. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(originalFileName).equals(newHashcodeZ); + String[] contentHash = getOriginalFilenameContentHashcode(); + if (dryRun) { + assert contentHash[0].equals(newContentY); + assert contentHash[1].equals(newHashcodeY); + } else { + assert contentHash[0].equals(newContentZ); + assert contentHash[1].equals(newHashcodeZ); + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().size() == 1 : this.diff; + assert this.diff.getChangedFiles().contains(originalFileName) : this.diff; + assert this.diff.getBackedUpFiles().size() == 1 : this.diff; + assert this.diff.getBackedUpFiles().containsKey(originalFileName) : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + + // verify the backup copy + File backupFile = new File(this.diff.getBackedUpFiles().get(originalFileName)); + if (dryRun) { + assert !backupFile.exists() : "dry run should not create backup"; + } else { + assert readFile(backupFile).equals(newContentY) : "did not backup the correct file?"; + } + } + + private void baseNoOriginalNoCurrentWithNew(boolean dryRun) throws Exception { + String newContent = "new content"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + String newFileName = "new_filename.new"; + File newZipFile = createZip(new String[] { originalContent, newContent }, tmpDir, "new.zip", new String[] { + originalFileName, newFileName }); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // the new deployment introduces a new file. This is simple - its just added to the filesystem + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 2; + assert newFileHashcodeMap.get(originalFileName).equals(originalHashcode); + assert newFileHashcodeMap.get(newFileName).equals(newHashcode); + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(originalContent); + assert contentHash[1].equals(originalHashcode); + try { + contentHash = getFilenameContentHashcode(newFileName); + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + } catch (FileNotFoundException e) { + // this is expected if we are in a dry run + if (!dryRun) { + throw e; + } + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().size() == 1 : this.diff; + assert this.diff.getAddedFiles().contains(newFileName) : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseNoOriginalWithCurrentWithNew(boolean dryRun) throws Exception { + String newContent = "new content"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + String newFileName = "new_filename.new"; + File newZipFile = createZip(new String[] { originalContent, newContent }, tmpDir, "new.zip", new String[] { + originalFileName, newFileName }); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + File inTheWayFile = new File(this.deployDir, newFileName); + String inTheWayContent = "this is in the way"; + String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); + writeFile(inTheWayContent, inTheWayFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // The new deployment introduces a new file. However, there is already a current file at the new file location. + // That current file is unknown and in the way. + // This normally is considered a "change" not an "addition" since the file system already had the file, it just got changed. + // Also, normally, it would be backed up. + // However, because we are not managing the root dir, that file "in the way" is simply skipped and not backed up. + // But because our new zip has the same file in it, it is considered "new" thus it will be "added" to the + // set of managed files. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 2; + assert newFileHashcodeMap.get(originalFileName).equals(originalHashcode); + assert newFileHashcodeMap.get(newFileName).equals(newHashcode); + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(originalContent); + assert contentHash[1].equals(originalHashcode); + contentHash = getFilenameContentHashcode(newFileName); + if (dryRun) { + assert contentHash[0].equals(inTheWayContent); + assert contentHash[1].equals(inTheWayHashcode); + } else { + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().size() == 1 : this.diff; + assert this.diff.getAddedFiles().contains(newFileName) : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().size() == 0 : this.diff; + assert this.diff.getBackedUpFiles().size() == 0 : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseNoCurrent(boolean dryRun) throws Exception { + assert this.currentFile.delete() : "Failed to delete the current file, cannot prepare the test"; + + DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, + null, false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // its the same deployment as before, except someone deleted our current file. + // This adds the new file back (which is the same as the original). + + assert newFileHashcodeMap.equals(this.originalFileHashcodeMap); + try { + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(this.originalContent); + assert contentHash[1].equals(this.originalHashcode); + } catch (FileNotFoundException e) { + // this is expected if we are in a dry run + if (!dryRun) { + throw e; + } + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().size() == 1 : this.diff; + assert this.diff.getAddedFiles().contains(this.originalFileName) : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseNoNew(boolean dryRun) throws Exception { + String newContent = "new content"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + String newFileName = "new_filename.new"; + File newZipFile = createZip(newContent, tmpDir, "new.zip", newFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // The new deployment removes a file that was in the original (it also introduces a new file). + // There is already a current file at the original file location that is the same as the original, as you would expect. + // That current file is to be deleted (since its not in the new deployment) and is not backed up since it is + // the same as the original. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(newFileName).equals(newHashcode); + if (dryRun) { + assert this.currentFile.exists() : "this should have been left as-is"; + } else { + assert !this.currentFile.exists() : "this should have been deleted"; + } + try { + String[] contentHash = getFilenameContentHashcode(newFileName); + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + } catch (FileNotFoundException e) { + // this is expected if we are in a dry run + if (!dryRun) { + throw e; + } + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().size() == 1 : this.diff; + assert this.diff.getAddedFiles().contains(newFileName) : this.diff; + assert this.diff.getDeletedFiles().size() == 1 : this.diff; + assert this.diff.getDeletedFiles().contains(originalFileName) : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + } + + private void baseNoNewWithCurrentDifferentThanOriginal(boolean dryRun) throws Exception { + String currentContent = "modified content"; + writeFile(currentContent, this.currentFile); + + String newContent = "new content"; + String newHashcode = MessageDigestGenerator.getDigestString(newContent); + String newFileName = "new_filename.new"; + File newZipFile = createZip(newContent, tmpDir, "new.zip", newFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + if (dryRun) { + newFileHashcodeMap = deployer.dryRun(this.diff); + } else { + newFileHashcodeMap = deployer.deploy(this.diff); + } + + // The new deployment removes a file that was in the original (it also introduces a new file). + // However, there is already a current file at the original file location as you would expect but + // its different than the original. + // That current file is to be deleted (since its not in the new deployment) and it must be backed up + // since it looks modified from the original. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(newFileName).equals(newHashcode); + if (dryRun) { + assert this.currentFile.exists() : "this should have been left as-is"; + } else { + assert !this.currentFile.exists() : "this should have been deleted"; + } + try { + String[] contentHash = getFilenameContentHashcode(newFileName); + assert contentHash[0].equals(newContent); + assert contentHash[1].equals(newHashcode); + } catch (FileNotFoundException e) { + // this is expected if we are in a dry run + if (!dryRun) { + throw e; + } + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().size() == 1 : this.diff; + assert this.diff.getAddedFiles().contains(newFileName) : this.diff; + assert this.diff.getDeletedFiles().size() == 1 : this.diff; + assert this.diff.getDeletedFiles().contains(originalFileName) : this.diff; + assert this.diff.getChangedFiles().isEmpty() : this.diff; + assert this.diff.getBackedUpFiles().size() == 1 : this.diff; + assert this.diff.getBackedUpFiles().containsKey(originalFileName) : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + + // verify the backup copy + File backupFile = new File(this.diff.getBackedUpFiles().get(originalFileName)); + if (dryRun) { + assert !backupFile.exists() : "dry run should not create backup"; + } else { + assert readFile(backupFile).equals(currentContent) : "did not backup the correct file?"; + } + } + + private void baseX_Y_Z_Restore(boolean dryRun) throws Exception { + String newContentY = "testX_Y_Z_YYY"; + writeFile(newContentY, this.currentFile); + String newHashcodeY = MessageDigestGenerator.getDigestString(newContentY); + + String newContentZ = "testX_Y_Z_ZZZ"; + String newHashcodeZ = MessageDigestGenerator.getDigestString(newContentZ); + File newZipFile = createZip(newContentZ, tmpDir, "new-content.zip", originalFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation + + // The new file changed the original, and our current file has been manually updated + // but that current file's change does not match the new file. Therefore, the current file + // is out of date. The safest thing to do is backup the current and copy the new file + // to become the current file. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(originalFileName).equals(newHashcodeZ); + String[] contentHash = getOriginalFilenameContentHashcode(); + assert contentHash[0].equals(newContentZ); + assert contentHash[1].equals(newHashcodeZ); + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().size() == 1 : this.diff; + assert this.diff.getChangedFiles().contains(originalFileName) : this.diff; + assert this.diff.getBackedUpFiles().size() == 1 : this.diff; + assert this.diff.getBackedUpFiles().containsKey(originalFileName) : this.diff; + assert this.diff.getRestoredFiles().isEmpty() : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + + // verify the backup copy + File backupFile = new File(this.diff.getBackedUpFiles().get(originalFileName)); + assert readFile(backupFile).equals(newContentY) : "did not backup the correct file?"; + + // all we did so far was upgrade to v2 and created a backup file, now we need to redeploy v1 and see the backup restored + DeploymentProperties v1Duplicate = new DeploymentProperties(); + v1Duplicate.putAll(this.originalDeployProps); + v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID + dd = new DeploymentData(v1Duplicate, originalZipFiles, null, deployDir, null, null, null, null, false); + deployer = new Deployer(dd); + this.diff = new DeployDifferences(); + FileHashcodeMap restoreFileHashcodeMap; + restoreFileHashcodeMap = deployer.redeployAndRestoreBackupFiles(this.diff, false, dryRun); + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().size() == 1 : this.diff; + assert this.diff.getChangedFiles().contains(originalFileName) : this.diff; + assert this.diff.getBackedUpFiles().isEmpty() : this.diff; + assert this.diff.getRestoredFiles().size() == 1 : this.diff; + assert this.diff.getRestoredFiles().containsKey(originalFileName) : this.diff; + assert this.diff.getIgnoredFiles().isEmpty() : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + assert restoreFileHashcodeMap.get(originalFileName).equals(newHashcodeY) : "hashcode doesn't reflect restored backup"; + + if (dryRun) { + // still our v2 + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } else { + // we reverted back to v1 with the manual changes + assert this.metadata.getCurrentDeploymentProperties().equals(v1Duplicate); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(restoreFileHashcodeMap); + assert MessageDigestGenerator.getDigestString(this.currentFile).equals(newHashcodeY) : "file wasn't restored"; + } + } + + private void baseX_Y_Z_Clean(boolean dryRun) throws Exception { + String newContentY = "testX_Y_Z_YYY"; + writeFile(newContentY, this.currentFile); + String newHashcodeY = MessageDigestGenerator.getDigestString(newContentY); + + String newContentZ = "testX_Y_Z_ZZZ"; + String newHashcodeZ = MessageDigestGenerator.getDigestString(newContentZ); + File newZipFile = createZip(newContentZ, tmpDir, "new-content.zip", originalFileName); + Set<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + + File ignoredSubdir = new File(this.deployDir, "ignoreSubdir"); + File ignoredFile = new File(ignoredSubdir, "ignore-me.txt"); + ignoredSubdir.mkdirs(); + writeFile("ignored content", ignoredFile); + Pattern iRegex = Pattern.compile(".*ignoreSubdir.*"); // this matches the subdirectory name, thus everything under it is ignored + assert ignoredFile.exists() : "for some reason we couldn't create our test file; cannot know if clean worked"; + + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, iRegex, + false); + Deployer deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap; + newFileHashcodeMap = deployer.deploy(this.diff, true, dryRun); // note: clean is true + + // The new file changed the original, and our current file has been manually updated + // but that current file's change does not match the new file. Therefore, the current file + // is out of date. The safest thing to do is backup the current and copy the new file + // to become the current file. + + assert !newFileHashcodeMap.equals(this.originalFileHashcodeMap); + assert newFileHashcodeMap.size() == 1; + assert newFileHashcodeMap.get(originalFileName).equals(newHashcodeZ); + String[] contentHash = getOriginalFilenameContentHashcode(); + if (dryRun) { + assert contentHash[0].equals(newContentY); + assert contentHash[1].equals(newHashcodeY); + } else { + assert contentHash[0].equals(newContentZ); + assert contentHash[1].equals(newHashcodeZ); + } + + assertUnrelatedFiles(); + assert this.diff.getAddedFiles().isEmpty() : this.diff; + assert this.diff.getDeletedFiles().isEmpty() : this.diff; + assert this.diff.getChangedFiles().size() == 1 : this.diff; + assert this.diff.getChangedFiles().contains(originalFileName) : this.diff; + assert this.diff.getBackedUpFiles().size() == 1 : this.diff; + assert this.diff.getBackedUpFiles().containsKey(originalFileName) : this.diff; + // because we are not managing the root dir, that ignore dir found at the root level is skipped + // so it never gets to the point where it matches the ignore regex therefore it doesn't count as ignored. + assert this.diff.getIgnoredFiles().size() == 0 : this.diff; + assert this.diff.getRealizedFiles().isEmpty() : this.diff; + assert this.diff.wasCleaned() : this.diff; + assert this.diff.getErrors().isEmpty() : this.diff; + + if (dryRun) { + assert this.metadata.getCurrentDeploymentProperties().equals(originalDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(originalFileHashcodeMap); + } else { + assert this.metadata.getCurrentDeploymentProperties().equals(newDeployProps); + assert this.metadata.getCurrentDeploymentFileHashcodes().equals(newFileHashcodeMap); + } + + // verify the backup copy + File backupFile = new File(this.diff.getBackedUpFiles().get(originalFileName)); + if (dryRun) { + assert !backupFile.exists() : "dry run should not create backup"; + } else { + assert readFile(backupFile).equals(newContentY) : "did not backup the correct file?"; + } + + // even though we cleaned, the ignored subdir and its file should have been skipped due to + // the fact were told the deployer not to manage the top root dir. Therefore, they should still exist. + if (dryRun) { + assert ignoredSubdir.isDirectory() : "dry run should not have really cleaned"; + assert ignoredFile.exists() : "dry run should not have really cleaned"; + } else { + assert ignoredSubdir.isDirectory() : "should not have really cleaned"; + assert ignoredFile.exists() : "should not have really cleaned"; + } + } + + private String[] getOriginalFilenameContentHashcode() throws Exception { + return getFilenameContentHashcode(this.originalFileName); + } + + private String[] getFilenameContentHashcode(String filename) throws Exception { + String content = readFile(new File(this.deployDir, filename)); + String hashcode = MessageDigestGenerator.getDigestString(content); + String[] contentHash = new String[] { content, hashcode }; + return contentHash; + } + + private String readFile(File file) throws Exception { + return new String(StreamUtil.slurp(new FileInputStream(file))); + } + + private File writeFile(String content, File fileToOverwrite) throws Exception { + FileOutputStream out = null; + + try { + fileToOverwrite.getParentFile().mkdirs(); + out = new FileOutputStream(fileToOverwrite); + out.write(content.getBytes()); + return fileToOverwrite; + } finally { + if (out != null) { + out.close(); + } + } + } + + private File writeFile(String content, File destDir, String fileName) throws Exception { + File destFile = new File(destDir, fileName); + return writeFile(content, destFile); + } + + private File createZip(String content, File destDir, String zipName, String entryName) throws Exception { + FileOutputStream stream = null; + ZipOutputStream out = null; + + try { + destDir.mkdirs(); + File zipFile = new File(destDir, zipName); + stream = new FileOutputStream(zipFile); + out = new ZipOutputStream(stream); + + ZipEntry zipAdd = new ZipEntry(entryName); + zipAdd.setTime(System.currentTimeMillis()); + out.putNextEntry(zipAdd); + out.write(content.getBytes()); + return zipFile; + } finally { + if (out != null) { + out.close(); + } + if (stream != null) { + stream.close(); + } + } + } + + private File createZip(String[] content, File destDir, String zipName, String[] entryName) throws Exception { + FileOutputStream stream = null; + ZipOutputStream out = null; + + try { + destDir.mkdirs(); + File zipFile = new File(destDir, zipName); + stream = new FileOutputStream(zipFile); + out = new ZipOutputStream(stream); + + assert content.length == entryName.length; + for (int i = 0; i < content.length; i++) { + ZipEntry zipAdd = new ZipEntry(entryName[i]); + zipAdd.setTime(System.currentTimeMillis()); + out.putNextEntry(zipAdd); + out.write(content[i].getBytes()); + } + return zipFile; + } finally { + if (out != null) { + out.close(); + } + if (stream != null) { + stream.close(); + } + } + } + + private void assertUnrelatedFiles() throws Exception { + // make sure we didn't delete or alter the file or dir that are unrelated to the deployed content + // the dir and its file... + assert this.unrelatedDir.isDirectory() : "unrelated directory was deleted: " + this.unrelatedDir; + assert this.unrelatedDirFile.exists() : "unrelated dir file was deleted: " + this.unrelatedDirFile; + String hash = MessageDigestGenerator.getDigestString(this.unrelatedDirFile); + assert this.unrelatedDirFileHashcode.equals(hash) : "unrelated dir file was changed: " + this.unrelatedDirFile; + + // the file located directly in the deployDir... + assert this.unrelatedFile.exists() : "unrelated file was deleted: " + this.unrelatedFile; + hash = MessageDigestGenerator.getDigestString(this.unrelatedFile); + assert this.unrelatedFileHashcode.equals(hash) : "unrelated file was changed: " + this.unrelatedFile; + } +} diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java index e1eafcb..16275ef 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawFileTest.java @@ -93,7 +93,7 @@ public class SimpleDeployerRawFileTest { this.sourceRawFiles.put(sourceRawFile, new File(extDir, originalFileName)); // note we name it different than the source file this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); DeploymentData dd = new DeploymentData(originalDeployProps, null, sourceRawFiles, deployDir, null, null, null, - null); + null, true); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = sourceRawFiles.get(sourceRawFile); @@ -206,7 +206,8 @@ public class SimpleDeployerRawFileTest { }
private void baseX_X_X(boolean dryRun) throws Exception { - DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -248,7 +249,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -294,7 +296,8 @@ public class SimpleDeployerRawFileTest { String newHashcode = MessageDigestGenerator.getDigestString(newContent); writeFile(newContent, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -342,7 +345,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -390,7 +394,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -453,7 +458,8 @@ public class SimpleDeployerRawFileTest { File newDestRawFile = new File(extDir, newFileName); newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -515,7 +521,8 @@ public class SimpleDeployerRawFileTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -575,7 +582,8 @@ public class SimpleDeployerRawFileTest { private void baseNoCurrent(boolean dryRun) throws Exception { assert this.currentFile.delete() : "Failed to delete the current file, cannot prepare the test";
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -626,7 +634,8 @@ public class SimpleDeployerRawFileTest { File newDestRawFile = new File(extDir, newFileName); newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -690,7 +699,8 @@ public class SimpleDeployerRawFileTest { File newDestRawFile = new File(extDir, newFileName); newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -763,7 +773,8 @@ public class SimpleDeployerRawFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -802,7 +813,7 @@ public class SimpleDeployerRawFileTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, deployDir, null, null, null, null); + dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, deployDir, null, null, null, null, true); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java index cf366cb..5a0f842 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerRawRelativeFileTest.java @@ -91,7 +91,7 @@ public class SimpleDeployerRawRelativeFileTest { this.sourceRawFiles.put(sourceRawFile, new File(originalFileName)); // RELATIVE! note we name it different than the source file this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); DeploymentData dd = new DeploymentData(originalDeployProps, null, sourceRawFiles, deployDir, null, null, null, - null); + null, true); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = sourceRawFiles.get(sourceRawFile); @@ -205,7 +205,8 @@ public class SimpleDeployerRawRelativeFileTest { }
private void baseX_X_X(boolean dryRun) throws Exception { - DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -247,7 +248,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -293,7 +295,8 @@ public class SimpleDeployerRawRelativeFileTest { String newHashcode = MessageDigestGenerator.getDigestString(newContent); writeFile(newContent, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -341,7 +344,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -389,7 +393,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -452,7 +457,8 @@ public class SimpleDeployerRawRelativeFileTest { File newDestRawFile = new File(newFileName); // RELATIVE! newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -514,7 +520,8 @@ public class SimpleDeployerRawRelativeFileTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -573,7 +580,8 @@ public class SimpleDeployerRawRelativeFileTest { private void baseNoCurrent(boolean dryRun) throws Exception { assert this.currentFileWithAbsolutePath.delete() : "Failed to delete the current file, cannot prepare the test";
- DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, sourceRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -624,7 +632,8 @@ public class SimpleDeployerRawRelativeFileTest { File newDestRawFile = new File(newFileName); // RELATIVE! newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -688,7 +697,8 @@ public class SimpleDeployerRawRelativeFileTest { File newDestRawFile = new File(newFileName); // RELATIVE! newRawFiles.put(newRawFile, newDestRawFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -761,7 +771,8 @@ public class SimpleDeployerRawRelativeFileTest { Map<File, File> newRawFiles = new HashMap<File, File>(1); newRawFiles.put(newRawFile, this.currentFile);
- DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, null, newRawFiles, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -800,7 +811,7 @@ public class SimpleDeployerRawRelativeFileTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, deployDir, null, null, null, null); + dd = new DeploymentData(v1Duplicate, null, sourceRawFiles, deployDir, null, null, null, null, true); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; diff --git a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java index 24884ed..712a984 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/updater/SimpleDeployerTest.java @@ -87,7 +87,7 @@ public class SimpleDeployerTest { this.originalZipFiles.add(originalZipFile); this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, - null, null); + null, null, true); Deployer deployer = new Deployer(dd); this.originalFileHashcodeMap = deployer.deploy(null); this.currentFile = new File(deployDir, originalFileName); @@ -205,9 +205,64 @@ public class SimpleDeployerTest { baseNoNewWithCurrentDifferentThanOriginal(true); }
+ public void testWithSubdirectories() throws Exception { + // this test is different than all the rest, start with clean tmp/dest dirs with no beforeMethod buildup + FileUtil.purge(this.tmpDir, false); + FileUtil.purge(this.deployDir, false); + + // fill the deployDir with some unrelated content + String unrelatedFileName1 = "unrelated.txt"; + String unrelatedFileName2 = "unrelateddir/unrelated.txt"; + File unrelated1 = writeFile("unrelated1", this.deployDir, unrelatedFileName1); + File unrelated2 = writeFile("unrelated2", this.deployDir, unrelatedFileName2); + assert unrelated1.exists(); + assert unrelated2.exists(); + + // deploy initial content + String origFileName1 = "original-file1.txt"; + String origFileName2 = "subdir/original-file2.txt"; + this.originalZipFile = createZip(new String[] { "content1", "content2" }, this.tmpDir, "original.zip", + new String[] { origFileName1, origFileName2 }); + this.originalZipFiles = new HashSet<File>(1); + this.originalZipFiles.add(originalZipFile); + this.originalDeployProps = new DeploymentProperties(1, "simple", "1.0", "original test deployment"); + DeploymentData dd = new DeploymentData(originalDeployProps, originalZipFiles, null, deployDir, null, null, + null, null, true); + Deployer deployer = new Deployer(dd); + this.originalFileHashcodeMap = deployer.deploy(null); + assert new File(this.deployDir, origFileName1).exists(); + assert new File(this.deployDir, origFileName2).exists(); + assert unrelated1.exists() : "the deployment removed unrelated file1"; + assert unrelated2.getParentFile().isDirectory() : "the deployment removed an unrelated dir"; + assert unrelated2.exists() : "the deployment removed unrelated file2"; + + // deploy new content + this.newDeployProps = new DeploymentProperties(2, "simple", "2.0", "new test deployment"); + this.diff = new DeployDifferences(); + this.metadata = new DeploymentsMetadata(this.deployDir); + String newFileName1 = "new-file1.txt"; + String newFileName2 = "newsubdir/new-file2.txt"; + File newZipFile = createZip(new String[] { "newcontent1", "newcontent2" }, this.tmpDir, "new.zip", + new String[] { newFileName1, newFileName2 }); + HashSet<File> newZipFiles = new HashSet<File>(1); + newZipFiles.add(newZipFile); + dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, true); + deployer = new Deployer(dd); + FileHashcodeMap newFileHashcodeMap = deployer.deploy(this.diff); + assert new File(this.deployDir, newFileName1).exists(); + assert new File(this.deployDir, newFileName2).exists(); + assert !new File(this.deployDir, origFileName1).exists(); + assert !new File(this.deployDir, origFileName2).exists(); + assert !unrelated1.exists() : "the deployment did not remove unrelated file1"; + assert !unrelated2.exists() : "the deployment did not remove unrelated file1"; + assert this.diff.getBackedUpFiles().size() == 2 : this.diff; + assert new File(this.diff.getBackedUpFiles().get(unrelatedFileName1)).exists() : this.diff; + assert new File(this.diff.getBackedUpFiles().get(unrelatedFileName2)).exists() : this.diff; + } + private void baseX_X_X(boolean dryRun) throws Exception { DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null); + null, true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -249,7 +304,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -296,7 +352,7 @@ public class SimpleDeployerTest { writeFile(newContent, this.currentFile);
DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null); + null, true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -344,7 +400,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -392,7 +449,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -454,7 +512,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -515,7 +574,8 @@ public class SimpleDeployerTest { String inTheWayHashcode = MessageDigestGenerator.getDigestString(inTheWayContent); writeFile(inTheWayContent, inTheWayFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -575,7 +635,7 @@ public class SimpleDeployerTest { assert this.currentFile.delete() : "Failed to delete the current file, cannot prepare the test";
DeploymentData dd = new DeploymentData(newDeployProps, originalZipFiles, null, deployDir, null, null, null, - null); + null, true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -625,7 +685,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -688,7 +749,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; if (dryRun) { @@ -761,7 +823,8 @@ public class SimpleDeployerTest { Set<File> newZipFiles = new HashSet<File>(1); newZipFiles.add(newZipFile);
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, null, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff); // no dry run - we need to do this to force backup file creation @@ -800,7 +863,7 @@ public class SimpleDeployerTest { DeploymentProperties v1Duplicate = new DeploymentProperties(); v1Duplicate.putAll(this.originalDeployProps); v1Duplicate.setDeploymentId(3); // this is the same as v1, but it needs a unique deployment ID - dd = new DeploymentData(v1Duplicate, originalZipFiles, null, deployDir, null, null, null, null); + dd = new DeploymentData(v1Duplicate, originalZipFiles, null, deployDir, null, null, null, null, true); deployer = new Deployer(dd); this.diff = new DeployDifferences(); FileHashcodeMap restoreFileHashcodeMap; @@ -849,7 +912,8 @@ public class SimpleDeployerTest { Pattern iRegex = Pattern.compile(".*ignoreSubdir.*"); // this matches the subdirectory name, thus everything under it is ignored assert ignoredFile.exists() : "for some reason we couldn't create our test file; cannot know if clean worked";
- DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, iRegex); + DeploymentData dd = new DeploymentData(newDeployProps, newZipFiles, null, deployDir, null, null, null, iRegex, + true); Deployer deployer = new Deployer(dd); FileHashcodeMap newFileHashcodeMap; newFileHashcodeMap = deployer.deploy(this.diff, true, dryRun); // note: clean is true @@ -928,8 +992,8 @@ public class SimpleDeployerTest { FileOutputStream out = null;
try { - out = new FileOutputStream(fileToOverwrite); fileToOverwrite.getParentFile().mkdirs(); + out = new FileOutputStream(fileToOverwrite); out.write(content.getBytes()); return fileToOverwrite; } finally {
commit f2f5fba1821350531a5eb90b7d71c6295ce37ab7 Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 21 12:24:11 2010 -0500
be able to delete deployments if they are finished
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeploymentStatus.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeploymentStatus.java index 5c9787b..8eca429 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeploymentStatus.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeploymentStatus.java @@ -31,12 +31,12 @@ package org.rhq.core.domain.bundle; * @author Jay Shaughnessy */ public enum BundleDeploymentStatus { - PENDING("Pending"), // - IN_PROGRESS("In Progress"), // + PENDING("Pending"), // for future, when we support true scheduling of bundle deployments + IN_PROGRESS("In Progress"), // MIXED("Mixed"), // SUCCESS("Success"), // - FAILURE("Failure"), // - WARN("Warning"); + FAILURE("Failure") // + ; // need this for GWT
private String displayName;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java index 9cb3f58..cea040d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java @@ -100,10 +100,10 @@ public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployme });
HashMap<String, String> statusIcons = new HashMap<String, String>(); + statusIcons.put(BundleDeploymentStatus.PENDING.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); statusField.setValueIcons(statusIcons); statusField.setValueIconWidth(11); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index 94b216a..870988e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -105,10 +105,10 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab //setMargin(10); // do not set margin, we already have our margin set outside of us
statusIcons = new HashMap<String, String>(); + statusIcons.put(BundleDeploymentStatus.PENDING.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java index 972e618..89eec9d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java @@ -69,10 +69,10 @@ public class BundleResourceDeploymentHistoryListView extends LocatableVLayout { this.resourceDeployment = resourceDeployment;
statusIcons = new HashMap<String, String>(); + statusIcons.put(BundleDeploymentStatus.PENDING.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java index 5bfc174..00d25df 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java @@ -101,10 +101,10 @@ public class BundleDestinationListView extends Table<RPCDataSource<BundleDestina });
HashMap<String, String> statusIcons = new HashMap<String, String>(); + statusIcons.put(BundleDeploymentStatus.PENDING.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); latestDeploymentStatusField.setValueIcons(statusIcons); latestDeploymentStatusField.setValueIconHeight(11); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java index a57b618..25ff496 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java @@ -1263,11 +1263,14 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot if (null == doomed) { return; } - if (!BundleDeploymentStatus.PENDING.equals(doomed.getStatus())) { + // only allow deployments to be deleted if they are finished + if (BundleDeploymentStatus.SUCCESS == doomed.getStatus() + || BundleDeploymentStatus.FAILURE == doomed.getStatus() + || BundleDeploymentStatus.MIXED == doomed.getStatus()) { + entityManager.remove(doomed); + } else { throw new IllegalArgumentException("Can not delete deployment with status [" + doomed.getStatus() + "]"); } - - entityManager.remove(doomed); }
@RequiredPermission(Permission.MANAGE_BUNDLE)
commit f2e70918b70c767edc3dca70442c0df09bfd556c Author: Ian Springer ian.springer@redhat.com Date: Tue Dec 21 18:32:12 2010 -0500
an initial revision of the job trigger editor widget; usage of the trigger editor on the create new resource operation schedule view
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java new file mode 100644 index 0000000..5684067 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/trigger/JobTriggerEditor.java @@ -0,0 +1,314 @@ +/* + * 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.trigger; + +import java.util.Date; +import java.util.LinkedHashMap; + +import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.fields.DateTimeItem; +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.RadioGroupItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; +import com.smartgwt.client.widgets.form.fields.TextItem; +import com.smartgwt.client.widgets.form.fields.events.BlurEvent; +import com.smartgwt.client.widgets.form.fields.events.BlurHandler; +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.FocusEvent; +import com.smartgwt.client.widgets.form.fields.events.FocusHandler; +import com.smartgwt.client.widgets.form.validator.RegExpValidator; + +import org.rhq.core.domain.common.JobTrigger; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * A SmartGWT widget that provides the ability to create a new {@link JobTrigger job trigger}, or view or edit an + * existing job trigger. + * + * @author Ian Springer + */ +public class JobTriggerEditor extends LocatableVLayout { + + private boolean isReadOnly; + private boolean isValid; + + /** + * Create a new job trigger. + * + * @param locatorId + */ + public JobTriggerEditor(String locatorId) { + super(locatorId); + } + + /** + * View or edit an existing job trigger. + * + * @param locatorId + * @param jobTrigger + * @param isReadOnly + */ + public JobTriggerEditor(String locatorId, JobTrigger jobTrigger, boolean isReadOnly) { + super(locatorId); + + this.isReadOnly = isReadOnly; + } + + @Override + protected void onDraw() { + super.onDraw(); + + DynamicForm modeForm = new DynamicForm(); + + RadioGroupItem modeItem = new RadioGroupItem("mode", "Schedule using"); + modeItem.setWidth(220); + LinkedHashMap<String, String> modeValueMap = new LinkedHashMap<String, String>(); + modeValueMap.put("calendar", "Calendar"); + modeValueMap.put("cron", "Cron Mode"); + modeItem.setValueMap(modeValueMap); + modeItem.setVertical(false); + + modeForm.setFields(modeItem); + addMember(modeForm); + + + final DynamicForm calendarTypeForm = new DynamicForm(); + + RadioGroupItem calendarTypeItem = new RadioGroupItem("calendarType"); + calendarTypeItem.setWidth(440); + calendarTypeItem.setShowTitle(false); + LinkedHashMap<String, String> calendarTypeValueMap = new LinkedHashMap<String, String>(); + calendarTypeValueMap.put("now", "Now"); + calendarTypeValueMap.put("nowAndRepeat", "Now & Repeat"); + calendarTypeValueMap.put("later", "Later"); + calendarTypeValueMap.put("laterAndRepeat", "Later & Repeat"); + calendarTypeItem.setValueMap(calendarTypeValueMap); + calendarTypeItem.setVertical(false); + + calendarTypeForm.setFields(calendarTypeItem); + calendarTypeForm.setVisible(false); + + addMember(calendarTypeForm); + + modeItem.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent event) { + if (event.getValue().equals("calendar")) { + calendarTypeForm.show(); + } + } + }); + + final DynamicForm laterForm = createLaterForm(); + addMember(laterForm); + + final DynamicForm repeatForm = createRepeatForm(); + addMember(repeatForm); + + calendarTypeItem.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent event) { + String value = (String)event.getValue(); + if (value.equals("now")) { + isValid = true; + } else if (value.equals("nowAndRepeat")) { + laterForm.hide(); + FormItem repeatIntervalItem = repeatForm.getItem("repeatInterval"); + repeatIntervalItem.setTitle("Run now and every"); + repeatIntervalItem.redraw(); + repeatForm.show(); + } else if (value.equals("later")) { + repeatForm.hide(); + laterForm.show(); + } else { + // later and repeat + laterForm.show(); + FormItem repeatIntervalItem = repeatForm.getItem("repeatInterval"); + repeatIntervalItem.setTitle("Repeat every"); + repeatIntervalItem.redraw(); + repeatForm.show(); + } + } + }); + } + + private DynamicForm createRepeatForm() { + final DynamicForm nowAndRepeatForm = new DynamicForm(); + nowAndRepeatForm.setNumCols(6); + nowAndRepeatForm.setColWidths(130, 130, 130, 130, 130); + + TextItem repeatIntervalItem = new TextItem("repeatInterval", "Run now and every"); + + // Configure hint. + repeatIntervalItem.setHint("[1-9][0-9]* (seconds|minutes|hours|days|weeks|months|quarters|years)"); + repeatIntervalItem.setShowHint(false); + repeatIntervalItem.addFocusHandler(new FocusHandler() { + public void onFocus(FocusEvent event) { + event.getItem().setShowHint(true); + } + }); + repeatIntervalItem.addBlurHandler(new BlurHandler() { + public void onBlur(BlurEvent event) { + event.getItem().setShowHint(false); + } + }); + + // Configure validation. + RegExpValidator repeatIntervalValidator = new RegExpValidator("[1-9][0-9]*[ ]+(seconds|minutes|hours|days|weeks|months|quarters|years)"); + repeatIntervalItem.setValidators(repeatIntervalValidator); + repeatIntervalItem.setValidateOnExit(true); + + RadioGroupItem recurrenceTypeItem = new RadioGroupItem("recurrenceType"); + recurrenceTypeItem.setShowTitle(false); + LinkedHashMap<String, String> recurrenceTypeValueMap = new LinkedHashMap<String, String>(); + recurrenceTypeValueMap.put("for", "For"); + recurrenceTypeValueMap.put("until", "Until"); + recurrenceTypeValueMap.put("indefinitely", "Indefinitely"); + recurrenceTypeItem.setValueMap(recurrenceTypeValueMap); + + final TextItem repeatDurationItem = new TextItem("repeatDuration"); + repeatDurationItem.setShowTitle(false); + repeatDurationItem.setVisible(false); + + // Configure hint. + repeatDurationItem.setHint("[1-9][0-9]* (repetitions|seconds|minutes|hours|days|weeks|months|quarters|years)"); + repeatDurationItem.setShowHint(false); + repeatDurationItem.addFocusHandler(new FocusHandler() { + public void onFocus(FocusEvent event) { + event.getItem().setShowHint(true); + } + }); + repeatDurationItem.addBlurHandler(new BlurHandler() { + public void onBlur(BlurEvent event) { + event.getItem().setShowHint(false); + } + }); + + // Configure validation. + RegExpValidator repeatDurationValidator = new RegExpValidator("[1-9][0-9]*[ ]+(repetitions|seconds|minutes|hours|days|weeks|months|quarters|years)"); + repeatDurationItem.setValidators(repeatDurationValidator); + repeatDurationItem.setValidateOnExit(true); + + + final DateTimeItem endTimeItem = createDateTimeItem("endTime"); + endTimeItem.setShowTitle(false); + endTimeItem.setVisible(false); + + SpacerItem spacerItem = new SpacerItem(); + + recurrenceTypeItem.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent event) { + String value = (String)event.getValue(); + if (value.equals("for")) { + endTimeItem.hide(); + repeatDurationItem.show(); + } else if (value.equals("until")) { + repeatDurationItem.hide(); + endTimeItem.show(); + } else { + repeatDurationItem.hide(); + endTimeItem.hide(); + } + } + }); + + nowAndRepeatForm.setFields(repeatIntervalItem, recurrenceTypeItem, repeatDurationItem, endTimeItem, spacerItem); + nowAndRepeatForm.setVisible(false); + + return nowAndRepeatForm; + } + + private DynamicForm createLaterForm() { + final DynamicForm laterForm = new DynamicForm(); + laterForm.setNumCols(4); + laterForm.setColWidths(130, 130, 130); + + RadioGroupItem startTypeItem = new RadioGroupItem("startType", "Run"); + LinkedHashMap<String, String> startTypeValueMap = new LinkedHashMap<String, String>(); + startTypeValueMap.put("on", "on"); + startTypeValueMap.put("in", "in"); + startTypeItem.setValueMap(startTypeValueMap); + + final DateTimeItem startTimeItem = createDateTimeItem("startTime"); + + final TextItem startDelayItem = new TextItem("startDelay"); + startDelayItem.setShowTitle(false); + startDelayItem.setVisible(false); + + // Configure hint. + startDelayItem.setHint("[1-9][0-9]* (seconds|minutes|hours|days|weeks|months|quarters|years)"); + startDelayItem.setShowHint(false); + startDelayItem.addFocusHandler(new FocusHandler() { + public void onFocus(FocusEvent event) { + event.getItem().setShowHint(true); + } + }); + startDelayItem.addBlurHandler(new BlurHandler() { + public void onBlur(BlurEvent event) { + event.getItem().setShowHint(false); + } + }); + + // Configure validation. + RegExpValidator startDelayValidator = new RegExpValidator("[1-9][0-9]*[ ]+(seconds|minutes|hours|days|weeks|months|quarters|years)"); + startDelayItem.setValidators(startDelayValidator); + startDelayItem.setValidateOnExit(true); + + SpacerItem spacerItem = new SpacerItem(); + + startTypeItem.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent event) { + String value = (String)event.getValue(); + if (value.equals("on")) { + startDelayItem.hide(); + startTimeItem.show(); + } else { + startTimeItem.hide(); + startDelayItem.show(); + } + } + }); + + laterForm.setFields(startTypeItem, startTimeItem, startDelayItem, spacerItem); + laterForm.setVisible(false); + + return laterForm; + } + + private static DateTimeItem createDateTimeItem(String name) { + final DateTimeItem dateTimeItem = new DateTimeItem(name); + dateTimeItem.setEnforceDate(true); + dateTimeItem.setCenturyThreshold(99); + dateTimeItem.setShowTitle(false); + dateTimeItem.setVisible(false); + dateTimeItem.setStartDate(new Date()); + dateTimeItem.setUseMask(true); + dateTimeItem.setShowHint(true); + return dateTimeItem; + } + + public boolean isReadOnly() { + return isReadOnly; + } + + public boolean isValid() { + return isValid; + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java index 3afb1e2..6da2ec5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java @@ -42,6 +42,7 @@ import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.form.AbstractRecordEditor; import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; +import org.rhq.enterprise.gui.coregui.client.components.trigger.JobTriggerEditor; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; @@ -115,6 +116,11 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { this.operationParametersConfigurationHolder.setVisible(false); contentPane.addMember(this.operationParametersConfigurationHolder);
+ if (isNewRecord()) { + JobTriggerEditor triggerEditor = new JobTriggerEditor(extendLocatorId("TriggerEditor")); + contentPane.addMember(triggerEditor); + } + EnhancedDynamicForm notesForm = new EnhancedDynamicForm(extendLocatorId("NotesForm"), isReadOnly(), isNewRecord()); TextAreaItem notesItem = new TextAreaItem(ResourceOperationScheduleDataSource.Field.DESCRIPTION, "Notes");
commit a2619e9946f686fdb50f161df01766d88964980f Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Dec 21 17:14:28 2010 -0500
[BZ 661808 - Removing portlets from the dashboard is not working] Actually it turns out it was "rapid" portlet removal was not working. There is a basic issue with the implementation in that the user can perform several callback-initiating actions (like portlet removal) faster than DashboardView's async save() method can complete. The save() method's async success() method updates the stored dashboard with the results of the save (merge operation). This in effect can "overwrite" any work that had been done on the "old" Dashboard while the update was taking place.
I've protected add/remove portlet using some synchronization but it we need to go further we may need to put a locking mechanism in place.
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 02e6b00..81d3bb2 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 @@ -238,7 +238,11 @@ public class DashboardView extends LocatableVLayout { } }
- private void addPortlet(String portletKey, String portletName) { + /** + * A synchronized call to ensure add/remove/save are exclusive. + * + */ + synchronized private void addPortlet(String portletKey, String portletName) { DashboardPortlet storedPortlet = new DashboardPortlet(portletName, portletKey, 250);
final PortletWindow newPortlet = new PortletWindow(extendLocatorId(portletKey), this, storedPortlet); @@ -278,11 +282,32 @@ public class DashboardView extends LocatableVLayout { newPortlet.show(); } }, 750); - save(); + save(storedDashboard); + } + + /** + * A synchronized call to ensure the remove and save are atomic. + * + * @param portlet + */ + synchronized public void removePortlet(DashboardPortlet portlet) { + storedDashboard.removePortlet(portlet); + save(storedDashboard); + } + + /** + * A synchronized call to ensure add/remove/save are exclusive. + */ + synchronized private void setDashboard(Dashboard dashboard) { + storedDashboard = dashboard; }
public void save() { - GWTServiceLookup.getDashboardService().storeDashboard(storedDashboard, new AsyncCallback<Dashboard>() { + save(storedDashboard); + } + + private void save(Dashboard dashboard) { + GWTServiceLookup.getDashboardService().storeDashboard(dashboard, new AsyncCallback<Dashboard>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.view_dashboardManager_error(), caught); } @@ -290,7 +315,11 @@ public class DashboardView extends LocatableVLayout { public void onSuccess(Dashboard result) { CoreGUI.getMessageCenter().notify( new Message(MSG.view_dashboardManager_saved(result.getName()), Message.Severity.Info)); - storedDashboard = result; + // use the synchronized call to ensure add/delete portlet doesn't get interrupted. This is really + // just limited protection for add/remove portlet. Since this now sets storedDashboard, + // anything using the old version could lose edits. If we want to make this more robust we'll probably + // need a locking mechanism for editing the dashboard. + setDashboard(storedDashboard);
updateConfigs(result); } 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 caffe54..3277aeb 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 @@ -148,8 +148,7 @@ public class PortletWindow extends LocatableWindow {
addCloseClickHandler(new CloseClickHandler() { public void onCloseClick(CloseClientEvent closeClientEvent) { - PortletWindow.this.dashboardPortlet.getDashboard().removePortlet(PortletWindow.this.dashboardPortlet); - save(); + PortletWindow.this.dashboardView.removePortlet(PortletWindow.this.dashboardPortlet); destroy(); } });
commit 4bda12a4c8de28aa2f7f8bf30d2536b1a4b7d9e5 Author: Joseph Marques joseph@redhat.com Date: Tue Dec 21 15:07:34 2010 -0500
fix serialization issues across the board for all gwt service implementations
use the following coding style:
public ReturnType someMethod(Args...) throws RuntimeException { try { // method body } 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/AgentGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AgentGWTServiceImpl.java index 80bc779..448debd 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AgentGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AgentGWTServiceImpl.java @@ -35,24 +35,24 @@ public class AgentGWTServiceImpl extends AbstractGWTServiceImpl implements Agent private AgentManagerLocal agentManager = LookupUtil.getAgentManager();
@Override - public Agent getAgentForResource(int resourceId) { + public Agent getAgentForResource(int resourceId) throws RuntimeException { try { //security handled in AgentManagerBean. requires View_Resource. return SerialUtility.prepare(agentManager.getAgentByResourceId(getSessionSubject(), resourceId), "AgentService.getAgentForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public Boolean pingAgentForResource(int resourceId) { + public Boolean pingAgentForResource(int resourceId) throws RuntimeException { try { //security handled in AgentManagerBean. requires View_Resource. return SerialUtility.prepare(agentManager.pingAgentByResourceId(getSessionSubject(), resourceId), "AgentService.pingAgentForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -60,8 +60,8 @@ public class AgentGWTServiceImpl extends AbstractGWTServiceImpl implements Agent // try { // return SerialUtility.prepare(availabilityManager.findAvailabilityForResource(getSessionSubject(), // resourceId, pc), "AvailabilityService.findAvailabilityForResource"); - // } catch (Exception e) { - // throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + // } 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/AlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertDefinitionGWTServiceImpl.java index c704b49..3ed01c2 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 @@ -39,98 +39,99 @@ public class AlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implem private AlertNotificationManagerLocal alertNotifManager = LookupUtil.getAlertNotificationManager();
@Override - public PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria) { + public PageList<AlertDefinition> findAlertDefinitionsByCriteria(AlertDefinitionCriteria criteria) + throws RuntimeException { try { PageList<AlertDefinition> results = this.alertDefManager.findAlertDefinitionsByCriteria( getSessionSubject(), criteria); return SerialUtility.prepare(results, "findAlertDefinitionsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws Exception { + public int createAlertDefinition(AlertDefinition alertDefinition, Integer resourceId) throws RuntimeException { try { int results = alertDefManager.createAlertDefinition(getSessionSubject(), alertDefinition, resourceId); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override public AlertDefinition updateAlertDefinition(int alertDefinitionId, AlertDefinition alertDefinition, - boolean updateInternals) throws Exception { + boolean updateInternals) throws RuntimeException { try { AlertDefinition results = alertDefManager.updateAlertDefinition(getSessionSubject(), alertDefinitionId, alertDefinition, updateInternals); return SerialUtility.prepare(results, "updateAlertDefinition"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int enableAlertDefinitions(int[] alertDefinitionIds) throws Exception { + public int enableAlertDefinitions(int[] alertDefinitionIds) throws RuntimeException { try { int results = alertDefManager.enableAlertDefinitions(getSessionSubject(), alertDefinitionIds); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int disableAlertDefinitions(int[] alertDefinitionIds) throws Exception { + public int disableAlertDefinitions(int[] alertDefinitionIds) throws RuntimeException { try { int results = alertDefManager.disableAlertDefinitions(getSessionSubject(), alertDefinitionIds); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int removeAlertDefinitions(int[] alertDefinitionIds) throws Exception { + public int removeAlertDefinitions(int[] alertDefinitionIds) throws RuntimeException { try { int results = alertDefManager.removeAlertDefinitions(getSessionSubject(), alertDefinitionIds); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws Exception { + public String[] getAlertNotificationConfigurationPreview(AlertNotification[] notifs) throws RuntimeException { try { String[] results = alertDefManager.getAlertNotificationConfigurationPreview(getSessionSubject(), notifs); return SerialUtility.prepare(results, "getAlertNotificationConfigurationPreview"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public String[] getAllAlertSenders() throws Exception { + public String[] getAllAlertSenders() throws RuntimeException { 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)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public ConfigurationDefinition getConfigurationDefinitionForSender(String sender) throws Exception { + public ConfigurationDefinition getConfigurationDefinitionForSender(String sender) throws RuntimeException { try { ConfigurationDefinition results = alertNotifManager.getConfigurationDefinitionForSender(sender); return SerialUtility.prepare(results, "getConfigurationDefinitionForSender"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/AlertGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertGWTServiceImpl.java index 9f66d19..3072708 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 @@ -37,44 +37,44 @@ public class AlertGWTServiceImpl extends AbstractGWTServiceImpl implements Alert
private AlertManagerLocal alertManager = LookupUtil.getAlertManager();
- public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) { + public PageList<Alert> findAlertsByCriteria(AlertCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(this.alertManager.findAlertsByCriteria(getSessionSubject(), criteria), "AlertService.findAlertsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int deleteAlerts(int[] alertIds) { + public int deleteAlerts(int[] alertIds) throws RuntimeException { try { return this.alertManager.deleteAlerts(getSessionSubject(), alertIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int deleteAlertsByContext(EntityContext context) { + public int deleteAlertsByContext(EntityContext context) throws RuntimeException { try { return this.alertManager.deleteAlertsByContext(getSessionSubject(), context); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int acknowledgeAlerts(int[] alertIds) { + public int acknowledgeAlerts(int[] alertIds) throws RuntimeException { try { return this.alertManager.acknowledgeAlerts(getSessionSubject(), alertIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int acknowledgeAlertsByContext(EntityContext context) { + public int acknowledgeAlertsByContext(EntityContext context) throws RuntimeException { try { return this.alertManager.acknowledgeAlertsByContext(getSessionSubject(), context); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertTemplateGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertTemplateGWTServiceImpl.java index 55a24e3..7179ffc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertTemplateGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AlertTemplateGWTServiceImpl.java @@ -31,55 +31,55 @@ public class AlertTemplateGWTServiceImpl extends AbstractGWTServiceImpl implemen private AlertTemplateManagerLocal alertTemplateManager = LookupUtil.getAlertTemplateManager();
@Override - public int createAlertTemplate(AlertDefinition alertDefinition, Integer resourceTypeId) throws Exception { + public int createAlertTemplate(AlertDefinition alertDefinition, Integer resourceTypeId) throws RuntimeException { try { int results = alertTemplateManager .createAlertTemplate(getSessionSubject(), alertDefinition, resourceTypeId); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override public AlertDefinition updateAlertTemplate(AlertDefinition alertDefinition, boolean purgeInternals) - throws Exception { + throws RuntimeException { try { AlertDefinition results = alertTemplateManager.updateAlertTemplate(getSessionSubject(), alertDefinition, purgeInternals); return SerialUtility.prepare(results, "AlertTemplateService.updateAlertTemplate"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public void enableAlertTemplates(Integer[] alertDefinitionIds) throws Exception { + public void enableAlertTemplates(Integer[] alertDefinitionIds) throws RuntimeException { try { alertTemplateManager.enableAlertTemplates(getSessionSubject(), alertDefinitionIds); return; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public void disableAlertTemplates(Integer[] alertDefinitionIds) throws Exception { + public void disableAlertTemplates(Integer[] alertDefinitionIds) throws RuntimeException { try { alertTemplateManager.disableAlertTemplates(getSessionSubject(), alertDefinitionIds); return; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public void removeAlertTemplates(Integer[] alertDefinitionIds) throws Exception { + public void removeAlertTemplates(Integer[] alertDefinitionIds) throws RuntimeException { try { alertTemplateManager.removeAlertTemplates(getSessionSubject(), alertDefinitionIds); return; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ 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 56a4857..a23bf27 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 @@ -37,49 +37,49 @@ public class AuthorizationGWTServiceImpl extends AbstractGWTServiceImpl implemen
private AuthorizationManagerLocal authorizationManager = LookupUtil.getAuthorizationManager();
- public Set<Permission> getExplicitResourcePermissions(int resourceId) { + public Set<Permission> getExplicitResourcePermissions(int resourceId) throws RuntimeException { try { return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getExplicitResourcePermissions( getSessionSubject(), resourceId)), "AuthorizationManager.getExplicitResourcePermissions"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Set<Permission> getImplicitResourcePermissions(int resourceId) { + public Set<Permission> getImplicitResourcePermissions(int resourceId) throws RuntimeException { try { return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getImplicitResourcePermissions( getSessionSubject(), resourceId)), "AuthorizationManager.getImplicitResourcePermissions"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Set<Permission> getExplicitGroupPermissions(int groupId) { + public Set<Permission> getExplicitGroupPermissions(int groupId) throws RuntimeException { try { return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getExplicitGroupPermissions( getSessionSubject(), groupId)), "AuthorizationManager.getExplicitGroupPermissions"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Set<Permission> getImplicitGroupPermissions(int groupId) { + public Set<Permission> getImplicitGroupPermissions(int groupId) throws RuntimeException { try { return SerialUtility.prepare(new HashSet<Permission>(authorizationManager.getImplicitGroupPermissions( getSessionSubject(), groupId)), "AuthorizationManager.getImplicitGroupPermissions"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Set<Permission> getExplicitGlobalPermissions() { + public Set<Permission> getExplicitGlobalPermissions() throws RuntimeException { try { return SerialUtility.prepare(new HashSet<Permission>(authorizationManager .getExplicitGlobalPermissions(getSessionSubject())), "AuthorizationManager.getExplicitGlobalPermissions"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/AvailabilityGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AvailabilityGWTServiceImpl.java index 4b636f0..93e16c9 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 @@ -36,12 +36,12 @@ public class AvailabilityGWTServiceImpl extends AbstractGWTServiceImpl implement
private AvailabilityManagerLocal availabilityManager = LookupUtil.getAvailabilityManager();
- public PageList<Availability> findAvailabilityForResource(int resourceId, PageControl pc) { + public PageList<Availability> findAvailabilityForResource(int resourceId, PageControl pc) throws RuntimeException { try { return SerialUtility.prepare(availabilityManager.findAvailabilityForResource(getSessionSubject(), resourceId, pc), "AvailabilityService.findAvailabilityForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/BundleGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java index 103fcac..4049454 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java @@ -48,218 +48,222 @@ public class BundleGWTServiceImpl extends AbstractGWTServiceImpl implements Bund
private BundleManagerLocal bundleManager = LookupUtil.getBundleManager();
- public BundleVersion createBundleVersionViaURL(String url) throws Exception { + public BundleVersion createBundleVersionViaURL(String url) throws RuntimeException { try { BundleVersion results = bundleManager.createBundleVersionViaURL(getSessionSubject(), url); return SerialUtility.prepare(results, "createBundleVersionViaURL"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public BundleVersion createBundleVersionViaRecipe(String recipe) throws Exception { + public BundleVersion createBundleVersionViaRecipe(String recipe) throws RuntimeException { try { BundleVersion results = bundleManager.createBundleVersionViaRecipe(getSessionSubject(), recipe); return SerialUtility.prepare(results, "createBundleVersionViaRecipe"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public BundleDeployment createBundleDeployment(int bundleVersionId, int bundleDestinationId, String description, Configuration configuration, boolean enforcePolicy, int enforcementInterval, boolean pinToBundle) - throws Exception { + throws RuntimeException {
try { BundleDeployment result = bundleManager.createBundleDeployment(getSessionSubject(), bundleVersionId, bundleDestinationId, description, configuration); return SerialUtility.prepare(result, "createBundleDeployment"); - } catch (Exception e) { - throw new Exception(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public BundleDestination createBundleDestination(int bundleId, String name, String description, String deployDir, - int groupId) throws Exception { + int groupId) throws RuntimeException {
try { BundleDestination result = bundleManager.createBundleDestination(getSessionSubject(), bundleId, name, description, deployDir, groupId); return SerialUtility.prepare(result, "createBundleDestination"); - } catch (Exception e) { - throw new Exception(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public BundleVersion createBundleVersion(int bundleId, String name, String version, String recipe) throws Exception { + public BundleVersion createBundleVersion(int bundleId, String name, String version, String recipe) + throws RuntimeException { try { BundleVersion results = bundleManager.createBundleVersion(getSessionSubject(), bundleId, name, null, version, recipe); return SerialUtility.prepare(results, "createBundleVersion"); - } catch (Exception e) { - throw new Exception(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteBundles(int[] bundleIds) throws Exception { + public void deleteBundles(int[] bundleIds) throws RuntimeException { try { bundleManager.deleteBundles(getSessionSubject(), bundleIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteBundle(int bundleId) throws Exception { + public void deleteBundle(int bundleId) throws RuntimeException { try { bundleManager.deleteBundle(getSessionSubject(), bundleId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteBundleDeployment(int bundleDeploymentId) throws Exception { + public void deleteBundleDeployment(int bundleDeploymentId) throws RuntimeException { try { bundleManager.deleteBundleDeployment(getSessionSubject(), bundleDeploymentId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteBundleDestination(int bundleDestinationId) throws Exception { + public void deleteBundleDestination(int bundleDestinationId) throws RuntimeException { try { bundleManager.deleteBundleDestination(getSessionSubject(), bundleDestinationId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteBundleVersion(int bundleVersionId, boolean deleteBundleIfEmpty) throws Exception { + public void deleteBundleVersion(int bundleVersionId, boolean deleteBundleIfEmpty) throws RuntimeException { try { bundleManager.deleteBundleVersion(getSessionSubject(), bundleVersionId, deleteBundleIfEmpty); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public ArrayList<BundleType> getAllBundleTypes() throws Exception { + public ArrayList<BundleType> getAllBundleTypes() throws RuntimeException { try { ArrayList<BundleType> bundleTypes = new ArrayList<BundleType>(); bundleTypes.addAll(bundleManager.getAllBundleTypes(getSessionSubject())); return SerialUtility.prepare(bundleTypes, "getAllBundleTypes"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public HashMap<String, Boolean> getAllBundleVersionFilenames(int bundleVersionId) throws Exception { + public HashMap<String, Boolean> getAllBundleVersionFilenames(int bundleVersionId) throws RuntimeException { HashMap<String, Boolean> results = new HashMap<String, Boolean>(); try { results.putAll(bundleManager.getAllBundleVersionFilenames(getSessionSubject(), bundleVersionId)); return SerialUtility.prepare(results, "getAllBundleVersionFilenames"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public String getBundleDeploymentName(int bundleDestinationId, int bundleVersionId, int prevDeploymentId) { + public String getBundleDeploymentName(int bundleDestinationId, int bundleVersionId, int prevDeploymentId) + throws RuntimeException { String result; try { result = bundleManager.getBundleDeploymentName(getSessionSubject(), bundleDestinationId, bundleVersionId, prevDeploymentId); return SerialUtility.prepare(result, "getBundleDeploymentName"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public BundleDeployment scheduleBundleDeployment(int bundleDeploymentId, boolean isCleanDeployment) - throws Exception { + throws RuntimeException { try { BundleDeployment result = bundleManager.scheduleBundleDeployment(getSessionSubject(), bundleDeploymentId, isCleanDeployment); return SerialUtility.prepare(result, "scheduleBundleDeployment"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public BundleDeployment scheduleRevertBundleDeployment(int bundleDeploymentId, String deploymentDescription, - boolean isCleanDeployment) throws Exception { + boolean isCleanDeployment) throws RuntimeException { try { BundleDeployment result = bundleManager.scheduleRevertBundleDeployment(getSessionSubject(), bundleDeploymentId, deploymentDescription, isCleanDeployment); return SerialUtility.prepare(result, "scheduleRevertBundleDeployment"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<Bundle> findBundlesByCriteria(BundleCriteria criteria) throws Exception { + public PageList<Bundle> findBundlesByCriteria(BundleCriteria criteria) throws RuntimeException { try { PageList<Bundle> results = bundleManager.findBundlesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "findBundlesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<BundleDeployment> findBundleDeploymentsByCriteria(BundleDeploymentCriteria criteria) { + public PageList<BundleDeployment> findBundleDeploymentsByCriteria(BundleDeploymentCriteria criteria) + throws RuntimeException { try { PageList<BundleDeployment> result = bundleManager.findBundleDeploymentsByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(result, "BundleService.findBundleDeploymentsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<BundleDestination> findBundleDestinationsByCriteria(BundleDestinationCriteria criteria) { + public PageList<BundleDestination> findBundleDestinationsByCriteria(BundleDestinationCriteria criteria) + throws RuntimeException { try { PageList<BundleDestination> result = bundleManager.findBundleDestinationsByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(result, "BundleService.findBundleDestinationsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<BundleFile> findBundleFilesByCriteria(BundleFileCriteria criteria) { + public PageList<BundleFile> findBundleFilesByCriteria(BundleFileCriteria criteria) throws RuntimeException { try { PageList<BundleFile> result = bundleManager.findBundleFilesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(result, "BundleService.findBundleFilesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<BundleResourceDeployment> findBundleResourceDeploymentsByCriteria( - BundleResourceDeploymentCriteria criteria) { + BundleResourceDeploymentCriteria criteria) throws RuntimeException { try { PageList<BundleResourceDeployment> result = bundleManager.findBundleResourceDeploymentsByCriteria( getSessionSubject(), criteria); return SerialUtility.prepare(result, "BundleService.findBundleResourceDeploymentsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<BundleVersion> findBundleVersionsByCriteria(BundleVersionCriteria criteria) throws Exception { + public PageList<BundleVersion> findBundleVersionsByCriteria(BundleVersionCriteria criteria) throws RuntimeException { try { PageList<BundleVersion> results = bundleManager.findBundleVersionsByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "findBundleVersionsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<BundleWithLatestVersionComposite> findBundlesWithLatestVersionCompositesByCriteria( - BundleCriteria criteria) throws Exception { + BundleCriteria criteria) throws RuntimeException { try { PageList<BundleWithLatestVersionComposite> results; results = bundleManager.findBundlesWithLatestVersionCompositesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "findBundlesWithLatestVersionCompositesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ No newline at end of file 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 211735d..ad81c84 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 @@ -28,6 +28,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.domain.resource.group.composite.ClusterFlyweight; +import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ClusterGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.resource.cluster.ClusterManagerLocal; @@ -42,24 +43,41 @@ public class ClusterGWTServiceImpl extends AbstractGWTServiceImpl implements Clu
private ClusterManagerLocal clusterManager = LookupUtil.getClusterManager();
- public ResourceGroup createAutoClusterBackingGroup(ClusterKey clusterKey, boolean addResources) { - return SerialUtility.prepare(clusterManager.createAutoClusterBackingGroup(getSessionSubject(), clusterKey, - addResources), "ClusterGWTServiceImpl.createAutoClusterBackingGroup"); + public ResourceGroup createAutoClusterBackingGroup(ClusterKey clusterKey, boolean addResources) + throws RuntimeException { + try { + return SerialUtility.prepare(clusterManager.createAutoClusterBackingGroup(getSessionSubject(), clusterKey, + addResources), "ClusterGWTServiceImpl.createAutoClusterBackingGroup"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
- public ResourceGroup getAutoClusterBackingGroup(ClusterKey clusterKey) { - return SerialUtility.prepare(clusterManager.getAutoClusterBackingGroup(getSessionSubject(), clusterKey), - "ClusterGWTServiceImpl.getAutoClusterBackingGroup"); + public ResourceGroup getAutoClusterBackingGroup(ClusterKey clusterKey) throws RuntimeException { + try { + return SerialUtility.prepare(clusterManager.getAutoClusterBackingGroup(getSessionSubject(), clusterKey), + "ClusterGWTServiceImpl.getAutoClusterBackingGroup"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
- public List<Resource> getAutoClusterResources(ClusterKey clusterKey) { - return SerialUtility.prepare(clusterManager.getAutoClusterResources(getSessionSubject(), clusterKey), - "ClusterGWTServiceImpl.getAutoClusterResources"); + public List<Resource> getAutoClusterResources(ClusterKey clusterKey) throws RuntimeException { + try { + return SerialUtility.prepare(clusterManager.getAutoClusterResources(getSessionSubject(), clusterKey), + "ClusterGWTServiceImpl.getAutoClusterResources"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
- public ClusterFlyweight getClusterTree(int groupId) { - return SerialUtility.prepare(clusterManager.getClusterTree(getSessionSubject(), groupId), - "ClusterGWTServiceImpl.getClusterTree"); + public ClusterFlyweight getClusterTree(int groupId) throws RuntimeException { + try { + return SerialUtility.prepare(clusterManager.getClusterTree(getSessionSubject(), groupId), + "ClusterGWTServiceImpl.getClusterTree"); + } 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/ConfigurationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java index 72515a4..935a3dd 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 @@ -47,122 +47,125 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen private ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); private ResourceGroupManagerLocal groupManager = LookupUtil.getResourceGroupManager();
- public Configuration getPluginConfiguration(int resourceId) { + public Configuration getPluginConfiguration(int resourceId) throws RuntimeException { try { Configuration configuration = configurationManager.getPluginConfiguration(getSessionSubject(), resourceId); return SerialUtility.prepare(configuration, "PluginConfiguration"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public ConfigurationDefinition getPluginConfigurationDefinition(int resourceTypeId) { + public ConfigurationDefinition getPluginConfigurationDefinition(int resourceTypeId) throws RuntimeException { try { ConfigurationDefinition definition = configurationManager.getPluginConfigurationDefinitionForResourceType( getSessionSubject(), resourceTypeId); return SerialUtility.prepare(definition, "PluginDefinition"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Configuration getResourceConfiguration(int resourceId) { + public Configuration getResourceConfiguration(int resourceId) throws RuntimeException { try { Configuration configuration = configurationManager .getResourceConfiguration(getSessionSubject(), resourceId); return SerialUtility.prepare(configuration, "ResourceConfiguration"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public ConfigurationDefinition getResourceConfigurationDefinition(int resourceTypeId) { + public ConfigurationDefinition getResourceConfigurationDefinition(int resourceTypeId) throws RuntimeException { try { ConfigurationDefinition definition = configurationManager .getResourceConfigurationDefinitionWithTemplatesForResourceType(getSessionSubject(), resourceTypeId); return SerialUtility.prepare(definition, "ResourceDefinition"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdates(Integer resourceId, Long beginDate, - Long endDate, boolean suppressOldest, PageControl pc) { + Long endDate, boolean suppressOldest, PageControl pc) throws RuntimeException { 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)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public ResourceConfigurationUpdate updateResourceConfiguration(int resourceId, Configuration configuration) { + public ResourceConfigurationUpdate updateResourceConfiguration(int resourceId, Configuration configuration) + throws RuntimeException { try { ResourceConfigurationUpdate update = configurationManager.updateResourceConfiguration(getSessionSubject(), resourceId, configuration); return SerialUtility.prepare(update, "ConfigurationService.updateResourceConfiguration"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PluginConfigurationUpdate updatePluginConfiguration(int resourceId, Configuration configuration) { + public PluginConfigurationUpdate updatePluginConfiguration(int resourceId, Configuration configuration) + throws RuntimeException { try { PluginConfigurationUpdate update = configurationManager.updatePluginConfiguration(getSessionSubject(), resourceId, configuration); return SerialUtility.prepare(update, "ConfigurationService.updatePluginConfiguration"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdatesByCriteria( - ResourceConfigurationUpdateCriteria criteria) { + ResourceConfigurationUpdateCriteria criteria) throws RuntimeException { try { PageList<ResourceConfigurationUpdate> updates = configurationManager .findResourceConfigurationUpdatesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(updates, "ConfigurationService.findResourceConfigurationUpdatesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<PluginConfigurationUpdate> findPluginConfigurationUpdatesByCriteria( - PluginConfigurationUpdateCriteria criteria) { + PluginConfigurationUpdateCriteria criteria) throws RuntimeException { try { PageList<PluginConfigurationUpdate> updates = configurationManager .findPluginConfigurationUpdatesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(updates, "ConfigurationService.findPluginConfigurationUpdatesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<GroupResourceConfigurationUpdate> findGroupResourceConfigurationUpdatesByCriteria( - GroupResourceConfigurationUpdateCriteria criteria) { + GroupResourceConfigurationUpdateCriteria criteria) throws RuntimeException { try { PageList<GroupResourceConfigurationUpdate> updates = configurationManager .findGroupResourceConfigurationUpdatesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(updates, "ConfigurationService.findGroupResourceConfigurationUpdatesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<GroupPluginConfigurationUpdate> findGroupPluginConfigurationUpdatesByCriteria( - GroupPluginConfigurationUpdateCriteria criteria) { + GroupPluginConfigurationUpdateCriteria criteria) throws RuntimeException { try { PageList<GroupPluginConfigurationUpdate> updates = configurationManager .findGroupPluginConfigurationUpdatesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(updates, "ConfigurationService.findGroupPluginConfigurationUpdatesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup(int groupId) { + public List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup(int groupId) + throws RuntimeException { try { ResourceGroup group = this.groupManager.getResourceGroup(getSessionSubject(), groupId); Map<Integer, Configuration> configurations = this.configurationManager @@ -176,12 +179,13 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen
return SerialUtility.prepare(disambiguatedConfigurationComposites, "ConfigurationService.findResourceConfigurationsForGroup"); - } catch (RuntimeException e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroup(int groupId) { + public List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroup(int groupId) + throws RuntimeException { try { Map<Integer, Configuration> configurations = this.configurationManager .getPluginConfigurationsForCompatibleGroup(getSessionSubject(), groupId); @@ -194,13 +198,13 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen
return SerialUtility.prepare(disambiguatedConfigurationComposites, "ConfigurationService.findPluginConfigurationsForGroup"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroupUpdate( - int groupUpdateId) { + int groupUpdateId) throws RuntimeException { try { Map<Integer, Configuration> configurations = this.configurationManager .getPluginConfigurationMapForGroupUpdate(groupUpdateId); @@ -213,76 +217,81 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen
return SerialUtility.prepare(disambiguatedConfigurationComposites, "ConfigurationService.findPluginConfigurationsForGroupUpdate"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public void updateResourceConfigurationsForGroup(int groupId, - List<ResourceConfigurationComposite> resourceConfigurations) { + List<ResourceConfigurationComposite> resourceConfigurations) throws RuntimeException { try { Map<Integer, Configuration> configurations = convertToMap(resourceConfigurations); this.configurationManager.scheduleGroupResourceConfigurationUpdate(getSessionSubject(), groupId, configurations); - } catch (RuntimeException e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public void updatePluginConfigurationsForGroup(int groupId, - List<ResourceConfigurationComposite> pluginConfigurations) { + List<ResourceConfigurationComposite> pluginConfigurations) throws RuntimeException { try { Map<Integer, Configuration> configurations = convertToMap(pluginConfigurations); this.configurationManager.scheduleGroupPluginConfigurationUpdate(getSessionSubject(), groupId, configurations); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteGroupPluginConfigurationUpdate(Integer groupId, Integer[] groupPluginConfigUpdateIds) { + public void deleteGroupPluginConfigurationUpdate(Integer groupId, Integer[] groupPluginConfigUpdateIds) + throws RuntimeException { try { this.configurationManager.deleteGroupPluginConfigurationUpdates(getSessionSubject(), groupId, groupPluginConfigUpdateIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteGroupResourceConfigurationUpdate(Integer groupId, Integer[] groupResourceConfigUpdateIds) { + public void deleteGroupResourceConfigurationUpdate(Integer groupId, Integer[] groupResourceConfigUpdateIds) + throws RuntimeException { try { this.configurationManager.deleteGroupResourceConfigurationUpdates(getSessionSubject(), groupId, groupResourceConfigUpdateIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- /* - // Dummy method for gwt compiler - public RawConfiguration dummy(RawConfiguration config) { - Log.info(config.getPath()); - return new RawConfiguration(); - } - */ - - 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); + private List<ResourceConfigurationComposite> convertToCompositesList(Map<Integer, Configuration> configurations) + throws RuntimeException { + try { + 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; + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } - 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()); + private Map<Integer, Configuration> convertToMap(List<ResourceConfigurationComposite> resourceConfigurations) + throws RuntimeException { + try { + Map<Integer, Configuration> configurations = new HashMap<Integer, Configuration>(resourceConfigurations + .size()); + for (ResourceConfigurationComposite resourceConfiguration : resourceConfigurations) { + configurations.put(resourceConfiguration.getResourceId(), resourceConfiguration.getConfiguration()); + } + return configurations; + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } - return configurations; } } 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 cc9c288..3df2f0b 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 @@ -33,7 +33,6 @@ 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; -import org.rhq.enterprise.server.content.ContentUIManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -44,50 +43,52 @@ public class ContentGWTServiceImpl extends AbstractGWTServiceImpl implements Con private static final long serialVersionUID = 1L;
private ContentManagerLocal contentManager = LookupUtil.getContentManager(); - private ContentUIManagerLocal contentUiManager = LookupUtil.getContentUIManager();
- public void deletePackageVersion(int packageVersionId) { + //private ContentUIManagerLocal contentUiManager = LookupUtil.getContentUIManager(); + + public void deletePackageVersion(int packageVersionId) throws RuntimeException { try { contentManager.deletePackageVersion(getSessionSubject(), packageVersionId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<PackageVersion> findPackageVersionsByCriteria(PackageVersionCriteria criteria) { + public PageList<PackageVersion> findPackageVersionsByCriteria(PackageVersionCriteria criteria) + throws RuntimeException { try { return SerialUtility.prepare(contentManager.findPackageVersionsByCriteria(getSessionSubject(), criteria), "ContentService.findPackageVersionsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- // public PageList<InstalledPackageHistory> getInstalledPackageHistoryForResource(int resourceId, int count) { + // public PageList<InstalledPackageHistory> getInstalledPackageHistoryForResource(int resourceId, int count) throws RuntimeException { // try { // PageControl pc = new PageControl(0, count); // return SerialUtility.prepare(contentUiManager.getInstalledPackageHistoryForResource(resourceId, pc), // "ContentService.getInstalledPackageHistoryForResource"); - // } catch (Exception e) { - // throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + // } catch (Throwable t) { + // throw new RuntimeException(ThrowableUtil.getAllMessages(t)); // } // }
- public List<Architecture> getArchitectures() { + public List<Architecture> getArchitectures() throws RuntimeException { try { return SerialUtility.prepare(contentManager.findArchitectures(getSessionSubject()), "ContentService.getArchitectures"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PackageType getResourceCreationPackageType(int resourceTypeId) { + public PackageType getResourceCreationPackageType(int resourceTypeId) throws RuntimeException { try { return SerialUtility.prepare(contentManager.getResourceCreationPackageType(resourceTypeId), "ContentService.getResourceCreationPackageType"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/DashboardGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DashboardGWTServiceImpl.java index 742c68e..c45ca10 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 @@ -40,38 +40,38 @@ public class DashboardGWTServiceImpl extends AbstractGWTServiceImpl implements D
private DashboardManagerLocal dashboardManager = LookupUtil.getDashboardManagerLocal();
- public List<Dashboard> findDashboardsForSubject() { + public List<Dashboard> findDashboardsForSubject() throws RuntimeException { try { return SerialUtility.prepare(dashboardManager.findDashboardsForSubject(getSessionSubject()), "DashboardManager.findDashboardsForSubject"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<Dashboard> findSharedDashboards() { + public List<Dashboard> findSharedDashboards() throws RuntimeException { try { return SerialUtility.prepare(dashboardManager.findSharedDashboards(getSessionSubject()), "DashboardManager.findSharedDashboards"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Dashboard storeDashboard(Dashboard dashboard) { + public Dashboard storeDashboard(Dashboard dashboard) throws RuntimeException { try { return SerialUtility.prepare(dashboardManager.storeDashboard(getSessionSubject(), dashboard), "DashboardManager.storeDashboard"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void removeDashboard(int dashboardId) { + public void removeDashboard(int dashboardId) throws RuntimeException { try { dashboardManager.removeDashboard(getSessionSubject(), dashboardId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/EventGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/EventGWTServiceImpl.java index 6369c90..9654a9d 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 @@ -46,32 +46,34 @@ public class EventGWTServiceImpl extends AbstractGWTServiceImpl implements Event
private EventManagerLocal eventManager = LookupUtil.getEventManager();
- public EventSeverity[] getSeverityBuckets(int resourceId, long begin, long end, int numBuckets) { + public EventSeverity[] getSeverityBuckets(int resourceId, long begin, long end, int numBuckets) + throws RuntimeException { try { return SerialUtility.prepare(eventManager.getSeverityBuckets(getSessionSubject(), resourceId, begin, end, numBuckets), "EventService.getSeverityBuckets"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public EventSeverity[] getSeverityBucketsForAutoGroup(int parentResourceId, int resourceTypeId, long begin, - long end, int numBuckets) { + long end, int numBuckets) throws RuntimeException { try { return SerialUtility.prepare(eventManager.getSeverityBucketsForAutoGroup(getSessionSubject(), parentResourceId, resourceTypeId, begin, end, numBuckets), "EventService.getSeverityBucketsForAutoGroup"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public EventSeverity[] getSeverityBucketsForCompGroup(int resourceGroupId, long begin, long end, int numBuckets) { + public EventSeverity[] getSeverityBucketsForCompGroup(int resourceGroupId, long begin, long end, int numBuckets) + throws RuntimeException { try { return SerialUtility.prepare(eventManager.getSeverityBucketsForCompGroup(getSessionSubject(), resourceGroupId, begin, end, numBuckets), "EventService.getSeverityBucketsForCompGroup"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -84,37 +86,37 @@ public class EventGWTServiceImpl extends AbstractGWTServiceImpl implements Event // } // }
- public PageList<Event> findEventsByCriteria(EventCriteria criteria) { + public PageList<Event> findEventsByCriteria(EventCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(eventManager.findEventsByCriteria(getSessionSubject(), criteria), "EventService.findEventsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<EventComposite> findEventCompositesByCriteria(EventCriteria criteria) { + public PageList<EventComposite> findEventCompositesByCriteria(EventCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(eventManager.findEventCompositesByCriteria(getSessionSubject(), criteria), "EventService.findEventsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int deleteEventsForContext(EntityContext context, List<Integer> eventIds) { + public int deleteEventsForContext(EntityContext context, List<Integer> eventIds) throws RuntimeException { try { return eventManager.deleteEventsForContext(getSessionSubject(), context, eventIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int purgeEventsForContext(EntityContext context) { + public int purgeEventsForContext(EntityContext context) throws RuntimeException { try { return eventManager.purgeEventsForContext(getSessionSubject(), context); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/GroupAlertDefinitionGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/GroupAlertDefinitionGWTServiceImpl.java index 7b65ee2..38a076b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/GroupAlertDefinitionGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/GroupAlertDefinitionGWTServiceImpl.java @@ -33,58 +33,58 @@ public class GroupAlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl i
@Override public int createGroupAlertDefinitions(AlertDefinition groupAlertDefinition, Integer resourceGroupId) - throws Exception { + throws RuntimeException { try { int results = groupAlertDefManager.createGroupAlertDefinitions(getSessionSubject(), groupAlertDefinition, resourceGroupId); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override public AlertDefinition updateGroupAlertDefinitions(AlertDefinition groupAlertDefinition, boolean purgeInternals) - throws Exception { + throws RuntimeException { try { AlertDefinition results = groupAlertDefManager.updateGroupAlertDefinitions(getSessionSubject(), groupAlertDefinition, purgeInternals); return SerialUtility.prepare(results, "updateGroupAlertDefinitions"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int enableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws Exception { + public int enableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws RuntimeException { try { int results = groupAlertDefManager .enableGroupAlertDefinitions(getSessionSubject(), groupAlertDefinitionIds); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int disableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws Exception { + public int disableGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws RuntimeException { try { int results = groupAlertDefManager.disableGroupAlertDefinitions(getSessionSubject(), groupAlertDefinitionIds); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public int removeGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws Exception { + public int removeGroupAlertDefinitions(Integer[] groupAlertDefinitionIds) throws RuntimeException { try { int results = groupAlertDefManager .removeGroupAlertDefinitions(getSessionSubject(), groupAlertDefinitionIds); return results; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/LdapGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/LdapGWTServiceImpl.java index 5969954..6e3363e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/LdapGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/LdapGWTServiceImpl.java @@ -19,7 +19,6 @@ 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 java.util.Set; @@ -57,11 +56,12 @@ public class LdapGWTServiceImpl extends AbstractGWTServiceImpl implements LdapGW private final Log log = LogFactory.getLog(LdapGWTServiceImpl.class);
@Override - public Set<Map<String, String>> findAvailableGroups() { - //add permissions check - Set<Permission> globalPermissions = authorizationManager.getExplicitGlobalPermissions(getSessionSubject()); - Boolean accessGranted = globalPermissions.contains(Permission.MANAGE_SECURITY); + public Set<Map<String, String>> findAvailableGroups() throws RuntimeException { try { + //add permissions check + Set<Permission> globalPermissions = authorizationManager.getExplicitGlobalPermissions(getSessionSubject()); + Boolean accessGranted = globalPermissions.contains(Permission.MANAGE_SECURITY); + Set<Map<String, String>> results = null; if (accessGranted) { results = ldapManager.findAvailableGroups(); @@ -77,11 +77,12 @@ public class LdapGWTServiceImpl extends AbstractGWTServiceImpl implements LdapGW } }
- public void setLdapGroupsForRole(int roleId, List<String> groupIds) { - //add permissions check - Set<Permission> globalPermissions = authorizationManager.getExplicitGlobalPermissions(getSessionSubject()); - Boolean accessGranted = globalPermissions.contains(Permission.MANAGE_SECURITY); + public void setLdapGroupsForRole(int roleId, List<String> groupIds) throws RuntimeException { try { + //add permissions check + Set<Permission> globalPermissions = authorizationManager.getExplicitGlobalPermissions(getSessionSubject()); + Boolean accessGranted = globalPermissions.contains(Permission.MANAGE_SECURITY); + if (accessGranted) { //clean out existing roles as this defines the new list of roles PageList<LdapGroup> existing = ldapManager.findLdapGroupsByRole(roleId, PageControl @@ -122,13 +123,12 @@ public class LdapGWTServiceImpl extends AbstractGWTServiceImpl implements LdapGW } }
- @Override - public PageList<LdapGroup> findLdapGroupsAssignedToRole(int roleId) { - //add permissions check - Set<Permission> globalPermissions = authorizationManager.getExplicitGlobalPermissions(getSessionSubject()); - Boolean accessGranted = globalPermissions.contains(Permission.MANAGE_SECURITY); - + public PageList<LdapGroup> findLdapGroupsAssignedToRole(int roleId) throws RuntimeException { try { + //add permissions check + Set<Permission> globalPermissions = authorizationManager.getExplicitGlobalPermissions(getSessionSubject()); + Boolean accessGranted = globalPermissions.contains(Permission.MANAGE_SECURITY); + PageList<LdapGroup> allAssignedLdapGroups = null; if (accessGranted) { allAssignedLdapGroups = ldapManager.findLdapGroupsByRole(roleId, PageControl.getUnlimitedInstance()); @@ -144,32 +144,26 @@ public class LdapGWTServiceImpl extends AbstractGWTServiceImpl implements LdapGW } }
- /**Light call to determine ldap configuration status. - * + /** + * Light call to determine ldap configuration status. */ - @Override - public Boolean checkLdapConfiguredStatus() { - Boolean ldapEnabled = false; + public Boolean checkLdapConfiguredStatus() throws RuntimeException { try { String provider = systemManager.getSystemConfiguration().getProperty(RHQConstants.JAASProvider); - ldapEnabled = ((provider != null) && provider.equals(RHQConstants.LDAPJAASProvider)); + return ((provider != null) && provider.equals(RHQConstants.LDAPJAASProvider)); } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } - return ldapEnabled; }
- /**Returns all LDAP details for a given user, using the configured ldap details of server. - * + /** + * Returns all LDAP details for a given user, using the configured ldap details of server. */ - @Override - public Map<String, String> getLdapDetailsFor(String user) { - Map<String, String> ldapDetails = new HashMap<String, String>(); + public Map<String, String> getLdapDetailsFor(String user) throws RuntimeException { try { - ldapDetails = ldapManager.findLdapUserDetails(user); + return ldapManager.findLdapUserDetails(user); } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } - return ldapDetails; } } \ No newline at end of file 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 0a83095..5ac43c3 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 @@ -60,179 +60,189 @@ public class MeasurementDataGWTServiceImpl extends AbstractGWTServiceImpl implem private MeasurementScheduleManagerLocal scheduleManager = LookupUtil.getMeasurementScheduleManager(); private MeasurementDefinitionManagerLocal definitionManager = LookupUtil.getMeasurementDefinitionManager();
- public List<MeasurementDataTrait> findCurrentTraitsForResource(int resourceId, DisplayType displayType) { + public List<MeasurementDataTrait> findCurrentTraitsForResource(int resourceId, DisplayType displayType) + throws RuntimeException { try { return SerialUtility.prepare(dataManager.findCurrentTraitsForResource(getSessionSubject(), resourceId, displayType), "MeasurementDataService.findCurrentTraitsForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Set<MeasurementData> findLiveData(int resourceId, int[] definitionIds) { + public Set<MeasurementData> findLiveData(int resourceId, int[] definitionIds) throws RuntimeException { try { return SerialUtility.prepare(dataManager.findLiveData(getSessionSubject(), resourceId, definitionIds), "MeasurementDataService.findLiveData"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public List<List<MeasurementDataNumericHighLowComposite>> findDataForResource(int resourceId, int[] definitionIds, - long beginTime, long endTime, int numPoints) { + long beginTime, long endTime, int numPoints) throws RuntimeException { try { return SerialUtility.prepare(dataManager.findDataForResource(getSessionSubject(), resourceId, definitionIds, beginTime, endTime, numPoints), "MeasurementDataService.findDataForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<CallTimeDataComposite> findCallTimeDataForResource(int scheduleId, long start, long end, - PageControl pageControl) { + PageControl pageControl) throws RuntimeException { try { return SerialUtility.prepare(callTimeDataManager.findCallTimeDataForResource(getSessionSubject(), scheduleId, start, end, pageControl), "MeasurementDataService.findCallTimeDataForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<MeasurementDefinition> findMeasurementDefinitionsByCriteria(MeasurementDefinitionCriteria criteria) { + public PageList<MeasurementDefinition> findMeasurementDefinitionsByCriteria(MeasurementDefinitionCriteria criteria) + throws RuntimeException { try { return SerialUtility.prepare(definitionManager.findMeasurementDefinitionsByCriteria(getSessionSubject(), criteria), "MeasurementDataService.findMeasurementDefinintionsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<MeasurementSchedule> findMeasurementSchedulesByCriteria(MeasurementScheduleCriteria criteria) { + public PageList<MeasurementSchedule> findMeasurementSchedulesByCriteria(MeasurementScheduleCriteria criteria) + throws RuntimeException { try { return SerialUtility.prepare(scheduleManager.findSchedulesByCriteria(getSessionSubject(), criteria), "MeasurementDataService.findMeasurementSchedulesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<MeasurementScheduleComposite> getMeasurementScheduleCompositesByContext(EntityContext context) { + public PageList<MeasurementScheduleComposite> getMeasurementScheduleCompositesByContext(EntityContext context) + throws RuntimeException { try { return SerialUtility.prepare(scheduleManager.getMeasurementScheduleCompositesByContext(getSessionSubject(), context, PageControl.getUnlimitedInstance()), "MeasurementDataService.getMeasurementScheduleCompositesByContext"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, String resourceNameFilter, - String parentNameFilter, PageControl pc) { + String parentNameFilter, PageControl pc) throws RuntimeException { try { return SerialUtility.prepare(measurementOOBManager.getSchedulesWithOOBs(getSessionSubject(), metricNameFilter, resourceNameFilter, parentNameFilter, pc), "MeasurementDataService.getSchedulesWithOOBs"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<MeasurementOOBComposite> getHighestNOOBsForResource(int resourceId, int n) { + public PageList<MeasurementOOBComposite> getHighestNOOBsForResource(int resourceId, int n) throws RuntimeException { try { return SerialUtility.prepare(measurementOOBManager.getHighestNOOBsForResource(getSessionSubject(), resourceId, n), "MeasurementDataService.getHighestNOOBsForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void enableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) { + public void enableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) throws RuntimeException { try { scheduleManager.enableSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void disableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) { + public void disableSchedulesForResource(int resourceId, int[] measurementDefinitionIds) throws RuntimeException { try { scheduleManager.disableSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateSchedulesForResource(int resourceId, int[] measurementDefinitionIds, long collectionInterval) { + public void updateSchedulesForResource(int resourceId, int[] measurementDefinitionIds, long collectionInterval) + throws RuntimeException { try { scheduleManager.updateSchedulesForResource(getSessionSubject(), resourceId, measurementDefinitionIds, collectionInterval); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void enableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) { + public void enableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) + throws RuntimeException { try { scheduleManager.enableSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, measurementDefinitionIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void disableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) { + public void disableSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds) + throws RuntimeException { try { scheduleManager.disableSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, measurementDefinitionIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public void updateSchedulesForCompatibleGroup(int resourceGroupId, int[] measurementDefinitionIds, - long collectionInterval) { + long collectionInterval) throws RuntimeException { try { scheduleManager.updateSchedulesForCompatibleGroup(getSessionSubject(), resourceGroupId, measurementDefinitionIds, collectionInterval); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void enableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules) { + public void enableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules) + throws RuntimeException { try { scheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(getSessionSubject(), measurementDefinitionIds, 0, updateExistingSchedules); - } catch (RuntimeException e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void disableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules) { + public void disableSchedulesForResourceType(int[] measurementDefinitionIds, boolean updateExistingSchedules) + throws RuntimeException { try { scheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(getSessionSubject(), measurementDefinitionIds, -1, updateExistingSchedules); - } catch (RuntimeException e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public void updateSchedulesForResourceType(int[] measurementDefinitionIds, long collectionInterval, - boolean updateExistingSchedules) { + boolean updateExistingSchedules) throws RuntimeException { try { scheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(getSessionSubject(), measurementDefinitionIds, collectionInterval, updateExistingSchedules); - } catch (RuntimeException e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<MeasurementDataTrait> findTraitsByCriteria(MeasurementDataTraitCriteria criteria) { + public PageList<MeasurementDataTrait> findTraitsByCriteria(MeasurementDataTraitCriteria criteria) + throws RuntimeException { try { return SerialUtility.prepare(dataManager.findTraitsByCriteria(getSessionSubject(), criteria), "MeasurementDataService.findTraitsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/OperationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/OperationGWTServiceImpl.java index a51ed3f..8d15f3c 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 @@ -52,21 +52,22 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O private ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
public PageList<ResourceOperationHistory> findResourceOperationHistoriesByCriteria( - ResourceOperationHistoryCriteria criteria) { + ResourceOperationHistoryCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(operationManager.findResourceOperationHistoriesByCriteria(getSessionSubject(), criteria), "OperationService.findResourceOperationHistoriesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<GroupOperationHistory> findGroupOperationHistoriesByCriteria(GroupOperationHistoryCriteria criteria) { + public PageList<GroupOperationHistory> findGroupOperationHistoriesByCriteria(GroupOperationHistoryCriteria criteria) + throws RuntimeException { try { return SerialUtility.prepare(operationManager.findGroupOperationHistoriesByCriteria(getSessionSubject(), criteria), "OperationService.findGroupOperationHistoriesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -75,8 +76,8 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O try { ResourceOperationSchedule opSchedule = operationManager.scheduleResourceOperation(getSessionSubject(), resourceId, operationName, 0, 0, 0, 0, parameters, description); - } catch (Exception e) { - throw new RuntimeException("Unable to invoke operation: " + e.getMessage()); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -86,9 +87,8 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O CronTrigger ct = new CronTrigger("resource " + resourceId + "_" + operationName, "group", cronString); ResourceOperationSchedule opSchedule = operationManager.scheduleResourceOperation(getSessionSubject(), resourceId, operationName, parameters, ct, description); - - } catch (Exception e) { - throw new RuntimeException("Unable to schedule operation execution: " + e.getMessage()); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -96,7 +96,7 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O * */ public List<DisambiguationReport<ResourceOperationLastCompletedComposite>> findRecentCompletedOperations( - int pageSize) { + int pageSize) throws RuntimeException { try { PageControl pageControl = new PageControl(0, pageSize); PageList<ResourceOperationLastCompletedComposite> lastCompletedResourceOps = operationManager @@ -108,15 +108,16 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O DefaultDisambiguationUpdateStrategies.getDefault());
return disambiguatedLastCompletedResourceOps; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
/** Find scheduled operations, disambiguate them and return that list. * */ - public List<DisambiguationReport<ResourceOperationScheduleComposite>> findScheduledOperations(int pageSize) { + public List<DisambiguationReport<ResourceOperationScheduleComposite>> findScheduledOperations(int pageSize) + throws RuntimeException { try { PageControl pageControl = new PageControl(0, pageSize); PageList<ResourceOperationScheduleComposite> scheduledResourceOps = operationManager @@ -128,30 +129,28 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O DefaultDisambiguationUpdateStrategies.getDefault());
return disambiguatedNextScheduledResourceOps; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public List<ResourceOperationSchedule> findScheduledResourceOperations(int resourceId) throws RuntimeException { try { - List<ResourceOperationSchedule> resourceOperationSchedules = - operationManager.findScheduledResourceOperations(getSessionSubject(), resourceId); + List<ResourceOperationSchedule> resourceOperationSchedules = operationManager + .findScheduledResourceOperations(getSessionSubject(), resourceId); return SerialUtility.prepare(resourceOperationSchedules, "findScheduledResourceOperations"); - } - catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public List<GroupOperationSchedule> findScheduledGroupOperations(int groupId) throws RuntimeException { try { - List<GroupOperationSchedule> groupOperationSchedules = - operationManager.findScheduledGroupOperations(getSessionSubject(), groupId); + List<GroupOperationSchedule> groupOperationSchedules = operationManager.findScheduledGroupOperations( + getSessionSubject(), groupId); return SerialUtility.prepare(groupOperationSchedules, "findScheduledGroupOperations"); - } - catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/RemoteInstallGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RemoteInstallGWTServiceImpl.java index f29598f..b397c15 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RemoteInstallGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RemoteInstallGWTServiceImpl.java @@ -38,66 +38,67 @@ public class RemoteInstallGWTServiceImpl extends AbstractGWTServiceImpl implemen
private RemoteInstallManagerLocal remoteInstallManager = LookupUtil.getRemoteInstallManager();
- public boolean agentInstallCheck(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) { + public boolean agentInstallCheck(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) + throws RuntimeException { try { return SerialUtility.prepare(remoteInstallManager.agentInstallCheck(getSessionSubject(), remoteAccessInfo, agentInstallPath), "RemoteInstallService.agentInstallCheck"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public AgentInstallInfo installAgent(RemoteAccessInfo remoteAccessInfo, String parentPath) { + public AgentInstallInfo installAgent(RemoteAccessInfo remoteAccessInfo, String parentPath) throws RuntimeException { try { return SerialUtility.prepare(remoteInstallManager.installAgent(getSessionSubject(), remoteAccessInfo, parentPath), "RemoteInstallService.installAgent"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public String startAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) { + public String startAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException { try { return SerialUtility.prepare(remoteInstallManager.startAgent(getSessionSubject(), remoteAccessInfo, agentInstallPath), "RemoteInstallService.startAgent"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public String stopAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) { + public String stopAgent(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException { try { return SerialUtility.prepare(remoteInstallManager.stopAgent(getSessionSubject(), remoteAccessInfo, agentInstallPath), "RemoteInstallService.stopAgent"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public String agentStatus(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) { + public String agentStatus(RemoteAccessInfo remoteAccessInfo, String agentInstallPath) throws RuntimeException { try { return SerialUtility.prepare(remoteInstallManager.agentStatus(getSessionSubject(), remoteAccessInfo, agentInstallPath), "RemoteInstallService.agentStatus"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public String findAgentInstallPath(RemoteAccessInfo remoteAccessInfo, String parentPath) { + public String findAgentInstallPath(RemoteAccessInfo remoteAccessInfo, String parentPath) throws RuntimeException { try { return SerialUtility.prepare((remoteInstallManager.findAgentInstallPath(getSessionSubject(), remoteAccessInfo, parentPath)), "RemoteInstallService.findAgentInstallPath"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public String[] remotePathDiscover(RemoteAccessInfo remoteAccessInfo, String parentPath) { + public String[] remotePathDiscover(RemoteAccessInfo remoteAccessInfo, String parentPath) throws RuntimeException { try { return SerialUtility.prepare((remoteInstallManager.remotePathDiscover(getSessionSubject(), remoteAccessInfo, parentPath)), "RemoteInstallService.remotePathDiscover"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/RepoGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/RepoGWTServiceImpl.java index 98c26cc..100289c 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 @@ -40,12 +40,12 @@ public class RepoGWTServiceImpl extends AbstractGWTServiceImpl implements RepoGW
private RepoManagerLocal repoManager = LookupUtil.getRepoManagerLocal();
- public PageList<Repo> findReposByCriteria(RepoCriteria criteria) throws Exception { + public PageList<Repo> findReposByCriteria(RepoCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(repoManager.findReposByCriteria(getSessionSubject(), criteria), "RepoService.findReposByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/ResourceBossGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceBossGWTServiceImpl.java index fb00c3a..046443d 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 @@ -44,11 +44,11 @@ public class ResourceBossGWTServiceImpl extends AbstractGWTServiceImpl implement return getInventorySummary(subject); }
- public InventorySummary getInventorySummary(Subject user) { + public InventorySummary getInventorySummary(Subject user) throws RuntimeException { try { return resourceBoss.getInventorySummary(user); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index 105963c..c2b7ab4 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 @@ -110,6 +110,12 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re
private static Set<String> importantFieldsSet = new HashSet<String>(Arrays.asList(importantFields));
+ private static final IntExtractor<ProblemResourceComposite> RESOURCE_ID_EXTRACTOR = new IntExtractor<ProblemResourceComposite>() { + public int extract(ProblemResourceComposite object) { + return object.getResourceId(); + } + }; + @Override public void init(ServletConfig config) throws ServletException { super.init(config); @@ -119,19 +125,20 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re public ResourceGWTServiceImpl() { }
- public PageList<Resource> findResourcesByCriteria(ResourceCriteria criteria) { + public PageList<Resource> findResourcesByCriteria(ResourceCriteria criteria) throws RuntimeException { try { PageList<Resource> result = resourceManager.findResourcesByCriteria(getSessionSubject(), criteria);
ObjectFilter.filterFieldsInCollection(result, importantFieldsSet);
return SerialUtility.prepare(result, "ResourceService.findResourcesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<ResourceComposite> findResourceCompositesByCriteria(ResourceCriteria criteria) { + public PageList<ResourceComposite> findResourceCompositesByCriteria(ResourceCriteria criteria) + throws RuntimeException { try { PageList<ResourceComposite> result = resourceManager.findResourceCompositesByCriteria(getSessionSubject(), criteria); @@ -142,15 +149,16 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re }
return SerialUtility.prepare(result, "ResourceService.findResourceCompositesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
/** Locate ProblemResourcesComposites and generate the disambiguation reports for them. * Criteria passed in not currently used. */ - public List<DisambiguationReport<ProblemResourceComposite>> findProblemResources(long ctime, int maxItems) { + public List<DisambiguationReport<ProblemResourceComposite>> findProblemResources(long ctime, int maxItems) + throws RuntimeException { try { List<ProblemResourceComposite> located = new ArrayList<ProblemResourceComposite>(); MeasurementProblemManagerLocal problemManager = LookupUtil.getMeasurementProblemManager(); @@ -163,38 +171,33 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re List<DisambiguationReport<ProblemResourceComposite>> translated = resourceManager.disambiguate(located, RESOURCE_ID_EXTRACTOR, DefaultDisambiguationUpdateStrategies.getDefault()); return translated; - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- private static final IntExtractor<ProblemResourceComposite> RESOURCE_ID_EXTRACTOR = new IntExtractor<ProblemResourceComposite>() { - public int extract(ProblemResourceComposite object) { - return object.getResourceId(); - } - }; - - public List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId) { + public List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId) throws RuntimeException { try { return SerialUtility.prepare( resourceManager.getResourceLineageAndSiblings(getSessionSubject(), resourceId), "ResourceService.getResourceLineageAndSiblings");
- } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Resource getPlatformForResource(int resourceId) { + public Resource getPlatformForResource(int resourceId) throws RuntimeException { try { return SerialUtility.prepare(resourceManager.getRootResourceForResource(resourceId), "ResourceService.getPlatformForResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<RecentlyAddedResourceComposite> findRecentlyAddedResources(long ctime, int maxItems) { + public List<RecentlyAddedResourceComposite> findRecentlyAddedResources(long ctime, int maxItems) + throws RuntimeException { try { List<RecentlyAddedResourceComposite> platforms = resourceManager.findRecentlyAddedPlatforms( getSessionSubject(), ctime, maxItems); @@ -206,32 +209,31 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re }
return SerialUtility.prepare(platforms, "ResourceService.findRecentlyAddedResources"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<Integer> uninventoryResources(int[] resourceIds) { + public List<Integer> uninventoryResources(int[] resourceIds) throws RuntimeException { try { return SerialUtility.prepare(resourceManager.uninventoryResources(getSessionSubject(), resourceIds), "ResourceService.uninventoryResources"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateResource(Resource resource) { + public void updateResource(Resource resource) throws RuntimeException { try { resourceManager.updateResource(getSessionSubject(), resource); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public void createResource(int parentResourceId, int newResourceTypeId, String newResourceName, - Configuration newResourceConfiguration) { + Configuration newResourceConfiguration) throws RuntimeException { try { - ConfigurationDefinition pluginConfigDefinition = LookupUtil.getConfigurationManager() .getPluginConfigurationDefinitionForResourceType(getSessionSubject(), newResourceTypeId); Configuration pluginConfig = null; @@ -246,15 +248,14 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re
resourceFactoryManager.createResource(getSessionSubject(), parentResourceId, newResourceTypeId, newResourceName, pluginConfig, newResourceConfiguration); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
public void createResource(int parentResourceId, int newResourceTypeId, String newResourceName, - Configuration deploymentTimeConfiguration, int packageVersionId) { + Configuration deploymentTimeConfiguration, int packageVersionId) throws RuntimeException { try { - ConfigurationDefinition pluginConfigDefinition = LookupUtil.getConfigurationManager() .getPluginConfigurationDefinitionForResourceType(getSessionSubject(), newResourceTypeId); Configuration pluginConfig = null; @@ -269,65 +270,71 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re
resourceFactoryManager.createPackageBackedResourceViaPackageVersion(getSessionSubject(), parentResourceId, newResourceTypeId, newResourceName, pluginConfig, deploymentTimeConfiguration, packageVersionId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<DeleteResourceHistory> deleteResources(int[] resourceIds) { + public List<DeleteResourceHistory> deleteResources(int[] resourceIds) throws RuntimeException { try { return SerialUtility.prepare(resourceFactoryManager.deleteResources(getSessionSubject(), resourceIds), "ResourceService.deleteResources"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Map<Resource, List<Resource>> getQueuedPlatformsAndServers(HashSet<InventoryStatus> statuses, PageControl pc) { + public Map<Resource, List<Resource>> getQueuedPlatformsAndServers(HashSet<InventoryStatus> statuses, PageControl pc) + throws RuntimeException { try { return SerialUtility.prepare(discoveryBoss.getQueuedPlatformsAndServers(getSessionSubject(), EnumSet .copyOf(statuses), pc), "ResourceService.getQueuedPlatformsAndServers"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void importResources(int[] resourceIds) { + public void importResources(int[] resourceIds) throws RuntimeException { try { discoveryBoss.importResources(getSessionSubject(), resourceIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void ignoreResources(int[] resourceIds) { + public void ignoreResources(int[] resourceIds) throws RuntimeException { try { discoveryBoss.ignoreResources(getSessionSubject(), resourceIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void unignoreResources(int[] resourceIds) { + public void unignoreResources(int[] resourceIds) throws RuntimeException { try { discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<ResourceError> findResourceErrors(int resourceId) { - return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), - "ResourceService.getResourceErrors"); + public List<ResourceError> findResourceErrors(int resourceId) throws RuntimeException { + try { + return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), + "ResourceService.getResourceErrors"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } }
- public Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration) { + public Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration) + throws RuntimeException { try { Resource result = discoveryBoss.manuallyAddResource(getSessionSubject(), resourceTypeId, parentResourceId, pluginConfiguration); return SerialUtility.prepare(result, "ResourceService.manuallyAddResource"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/ResourceGroupGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java index 2ef7eec..6963b8c 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 @@ -42,7 +42,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen private ResourceGroupManagerLocal groupManager = LookupUtil.getResourceGroupManager(); private GroupDefinitionManagerLocal definitionManager = LookupUtil.getGroupDefinitionManager();
- public PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria) { + public PageList<ResourceGroup> findResourceGroupsByCriteria(ResourceGroupCriteria criteria) throws RuntimeException { try { PageList<ResourceGroup> groups = groupManager.findResourceGroupsByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(groups, "ResourceGroupService.findResourceGroupsByCriteria"); @@ -51,7 +51,8 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria) { + public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(ResourceGroupCriteria criteria) + throws RuntimeException { try { PageList<ResourceGroupComposite> composites = groupManager.findResourceGroupCompositesByCriteria( getSessionSubject(), criteria); @@ -61,7 +62,8 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria) { + public PageList<GroupDefinition> findGroupDefinitionsByCriteria(ResourceGroupDefinitionCriteria criteria) + throws RuntimeException { try { PageList<GroupDefinition> definitions = definitionManager.findGroupDefinitionsByCriteria( getSessionSubject(), criteria); @@ -71,7 +73,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void setAssignedResources(int groupId, int[] resourceIds, boolean setType) { + public void setAssignedResources(int groupId, int[] resourceIds, boolean setType) throws RuntimeException { try { groupManager.setAssignedResources(getSessionSubject(), groupId, resourceIds, setType); } catch (Throwable t) { @@ -79,7 +81,8 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType) { + public void setAssignedResourceGroupsForResource(int resourceId, int[] resourceGroupIds, boolean setType) + throws RuntimeException { try { groupManager.setAssignedResourceGroupsForResource(getSessionSubject(), resourceId, resourceGroupIds, setType); @@ -88,7 +91,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public ResourceGroup createPrivateResourceGroup(ResourceGroup group, int[] resourceIds) { + public ResourceGroup createPrivateResourceGroup(ResourceGroup group, int[] resourceIds) throws RuntimeException { try { Subject user = getSessionSubject(); group = groupManager.createPrivateResourceGroup(user, group); @@ -99,7 +102,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds) { + public ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds) throws RuntimeException { try { Subject user = getSessionSubject(); group = groupManager.createResourceGroup(user, group); @@ -110,7 +113,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void deleteResourceGroups(int[] groupIds) { + public void deleteResourceGroups(int[] groupIds) throws RuntimeException { try { groupManager.deleteResourceGroups(getSessionSubject(), groupIds); } catch (Throwable t) { @@ -118,7 +121,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void updateResourceGroup(ResourceGroup group) { + public void updateResourceGroup(ResourceGroup group) throws RuntimeException { try { groupManager.updateResourceGroup(getSessionSubject(), group); } catch (Throwable t) { @@ -126,7 +129,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void updateResourceGroup(ResourceGroup group, boolean updateMembership) { + public void updateResourceGroup(ResourceGroup group, boolean updateMembership) throws RuntimeException { try { groupManager.updateResourceGroup(getSessionSubject(), group, null, updateMembership); } catch (Throwable t) { @@ -134,7 +137,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public GroupDefinition createGroupDefinition(GroupDefinition groupDefinition) { + public GroupDefinition createGroupDefinition(GroupDefinition groupDefinition) throws RuntimeException { try { GroupDefinition results = definitionManager.createGroupDefinition(getSessionSubject(), groupDefinition);
@@ -144,7 +147,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void updateGroupDefinition(GroupDefinition groupDefinition) { + public void updateGroupDefinition(GroupDefinition groupDefinition) throws RuntimeException { try { definitionManager.updateGroupDefinition(getSessionSubject(), groupDefinition); } catch (Throwable t) { @@ -152,7 +155,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void recalculateGroupDefinitions(int[] groupDefinitionIds) { + public void recalculateGroupDefinitions(int[] groupDefinitionIds) throws RuntimeException { try { for (int nextGroupDefinitionId : groupDefinitionIds) { definitionManager.calculateGroupMembership(getSessionSubject(), nextGroupDefinitionId); @@ -162,7 +165,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public void deleteGroupDefinitions(int[] groupDefinitionIds) { + public void deleteGroupDefinitions(int[] groupDefinitionIds) throws RuntimeException { try { for (int nextGroupDefinitionId : groupDefinitionIds) { definitionManager.removeGroupDefinition(getSessionSubject(), nextGroupDefinitionId); @@ -173,7 +176,7 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen }
@Override - public void setRecursive(int groupId, boolean isRecursive) throws Exception { + public void setRecursive(int groupId, boolean isRecursive) throws RuntimeException { try { groupManager.setRecursive(getSessionSubject(), groupId, isRecursive); } catch (Throwable t) { 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 5cffd24..223a23e 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 @@ -22,14 +22,14 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement private static final long serialVersionUID = 1L;
@Override - public PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria) { + public PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria) throws RuntimeException { try { ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager();
return SerialUtility.prepare(typeManager.findResourceTypesByCriteria(getSessionSubject(), criteria), "ResourceTypes.findResourceTypesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@@ -37,7 +37,7 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement * Given a resource ID, this gets all resource types for all ancestors in that resource's lineage. */ @Override - public ArrayList<ResourceType> getResourceTypesForResourceAncestors(int resourceId) { + public ArrayList<ResourceType> getResourceTypesForResourceAncestors(int resourceId) throws RuntimeException { try { ResourceManagerLocal manager = LookupUtil.getResourceManager(); List<ResourceLineageComposite> lineage = manager.getResourceLineage(getSessionSubject(), resourceId); @@ -46,43 +46,44 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement types.add(composite.getResource().getResourceType()); } return SerialUtility.prepare(types, "ResourceTypes.getResourceTypesForResourceAncestors"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId) { + public ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId) throws RuntimeException { 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)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public HashMap<Integer, String> getResourceTypeDescendantsWithOperations(int resourceTypeId) { + public HashMap<Integer, String> getResourceTypeDescendantsWithOperations(int resourceTypeId) + throws RuntimeException { try { ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); HashMap<Integer, String> map = typeManager.getResourceTypeDescendantsWithOperations(getSessionSubject(), resourceTypeId); return SerialUtility.prepare(map, "ResourceTypes.getResourceTypeDescendantsWithOperations"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
@Override - public Map<Integer, ResourceTypeTemplateCountComposite> getTemplateCountCompositeMap() { + public Map<Integer, ResourceTypeTemplateCountComposite> getTemplateCountCompositeMap() throws RuntimeException { try { ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); Map<Integer, ResourceTypeTemplateCountComposite> map = typeManager.getTemplateCountCompositeMap(); return SerialUtility.prepare(map, "ResourceTypes.getTemplateCountCompositeMap"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ No newline at end of file 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 2f1dcbc..73659e0 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 @@ -36,60 +36,60 @@ public class RoleGWTServiceImpl extends AbstractGWTServiceImpl implements RoleGW
private RoleManagerLocal roleManager = LookupUtil.getRoleManager();
- public PageList<Role> findRolesByCriteria(RoleCriteria criteria) { + public PageList<Role> findRolesByCriteria(RoleCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(roleManager.findRolesByCriteria(getSessionSubject(), criteria), "RoleService.findRolesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Role createRole(Role role) { + public Role createRole(Role role) throws RuntimeException { try { return SerialUtility.prepare(roleManager.createRole(getSessionSubject(), role), "RoleService.createRole"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Role updateRole(Role role) { + public Role updateRole(Role role) throws RuntimeException { try { return SerialUtility.prepare(roleManager.updateRole(getSessionSubject(), role), "RoleService.updateRole"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void removeRoles(int[] roleIds) { + public void removeRoles(int[] roleIds) throws RuntimeException { try { roleManager.deleteRoles(getSessionSubject(), roleIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void setAssignedResourceGroups(int roleId, int[] resourceGroupIds) { + public void setAssignedResourceGroups(int roleId, int[] resourceGroupIds) throws RuntimeException { try { roleManager.setAssignedResourceGroups(getSessionSubject(), roleId, resourceGroupIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void setAssignedSubjects(int roleId, int[] subjectIds) { + public void setAssignedSubjects(int roleId, int[] subjectIds) throws RuntimeException { try { roleManager.setAssignedSubjects(getSessionSubject(), roleId, subjectIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void setAssignedRolesForSubject(int subjectId, int[] roleIds) { + public void setAssignedRolesForSubject(int subjectId, int[] roleIds) throws RuntimeException { try { roleManager.setAssignedSubjectRoles(getSessionSubject(), subjectId, roleIds); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ 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 ae72b4c..c80728e 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 @@ -41,56 +41,57 @@ public class SearchGWTServiceImpl extends AbstractGWTServiceImpl implements Sear private SavedSearchManagerLocal savedSearchManager = LookupUtil.getSavedSearchManager();
public List<SearchSuggestion> getTabAwareSuggestions(SearchSubsystem searchSubsystem, String expression, - int caretPosition, String tab) { + int caretPosition, String tab) throws RuntimeException { 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)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<SearchSuggestion> getSuggestions(SearchSubsystem searchSubsystem, String expression, int caretPosition) { + public List<SearchSuggestion> getSuggestions(SearchSubsystem searchSubsystem, String expression, int caretPosition) + throws RuntimeException { 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)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public int createSavedSearch(SavedSearch savedSearch) { + public int createSavedSearch(SavedSearch savedSearch) throws RuntimeException { try { return savedSearchManager.createSavedSearch(getSessionSubject(), savedSearch); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateSavedSearch(SavedSearch savedSearch) { + public void updateSavedSearch(SavedSearch savedSearch) throws RuntimeException { try { savedSearchManager.updateSavedSearch(getSessionSubject(), savedSearch); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteSavedSearch(int savedSearchId) { + public void deleteSavedSearch(int savedSearchId) throws RuntimeException { try { savedSearchManager.deleteSavedSearch(getSessionSubject(), savedSearchId); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public List<SavedSearch> findSavedSearchesByCriteria(SavedSearchCriteria criteria) { + public List<SavedSearch> findSavedSearchesByCriteria(SavedSearchCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(savedSearchManager.findSavedSearchesByCriteria(getSessionSubject(), criteria), "SearchService.findRolesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } 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/SubjectGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java index d9b50fd..df34cab 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 @@ -18,8 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
-import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.SubjectCriteria; import org.rhq.core.domain.util.PageList; @@ -37,85 +35,77 @@ public class SubjectGWTServiceImpl extends AbstractGWTServiceImpl implements Sub
private static final long serialVersionUID = 1L;
- private final Log log = LogFactory.getLog(this.getClass()); - private SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager();
- public void createPrincipal(String username, String password) { + public void createPrincipal(String username, String password) throws RuntimeException { try { subjectManager.createPrincipal(getSessionSubject(), username, password); - } catch (RuntimeException e) { - handleException(e); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Subject createSubject(Subject subjectToCreate) { + public Subject createSubject(Subject subjectToCreate) throws RuntimeException { try { return SerialUtility.prepare(subjectManager.createSubject(getSessionSubject(), subjectToCreate), "SubjectManager.createSubject"); - } catch (RuntimeException e) { - handleException(e); - return null; + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Subject createSubject(Subject subjectToCreate, String password) throws Exception { + public Subject createSubject(Subject subjectToCreate, String password) throws RuntimeException { try { return SerialUtility.prepare(subjectManager.createSubject(getSessionSubject(), subjectToCreate, password), "SubjectManager.createSubject"); - } catch (RuntimeException e) { - throw new Exception(e); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void deleteSubjects(int[] subjectIds) { + public void deleteSubjects(int[] subjectIds) throws RuntimeException { try { subjectManager.deleteSubjects(getSessionSubject(), subjectIds); - } catch (RuntimeException e) { - handleException(e); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Subject login(String username, String password) { + public Subject login(String username, String password) throws RuntimeException { try { return SerialUtility.prepare(subjectManager.login(username, password), "SubjectManager.login"); - } catch (LoginException e) { - throw new RuntimeException("LoginException: " + e.getMessage()); - } catch (RuntimeException e) { - handleException(e); - return null; + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void logout(Subject subject) { + public void logout(Subject subject) throws RuntimeException { try { subjectManager.logout(subject.getSessionId()); - } catch (RuntimeException e) { - handleException(e); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Subject updateSubject(Subject subjectToModify) { + public Subject updateSubject(Subject subjectToModify) throws RuntimeException { try { return SerialUtility.prepare(subjectManager.updateSubject(getSessionSubject(), subjectToModify), "SubjectManager.updateSubject"); - } catch (RuntimeException e) { - handleException(e); - return null; + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Subject updateSubject(Subject subjectToModify, String newPassword) { + public Subject updateSubject(Subject subjectToModify, String newPassword) throws RuntimeException { try { - return SerialUtility.prepare(subjectManager.updateSubject(getSessionSubject(), subjectToModify, newPassword), - "SubjectManager.updateSubject"); - } catch (RuntimeException e) { - handleException(e); - return null; + return SerialUtility.prepare(subjectManager + .updateSubject(getSessionSubject(), subjectToModify, newPassword), "SubjectManager.updateSubject"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Subject processSubjectForLdap(Subject subjectToModify, String password) { + public Subject processSubjectForLdap(Subject subjectToModify, String password) throws RuntimeException { //no permissions check as embedded in the SLSB call. try { Subject processedSubject = subjectManager.processSubjectForLdap(subjectToModify, password); @@ -146,28 +136,25 @@ public class SubjectGWTServiceImpl extends AbstractGWTServiceImpl implements Sub } catch (LoginException e) { throw new RuntimeException("LoginException: " + e.getMessage()); } catch (RuntimeException e) { - handleException(e); - return null; + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } }
- public PageList<Subject> findSubjectsByCriteria(SubjectCriteria criteria) { + public PageList<Subject> findSubjectsByCriteria(SubjectCriteria criteria) throws RuntimeException { try { return SerialUtility.prepare(subjectManager.findSubjectsByCriteria(getSessionSubject(), criteria), "SubjectManager.findSubjectsByCriteria"); - } catch (RuntimeException e) { - handleException(e); - return null; + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } - - public boolean isUserWithPrincipal(String username) { - return subjectManager.isUserWithPrincipal(username); - }
- private void handleException(Exception e) { - log.error("Unexpected error.", e); - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + public boolean isUserWithPrincipal(String username) throws RuntimeException { + try { + return subjectManager.isUserWithPrincipal(username); + } 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/SystemGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java index 43431c7..eb1f3c9 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 @@ -33,11 +33,11 @@ public class SystemGWTServiceImpl extends AbstractGWTServiceImpl implements Syst
private SystemManagerLocal systemManager = LookupUtil.getSystemManager();
- public ProductInfo getProductInfo() { + public ProductInfo getProductInfo() throws RuntimeException { try { return this.systemManager.getProductInfo(getSessionSubject()); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } } \ 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 7ab6941..2f28bbf 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 @@ -43,86 +43,87 @@ public class TagGWTServiceImpl extends AbstractGWTServiceImpl implements TagGWTS
private TagManagerLocal tagManager = LookupUtil.getTagManager();
- public PageList<Tag> findTagsByCriteria(TagCriteria tagCriteria) { + public PageList<Tag> findTagsByCriteria(TagCriteria tagCriteria) throws RuntimeException { try { return SerialUtility.prepare(tagManager.findTagsByCriteria(getSessionSubject(), tagCriteria), "TagService.findTagsByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public Set<Tag> addTags(Set<Tag> tags) { + public Set<Tag> addTags(Set<Tag> tags) throws RuntimeException { try { return SerialUtility.prepare(tagManager.addTags(getSessionSubject(), tags), "TagService.addTags"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void removeTags(Set<Tag> tags) { + public void removeTags(Set<Tag> tags) throws RuntimeException { try { tagManager.removeTags(getSessionSubject(), tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateResourceTags(int resourceId, Set<Tag> tags) { + public void updateResourceTags(int resourceId, Set<Tag> tags) throws RuntimeException { try { tagManager.updateResourceTags(getSessionSubject(), resourceId, tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateResourceGroupTags(int resourceGroupId, Set<Tag> tags) { + public void updateResourceGroupTags(int resourceGroupId, Set<Tag> tags) throws RuntimeException { try { tagManager.updateResourceGroupTags(getSessionSubject(), resourceGroupId, tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateBundleTags(int bundleId, Set<Tag> tags) { + public void updateBundleTags(int bundleId, Set<Tag> tags) throws RuntimeException { try { tagManager.updateBundleTags(getSessionSubject(), bundleId, tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateBundleVersionTags(int bundleVersionId, Set<Tag> tags) { + public void updateBundleVersionTags(int bundleVersionId, Set<Tag> tags) throws RuntimeException { try { tagManager.updateBundleVersionTags(getSessionSubject(), bundleVersionId, tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateBundleDeploymentTags(int bundleDeploymentId, Set<Tag> tags) { + public void updateBundleDeploymentTags(int bundleDeploymentId, Set<Tag> tags) throws RuntimeException { try { tagManager.updateBundleDeploymentTags(getSessionSubject(), bundleDeploymentId, tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public void updateBundleDestinationTags(int bundleDestinationId, Set<Tag> tags) { + public void updateBundleDestinationTags(int bundleDestinationId, Set<Tag> tags) throws RuntimeException { try { tagManager.updateBundleDestinationTags(getSessionSubject(), bundleDestinationId, tags); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } }
- public PageList<TagReportComposite> findTagReportCompositesByCriteria(TagCriteria tagCriteria) { + public PageList<TagReportComposite> findTagReportCompositesByCriteria(TagCriteria tagCriteria) + throws RuntimeException { try { return SerialUtility.prepare( tagManager.findTagReportCompositesByCriteria(getSessionSubject(), tagCriteria), "TagService.findTagReportCompositesByCriteria"); - } catch (Exception e) { - throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); } } }
commit 8c639f21851747d2b128e80682419101c5e640e7 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Dec 21 14:47:50 2010 -0500
remove assumptions about fetch return order, which is not guaranteed by a db impl. hopefully got them all...
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java index 932e617..d4963a2 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java @@ -535,6 +535,7 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { assertNotNull(b1);
BundleCriteria criteria = new BundleCriteria(); + criteria.addSortName(PageOrdering.ASC); PageList<BundleWithLatestVersionComposite> results;
// verify there are no bundle versions yet @@ -922,33 +923,35 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { BundleVersion bv3 = createBundleVersion(b1.getName(), "2.1", b1); BundleVersionCriteria c = new BundleVersionCriteria(); PageList<BundleVersion> bvs = null; - BundleVersion bv = null; + BundleVersion bvOut = null;
// return all with no optional data c.addFilterName(TEST_PREFIX); bvs = bundleManager.findBundleVersionsByCriteria(overlord, c); - bv = bvs.get(1); - EntityManager em = getEntityManager(); - bv = em.merge(bv); assertNotNull(bvs); assertEquals(3, bvs.size()); - assertEquals(bv2, bv); + assertFalse(bvs.get(0).equals(bvs.get(1))); + assertFalse(bvs.get(0).equals(bvs.get(2))); + assertFalse(bvs.get(1).equals(bvs.get(2))); + assertTrue(bvs.get(0).equals(bvs.get(0))); + assertTrue(bvs.get(0).equals(bv2) || bvs.get(1).equals(bv2) || bvs.get(2).equals(bv2));
// return bundle version using all criteria and with all optional data - c.addFilterId(bv.getId()); - c.addFilterName(bv.getName()); + BundleVersion bvIn = bvs.get(1); + c.addFilterId(bvIn.getId()); + c.addFilterName(bvIn.getName()); c.addFilterBundleName("one"); - c.addFilterVersion(bv.getVersion()); + c.addFilterVersion(bvIn.getVersion()); c.fetchBundle(true); c.fetchBundleDeployments(true); bvs = bundleManager.findBundleVersionsByCriteria(overlord, c); assertNotNull(bvs); assertEquals(1, bvs.size()); - bv = bvs.get(0); - assertEquals(bv2, bv); - assertEquals(bv.getBundle(), b1); - assertNotNull(bv.getBundleDeployments()); - assertTrue(bv.getBundleDeployments().isEmpty()); + bvOut = bvs.get(0); + assertEquals(bvIn, bvOut); + assertEquals(bvOut.getBundle(), b1); + assertNotNull(bvOut.getBundleDeployments()); + assertTrue(bvOut.getBundleDeployments().isEmpty()); }
@Test(enabled = DISABLED)
commit d861e2386d02b68b19b640ff535c6b7268f9ad31 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Dec 21 13:43:18 2010 -0500
Not sure what changed to make "Logout" start hanging off the right side, but instead of trying to force min size, now provide ample space.
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 77d24fd..a4a1e40 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 @@ -161,7 +161,7 @@ public class MenuBarView extends LocatableVLayout { lineLabel.setAlign(Alignment.CENTER);
Hyperlink logoutLink = SeleniumUtility.setHtmlId(new Hyperlink(MSG.view_menuBar_logout(), "LogOut")); - logoutLink.setWidth("1px"); + logoutLink.setWidth("50px");
layout.addMember(userLabel); layout.addMember(lineLabel);
commit a1d95800d25edf92c3a9f96e3f27a133f93ad1b4 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Dec 21 11:43:48 2010 -0500
Some tweaks to Bundle Domain objects. - add some missing null protection in toString() - remove ctime from BundleDeployment hashCode as it's not part of the natural key and could cause issues due to the way its initialized at construction-time. - for relevant entities add some jdoc for hashcode/equals impls noting the use of lazy loaded fields in the natural key. This should not be a problem for real-work scenarios but is a subtlety that may need to be made clear, especially for test code.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java index 6dd4a02..9bf477f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java @@ -217,7 +217,10 @@ public class Bundle implements Serializable {
@Override public String toString() { - return "Bundle[id=" + id + ",name=" + name + ",bundleType=" + bundleType + ",packageType=" + packageType + "]"; + return "Bundle[id=" + id // + + ",name=" + name // + + ",bundleType=" + bundleType // + + ",packageType=" + packageType + "]"; }
@Override diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeployment.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeployment.java index c2a062b..fc0c72c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeployment.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDeployment.java @@ -360,6 +360,12 @@ public class BundleDeployment implements Serializable { return "BundleDeployment[id=" + id + ", name=" + name + "]"; }
+ /* + * These fields make up the natural key but note that some fields are lazy loaded. As such care should + * be taken to have properly loaded instances when required. + * + * @see java.lang.Object#hashCode() + */ @Override public int hashCode() { final int prime = 31; @@ -367,10 +373,15 @@ public class BundleDeployment implements Serializable { result = prime * result + ((this.bundleVersion == null) ? 0 : this.bundleVersion.hashCode()); result = prime * result + ((this.destination == null) ? 0 : this.destination.hashCode()); result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); - result = prime * result + ((this.ctime == null) ? 0 : this.ctime.hashCode()); return result; }
+ /* + * These fields make up the natural key but note that some fields are lazy loaded. As such care should + * be taken to have properly loaded instances when required. + * + * @see java.lang.Object#equals(java.lang.Object) + */ @Override public boolean equals(Object obj) { if (this == obj) { @@ -406,14 +417,6 @@ public class BundleDeployment implements Serializable { return false; }
- if (this.ctime == null) { - if (other.ctime != null) { - return false; - } - } else if (!this.ctime.equals(other.ctime)) { - return false; - } - return true; } } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDestination.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDestination.java index 5c37ebf..dc730c7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDestination.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleDestination.java @@ -224,10 +224,18 @@ public class BundleDestination implements Serializable {
@Override public String toString() { - return "BundleDestination[id=" + id + ", bundle=" + bundle.getName() + ", group=" + group.getName() + ", name=" - + name + "]"; + return "BundleDestination[id=" + id // + + ((null != bundle) ? (", bundle=" + bundle.getName()) : "") // + + ((null != group) ? (", group=" + group.getName()) : "") // + + ", name=" + name + "]"; }
+ /* + * These fields make up the natural key but note that some fields are lazy loaded. As such care should + * be taken to have properly loaded instances when required. + * + * @see java.lang.Object#hashCode() + */ @Override public int hashCode() { final int prime = 31; @@ -238,6 +246,12 @@ public class BundleDestination implements Serializable { return result; }
+ /* + * These fields make up the natural key but note that some fields are lazy loaded. As such care should + * be taken to have properly loaded instances when required. + * + * @see java.lang.Object#equals(java.lang.Object) + */ @Override public boolean equals(Object obj) { if (this == obj) { diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeployment.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeployment.java index 1bc3c25..7cd7b50 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeployment.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleResourceDeployment.java @@ -172,6 +172,12 @@ public class BundleResourceDeployment implements Serializable { return str.toString(); }
+ /* + * These fields make up the natural key but note that some fields are lazy loaded. As such care should + * be taken to have properly loaded instances when required. + * + * @see java.lang.Object#hashCode() + */ @Override public int hashCode() { int result = 1; @@ -180,6 +186,12 @@ public class BundleResourceDeployment implements Serializable { return result; }
+ /* + * These fields make up the natural key but note that some fields are lazy loaded. As such care should + * be taken to have properly loaded instances when required. + * + * @see java.lang.Object#equals(java.lang.Object) + */ @Override public boolean equals(Object obj) { if (this == obj) { diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleVersion.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleVersion.java index 0afdb13..cfbb9d7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleVersion.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/BundleVersion.java @@ -261,7 +261,8 @@ public class BundleVersion implements Serializable {
@Override public String toString() { - return "BundleVersion[id=" + id + ",name=" + name + ",version=" + version + ",bundle=" + bundle.getName() + "]"; + return "BundleVersion[id=" + id + ",name=" + name + ",version=" + version + + ((null != bundle) ? (",bundle=" + bundle.getName()) : "") + "]"; }
@Override
commit 2c3e0d126fd58d775bdce779e86ffcd2387014d0 Author: Simeon Pinder spinder@redhat.com Date: Tue Dec 21 09:00:13 2010 -0500
i)fix copy paste error in ImgManager ii)removed redundant method for configIcon status
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java index 7b79f88..437cb54 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java @@ -352,44 +352,20 @@ public class ImageManager { return "subsystems/configure/Configure_failed_16.png"; } case INPROGRESS: { - return "subsystems/inventory/Configure_inprogress_16.png"; + return "subsystems/configure/Configure_inprogress_16.png"; } case NOCHANGE: - return "subsystems/inventory/Configure_16.png"; + return "subsystems/configure/Configure_16.png"; } }
- return "subsystems/inventory/Configure_16.png"; + return "subsystems/configure/Configure_16.png"; }
public static String getLockedIcon() { return "global/Locked_16.png"; }
- /** - * Returns the configuration update status icon. If status is null, returns - * the plain, unbadged, configuration icon. - */ - public static String getConfigurationUpdateResultsIcon(ConfigurationUpdateStatus status) { - String icon = ""; - if (status != null) { - switch (status) { - case INPROGRESS: - icon = "_inprogress"; - break; - case SUCCESS: - icon = "_ok"; - break; - case FAILURE: - icon = "_failed"; - break; - } - } - - return "subsystems/configure/Configure" + icon + "_16.png"; - - } - public static String getEventSeverityIcon(EventSeverity severity) { String icon = ""; if (severity != null) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java index 8907f16..15969bb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java @@ -364,7 +364,7 @@ public class ActivityView2 extends LocatableHLayout implements RefreshableView {
StaticTextItem iconItem = new StaticTextItem(); FormItemIcon img = new FormItemIcon(); - img.setSrc(ImageManager.getConfigurationUpdateResultsIcon(update.getStatus())); + img.setSrc(ImageManager.getResourceConfigurationIcon(update.getStatus())); img.setWidth(16); img.setHeight(16); iconItem.setIcons(img);
commit c68e0e42d9b2bdb075372e87e1b62f5e1fbcc000 Author: Simeon Pinder spinder@redhat.com Date: Mon Dec 20 21:04:46 2010 -0500
initial commit of resource/activity. There are several jsf pieces that are non-trivial to replace. Will keep both iframe and gwt versions until more functionality can be moved.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java index 576af53..7b79f88 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java @@ -2,6 +2,7 @@ package org.rhq.enterprise.gui.coregui.client;
import org.rhq.core.domain.alert.AlertPriority; import org.rhq.core.domain.configuration.ConfigurationUpdateStatus; +import org.rhq.core.domain.event.EventSeverity; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.measurement.ResourceAvailability; import org.rhq.core.domain.operation.OperationRequestStatus; @@ -364,4 +365,53 @@ public class ImageManager { public static String getLockedIcon() { return "global/Locked_16.png"; } + + /** + * Returns the configuration update status icon. If status is null, returns + * the plain, unbadged, configuration icon. + */ + public static String getConfigurationUpdateResultsIcon(ConfigurationUpdateStatus status) { + String icon = ""; + if (status != null) { + switch (status) { + case INPROGRESS: + icon = "_inprogress"; + break; + case SUCCESS: + icon = "_ok"; + break; + case FAILURE: + icon = "_failed"; + break; + } + } + + return "subsystems/configure/Configure" + icon + "_16.png"; + + } + + public static String getEventSeverityIcon(EventSeverity severity) { + String icon = ""; + if (severity != null) { + switch (severity) { + case DEBUG: + icon = "_debug"; + break; + case INFO: + icon = "_info"; + break; + case WARN: + icon = "_warning"; + break; + case ERROR: + icon = "_info"; + break; + case FATAL: + icon = "_fatal"; + break; + } + } + + return "subsystems/event/Events" + icon + "_16.png"; + } } 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 ffc4ca5..0c61ed0 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 @@ -63,6 +63,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitorin import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.history.ResourceOperationHistoryListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary.ActivityView; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary.ActivityView2; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.util.message.Message;
@@ -92,6 +93,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo private TwoLevelTab contentTab;
private SubTab summaryActivity; + private SubTab summaryActivity2; private SubTab summaryTimeline; private SubTab monitorGraphs; private SubTab monitorTables; @@ -129,9 +131,12 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo .view_tabs_common_summary()), ImageManager.getResourceIcon(ResourceCategory.SERVICE, Boolean.TRUE)); summaryActivity = new SubTab(summaryTab.extendLocatorId("Activity"), new ViewName("Activity", MSG .view_tabs_common_activity()), null); + summaryActivity2 = new SubTab(summaryTab.extendLocatorId("Activity2"), new ViewName("Activity2", MSG + .view_tabs_common_activity() + 2), null); summaryTimeline = new SubTab(summaryTab.extendLocatorId("Timeline"), new ViewName("Timeline", MSG .view_tabs_common_timeline()), null); - summaryTab.registerSubTabs(summaryActivity, summaryTimeline); + // summaryTab.registerSubTabs(summaryActivity, summaryTimeline); + summaryTab.registerSubTabs(summaryActivity, summaryActivity2, summaryTimeline); tabs.add(summaryTab);
inventoryTab = new TwoLevelTab(getTabSet().extendLocatorId("Inventory"), new ViewName("Inventory", MSG @@ -255,6 +260,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo private void updateSummaryTabContent(Resource resource) { updateSubTab(this.summaryTab, this.summaryActivity, new ActivityView(this.summaryActivity .extendLocatorId("View"), this.resourceComposite), true, true); + updateSubTab(this.summaryTab, this.summaryActivity2, new ActivityView2(this.summaryActivity2 + .extendLocatorId("View"), this.resourceComposite), true, true);
updateSubTab(this.summaryTab, this.summaryTimeline, new FullHTMLPane(this.summaryTimeline .extendLocatorId("View"), "/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()), true, true); @@ -347,7 +354,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.operationsTab, this.operationsHistory, new ResourceOperationHistoryListView(operationsTab .extendLocatorId("HistoryView"), this.resourceComposite), true, true);
- updateSubTab(this.operationsTab, this.operationsSchedule,new ResourceOperationScheduleListView( + updateSubTab(this.operationsTab, this.operationsSchedule, new ResourceOperationScheduleListView( operationsTab.extendLocatorId("SchedulesView"), this.resourceComposite), true, true); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java new file mode 100644 index 0000000..8907f16 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView2.java @@ -0,0 +1,618 @@ +/* + * 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 com.allen_sauer.gwt.log.client.Log; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.Canvas; +import com.smartgwt.client.widgets.HTMLFlow; +import com.smartgwt.client.widgets.Img; +import com.smartgwt.client.widgets.form.fields.FormItemIcon; +import com.smartgwt.client.widgets.form.fields.LinkItem; +import com.smartgwt.client.widgets.form.fields.StaticTextItem; + +import org.rhq.core.domain.alert.Alert; +import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; +import org.rhq.core.domain.criteria.AlertCriteria; +import org.rhq.core.domain.criteria.EventCriteria; +import org.rhq.core.domain.criteria.InstalledPackageCriteria; +import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria; +import org.rhq.core.domain.measurement.composite.MeasurementOOBComposite; +import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; +import org.rhq.core.domain.resource.composite.DisambiguationReport; +import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.core.domain.util.PageControl; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.ImageManager; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.resource.disambiguation.ReportDecorator; +import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableCanvas; +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.LocatableVLayout; + +/** + * The content pane of the Resource Summary>Activity tab. + * + * @author Simeon Pinder + */ +public class ActivityView2 extends LocatableHLayout implements RefreshableView { + private LocatableVLayout leftPane; + private LocatableVLayout rightPane; + private LocatableCanvas recentMeasurementsContent = new LocatableCanvas(extendLocatorId("RecentMetricsContent")); + private LocatableCanvas recentAlertsContent = new LocatableCanvas(extendLocatorId("RecentAlertsContent")); + private LocatableCanvas recentOobContent = new LocatableCanvas(extendLocatorId("RecentOobsContent")); + private LocatableCanvas recentConfigurationContent = new LocatableCanvas(extendLocatorId("RecentConfigContent")); + private LocatableCanvas recentOperationsContent = new LocatableCanvas(extendLocatorId("RecentOperationsContent")); + private LocatableCanvas recentEventsContent = new LocatableCanvas(extendLocatorId("RecentEventsContent")); + private LocatableCanvas recentPkgHistoryContent = new LocatableCanvas(extendLocatorId("RecentPkgHistoryContent")); + private String RECENT_MEASUREMENTS = MSG.common_title_recent_measurements(); + private String RECENT_MEASUREMENTS_NONE = MSG.view_resource_inventory_activity_no_recent_metrics(); + private String RECENT_ALERTS = MSG.common_title_recent_alerts(); + private String RECENT_ALERTS_NONE = MSG.view_resource_inventory_activity_no_recent_alerts(); + private String RECENT_OOB = MSG.common_title_recent_oob_metrics(); + private String RECENT_OOB_NONE = MSG.view_resource_inventory_activity_no_recent_oob(); + private String RECENT_CONFIGURATIONS = MSG.common_title_recent_configuration_updates(); + private String RECENT_CONFIGURATIONS_NONE = MSG.view_resource_inventory_activity_no_recent_config_history(); + private String RECENT_OPERATIONS = MSG.common_title_recent_operations(); + private String RECENT_OPERATIONS_NONE = MSG.view_resource_inventory_activity_no_recent_operations(); + private String RECENT_EVENTS = MSG.common_title_recent_event_counts(); + private String RECENT_EVENTS_NONE = MSG.view_resource_inventory_activity_no_recent_events(); + private String RECENT_PKG_HISTORY = MSG.common_title_recent_pkg_history(); + private String RECENT_PKG_HISTORY_NONE = MSG.view_resource_inventory_activity_no_recent_pkg_history(); + + private ResourceComposite resourceComposite; + + public ActivityView2(String locatorId, ResourceComposite resourceComposite) { + super(locatorId); + this.resourceComposite = resourceComposite; + initializeUi(); + } + + private void initializeUi() { + setPadding(5); + setMembersMargin(5); + //dividers definition + HTMLFlow divider1 = new HTMLFlow("<hr/>"); + HTMLFlow divider2 = new HTMLFlow("<hr/>"); + HTMLFlow divider3 = new HTMLFlow("<hr/>"); + HTMLFlow divider4 = new HTMLFlow("<hr/>"); + HTMLFlow divider5 = new HTMLFlow("<hr/>"); + divider1.setWidth("50%"); + divider2.setWidth("50%"); + divider3.setWidth("50%"); + divider4.setWidth("50%"); + divider5.setWidth("50%"); + + //leftPane + leftPane = new LocatableVLayout(extendLocatorId("Left")); + leftPane.setWidth("50%"); + leftPane.setPadding(5); + leftPane.setMembersMargin(5); + leftPane.setAutoHeight(); + //recentMetrics.xhtml + LocatableHLayout recentMetricsTitle = new TitleWithIcon(leftPane, "RecentMetrics", + "subsystems/monitor/Monitor_24.png", RECENT_MEASUREMENTS); + leftPane.addMember(recentMetricsTitle); + leftPane.addMember(recentMeasurementsContent); + recentMeasurementsContent.setHeight(20); + recentMeasurementsContent.setContents(RECENT_MEASUREMENTS_NONE); + leftPane.addMember(divider1); + //recentAlerts.xhtml + LocatableHLayout recentAlertsTitle = new TitleWithIcon(leftPane, "RecentAlerts", + "subsystems/alert/Flag_blue_24.png", RECENT_ALERTS); + leftPane.addMember(recentAlertsTitle); + leftPane.addMember(recentAlertsContent); + recentAlertsContent.setHeight(20); + // recentAlertsContent.setContents(RECENT_ALERTS_NONE); + leftPane.addMember(divider2); + //recentOOBs.xhtml + LocatableHLayout recentOobsTitle = new TitleWithIcon(leftPane, "RecentOobs", + "subsystems/monitor/Monitor_failed_24.png", RECENT_OOB); + leftPane.addMember(recentOobsTitle); + leftPane.addMember(recentOobContent); + recentOobContent.setHeight(20); + recentOobContent.setContents(RECENT_OOB_NONE); + + //rightPane + rightPane = new LocatableVLayout(extendLocatorId("Right")); + rightPane.setWidth("50%"); + rightPane.setPadding(5); + rightPane.setMembersMargin(5); + rightPane.setAutoHeight(); + //recentConfigUpdates.xhtml + LocatableHLayout recentConfigUpdatesTitle = new TitleWithIcon(leftPane, "RecentConfigUpdates", + "subsystems/configure/Configure_24.png", RECENT_CONFIGURATIONS); + rightPane.addMember(recentConfigUpdatesTitle); + rightPane.addMember(recentConfigurationContent); + recentConfigurationContent.setHeight(20); + // recentConfigurationContent.setContents(RECENT_CONFIGURATIONS_NONE); + rightPane.addMember(divider3); + //recentOperations.xhtml + LocatableHLayout recentOperationsTitle = new TitleWithIcon(leftPane, "RecentOperations", + "subsystems/control/Operation_24.png", RECENT_OPERATIONS); + rightPane.addMember(recentOperationsTitle); + rightPane.addMember(recentOperationsContent); + recentOperationsContent.setHeight(20); + // recentOperationsContent.setContents(RECENT_OPERATIONS_NONE); + rightPane.addMember(divider4); + //recentEventCounts.xhtml + LocatableHLayout recentEventsTitle = new TitleWithIcon(leftPane, "RecentEvent", + "subsystems/event/Events_24.png", RECENT_EVENTS); + rightPane.addMember(recentEventsTitle); + rightPane.addMember(recentEventsContent); + recentEventsContent.setHeight(20); + recentEventsContent.setContents(RECENT_EVENTS_NONE); + rightPane.addMember(divider5); + //recentPackageHistory.xhtml + LocatableHLayout recentPkgHistoryTitle = new TitleWithIcon(leftPane, "RecentPkgHistory", + "subsystems/content/Content_24.png", RECENT_PKG_HISTORY); + rightPane.addMember(recentPkgHistoryTitle); + rightPane.addMember(recentPkgHistoryContent); + recentPkgHistoryContent.setHeight(20); + recentPkgHistoryContent.setContents(RECENT_PKG_HISTORY_NONE); + loadData(); + } + + private void loadData() { + getRecentAlerts(); + getRecentOperations(); + getRecentConfigurationUpdates(); + getRecentEventUpdates(); + getRecentOobs(); + getRecentPkgHistory(); + } + + @Override + protected void onDraw() { + super.onDraw(); + + addMember(leftPane); + addMember(rightPane); + refresh(); + } + + @Override + public void refresh() { + // int resourceId = this.resourceComposite.getResource().getId(); + // this.iFrame.setContentsURL("/rhq/resource/summary/overview-plain.xhtml?id=" + resourceId); + loadData(); + markForRedraw(); + } + + class TitleWithIcon extends LocatableHLayout { + public TitleWithIcon(String locatorId) { + super(locatorId); + } + + public TitleWithIcon(Locatable parentContainer, String locatorIdentifier, String imageUrl, String title) { + super(parentContainer.extendLocatorId(locatorIdentifier)); + Img titleImage = new Img(imageUrl, 24, 24); + HTMLFlow titleElement = new HTMLFlow(); + titleElement.setWidth("*"); + titleElement.setContents(title); + titleElement.setStyleName("HeaderLabel"); + addMember(titleImage); + addMember(titleElement); + setMembersMargin(10); + } + } + + private void getRecentAlerts() { + final int resourceId = this.resourceComposite.getResource().getId(); + AlertCriteria criteria = new AlertCriteria(); + criteria.addFilterResourceIds(resourceId); + PageControl pageControl = new PageControl(0, 5); + criteria.setPageControl(pageControl); + GWTServiceLookup.getAlertService().findAlertsByCriteria(criteria, new AsyncCallback<PageList<Alert>>() { + @Override + public void onSuccess(PageList<Alert> result) { + LocatableVLayout column = new LocatableVLayout(recentAlertsContent.extendLocatorId("Content")); + column.setHeight(10); + if (!result.isEmpty()) { + for (Alert alert : result) { + LocatableDynamicForm row = new LocatableDynamicForm(recentAlertsContent + .extendLocatorId("ContentForm")); + row.setNumCols(3); + + StaticTextItem iconItem = new StaticTextItem(); + FormItemIcon img = new FormItemIcon(); + img.setSrc(ImageManager.getAlertIcon(alert.getAlertDefinition().getPriority())); + img.setWidth(16); + img.setHeight(16); + iconItem.setIcons(img); + iconItem.setShowTitle(false); + + LinkItem link = new LinkItem(); + link.setLinkTitle(alert.getAlertDefinition().getName()); + link.setTitle(alert.getAlertDefinition().getName()); + link.setValue(ReportDecorator.GWT_RESOURCE_URL + resourceId + "/Alerts/Definitions/" + + alert.getAlertDefinition().getId()); + link.setTarget("_self"); + link.setShowTitle(false); + + StaticTextItem time = new StaticTextItem(); + time.setDefaultValue(new Date(alert.getAlertDefinition().getCtime()).toString()); + time.setShowTitle(false); + time.setShowPickerIcon(false); + time.setWrap(false); + row.setItems(iconItem, link, time); + + column.addMember(row); + } + } else { + column.setContents(RECENT_ALERTS_NONE); + } + recentAlertsContent.setContents(""); + for (Canvas child : recentAlertsContent.getChildren()) { + child.destroy(); + } + recentAlertsContent.addChild(column); + recentAlertsContent.markForRedraw(); + } + + @Override + public void onFailure(Throwable caught) { + Log.debug("Error retrieving recent alerts for resource [" + resourceId + "]:" + caught.getMessage()); + } + }); + } + + private void getRecentOperations() { + final int resourceId = this.resourceComposite.getResource().getId(); + GWTServiceLookup.getOperationService().findRecentCompletedOperations(5, + new AsyncCallback<List<DisambiguationReport<ResourceOperationLastCompletedComposite>>>() { + + @Override + public void onFailure(Throwable caught) { + Log.debug("Error retrieving recent operations for resource [" + resourceId + "]:" + + caught.getMessage()); + } + + @Override + public void onSuccess(List<DisambiguationReport<ResourceOperationLastCompletedComposite>> result) { + LocatableVLayout column = new LocatableVLayout(recentOperationsContent.extendLocatorId("Content")); + column.setHeight(10); + if (!result.isEmpty()) { + for (DisambiguationReport<ResourceOperationLastCompletedComposite> report : result) { + LocatableDynamicForm row = new LocatableDynamicForm(recentOperationsContent + .extendLocatorId("ContentForm")); + row.setNumCols(3); + + StaticTextItem iconItem = new StaticTextItem(); + FormItemIcon img = new FormItemIcon(); + img.setSrc(ImageManager.getOperationResultsIcon(report.getOriginal().getOperationStatus())); + img.setWidth(16); + img.setHeight(16); + iconItem.setIcons(img); + iconItem.setShowTitle(false); + + LinkItem link = new LinkItem(); + link.setLinkTitle(report.getOriginal().getOperationName()); + link.setTitle(report.getOriginal().getOperationName()); + link.setValue(ReportDecorator.GWT_RESOURCE_URL + resourceId + "/Operations/History/" + + report.getOriginal().getOperationHistoryId()); + link.setTarget("_self"); + link.setShowTitle(false); + + StaticTextItem time = new StaticTextItem(); + time.setDefaultValue(new Date(report.getOriginal().getOperationStartTime()).toString()); + time.setShowTitle(false); + time.setShowPickerIcon(false); + time.setWrap(false); + row.setItems(iconItem, link, time); + + column.addMember(row); + } + } else { + column.setContents(RECENT_OPERATIONS_NONE); + } + for (Canvas child : recentOperationsContent.getChildren()) { + child.destroy(); + } + recentOperationsContent.addChild(column); + recentOperationsContent.markForRedraw(); + } + }); + } + + private void getRecentConfigurationUpdates() { + final int resourceId = this.resourceComposite.getResource().getId(); + ResourceConfigurationUpdateCriteria criteria = new ResourceConfigurationUpdateCriteria(); + criteria.addFilterResourceIds(resourceId); + PageControl pageControl = new PageControl(0, 5); + criteria.setPageControl(pageControl); + GWTServiceLookup.getConfigurationService().findResourceConfigurationUpdatesByCriteria(criteria, + new AsyncCallback<PageList<ResourceConfigurationUpdate>>() { + + @Override + public void onFailure(Throwable caught) { + Log.debug("Error retrieving recent configuration updates for resource [" + resourceId + "]:" + + caught.getMessage()); + } + + @Override + public void onSuccess(PageList<ResourceConfigurationUpdate> result) { + LocatableVLayout column = new LocatableVLayout(recentOperationsContent.extendLocatorId("Content")); + column.setHeight(10); + if (!result.isEmpty()) { + for (ResourceConfigurationUpdate update : result) { + LocatableDynamicForm row = new LocatableDynamicForm(recentConfigurationContent + .extendLocatorId("ContentForm")); + row.setNumCols(3); + + StaticTextItem iconItem = new StaticTextItem(); + FormItemIcon img = new FormItemIcon(); + img.setSrc(ImageManager.getConfigurationUpdateResultsIcon(update.getStatus())); + img.setWidth(16); + img.setHeight(16); + iconItem.setIcons(img); + iconItem.setShowTitle(false); + + LinkItem link = new LinkItem(); + link.setLinkTitle(MSG.view_resource_inventory_activity_changed_by() + + update.getSubjectName()); + link.setTitle(MSG.view_resource_inventory_activity_changed_by() + update.getSubjectName()); + link.setValue(ReportDecorator.GWT_RESOURCE_URL + resourceId + "/Configuration/History/" + + update.getId()); + link.setTarget("_self"); + link.setShowTitle(false); + + StaticTextItem time = new StaticTextItem(); + time.setDefaultValue(new Date(update.getCreatedTime()).toString()); + time.setShowTitle(false); + time.setShowPickerIcon(false); + time.setWrap(false); + row.setItems(iconItem, link, time); + + column.addMember(row); + } + } else { + LocatableDynamicForm row = new LocatableDynamicForm(recentConfigurationContent + .extendLocatorId("ContentForm")); + row.setNumCols(3); + StaticTextItem none = new StaticTextItem(); + none.setShowTitle(false); + none.setDefaultValue(RECENT_CONFIGURATIONS_NONE); + none.setWrap(false); + row.setItems(none); + column.addMember(row); + } + //cleanup + for (Canvas child : recentConfigurationContent.getChildren()) { + child.destroy(); + } + recentConfigurationContent.addChild(column); + recentConfigurationContent.markForRedraw(); + } + }); + } + + private void getRecentEventUpdates() { + final int resourceId = this.resourceComposite.getResource().getId(); + EventCriteria criteria = new EventCriteria(); + // criteria.addFilterResourceIds(resourceId); + long now = System.currentTimeMillis(); + long nowMinus24Hours = now - (24 * 60 * 60 * 1000); + + criteria.addFilterResourceId(resourceId); + PageControl pageControl = PageControl.getUnlimitedInstance(); + criteria.setPageControl(pageControl); + //Error retrieving recent event counts for resource [" + resourceId + "]:" + // GWTServiceLookup.getEventService().getEventCountsBySeverity(resourceId, nowMinus24Hours, now, + // new AsyncCallback<Map<EventSeverity, Integer>>() { + // @Override + // public void onFailure(Throwable caught) { + // Log.debug("Error retrieving recent event counts for resource [" + resourceId + "]:" + // + caught.getMessage()); + // } + // + // @Override + // public void onSuccess(Map<EventSeverity, Integer> result) { + // LocatableVLayout column = new LocatableVLayout(recentOperationsContent.extendLocatorId("Content")); + // column.setHeight(10); + // if (!result.isEmpty()) { + // for (Entry<EventSeverity, Integer> entry : result.entrySet()) { + // EventSeverity severity = entry.getKey(); + // LocatableDynamicForm row = new LocatableDynamicForm(recentOperationsContent + // .extendLocatorId("ContentForm")); + // row.setNumCols(2); + // + // StaticTextItem iconItem = new StaticTextItem(); + // FormItemIcon img = new FormItemIcon(); + // img.setSrc(ImageManager.getEventSeverityIcon(severity)); + // // img.set + // img.setWidth(16); + // img.setHeight(16); + // iconItem.setIcons(img); + // iconItem.setShowTitle(false); + // + // StaticTextItem time = new StaticTextItem(); + // time.setDefaultValue(entry.getValue()); + // time.setShowTitle(false); + // time.setShowPickerIcon(false); + // time.setWrap(false); + // row.setItems(iconItem, time); + // + // column.addMember(row); + // } + // } else { + // LocatableDynamicForm row = new LocatableDynamicForm(recentEventsContent + // .extendLocatorId("ContentForm")); + // row.setNumCols(3); + // StaticTextItem none = new StaticTextItem(); + // none.setShowTitle(false); + // none.setDefaultValue(RECENT_EVENTS_NONE); + // none.setWrap(false); + // row.setItems(none); + // column.addMember(row); + // } + // //cleanup + // for (Canvas child : recentEventsContent.getChildren()) { + // child.destroy(); + // } + // recentEventsContent.addChild(column); + // recentEventsContent.markForRedraw(); + // } + // }); + } + + private void getRecentOobs() { + final int resourceId = this.resourceComposite.getResource().getId(); + AlertCriteria criteria = new AlertCriteria(); + criteria.addFilterResourceIds(resourceId); + PageControl pageControl = new PageControl(0, 5); + criteria.setPageControl(pageControl); + GWTServiceLookup.getMeasurementDataService().getHighestNOOBsForResource(resourceId, 5, + new AsyncCallback<PageList<MeasurementOOBComposite>>() { + @Override + public void onFailure(Throwable caught) { + Log.debug("Error retrieving recent out of bound metrics for resource [" + resourceId + "]:" + + caught.getMessage()); + } + + @Override + public void onSuccess(PageList<MeasurementOOBComposite> result) { + LocatableVLayout column = new LocatableVLayout(recentAlertsContent.extendLocatorId("Content")); + column.setHeight(10); + if (!result.isEmpty()) { + for (MeasurementOOBComposite oob : result) { + LocatableDynamicForm row = new LocatableDynamicForm(recentOobContent + .extendLocatorId("ContentForm")); + row.setNumCols(3); + + // StaticTextItem iconItem = new StaticTextItem(); + // FormItemIcon img = new FormItemIcon(); + // img.setSrc(ImageManager.getAlertIcon(alert.getAlertDefinition().getPriority())); + // img.setWidth(16); + // img.setHeight(16); + // iconItem.setIcons(img); + // iconItem.setShowTitle(false); + // + // LinkItem link = new LinkItem(); + // link.setLinkTitle(alert.getAlertDefinition().getName()); + // link.setTitle(alert.getAlertDefinition().getName()); + // link.setValue(ReportDecorator.GWT_RESOURCE_URL + resourceId + "/Alerts/Definitions/" + // + alert.getAlertDefinition().getId()); + // link.setTarget("_self"); + // link.setShowTitle(false); + // + // StaticTextItem time = new StaticTextItem(); + // time.setDefaultValue(new Date(alert.getAlertDefinition().getCtime()).toString()); + // time.setShowTitle(false); + // time.setShowPickerIcon(false); + // time.setWrap(false); + // row.setItems(iconItem, link, time); + // + // column.addMember(row); + } + } else { + column.setContents(RECENT_OOB_NONE); + } + recentOobContent.setContents(""); + for (Canvas child : recentOobContent.getChildren()) { + child.destroy(); + } + recentOobContent.addChild(column); + recentOobContent.markForRedraw(); + + } + }); + } + + private void getRecentPkgHistory() { + final int resourceId = this.resourceComposite.getResource().getId(); + InstalledPackageCriteria criteria = new InstalledPackageCriteria(); + criteria.addFilterResourceId(resourceId); + // criteria. + PageControl pageControl = new PageControl(0, 5); + criteria.setPageControl(pageControl); + + // GWTServiceLookup.getContentService().getInstalledPackageHistoryForResource(resourceId, 5, + // new AsyncCallback<PageList<InstalledPackageHistory>>() { + // @Override + // public void onFailure(Throwable caught) { + // Log.debug("Error retrieving installed package history for resource [" + resourceId + "]:" + // + caught.getMessage()); + // } + // + // @Override + // public void onSuccess(PageList<InstalledPackageHistory> result) { + // LocatableVLayout column = new LocatableVLayout(recentPkgHistoryContent.extendLocatorId("Content")); + // column.setHeight(10); + // if (!result.isEmpty()) { + // for (InstalledPackageHistory history : result) { + // LocatableDynamicForm row = new LocatableDynamicForm(recentPkgHistoryContent + // .extendLocatorId("ContentForm")); + // row.setNumCols(3); + // + // StaticTextItem iconItem = new StaticTextItem(); + // FormItemIcon img = new FormItemIcon(); + // img.setSrc("subsystems/content/Content_16.png"); + // img.setWidth(16); + // img.setHeight(16); + // iconItem.setIcons(img); + // iconItem.setShowTitle(false); + // + // LinkItem link = new LinkItem(); + // link.setLinkTitle(history.getPackageVersion().getDisplayName()); + // link.setTitle(history.getPackageVersion().getDisplayName()); + // // link.setValue(ReportDecorator.GWT_RESOURCE_URL + resourceId + "/Configuration/History/" + // // + update.getId()); + // //link.setValue(rhq/resource/content/audit-trail-item.xhtml?id=10005&selectedHistoryId=10002 + // link.setValue("rhq/resource/content/audit-trail-item.xhtml?id=" + resourceId + // + "&selectedHistoryId=" + history.getId()); + // link.setTarget("_self"); + // link.setShowTitle(false); + // + // StaticTextItem time = new StaticTextItem(); + // time.setDefaultValue(new Date(history.getTimestamp()).toString()); + // time.setShowTitle(false); + // time.setShowPickerIcon(false); + // time.setWrap(false); + // row.setItems(iconItem, link, time); + // + // column.addMember(row); + // } + // } else { + // LocatableDynamicForm row = new LocatableDynamicForm(recentPkgHistoryContent + // .extendLocatorId("ContentForm")); + // row.setNumCols(3); + // StaticTextItem none = new StaticTextItem(); + // none.setShowTitle(false); + // none.setDefaultValue(RECENT_PKG_HISTORY_NONE); + // none.setWrap(false); + // row.setItems(none); + // column.addMember(row); + // } + // //cleanup + // for (Canvas child : recentPkgHistoryContent.getChildren()) { + // child.destroy(); + // } + // recentPkgHistoryContent.addChild(column); + // recentPkgHistoryContent.markForRedraw(); + // } + // }); + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java new file mode 100644 index 0000000..36dee5e --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java @@ -0,0 +1,99 @@ +package org.rhq.enterprise.gui.coregui.client.util; + +//import java.text.SimpleDateFormat; +import java.util.Date; + +import com.google.gwt.i18n.client.DateTimeFormat; +import com.google.gwt.i18n.client.TimeZone; +import com.google.gwt.i18n.client.TimeZoneInfo; + +/** An RPC gwt serializable implemenation of the jsf RelativeDurationConverter + * utility. + * + * Convert the passed value in to a relative date compared to now. + * If the passed value is -1, the output will be empty (as a value of 0 + * returns the number of days since the epoch) + * @author Joseph Marques + * @author Simeon Pinder + */ +public class GwtRelativeDurationConverter { + private static final long MILLIS_IN_SECOND = 1000L; + private static final long MILLIS_IN_MINUTE = 60 * MILLIS_IN_SECOND; + private static final long MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE; + private static final long NEVER = -1; + + private static final long MILLIS_IN_DAY = 24 * MILLIS_IN_HOUR; + // private static final SimpleDateFormat dayFormatter = new SimpleDateFormat("D"); + // private static final SimpleDateFormat formatter = new SimpleDateFormat("hh:mm aaa z"); + private static final DateTimeFormat dayFormatter = DateTimeFormat.getFormat("D"); + private static final DateTimeFormat formatter = DateTimeFormat.getFormat("hh:mm aaa z"); + + public static TimeZone tz = null; + + public static String format(long eventMillis) { + int dayOfYearToday = Integer.parseInt(dayFormatter.format(new Date(System.currentTimeMillis()))); + int dayOfYearEvent = Integer.parseInt(dayFormatter.format(new Date(eventMillis))); + String result = null; + if (dayOfYearEvent == dayOfYearToday) { + // <time> + result = formatter.format(new Date(eventMillis)); + } else if (dayOfYearEvent == dayOfYearToday - 1) { + // "yesterday" <time> + result = "Yesterday, " + formatter.format(new Date(eventMillis)); + } else { + // <time> "ago" + result = getRelativeTimeAgo(eventMillis) + " ago"; + } + return result; + } + + private static TimeZone getTimeZone() { + if (tz == null) { + // return TimeZone.getDefault(); + return TimeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(String.valueOf(System.currentTimeMillis()))); + } else { + return tz; + } + } + + private static String getRelativeTimeAgo(long millis) { + StringBuilder buf = new StringBuilder(); + long timeAgo = System.currentTimeMillis() - millis; + + int count = 0; + int days = (int) (timeAgo / MILLIS_IN_DAY); + timeAgo %= MILLIS_IN_DAY; + if (days > 0) { + count++; + buf.append(days).append(" day"); + if (days != 1) + buf.append("s"); + } + + int hours = (int) (timeAgo / MILLIS_IN_HOUR); + timeAgo %= MILLIS_IN_HOUR; + if (hours > 0) { + count++; + if (buf.length() > 0) + buf.append(", "); + buf.append(hours).append(" hour"); + if (hours != 1) + buf.append("s"); + } + + if (count < 2) { + int mins = (int) (timeAgo / MILLIS_IN_MINUTE); + timeAgo %= MILLIS_IN_MINUTE; + if (mins > 0) { + if (buf.length() > 0) + buf.append(", "); + buf.append(mins).append(" minute"); + if (mins != 1) + buf.append("s"); + } + } + + return buf.toString(); + } + +} 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 bd6da37..cc9c288 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 @@ -33,6 +33,7 @@ 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; +import org.rhq.enterprise.server.content.ContentUIManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -43,6 +44,7 @@ public class ContentGWTServiceImpl extends AbstractGWTServiceImpl implements Con private static final long serialVersionUID = 1L;
private ContentManagerLocal contentManager = LookupUtil.getContentManager(); + private ContentUIManagerLocal contentUiManager = LookupUtil.getContentUIManager();
public void deletePackageVersion(int packageVersionId) { try { @@ -61,6 +63,16 @@ public class ContentGWTServiceImpl extends AbstractGWTServiceImpl implements Con } }
+ // public PageList<InstalledPackageHistory> getInstalledPackageHistoryForResource(int resourceId, int count) { + // try { + // PageControl pc = new PageControl(0, count); + // return SerialUtility.prepare(contentUiManager.getInstalledPackageHistoryForResource(resourceId, pc), + // "ContentService.getInstalledPackageHistoryForResource"); + // } catch (Exception e) { + // throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + // } + // } + public List<Architecture> getArchitectures() { try { return SerialUtility.prepare(contentManager.findArchitectures(getSessionSubject()), 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 3dbae8e..6369c90 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 @@ -75,6 +75,15 @@ public class EventGWTServiceImpl extends AbstractGWTServiceImpl implements Event } }
+ // public Map<EventSeverity, Integer> getEventCountsBySeverity(int resourceId, long startDate, long endDate) { + // try { + // return SerialUtility.prepare(eventManager.getEventCountsBySeverity(getSessionSubject(), resourceId, + // startDate, endDate), "EventService.getEventCountsBySeverity"); + // } catch (Exception e) { + // throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + // } + // } + public PageList<Event> findEventsByCriteria(EventCriteria criteria) { try { return SerialUtility.prepare(eventManager.findEventsByCriteria(getSessionSubject(), criteria), diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 2c45fbb..8f06b15 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -133,7 +133,12 @@ common_title_port = Port common_title_providers = Providers common_title_recently_added = Recently Added Resources common_title_recent_alerts = Recent Alerts +common_title_recent_configuration_updates=Recent Configuration Updates +common_title_recent_event_counts=Recent Event Counts +common_title_recent_measurements=Recent Measurements +common_title_recent_oob_metrics=Recent Out of Bound metrics common_title_recent_operations = Recent Operations +common_title_recent_pkg_history=Recent Package History common_title_remove_column = Remove Column common_title_repositories = Repositories common_title_resource = Resource @@ -1286,6 +1291,14 @@ view_inventory_resources_loadFailed = Failed to load resource composite data view_inventory_resources_title = Member Resources view_inventory_resources_title_children = Child Resources view_inventory_resources_title_members = Member Resources +view_resource_inventory_activity_changed_by=Changed by +view_resource_inventory_activity_no_recent_alerts=No recent alerts +view_resource_inventory_activity_no_recent_config_history=No configuration change history +view_resource_inventory_activity_no_recent_events =No events in the last 24 hours +view_resource_inventory_activity_no_recent_metrics=This resource has no recent metrics +view_resource_inventory_activity_no_recent_oob=No OOB conditions found +view_resource_inventory_activity_no_recent_operations=No recent operation history +view_resource_inventory_activity_no_recent_pkg_history=No recent package history view_resource_monitor_availability_loadFailed = Failed to load availability history view_resource_monitor_graphs_noneAvailable = No graphs available view_resource_monitor_graphs_loadFailed = Failed to load graph data
commit 79bcb67697b578e110e62bed262ec9a363fbb1bd Author: Heiko W. Rupp hwr@redhat.com Date: Tue Dec 21 11:46:35 2010 +0100
See if attaching the BundleVersion to the EM allows to pick up the Bundle for the implicit toString() call to work.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java index 968d5cd..932e617 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java @@ -158,7 +158,7 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { // remove bundleversions which cascade remove bundlefiles and bundledeployments // bundlefiles cascaderemove packageversions // bundledeployments cascade remove bundleresourcedeployments - // bundleresourcedeployments cascade remove bundleresourcedeploymenthistory + // bundleresourcedeployments cascade remove bundleresourcedeploymenthistory q = em.createQuery("SELECT bv FROM BundleVersion bv WHERE bv.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { @@ -172,7 +172,7 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { for (Object removeMe : doomed) { em.remove(em.getReference(BundleFile.class, ((BundleFile) removeMe).getId())); } - // remove any orphaned deployment history + // remove any orphaned deployment history q = em .createQuery("SELECT brdh FROM BundleResourceDeploymentHistory brdh WHERE brdh.resourceDeployment.bundleDeployment.name LIKE '" + TEST_PREFIX + "%'"); @@ -198,7 +198,7 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase {
// remove bundles which cascade remove packageTypes and destinations // packagetypes cascade remove packages - // package cascade remove packageversions + // package cascade remove packageversions q = em.createQuery("SELECT b FROM Bundle b WHERE b.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { @@ -218,27 +218,27 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { for (Object removeMe : doomed) { em.remove(em.getReference(Package.class, ((Package) removeMe).getId())); } - // remove any orphaned packagetypes + // remove any orphaned packagetypes q = em.createQuery("SELECT pt FROM PackageType pt WHERE pt.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { em.remove(em.getReference(PackageType.class, ((PackageType) removeMe).getId())); } - // remove any orphaned destinations + // remove any orphaned destinations q = em.createQuery("SELECT bd FROM BundleDestination bd WHERE bd.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { em.remove(em.getReference(BundleDestination.class, ((BundleDestination) removeMe).getId())); }
- // remove repos no longer referenced by bundles + // remove repos no longer referenced by bundles q = em.createQuery("SELECT r FROM Repo r WHERE r.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { em.remove(em.getReference(Repo.class, ((Repo) removeMe).getId())); }
- // remove Resource Groups left over from test deployments freeing up test resources + // remove Resource Groups left over from test deployments freeing up test resources q = em.createQuery("SELECT rg FROM ResourceGroup rg WHERE rg.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { @@ -259,7 +259,7 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { em.remove(em.getReference(BundleType.class, ((BundleType) removeMe).getId())); }
- // remove Agents left over from test resources + // remove Agents left over from test resources q = em.createQuery("SELECT a FROM Agent a WHERE a.name LIKE '" + TEST_PREFIX + "%'"); doomed = q.getResultList(); for (Object removeMe : doomed) { @@ -928,6 +928,8 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { c.addFilterName(TEST_PREFIX); bvs = bundleManager.findBundleVersionsByCriteria(overlord, c); bv = bvs.get(1); + EntityManager em = getEntityManager(); + bv = em.merge(bv); assertNotNull(bvs); assertEquals(3, bvs.size()); assertEquals(bv2, bv);
commit 77fdb652eb6ffd64f2a89800a3d9e03900b44f71 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Dec 20 21:50:25 2010 -0500
Group Authorization work - enhanced AuthorizationManager to handle more group authz cases - enhanced findResourceGroup[Composite]sByCriteria to handle more group authz cases and to return proper resourcePermission for all cases, for composites.
Group Context Menu work - fixed issues in autogroup and clustergroup context menus - added authz to the group context menus
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 4855575..e819c36 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 @@ -65,6 +65,15 @@ public class LinkManager { } }
+ public static String getAutoClusterTabLink(int autoClusterGroupId, String tabName, String subTabName) { + if (GWT) { + return "#ResourceGroup/AutoCluster/" + autoClusterGroupId + "/" + tabName + + ((null == subTabName) ? "" : ("/" + subTabName)); + } else { + return "/rhq/group/inventory/view.xhtml?groupId=" + autoClusterGroupId; + } + } + public static String getResourceGroupTabLink(int resourceGroupId, String tabName, String subTabName) { if (GWT) { return "#ResourceGroup/" + resourceGroupId + "/" + tabName diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java index c6ce934..0b454bf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java @@ -26,9 +26,6 @@ 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; @@ -36,19 +33,19 @@ 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.criteria.ResourceGroupCriteria; 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.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.LinkManager; 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; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; @@ -58,37 +55,70 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; */ public class ResourceGroupContextMenu extends LocatableMenu {
+ private ResourceGroupComposite groupComposite; + private ResourceGroup group; + private ResourceType groupMemberType; + + private boolean isAutoCluster = false; private boolean isAutoGroup = false;
public ResourceGroupContextMenu(String locatorId) { super(locatorId); }
- public ResourceGroupContextMenu(String locatorId, boolean isAutoGroup) { - super(locatorId); - this.isAutoGroup = isAutoGroup; - } + public void showContextMenu(final ResourceGroup group) { + // we need the group composite to access permissions for context menu authz, so get it now + ResourceGroupCriteria criteria = new ResourceGroupCriteria(); + criteria.addFilterId(group.getId()); + + // for autoclusters and private groups (autogroups) we need to add more criteria + isAutoCluster = (null != group.getClusterResourceGroup()); + isAutoGroup = (null != group.getSubject()); + + if (isAutoCluster) { + criteria.addFilterVisible(false); + + } else if (isAutoGroup) { + criteria.addFilterVisible(false); + criteria.addFilterPrivate(true); + }
- private ResourceType currentType; - //private ResourceGroup group; - private ResourceGroup currentGroup; + GWTServiceLookup.getResourceGroupService().findResourceGroupCompositesByCriteria(criteria, + new AsyncCallback<PageList<ResourceGroupComposite>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_group_detail_failLoadComp(String.valueOf(group.getId())), caught); + } + + public void onSuccess(PageList<ResourceGroupComposite> result) { + if (result.isEmpty()) { + CoreGUI.getErrorHandler().handleError( + MSG.view_group_detail_failLoadComp(String.valueOf(group.getId()))); + } else { + showContextMenu(result.get(0)); + } + } + }); + }
- public void showContextMenu(ResourceGroup compatibleGroup) { - this.currentType = compatibleGroup.getResourceType(); - this.currentGroup = compatibleGroup; + public void showContextMenu(ResourceGroupComposite groupComposite) { + this.groupComposite = groupComposite; + group = groupComposite.getResourceGroup(); + groupMemberType = group.getResourceType(); + isAutoCluster = (null != group.getClusterResourceGroup()); + isAutoGroup = (null != group.getSubject());
ResourceTypeRepository.Cache.getInstance().getResourceTypes( - currentType.getId(), + groupMemberType.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) { + groupMemberType = type;
- currentType = type; - - buildResourceGroupContextMenu(currentGroup, type); + buildResourceGroupContextMenu(group, type); showContextMenu(); } }); @@ -105,87 +135,67 @@ public class ResourceGroupContextMenu extends LocatableMenu { addItem(new MenuItemSeparator());
// plugin config - MenuItem editPluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); - editPluginConfiguration.addClickHandler(new ClickHandler() { + MenuItem pluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); + pluginConfiguration.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { if (isAutoGroup) { CoreGUI.goToView(LinkManager.getAutoGroupTabLink(group.getId(), "Inventory", "ConnectionSettings")); + } else if (isAutoCluster) { + CoreGUI.goToView(LinkManager + .getAutoClusterTabLink(group.getId(), "Inventory", "ConnectionSettings")); } else { CoreGUI.goToView(LinkManager.getResourceGroupTabLink(group.getId(), "Inventory", "ConnectionSettings")); } } }); - editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); - addItem(editPluginConfiguration); - - MenuItem editResourceConfiguration = new MenuItem(MSG.view_tree_common_contextMenu_resourceConfiguration()); - editResourceConfiguration.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - int groupId = group.getId(); - int resourceTypeId = resourceType.getId(); - - final Window configEditor = new Window(); - configEditor.setTitle(MSG.view_tree_common_contextMenu_editResourceConfiguration(group.getName())); - 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(); + pluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); + addItem(pluginConfiguration); + + MenuItem resourceConfiguration = new MenuItem(MSG.view_tree_common_contextMenu_resourceConfiguration()); + boolean enabled = groupComposite.getResourcePermission().isConfigureRead() + && resourceType.getResourceConfigurationDefinition() != null; + resourceConfiguration.setEnabled(enabled); + if (enabled) { + resourceConfiguration.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + if (isAutoGroup) { + CoreGUI.goToView(LinkManager.getAutoGroupTabLink(group.getId(), "Configuration", "Current")); + } else if (isAutoCluster) { + CoreGUI.goToView(LinkManager.getAutoClusterTabLink(group.getId(), "Configuration", "Current")); + } else { + CoreGUI.goToView(LinkManager.getResourceGroupTabLink(group.getId(), "Inventory", + "ConnectionSettings")); } - }); - // TODO group config editor - // configEditor.addItem(new ConfigurationEditor(resourceId, resourceTypeId, - // ConfigurationEditor.ConfigType.resource)); - configEditor.show(); - - } - }); - editResourceConfiguration.setEnabled(resourceType.getResourceConfigurationDefinition() != null); - addItem(editResourceConfiguration); + } + }); + } + addItem(resourceConfiguration);
+ // separator addItem(new MenuItemSeparator());
// Operations Menu MenuItem operations = new MenuItem(MSG.view_tree_common_contextMenu_operations()); - Menu opSubMenu = new Menu(); - if (resourceType.getOperationDefinitions() != null) { + enabled = (groupComposite.getResourcePermission().isControl() && null != resourceType.getOperationDefinitions() && !resourceType + .getOperationDefinitions().isEmpty()); + operations.setEnabled(enabled); + if (enabled) { + Menu opSubMenu = new Menu(); 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(); - // } - // }); - + // TODO Group version, wizard invoke or tab nav? } }); opSubMenu.addItem(operationItem); } + operations.setSubmenu(opSubMenu); } - operations.setEnabled(resourceType.getOperationDefinitions() != null - && !resourceType.getOperationDefinitions().isEmpty()); - operations.setSubmenu(opSubMenu); addItem(operations);
+ // Metric graph addition menu addItem(buildMetricsMenu(resourceType));
/* TODO: We don't support group factory create @@ -227,6 +237,7 @@ public class ResourceGroupContextMenu extends LocatableMenu { */ }
+ /* private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu) { ResourceTypeGWTServiceAsync rts = GWTServiceLookup.getResourceTypeGWTService();
@@ -248,6 +259,7 @@ public class ResourceGroupContextMenu extends LocatableMenu { } }); } + */
private MenuItem buildMetricsMenu(final ResourceType type) { MenuItem measurements = new MenuItem(MSG.view_tree_common_contextMenu_measurements()); @@ -279,7 +291,7 @@ public class ResourceGroupContextMenu extends LocatableMenu { DashboardPortlet p = new DashboardPortlet(def.getDisplayName() + " " + MSG.view_tree_common_contextMenu_chart(), GraphPortlet.KEY, 250); p.getConfiguration().put( - new PropertySimple(GraphPortlet.CFG_RESOURCE_GROUP_ID, currentGroup.getId())); + new PropertySimple(GraphPortlet.CFG_RESOURCE_GROUP_ID, group.getId())); p.getConfiguration().put( new PropertySimple(GraphPortlet.CFG_DEFINITION_ID, def.getId()));
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 de0f1ea..a056ca1 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 @@ -74,6 +74,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka private ViewId currentViewId; private int rootGroupId; private int selectedGroupId; + private String selectedNodeId;
private ResourceGroupTreeContextMenu contextMenu;
@@ -111,8 +112,9 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { @Override public void onSelectionChanged(SelectionEvent selectionEvent) { - if (selectionEvent.getState()) { + if (!selectionEvent.isRightButtonDown() && selectionEvent.getState()) { Record selectedNode = selectionEvent.getRecord(); + selectedNodeId = selectedNode.getAttribute("id"); com.allen_sauer.gwt.log.client.Log.info("Node selected in tree: " + selectedNode); ResourceType type = (ResourceType) selectedNode.getAttributeAsObject("resourceType"); if (type != null) { @@ -138,9 +140,15 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
treeGrid.addNodeContextClickHandler(new NodeContextClickHandler() { public void onNodeContextClick(final NodeContextClickEvent event) { - event.getNode(); + // stop the browser right-click menu event.cancel();
+ // don't select the node on a right click, since we're not navigating to it + treeGrid.deselectRecord(event.getNode()); + if (null != selectedNodeId) { + treeGrid.selectRecord(treeGrid.getTree().findById(selectedNodeId)); + } + contextMenu.showContextMenu(event.getNode()); } }); 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 b636b38..9cebc97 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 @@ -85,6 +85,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.factory.Resource import org.rhq.enterprise.gui.coregui.client.inventory.resource.factory.ResourceFactoryImportWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -136,8 +137,8 @@ public class ResourceTreeView extends LocatableVLayout {
treeGrid.setLeaveScrollbarGap(false);
- resourceContextMenu = new Menu(); - autoGroupContextMenu = new ResourceGroupContextMenu(extendLocatorId("autoGroupContextMenu"), true); + resourceContextMenu = new LocatableMenu(extendLocatorId("resourceContextMenu")); + autoGroupContextMenu = new ResourceGroupContextMenu(extendLocatorId("autoGroupContextMenu"));
treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { @@ -383,35 +384,36 @@ public class ResourceTreeView extends LocatableVLayout { resourceContextMenu.addItem(new MenuItemSeparator());
// plugin config - MenuItem editPluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); - editPluginConfiguration.addClickHandler(new ClickHandler() { + MenuItem pluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); + pluginConfiguration.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { CoreGUI.goToView(LinkManager.getResourceTabLink(resource.getId(), "Inventory", "ConnectionSettings")); } }); - editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); - resourceContextMenu.addItem(editPluginConfiguration); + pluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); + resourceContextMenu.addItem(pluginConfiguration);
// resource config - MenuItem editResourceConfiguration = new MenuItem(MSG.view_tree_common_contextMenu_resourceConfiguration()); + MenuItem resourceConfiguration = new MenuItem(MSG.view_tree_common_contextMenu_resourceConfiguration()); boolean enabled = resourcePermission.isConfigureRead() && resourceType.getResourceConfigurationDefinition() != null; - editResourceConfiguration.setEnabled(enabled); + resourceConfiguration.setEnabled(enabled); if (enabled) { - editResourceConfiguration.addClickHandler(new ClickHandler() { + resourceConfiguration.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { CoreGUI.goToView(LinkManager.getResourceTabLink(resource.getId(), "Configuration", "Current")); } }); } - resourceContextMenu.addItem(editResourceConfiguration); + resourceContextMenu.addItem(resourceConfiguration);
// separator resourceContextMenu.addItem(new MenuItemSeparator());
// Operations Menu MenuItem operations = new MenuItem(MSG.view_tree_common_contextMenu_operations()); - enabled = (resourcePermission.isControl() && !resourceType.getOperationDefinitions().isEmpty()); + enabled = (resourcePermission.isControl() && null == resourceType.getOperationDefinitions() && !resourceType + .getOperationDefinitions().isEmpty()); operations.setEnabled(enabled); if (enabled) { Menu opSubMenu = new Menu(); @@ -419,29 +421,10 @@ 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(resourceId); - - GWTServiceLookup.getResourceService().findResourcesByCriteria(criteria, - new AsyncCallback<PageList<Resource>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - MSG.view_tree_common_contextMenu_operations_loadFailed(), caught); - } - - public void onSuccess(PageList<Resource> result) { - new OperationCreateWizard(result.get(0), operationDefinition) - .startOperationWizard(); - } - }); - + new OperationCreateWizard(resource, operationDefinition).startOperationWizard(); } }); opSubMenu.addItem(operationItem); - // todo action } operations.setSubmenu(opSubMenu); } 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 1da673c..d7eb82f 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,7 +18,6 @@ */ package org.rhq.enterprise.server.authz;
-import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; @@ -33,7 +32,6 @@ 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;
@@ -69,16 +67,35 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
@SuppressWarnings("unchecked") public Set<Permission> getExplicitGroupPermissions(Subject subject, int groupId) { - Query query = entityManager.createNamedQuery(Subject.QUERY_GET_PERMISSIONS_BY_GROUP_ID); - query.setParameter("subject", subject); - query.setParameter("groupId", groupId); - List<Permission> intermediate = query.getResultList(); - Set<Permission> results = new HashSet<Permission>(); - for (Permission permission : intermediate) { - results.add(permission); + Set<Permission> result = new HashSet<Permission>(); + + ResourceGroup group = entityManager.find(ResourceGroup.class, groupId); + Subject owner = group.getSubject(); + + if (null == owner) { + // role-owned group + Query query = entityManager.createNamedQuery(Subject.QUERY_GET_PERMISSIONS_BY_GROUP_ID); + query.setParameter("subject", subject); + query.setParameter("groupId", groupId); + List<Permission> resultList = query.getResultList(); + for (Permission permission : resultList) { + result.add(permission); + } + + } else { + // don't let a user other than the owner do anything with this group + if (subject.equals(owner)) { + Query query = entityManager.createNamedQuery(Subject.QUERY_GET_PERMISSIONS_BY_PRIVATE_GROUP_ID); + query.setParameter("subjectId", subject.getId()); + query.setParameter("privateGroupId", groupId); + List<Object[]> resultList = query.getResultList(); + for (Object[] row : resultList) { + result.add((Permission) row[0]); + } + } }
- return results; + return result; }
public Set<Permission> getImplicitGroupPermissions(Subject subject, int groupId) { @@ -119,6 +136,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal { return (count != 0); }
+ @SuppressWarnings("unchecked") public boolean hasGroupPermission(Subject subject, Permission permission, int groupId) { if (isInventoryManager(subject)) { return true; @@ -142,14 +160,12 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal { 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); + Query query = entityManager.createNamedQuery(Subject.QUERY_HAS_PRIVATE_GROUP_PERMISSION); + query.setParameter("subjectId", subject.getId()); + query.setParameter("permission", permission); + query.setParameter("privateGroupId", groupId); + List<Object[]> resultList = query.getResultList(); + return (!resultList.isEmpty()); } }
commit bd452aa44978444ceb728ea14ba166656744f995 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Dec 20 12:20:32 2010 -0500
Fix longstanding bug where authz to resources could be denied if any of the resources were available via multiple groups to the user.
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 f870539..182b74b 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 @@ -153,12 +153,11 @@ import org.rhq.core.domain.resource.group.ResourceGroup; + " JOIN r.permissions p " // + " JOIN r.subjects s " // + " WHERE s.id = :subjectId and p = :permission ) ) "), - @NamedQuery(name = Subject.QUERY_CAN_VIEW_RESOURCE, query = "SELECT COUNT(res) " + "FROM Resource res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.subjects) s " + "WHERE s = :subject AND res.id = :resourceId"),
- @NamedQuery(name = Subject.QUERY_CAN_VIEW_RESOURCES, query = "SELECT DISTINCT COUNT(res) " + @NamedQuery(name = Subject.QUERY_CAN_VIEW_RESOURCES, query = "SELECT COUNT(DISTINCT res) " + "FROM Resource res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.subjects) s " + "WHERE s = :subject AND res.id IN (:resourceIds)"),
@@ -247,6 +246,7 @@ public class Subject implements Serializable { public static final String QUERY_HAS_RESOURCE_PERMISSION = "Subject.hasResourcePermission"; public static final String QUERY_HAS_AUTO_GROUP_PERMISSION = "Subject.hasAutoGroupPermission";
+ /** This query can return more than 1 if the resource is accessible via separate groups */ public static final String QUERY_CAN_VIEW_RESOURCE = "Subject.canViewResource"; public static final String QUERY_CAN_VIEW_RESOURCES = "Subject.canViewResources"; public static final String QUERY_CAN_VIEW_GROUP = "Subject.canViewGroup";
commit 45752848315ab7ddb587566059558ab77523c5f7 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Dec 17 17:56:12 2010 -0500
Work for autogroup and autocluster context menu rendering, navigation and authorization.
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 46b4e41..4855575 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 @@ -56,6 +56,24 @@ public class LinkManager { } }
+ public static String getAutoGroupTabLink(int autoGroupId, String tabName, String subTabName) { + if (GWT) { + return "#Resource/AutoGroup/" + autoGroupId + "/" + tabName + + ((null == subTabName) ? "" : ("/" + subTabName)); + } else { + return "/rhq/group/inventory/view.xhtml?groupId=" + autoGroupId; + } + } + + public static String getResourceGroupTabLink(int resourceGroupId, String tabName, String subTabName) { + if (GWT) { + return "#ResourceGroup/" + resourceGroupId + "/" + tabName + + ((null == subTabName) ? "" : ("/" + subTabName)); + } else { + return "/rhq/group/inventory/view.xhtml?groupId=" + resourceGroupId; + } + } + public static String getGroupPluginConfigurationUpdateHistoryLink(int groupId) { return getResourceGroupLink(groupId) + "/Inventory/ConnectionSettingsHistory"; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java index 972ba73..c6ce934 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java @@ -45,6 +45,7 @@ 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.LinkManager; 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; @@ -57,10 +58,17 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; */ public class ResourceGroupContextMenu extends LocatableMenu {
+ private boolean isAutoGroup = false; + public ResourceGroupContextMenu(String locatorId) { super(locatorId); }
+ public ResourceGroupContextMenu(String locatorId, boolean isAutoGroup) { + super(locatorId); + this.isAutoGroup = isAutoGroup; + } + private ResourceType currentType; //private ResourceGroup group; private ResourceGroup currentGroup; @@ -84,33 +92,28 @@ public class ResourceGroupContextMenu extends LocatableMenu { showContextMenu(); } }); - }
private void buildResourceGroupContextMenu(final ResourceGroup group, final ResourceType resourceType) { + // name setItems(new MenuItem(group.getName()));
+ // type name addItem(new MenuItem("Type: " + resourceType.getName()));
+ // separator + addItem(new MenuItemSeparator()); + + // plugin config MenuItem editPluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); 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(); - + if (isAutoGroup) { + CoreGUI.goToView(LinkManager.getAutoGroupTabLink(group.getId(), "Inventory", "ConnectionSettings")); + } else { + CoreGUI.goToView(LinkManager.getResourceGroupTabLink(group.getId(), "Inventory", + "ConnectionSettings")); + } } }); editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); 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 9cd3ded..8c4d6a2 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 @@ -280,8 +280,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
private void updateInventoryTab(int groupId, Set<ResourceTypeFacet> facets) { // Inventory tab is always visible and enabled. - boolean canModifyMembers = (!isAutoGroup() && !isAutoCluster() - && globalPermissions.contains(Permission.MANAGE_INVENTORY)); + boolean canModifyMembers = (!isAutoGroup() && !isAutoCluster() && globalPermissions + .contains(Permission.MANAGE_INVENTORY)); updateSubTab(this.inventoryTab, this.inventoryMembers, new MembersView(this.inventoryMembers .extendLocatorId("View"), groupId, canModifyMembers), true, true); updateSubTab(this.inventoryTab, this.inventoryConn, new CurrentGroupPluginConfigurationView(this.inventoryConn @@ -310,14 +310,15 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource .extendLocatorId("View"), groupComposite), true, true); // but alert definitions can only be created on compatible groups boolean visible = (groupCategory == GroupCategory.COMPATIBLE); - Canvas canvas = (visible) ? new GroupAlertDefinitionsView(alertDef.extendLocatorId("View"), this.groupComposite) - : null; + Canvas canvas = (visible) ? new GroupAlertDefinitionsView(alertDef.extendLocatorId("View"), + this.groupComposite) : null; updateSubTab(this.alertsTab, this.alertDef, canvas, visible, true); } }
private void updateConfigurationTab(int groupId, GroupCategory groupCategory, Set<ResourceTypeFacet> facets) { - boolean visible = (groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.CONFIGURATION)); + boolean visible = (groupCategory == GroupCategory.COMPATIBLE && facets + .contains(ResourceTypeFacet.CONFIGURATION)); Set<Permission> groupPermissions = this.groupComposite.getResourcePermission().getPermissions(); if (updateTab(this.configurationTab, visible, visible && groupPermissions.contains(Permission.CONFIGURE_READ))) { //updateSubTab(this.configurationTab, this.configCurrent, new FullHTMLPane( @@ -331,10 +332,10 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource }
private void updateEventsTab(ResourceGroupComposite groupComposite, GroupCategory groupCategory, - Set<ResourceTypeFacet> facets) { + Set<ResourceTypeFacet> facets) { // allow mixed groups to show events from supporting resources - boolean visible = (groupCategory == GroupCategory.MIXED - || (groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.EVENT))); + boolean visible = (groupCategory == GroupCategory.MIXED || (groupCategory == GroupCategory.COMPATIBLE && facets + .contains(ResourceTypeFacet.EVENT))); if (updateTab(this.eventsTab, visible, true)) { updateSubTab(this.eventsTab, this.eventHistory, EventCompositeHistoryView.get(this.eventHistory .extendLocatorId("View"), groupComposite), true, true); @@ -354,10 +355,10 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
// for autoclusters and autogroups we need to add more criteria if (isAutoCluster()) { - criteria.addFilterVisible(null); + criteria.addFilterVisible(false);
} else if (isAutoGroup()) { - criteria.addFilterVisible(null); + criteria.addFilterVisible(false); criteria.addFilterPrivate(true); }
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 3940108..042311b 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 @@ -113,9 +113,9 @@ public class ResourceGroupTitleBar extends LocatableVLayout { criteria.addFilterId(this.group.getId()); // for autoclusters and autogroups we need to add more criteria if (isAutoCluster) { - criteria.addFilterVisible(null); + criteria.addFilterVisible(false); } else if (isAutoGroup) { - criteria.addFilterVisible(null); + criteria.addFilterVisible(false); criteria.addFilterPrivate(true); }
@@ -200,7 +200,13 @@ public class ResourceGroupTitleBar extends LocatableVLayout { private void loadTags(final TagEditorView tagEditorView) { ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(group.getId()); - criteria.addFilterVisible(null); // default is only visible groups, null to support auto-cluster-groups + // for autoclusters and autogroups we need to add more criteria + if (isAutoCluster) { + criteria.addFilterVisible(false); + } else if (isAutoGroup) { + criteria.addFilterVisible(false); + criteria.addFilterPrivate(true); + } criteria.fetchTags(true);
GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, 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 0684946..de0f1ea 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 @@ -147,12 +147,12 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
}
- public void setSelectedGroup(final int groupId) { + public void setSelectedGroup(final int groupId, boolean isAutoCluster) { this.selectedGroupId = groupId;
ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(groupId); - criteria.addFilterVisible(null); + criteria.addFilterVisible(Boolean.valueOf(!isAutoCluster)); criteria.fetchResourceType(true);
GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, @@ -422,11 +422,11 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka currentViewId = viewPath.getNext(); String clusterGroupIdString = currentViewId.getPath(); Integer clusterGroupId = Integer.parseInt(clusterGroupIdString); - setSelectedGroup(clusterGroupId); + setSelectedGroup(clusterGroupId, true); } else { String groupIdString = currentViewId.getPath(); int groupId = Integer.parseInt(groupIdString); - setSelectedGroup(groupId); + setSelectedGroup(groupId, false); } } } 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 a0d233d..b636b38 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 @@ -137,7 +137,7 @@ public class ResourceTreeView extends LocatableVLayout { treeGrid.setLeaveScrollbarGap(false);
resourceContextMenu = new Menu(); - autoGroupContextMenu = new ResourceGroupContextMenu(extendLocatorId("autoGroupContextMenu")); + autoGroupContextMenu = new ResourceGroupContextMenu(extendLocatorId("autoGroupContextMenu"), true);
treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) {
commit e6bd91db98a6a711979d6d22cb8b221ebe532a9d Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Dec 17 17:55:17 2010 -0500
Group Authz work to cover role-owned (typical), subject-owned (private, like an auto-group backing group, and auto-cluster backing groups (role-owned, but by the root clusterResourceGroup (i.e. the recursive compatible resource group)).
This includes work in AuthorizationManager and ResourceGroupManager. It depends on pending work in CriteriaQueryGenerator.
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 e2447cd..f870539 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 @@ -63,14 +63,17 @@ import org.rhq.core.domain.resource.group.ResourceGroup; + " WHERE s.id IN ( :ids ) " // + " AND s.fsystem = FALSE " // + " AND s.factive = TRUE"), + @NamedQuery(name = Subject.QUERY_FIND_ALL, query = "" // + "SELECT s " // + " FROM Subject s " // + " WHERE s.fsystem = false"), + @NamedQuery(name = Subject.QUERY_FIND_BY_NAME, query = "" // + "SELECT s " // + " FROM Subject s " // + " WHERE s.name = :name"), + @NamedQuery(name = Subject.QUERY_GET_SUBJECTS_ASSIGNED_TO_ROLE, query = "" // + "SELECT s " // + " FROM Subject s " // @@ -94,18 +97,41 @@ import org.rhq.core.domain.resource.group.ResourceGroup; + "FROM Role r JOIN r.subjects s JOIN r.permissions p " + "WHERE " + " (" - + " r in (SELECT r2 from ResourceGroup g JOIN g.roles r2 WHERE g.id = :groupId) " + + " r in (SELECT r2 from ResourceGroup g JOIN g.roles r2 WHERE g.id = :groupId) " + " OR r in (SELECT r3 from ResourceGroup g JOIN g.clusterResourceGroup crg JOIN crg.roles r3 WHERE g.id = :groupId AND crg.recursive = true) " + " ) " + " AND s = :subject"),
+ @NamedQuery(name = Subject.QUERY_GET_PERMISSIONS_BY_PRIVATE_GROUP_ID, query = "" // + + "SELECT p, count(distinct res.id) " // + + " FROM ResourceGroup rg, IN (rg.explicitResources) res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.permissions) p " // + + " WHERE rg.id = :privateGroupId " // + + " AND rg.subject.id = :subjectId " // + + " GROUP BY p " // + + " HAVING count(distinct res.id) = " // + + " ( SELECT count(*) " // + + " FROM ResourceGroup g2 JOIN g2.explicitResources res2 " // + + " WHERE g2.id = :privateGroupId )"), + @NamedQuery(name = Subject.QUERY_HAS_GROUP_PERMISSION, query = "SELECT count(r) " + "FROM Role r JOIN r.subjects s JOIN r.permissions p " + "WHERE " + " (" - + " r in (SELECT r2 from ResourceGroup g JOIN g.roles r2 WHERE g.id = :groupId) " + + " r in (SELECT r2 from ResourceGroup g JOIN g.roles r2 WHERE g.id = :groupId) " + " OR r in (SELECT r3 from ResourceGroup g JOIN g.clusterResourceGroup crg JOIN crg.roles r3 WHERE g.id = :groupId AND crg.recursive = true) " + " ) " + " AND s = :subject " + " AND p = :permission"),
+ @NamedQuery(name = Subject.QUERY_HAS_PRIVATE_GROUP_PERMISSION, query = "" // + + "SELECT p, count(distinct res.id) " // + + " FROM ResourceGroup rg, IN (rg.explicitResources) res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.permissions) p " // + + " WHERE rg.id = :privateGroupId " // + + " AND rg.subject.id = :subjectId " // + + " AND p = :permission " // + + " GROUP BY p " // + + " HAVING count(distinct res.id) = " // + + " ( SELECT count(*) " // + + " FROM ResourceGroup g2 JOIN g2.explicitResources res2 " // + + " WHERE g2.id = :privateGroupId )"), + @NamedQuery(name = Subject.QUERY_GET_PERMISSIONS_BY_RESOURCE_ID, query = "SELECT distinct p " + "FROM Resource res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.subjects) s, IN (r.permissions) p " + "WHERE s = :subject AND res.id = :resourceId"), @@ -114,6 +140,7 @@ import org.rhq.core.domain.resource.group.ResourceGroup; + "FROM Resource res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.subjects) s, IN (r.permissions) p " + "WHERE s = :subject AND res.id = :resourceId AND p = :permission"),
+ //@Deprecated @NamedQuery(name = Subject.QUERY_HAS_AUTO_GROUP_PERMISSION, query = "" // + "SELECT COUNT(res.id) " // + " FROM Resource res " // @@ -138,19 +165,20 @@ import org.rhq.core.domain.resource.group.ResourceGroup; @NamedQuery(name = Subject.QUERY_CAN_VIEW_GROUP, query = "" // + "SELECT count(g) " // + " FROM ResourceGroup g " // - + " WHERE (g.id IN (SELECT rg.id " // - + " FROM ResourceGroup rg " // - + " JOIN rg.roles r " // - + " JOIN r.subjects s " // - + " WHERE s = :subject) " // - + " OR g.id IN (SELECT rg.id " // - + " FROM ResourceGroup rg " // - + " JOIN rg.clusterResourceGroup crg " // - + " JOIN crg.roles r " // - + " JOIN r.subjects s " // - + " WHERE crg.recursive = true AND s = :subject)) " // - + " AND g.id = :groupId"), - + + " WHERE g.id = :groupId " // + + " AND ( g.subject = :subject " // private group case (autogroup backing group) + + " OR g.id IN (SELECT rg.id " // role-associated group case + + " FROM ResourceGroup rg " // + + " JOIN rg.roles r " // + + " JOIN r.subjects s " // + + " WHERE s = :subject) " // + + " OR g.id IN (SELECT rg.id " // autocluster backing group case + + " FROM ResourceGroup rg " // + + " JOIN rg.clusterResourceGroup crg " // + + " JOIN crg.roles r " // + + " JOIN r.subjects s " // + + " WHERE crg.recursive = true AND s = :subject))"), + // @Deprecated @NamedQuery(name = Subject.QUERY_CAN_VIEW_AUTO_GROUP, query = "" // + "SELECT COUNT(res.id) " // + " FROM Resource res " // @@ -209,10 +237,13 @@ public class Subject implements Serializable {
public static final String QUERY_GET_GLOBAL_PERMISSIONS = "Subject.getGlobalPermissions"; public static final String QUERY_GET_PERMISSIONS_BY_GROUP_ID = "Subject.getPermissionsByGroup"; + public static final String QUERY_GET_PERMISSIONS_BY_PRIVATE_GROUP_ID = "Subject.getPermissionsByPrivateGroup"; public static final String QUERY_GET_PERMISSIONS_BY_RESOURCE_ID = "Subject.getPermissionsByResource"; + public static final String QUERY_ROLES_BY_RESOURCE_IDS = "Subject.getRolesByResources";
public static final String QUERY_HAS_GLOBAL_PERMISSION = "Subject.hasGlobalPermission"; public static final String QUERY_HAS_GROUP_PERMISSION = "Subject.hasGroupPermission"; + public static final String QUERY_HAS_PRIVATE_GROUP_PERMISSION = "Subject.hasPrivateGroupPermission"; public static final String QUERY_HAS_RESOURCE_PERMISSION = "Subject.hasResourcePermission"; public static final String QUERY_HAS_AUTO_GROUP_PERMISSION = "Subject.hasAutoGroupPermission";
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 09eccfc..6f99a24 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 @@ -220,10 +220,20 @@ public class ResourceGroupCriteria extends TaggedCriteria { return (Boolean.TRUE.equals(this.filterPrivate)); }
+ /** + * @param filterVisible not null. A single fetch may be for visible or invisible groups, but not both. + */ public void addFilterVisible(Boolean filterVisible) { + if (null == filterVisible) { + throw new IllegalArgumentException("A single fetch may be for visible or invisible groups, but not both."); + } this.filterVisible = filterVisible; }
+ public boolean isFilterVisible() { + return (Boolean.TRUE.equals(this.filterVisible)); + } + public void addFilterIds(Integer... filterIds) { this.filterIds = CriteriaUtils.getListIgnoringNulls(filterIds); } 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 3208c7e..a6c26e2 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 @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -1003,82 +1004,6 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso return (int) count; }
- /** - * This method adheres to all of the regular semantics of {@link Criteria}-based queries. In other words, - * all of the methods on the {@link Criteria} object - including paging, sorting, filtering, fetching - will - * work with this method. The only thing that differs is the ResultSet which, instead of being a collection - * of {@link ResourceGroup} objects is a collection of {@link ResourceGroupComposite} objects. - * - * The extended data in the composite object, however, is treated differently: - * - * 1) It is always fetched - * 2) It can not be a candidate for filtering - * 3) It must be sorted by using the zero-based positional ordinal within the projection - * - * This method offers 4 new aggregates that you can sort on. The - * - * explicitCount (ordinal 0) - the count of the number of children in the group - * explicitAvail (ordinal 1) - decimal percentage representing the number of UP children relative to the total - * number of children in the group - * implicitCount (ordinal 2) - the count of the number of descendents in the group - * implicitAvail (ordinal 3) - decimal percentage representing the number of UP descendents relative to the total - * number of descendents in the group - */ - public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(Subject subject, - ResourceGroupCriteria criteria) { - - Set<Permission> userGlobalPermissions = authorizationManager.getExplicitGlobalPermissions(subject); - - String compositeProjection; - if (userGlobalPermissions.contains(Permission.MANAGE_INVENTORY)) { - compositeProjection = "" - + " new org.rhq.core.domain.resource.group.composite.ResourceGroupComposite( " - + " ( SELECT COUNT(avail) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitCount," // explicit member count - + " ( SELECT AVG(avail.availabilityType) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitAvail," // explicit member availability - + " ( SELECT COUNT(avail) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitCount," // implicit member count - + " ( SELECT AVG(avail.availabilityType) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitAvail," // implicit member availability - + " %alias% ) "; // ResourceGroup - } else { - compositeProjection = "" - + " new org.rhq.core.domain.resource.group.composite.ResourceGroupComposite( " - + " ( SELECT COUNT(avail) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitCount," // explicit member count - + " ( SELECT AVG(avail.availabilityType) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitAvail," // explicit member availability - + " ( SELECT COUNT(avail) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitCount," // implicit member count - + " ( SELECT AVG(avail.availabilityType) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitAvail," // implicit member availability - + " %alias%, " // ResourceGroup - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 8 ), " // MANAGE_MEASUREMENTS - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 4 ), " // MODIFY_RESOURCE - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 10 ), " // CONTROL - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 7 ), " // MANAGE_ALERTS - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 14 ), " // MANAGE_EVENTS - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 13 ), " // CONFIGURE_READ - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 11 ), " // CONFIGURE_WRITE - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 9 ), " // MANAGE_CONTENT - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 6 ), " // CREATE_CHILD_RESOURCES - + " ( SELECT count(p) FROM %alias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 5 ))"; // DELETE_RESOURCES - compositeProjection = compositeProjection.replace("%subjectId%", String.valueOf(subject.getId())); - } - compositeProjection = compositeProjection.replace("%alias%", criteria.getAlias()); - - CriteriaQueryGenerator generator = getCriteriaQueryGenerator(subject, criteria, userGlobalPermissions); - generator.alterProjection(compositeProjection); - - CriteriaQueryRunner<ResourceGroupComposite> queryRunner = new CriteriaQueryRunner<ResourceGroupComposite>( - criteria, generator, entityManager, false); // don't auto-init bags, we're returning composites not entities - PageList<ResourceGroupComposite> results = queryRunner.execute(); - - for (ResourceGroupComposite composite : results) { - ResourceGroup group = composite.getResourceGroup(); - ResourceType type = group.getResourceType(); - ResourceFacets facets = (type != null) ? resourceTypeManager.getResourceFacets(type.getId()) - : ResourceFacets.NONE; - - queryRunner.initFetchFields(group); // manual field fetch for composite-wrapped entity - composite.setResourceFacets(facets); - } - return results; - } - // note, resourceId and groupId can both be NULL, and so must use the numeric wrapper classes public PageList<ResourceGroupComposite> findResourceGroupComposites(Subject subject, GroupCategory groupCategory, ResourceCategory resourceCategory, String resourceTypeName, String pluginName, String nameFilter, @@ -1503,32 +1428,151 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso @SuppressWarnings("unchecked") public PageList<ResourceGroup> findResourceGroupsByCriteria(Subject subject, ResourceGroupCriteria criteria) {
- Set<Permission> globalUserPerms = authorizationManager.getExplicitGlobalPermissions(subject); - CriteriaQueryGenerator generator = getCriteriaQueryGenerator(subject, criteria, globalUserPerms); + CriteriaAuthzType authzType = getCriteriaAuthzType(subject, criteria); + + CriteriaQueryGenerator generator = getCriteriaQueryGenerator(subject, criteria, authzType);
CriteriaQueryRunner<ResourceGroup> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); + PageList<ResourceGroup> result = queryRunner.execute(); + return result; }
- private CriteriaQueryGenerator getCriteriaQueryGenerator(Subject subject, ResourceGroupCriteria criteria, - Set<Permission> globalUserPerms) { + /** + * This method adheres to all of the regular semantics of {@link Criteria}-based queries. In other words, + * all of the methods on the {@link Criteria} object - including paging, sorting, filtering, fetching - will + * work with this method. The only thing that differs is the ResultSet which, instead of being a collection + * of {@link ResourceGroup} objects is a collection of {@link ResourceGroupComposite} objects. + * + * The extended data in the composite object, however, is treated differently: + * + * 1) It is always fetched + * 2) It can not be a candidate for filtering + * 3) It must be sorted by using the zero-based positional ordinal within the projection + * + * This method offers 4 new aggregates that you can sort on. The + * + * explicitCount (ordinal 0) - the count of the number of children in the group + * explicitAvail (ordinal 1) - decimal percentage representing the number of UP children relative to the total + * number of children in the group + * implicitCount (ordinal 2) - the count of the number of descendents in the group + * implicitAvail (ordinal 3) - decimal percentage representing the number of UP descendents relative to the total + * number of descendents in the group + */ + public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(Subject subject, + ResourceGroupCriteria criteria) { + + CriteriaAuthzType authzType = getCriteriaAuthzType(subject, criteria); + + String compositeProjection = null; + switch (authzType) { + case NONE: + case SUBJECT_OWNED: + compositeProjection = "" + + " new org.rhq.core.domain.resource.group.composite.ResourceGroupComposite( " + + " ( SELECT COUNT(avail) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitCount," // explicit member count + + " ( SELECT AVG(avail.availabilityType) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitAvail," // explicit member availability + + " ( SELECT COUNT(avail) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitCount," // implicit member count + + " ( SELECT AVG(avail.availabilityType) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitAvail," // implicit member availability + + " %alias% ) "; // ResourceGroup + break; + case ROLE_OWNED: + case AUTO_CLUSTER: + compositeProjection = "" + + " new org.rhq.core.domain.resource.group.composite.ResourceGroupComposite( " + + " ( SELECT COUNT(avail) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitCount," // explicit member count + + " ( SELECT AVG(avail.availabilityType) FROM %alias%.explicitResources res JOIN res.currentAvailability avail ) AS explicitAvail," // explicit member availability + + " ( SELECT COUNT(avail) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitCount," // implicit member count + + " ( SELECT AVG(avail.availabilityType) FROM %alias%.implicitResources res JOIN res.currentAvailability avail ) AS implicitAvail," // implicit member availability + + " %alias%, " // ResourceGroup + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 8 ), " // MANAGE_MEASUREMENTS + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 4 ), " // MODIFY_RESOURCE + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 10 ), " // CONTROL + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 7 ), " // MANAGE_ALERTS + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 14 ), " // MANAGE_EVENTS + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 13 ), " // CONFIGURE_READ + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 11 ), " // CONFIGURE_WRITE + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 9 ), " // MANAGE_CONTENT + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 6 ), " // CREATE_CHILD_RESOURCES + + " ( SELECT count(p) FROM %permAlias%.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 5 ))"; // DELETE_RESOURCES + compositeProjection = compositeProjection.replace("%subjectId%", String.valueOf(subject.getId())); + break; + default: + throw new IllegalStateException("Unexpected CriteriaAuthzType: " + authzType); + } + + String alias = criteria.getAlias(); + compositeProjection = compositeProjection.replace("%alias%", alias); + String permAlias = alias + ((authzType == CriteriaAuthzType.AUTO_CLUSTER) ? ".clusterResourceGroup" : ""); + compositeProjection = compositeProjection.replace("%permAlias%", permAlias); + + CriteriaQueryGenerator generator = getCriteriaQueryGenerator(subject, criteria, authzType); + generator.alterProjection(compositeProjection); + + CriteriaQueryRunner<ResourceGroupComposite> queryRunner = new CriteriaQueryRunner<ResourceGroupComposite>( + criteria, generator, entityManager, false); // don't auto-init bags, we're returning composites not entities + PageList<ResourceGroupComposite> results = queryRunner.execute(); + + results = getAuthorizedGroupComposites(subject, authzType, results); + + for (ResourceGroupComposite composite : results) { + ResourceGroup group = composite.getResourceGroup(); + ResourceType type = group.getResourceType(); + ResourceFacets facets = (type != null) ? resourceTypeManager.getResourceFacets(type.getId()) + : ResourceFacets.NONE; + + queryRunner.initFetchFields(group); // manual field fetch for composite-wrapped entity + composite.setResourceFacets(facets); + } + return results; + } + + private enum CriteriaAuthzType { + // inv manager / no auth required + NONE, + // standard role-subject-group auth + ROLE_OWNED, + // private group auth + SUBJECT_OWNED, + // auto cluster backing group + AUTO_CLUSTER + } + + private CriteriaAuthzType getCriteriaAuthzType(Subject subject, ResourceGroupCriteria criteria) { + Set<Permission> globalUserPerms = authorizationManager.getExplicitGlobalPermissions(subject); + if (criteria.isSecurityManagerRequired() && !globalUserPerms.contains(Permission.MANAGE_SECURITY)) { throw new PermissionException("Subject [" + subject.getName() + "] requires SecurityManager permission for requested query criteria."); }
boolean isInventoryManager = globalUserPerms.contains(Permission.MANAGE_INVENTORY); - boolean groupAuthzRequired = (!(criteria.isFilterPrivate() || isInventoryManager));
if (criteria.isInventoryManagerRequired() && !isInventoryManager) { throw new PermissionException("Subject [" + subject.getName() + "] requires InventoryManager permission for requested query criteria."); }
- // if we're searching for private groups set the subject filter to the current user's subjectId + CriteriaAuthzType result = CriteriaAuthzType.ROLE_OWNED; + + if (isInventoryManager) { + result = CriteriaAuthzType.NONE; + } else if (criteria.isFilterPrivate()) { + result = CriteriaAuthzType.SUBJECT_OWNED; + } else if (!criteria.isFilterVisible()) { + result = CriteriaAuthzType.AUTO_CLUSTER; + } + + return result; + } + + private CriteriaQueryGenerator getCriteriaQueryGenerator(Subject subject, ResourceGroupCriteria criteria, + CriteriaAuthzType authzType) { + + // 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 + // private filters are different. The subject filter can specify any user and therefore requires // inventory manager. if (criteria.isFilterPrivate()) { criteria.addFilterPrivate(null); @@ -1536,7 +1580,7 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso }
CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - if (groupAuthzRequired) { + if (authzType != CriteriaAuthzType.NONE) { generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.GROUP, null, subject.getId()); } @@ -1544,6 +1588,41 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso return generator; }
+ private PageList<ResourceGroupComposite> getAuthorizedGroupComposites(Subject subject, CriteriaAuthzType authzType, + PageList<ResourceGroupComposite> groupComposites) { + + switch (authzType) { + case NONE: + // leave resourcePermissions unset on the assumption that it will not be checked for inv managers + break; + case ROLE_OWNED: + // the permissions are already set by the query projection + break; + case AUTO_CLUSTER: + // the permissions are already set by the query projection + break; + case SUBJECT_OWNED: + Iterator<ResourceGroupComposite> iterator = groupComposites.iterator(); + while (iterator.hasNext()) { + ResourceGroupComposite groupComposite = iterator.next(); + ResourceGroup group = groupComposite.getResourceGroup(); + Subject groupOwner = group.getSubject(); + if (null != groupOwner) { + // private group, we need to set the group resource permissions since we couldn't do it in + // the projection. + groupComposite.setResourcePermission(new ResourcePermission(authorizationManager + .getExplicitGroupPermissions(groupOwner, group.getId()))); + } else { + throw new IllegalStateException("Unexpected group, not subject owned: " + groupComposite); + } + } + break; + default: + throw new IllegalStateException("Unexpected CriteriaAuthzType: " + authzType); + } + return groupComposites; + } + @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @RequiredPermission(Permission.MANAGE_INVENTORY) public void uninventoryMembers(Subject subject, int groupId) {
commit 1a30dca496cb0a95b0216c578c019ab7265a57da Author: Ian Springer ian.springer@redhat.com Date: Mon Dec 20 18:14:26 2010 -0500
add operation parameters to operation schedules details view; get rid of tabs in config editor, since we currently don't support raw config; only show collapsible section stack in config editor if the configdef includes one or more prop groups
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 9b6a063..c2e2626 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 @@ -40,7 +40,6 @@ 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; import com.smartgwt.client.util.BooleanCallback; import com.smartgwt.client.util.SC; @@ -87,8 +86,6 @@ 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; -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.layout.SectionStack; @@ -99,12 +96,7 @@ 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.tab.Tab; -import com.smartgwt.client.widgets.tab.TabSet; import com.smartgwt.client.widgets.toolbar.ToolStrip; -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.configuration.AbstractPropertyMap; import org.rhq.core.domain.configuration.Configuration; @@ -112,7 +104,6 @@ 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.RawConfiguration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.ConfigurationFormat; import org.rhq.core.domain.configuration.definition.PropertyDefinition; @@ -135,15 +126,11 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTyp 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; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIMenuButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTab; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTabSet; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -164,16 +151,12 @@ public class ConfigurationEditor extends LocatableVLayout {
private ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService();
- private TabSet tabSet; private LocatableToolStrip toolStrip;
private ConfigurationDefinition configurationDefinition; private Configuration configuration; private Configuration originalConfiguration;
- private String structConfigTabTitle = MSG.view_configEdit_properties(); - private String rawConfigTabTitle = MSG.view_configEdit_files(); - private ValuesManager valuesManager = new ValuesManager();
private boolean changed = false; @@ -236,22 +219,6 @@ public class ConfigurationEditor extends LocatableVLayout { addMember(new Label(message)); }
- public String getRawConfigTabTitle() { - return this.rawConfigTabTitle; - } - - public void setRawConfigTabTitle(String title) { - this.rawConfigTabTitle = title; - } - - public String getStructuredConfigTabTitle() { - return this.structConfigTabTitle; - } - - public void setStructuredConfigTabTitle(String title) { - this.structConfigTabTitle = title; - } - public boolean validate() { return this.valuesManager.validate(); } @@ -335,36 +302,26 @@ public class ConfigurationEditor extends LocatableVLayout {
public void reload() { if (configurationDefinition == null || configuration == null) { - // Wait for both to load + // Wait for both to load. return; }
originalConfiguration = configuration.deepCopy();
- tabSet = new LocatableTabSet(getLocatorId()); - - 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", getRawConfigTabTitle()); - tab.setPane(buildRawPane()); - tabSet.addTab(tab); + for (Canvas childCanvas : getChildren()) { + childCanvas.destroy(); }
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", getStructuredConfigTabTitle()); - tab.setPane(buildStructuredPane()); - tabSet.addTab(tab); - } - - for (Canvas c : getChildren()) { - c.destroy(); + Log.info("Building structured configuration editor..."); + LocatableVLayout structuredConfigLayout = buildStructuredPane(); + addMember(structuredConfigLayout); + } else { + Label label = new Label("Structured configuration is not supported."); + addMember(label); }
- addMember(tabSet); - this.markForRedraw(); }
@@ -373,129 +330,90 @@ public class ConfigurationEditor extends LocatableVLayout { reload(); }
- protected HLayout buildRawPane() { - - LocatableHLayout layout = new LocatableHLayout(extendLocatorId("Raw")); - final HashMap<String, RawConfiguration> filesMap = new HashMap<String, RawConfiguration>(); - - TreeGrid fileTree = new LocatableTreeGrid(layout.extendLocatorId("Files")); - fileTree.setShowResizeBar(true); - - Tree files = new Tree(); - files.setModelType(TreeModelType.CHILDREN); - TreeNode root = new TreeNode("root"); - TreeNode[] children = new TreeNode[configuration.getRawConfigurations().size()]; - int i = 0; - for (RawConfiguration rawConfiguration : configuration.getRawConfigurations()) { - children[i++] = new TreeNode(rawConfiguration.getPath()); - filesMap.put(rawConfiguration.getPath(), rawConfiguration); - } - root.setChildren(children); - files.setRoot(root); - fileTree.setData(files); - fileTree.setWidth(250); - - DynamicForm form = new LocatableDynamicForm(layout.extendLocatorId("Editor")); - final TextAreaItem rawEditor = new TextAreaItem(); - // rawEditor.setValue("This is a test"); - rawEditor.setShowTitle(false); - form.setItems(rawEditor); - form.setHeight100(); - form.setWidth100(); - - fileTree.addSelectionChangedHandler(new SelectionChangedHandler() { - public void onSelectionChanged(SelectionEvent selectionEvent) { - String path = selectionEvent.getRecord().getAttribute("name"); - com.allen_sauer.gwt.log.client.Log.info("Getting Path: " + path); - rawEditor.setValue(filesMap.get(path).getContents()); - rawEditor.redraw(); - com.allen_sauer.gwt.log.client.Log.info("Data: " + filesMap.get(path).getContents()); - } - }); - - if (children.length > 0) { - fileTree.selectRecord(children[0]); - rawEditor.setValue(filesMap.get(children[0].getName()).getContents()); - } - - layout.setMembers(fileTree, form); - return layout; - } - - protected VLayout buildStructuredPane() { + protected LocatableVLayout buildStructuredPane() {
LocatableVLayout layout = new LocatableVLayout(extendLocatorId("Structured")); List<PropertyGroupDefinition> groupDefinitions = configurationDefinition.getGroupDefinitions();
- final SectionStack sectionStack = new LocatableSectionStack(layout.extendLocatorId("Sections")); - sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); - sectionStack.setWidth100(); - sectionStack.setHeight100(); - sectionStack.setScrollSectionIntoView(true); - sectionStack.setOverflow(Overflow.AUTO); - - if (!configurationDefinition.getNonGroupedProperties().isEmpty()) { - sectionStack.addSection(buildGroupSection(layout.extendLocatorId("NoGroup"), null)); - } - - for (PropertyGroupDefinition definition : groupDefinitions) { - // com.allen_sauer.gwt.log.client.Log.info("building: " + definition.getDisplayName()); - sectionStack.addSection(buildGroupSection(layout.extendLocatorId(definition.getName()), definition)); - } + if (groupDefinitions.isEmpty()) { + // No prop groups, so we just need a single form for the non-grouped props. + List<PropertyDefinition> propertyDefinitions = + new ArrayList<PropertyDefinition>(configurationDefinition.getNonGroupedProperties());
- // TODO GH: Save button as saveListener() or remove the buttons from this form and have - // the container provide them? + DynamicForm form = buildPropertiesForm(layout.extendLocatorId("Props"), propertyDefinitions, configuration); + form.setBorder("1px solid #AAA"); + layout.addMember(form); + } else { + // One or more prop groups, so create a section stack with one section per group. + final SectionStack sectionStack = new LocatableSectionStack(layout.extendLocatorId("Sections")); + sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); + sectionStack.setWidth100(); + sectionStack.setHeight100(); + sectionStack.setScrollSectionIntoView(true); + sectionStack.setOverflow(Overflow.AUTO); + + if (!configurationDefinition.getNonGroupedProperties().isEmpty()) { + sectionStack.addSection(buildGroupSection(layout.extendLocatorId("NoGroup"), null)); + }
- toolStrip = new LocatableToolStrip(layout.extendLocatorId("Tools")); - toolStrip.setBackgroundImage(null); + for (PropertyGroupDefinition definition : groupDefinitions) { + // com.allen_sauer.gwt.log.client.Log.info("building: " + definition.getDisplayName()); + sectionStack.addSection(buildGroupSection(layout.extendLocatorId(definition.getName()), definition)); + }
- toolStrip.setWidth100(); + toolStrip = new LocatableToolStrip(layout.extendLocatorId("Tools")); + toolStrip.setBackgroundImage(null); + toolStrip.setWidth100();
- toolStrip.addMember(new LayoutSpacer()); - saveButton = new LocatableIButton(toolStrip.extendLocatorId("Save"), MSG.common_button_save()); - saveButton.setAlign(Alignment.CENTER); - saveButton.setDisabled(true); - // toolStrip.addMember(saveButton); + toolStrip.addMember(new LayoutSpacer()); + saveButton = new LocatableIButton(toolStrip.extendLocatorId("Save"), MSG.common_button_save()); + saveButton.setAlign(Alignment.CENTER); + saveButton.setDisabled(true); + //toolStrip.addMember(saveButton);
- IButton resetButton = new LocatableIButton(toolStrip.extendLocatorId("Reset"), MSG.common_button_reset()); - resetButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { - public void onClick(ClickEvent clickEvent) { - reload(); + IButton resetButton = new LocatableIButton(toolStrip.extendLocatorId("Reset"), MSG.common_button_reset()); + resetButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + reload(); + } + }); + //toolStrip.addMember(resetButton); + + toolStrip.addMember(new LayoutSpacer()); + + Menu menu = new LocatableMenu(toolStrip.extendLocatorId("JumpMenu")); + for (SectionStackSection section : sectionStack.getSections()) { + MenuItem item = new MenuItem(section.getTitle()); + item.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + int x = event.getMenu().getItemNum(event.getItem()); + sectionStack.expandSection(x); + sectionStack.showSection(x); + } + }); + menu.addItem(item); } - }); + menu.addItem(new MenuItemSeparator());
- Menu menu = new LocatableMenu(toolStrip.extendLocatorId("JumpMenu")); - for (SectionStackSection section : sectionStack.getSections()) { - MenuItem item = new MenuItem(section.getTitle()); - item.addClickHandler(new ClickHandler() { + MenuItem hideAllItem = new MenuItem(MSG.view_configEdit_hideAll()); + hideAllItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { - int x = event.getMenu().getItemNum(event.getItem()); - sectionStack.expandSection(x); - sectionStack.showSection(x); + for (int i = 0; i < sectionStack.getSections().length; i++) { + sectionStack.collapseSection(i); + } } }); - menu.addItem(item); - } - menu.addItem(new MenuItemSeparator()); - - MenuItem hideAllItem = new MenuItem(MSG.view_configEdit_hideAll()); - hideAllItem.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - for (int i = 0; i < sectionStack.getSections().length; i++) { - sectionStack.collapseSection(i); - } - } - }); - menu.addItem(hideAllItem); + menu.addItem(hideAllItem);
- // toolStrip.addMember(resetButton); - toolStrip.addMember(new LayoutSpacer()); - toolStrip.addMember(new LocatableIMenuButton(toolStrip.extendLocatorId("Jump"), MSG - .view_configEdit_jumpToSection(), menu)); + // TODO GH: Save button as saveListener() or remove the buttons from this form and have + // the container provide them?
- layout.addMember(toolStrip); + toolStrip.addMember(new LocatableIMenuButton(toolStrip.extendLocatorId("Jump"), MSG + .view_configEdit_jumpToSection(), menu));
- layout.addMember(sectionStack); + layout.addMember(toolStrip); + layout.addMember(sectionStack); + }
return layout; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java index e9fe59a..c134b69 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java @@ -214,6 +214,10 @@ public abstract class AbstractRecordEditor<DS extends RPCDataSource> extends Loc return this.recordId; }
+ public boolean isNewRecord() { + return (getRecordId() == ID_NEW); + } + public String getListViewPath() { return this.listViewPath; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/history/ResourceOperationHistoryDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/history/ResourceOperationHistoryDetailsView.java index 208404f..b3e869a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/history/ResourceOperationHistoryDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/history/ResourceOperationHistoryDetailsView.java @@ -23,6 +23,7 @@ import java.util.Date; 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.Window; import com.smartgwt.client.widgets.events.CloseClickHandler; import com.smartgwt.client.widgets.events.CloseClientEvent; @@ -201,18 +202,22 @@ public class ResourceOperationHistoryDetailsView extends LocatableVLayout implem // params/results
if (operationHistory.getParameters() != null) { + Label title = new Label(MSG.view_operationHistoryDetails_parameters()); + addMember(title); + ConfigurationEditor editor = new ConfigurationEditor(extendLocatorId("params"), definition .getParametersConfigurationDefinition(), operationHistory.getParameters()); editor.setReadOnly(true); - editor.setStructuredConfigTabTitle(MSG.view_operationHistoryDetails_parameters()); addMember(editor); }
if (status == OperationRequestStatus.SUCCESS && operationHistory.getResults() != null) { + Label title = new Label(MSG.view_operationHistoryDetails_results()); + addMember(title); + ConfigurationEditor editor = new ConfigurationEditor(extendLocatorId("results"), definition .getResultsConfigurationDefinition(), operationHistory.getResults()); editor.setReadOnly(true); - editor.setStructuredConfigTabTitle(MSG.view_operationHistoryDetails_results()); addMember(editor); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java index 263c3ae..3afb1e2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Set;
+import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; @@ -32,13 +33,18 @@ import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
+import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.enterprise.gui.coregui.client.ViewPath; +import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.form.AbstractRecordEditor; import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleDataSource; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Ian Springer @@ -46,19 +52,27 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor {
private static final String FIELD_OPERATION_DESCRIPTION = "operationDescription"; + private static final String FIELD_OPERATION_PARAMETERS = "operationParameters";
private ResourceComposite resourceComposite; private Map<String, String> operationNameToDescriptionMap = new HashMap<String, String>(); + private Map<String, ConfigurationDefinition> operationNameToParametersDefinitionMap = + new HashMap<String, ConfigurationDefinition>(); private SelectItem operationNameItem; private StaticTextItem operationDescriptionItem; + private StaticTextItem operationParametersItem; + private LocatableHLayout operationParametersConfigurationHolder;
public ResourceOperationScheduleDetailsView(String locatorId, ResourceComposite resourceComposite, int scheduleId) { super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite), scheduleId, "Scheduled Operation", null); + this.resourceComposite = resourceComposite; ResourceType resourceType = this.resourceComposite.getResource().getResourceType(); Set<OperationDefinition> operationDefinitions = resourceType.getOperationDefinitions(); for (OperationDefinition operationDefinition : operationDefinitions) { this.operationNameToDescriptionMap.put(operationDefinition.getName(), operationDefinition.getDescription()); + this.operationNameToParametersDefinitionMap.put(operationDefinition.getName(), + operationDefinition.getParametersConfigurationDefinition()); } }
@@ -79,24 +93,44 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { items.add(this.operationNameItem); this.operationNameItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { - updateOperationDescriptionItem(); + refreshOperationDescriptionItem(); + refreshOperationParametersItem(); } });
this.operationDescriptionItem = new StaticTextItem(FIELD_OPERATION_DESCRIPTION, "Operation Description"); items.add(this.operationDescriptionItem);
- TextAreaItem notesItem = new TextAreaItem(ResourceOperationScheduleDataSource.Field.DESCRIPTION, "Notes"); - notesItem.setColSpan(form.getNumCols()); - items.add(notesItem); + this.operationParametersItem = new StaticTextItem(FIELD_OPERATION_PARAMETERS, "Operation Parameters"); + items.add(this.operationParametersItem);
return items; }
@Override + protected LocatableVLayout buildContentPane() { + LocatableVLayout contentPane = super.buildContentPane(); + + this.operationParametersConfigurationHolder = new LocatableHLayout(extendLocatorId("ConfigHolder")); + this.operationParametersConfigurationHolder.setVisible(false); + contentPane.addMember(this.operationParametersConfigurationHolder); + + EnhancedDynamicForm notesForm = new EnhancedDynamicForm(extendLocatorId("NotesForm"), isReadOnly(), + isNewRecord()); + TextAreaItem notesItem = new TextAreaItem(ResourceOperationScheduleDataSource.Field.DESCRIPTION, "Notes"); + notesItem.setStartRow(true); + notesItem.setColSpan(4); + notesForm.setFields(notesItem); + contentPane.addMember(notesForm); + + return contentPane; + } + + @Override protected void onDraw() { super.onDraw(); - updateOperationDescriptionItem(); + refreshOperationDescriptionItem(); + refreshOperationParametersItem(); }
@Override @@ -104,15 +138,47 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { return ResourceOperationScheduleDataSource.Field.OPERATION_DISPLAY_NAME; }
- private void updateOperationDescriptionItem() { + private void refreshOperationDescriptionItem() { String operationName = this.operationNameItem.getValueAsString(); String value; if (operationName == null) { - value = "<i>Select an operation to view its description.</i>"; + value = "<i>Select an operation.</i>"; } else { value = this.operationNameToDescriptionMap.get(operationName); } this.operationDescriptionItem.setValue(value); }
+ private void refreshOperationParametersItem() { + String operationName = this.operationNameItem.getValueAsString(); + String value; + if (operationName == null) { + value = "<i>Select an operation.</i>"; + } else { + ConfigurationDefinition parametersDefinition = this.operationNameToParametersDefinitionMap.get(operationName); + if (parametersDefinition == null || parametersDefinition.getPropertyDefinitions().isEmpty()) { + value = "<i>" + MSG.view_operationCreateWizard_parametersStep_noParameters() + "</i>"; + + for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { + child.destroy(); + } + this.operationParametersConfigurationHolder.hide(); + } else { + value = "<i>Enter parameters below...</i>"; + + for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { + child.destroy(); + } + Configuration defaultConfiguration = (parametersDefinition.getDefaultTemplate() != null) ? + parametersDefinition.getDefaultTemplate().createConfiguration() : new Configuration(); + ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", parametersDefinition, + defaultConfiguration); + configurationEditor.setReadOnly(isReadOnly()); + this.operationParametersConfigurationHolder.addMember(configurationEditor); + this.operationParametersConfigurationHolder.show(); + } + } + this.operationParametersItem.setValue(value); + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/CurrentGroupPluginConfigurationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/CurrentGroupPluginConfigurationView.java index 2ad9f55..87c4179 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/CurrentGroupPluginConfigurationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/CurrentGroupPluginConfigurationView.java @@ -27,6 +27,7 @@ import java.util.Set; 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.Label; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.toolbar.ToolStrip; @@ -125,12 +126,14 @@ public class CurrentGroupPluginConfigurationView extends LocatableVLayout implem
private void initEditor() { if (this.configurationDefinition != null && this.memberConfigurations != null) { + Label title = new Label(MSG.view_group_pluginConfig_edit_currentGroupProperties()); + addMember(title); + this.editor = new GroupConfigurationEditor(this.extendLocatorId("Editor"), this.configurationDefinition, this.memberConfigurations); this.editor.setOverflow(Overflow.AUTO); this.editor.addPropertyValueChangeListener(this); - this.editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); - this.editor.setStructuredConfigTabTitle(MSG.view_group_pluginConfig_edit_currentGroupProperties()); + this.editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); addMember(this.editor); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java index 787e1ea..22aa7be 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java @@ -25,6 +25,7 @@ import java.util.Map;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.Label;
import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; @@ -86,12 +87,14 @@ public class HistoryGroupPluginConfigurationSettings extends LocatableVLayout {
private void initEditor() { if (this.configurationDefinition != null && this.memberConfigurations != null) { + Label title = new Label(MSG.view_group_pluginConfig_view_groupProperties() + " - " + + this.groupUpdateId); + addMember(title); + this.editor = new GroupConfigurationEditor(this.extendLocatorId("Editor"), this.configurationDefinition, this.memberConfigurations); this.editor.setOverflow(Overflow.AUTO); this.editor.setReadOnly(true); - this.editor.setStructuredConfigTabTitle(MSG.view_group_pluginConfig_view_groupProperties() + " - " - + this.groupUpdateId); addMember(this.editor); } }
commit eb88d3f495920873b3e469bde1d39024ed6d2f4e Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 17:46:48 2010 -0500
fix long message names that are expanding the message center too much - use concise messages
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java index 4580301..0f86d64 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java @@ -73,19 +73,24 @@ public class ConfirmationStep extends AbstractWizardStep { public void onSuccess(PageList<BundleDeployment> liveDeployments) { if (1 != liveDeployments.size()) { nextPage = false; + String messageConcise = MSG.view_bundle_revertWizard_confirmStep_noLiveDeployment_concise(); String message = MSG.view_bundle_revertWizard_confirmStep_noLiveDeployment(wizard .getDestination().toString()); wizard.getView().showMessage(message); - CoreGUI.getMessageCenter().notify(new Message(message, Message.Severity.Warning)); + CoreGUI.getMessageCenter().notify( + new Message(messageConcise, message, Message.Severity.Warning)); } wizard.setLiveDeployment(liveDeployments.get(0)); wizard.setPreviousDeployment(wizard.getLiveDeployment().getReplacedBundleDeployment()); if (null == wizard.getPreviousDeployment()) { nextPage = false; + String messageConcise = MSG + .view_bundle_revertWizard_confirmStep_noPriorDeployment_concise(); String message = MSG.view_bundle_revertWizard_confirmStep_noPriorDeployment(wizard .getLiveDeployment().toString(), wizard.getDestination().toString()); wizard.getView().showMessage(message); - CoreGUI.getMessageCenter().notify(new Message(message, Message.Severity.Warning)); + CoreGUI.getMessageCenter().notify( + new Message(messageConcise, message, Message.Severity.Warning)); }
setLayout(); diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index a34c71c..2c45fbb 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -922,7 +922,9 @@ view_bundle_revertWizard_getInfoStep_revertDeployDescFull = [REVERT From]\n{0}\ view_bundle_revertWizard_getInfoStep_cleanDeploy = Clean Deployment? (this will delete an old, existing deploy directory prior to starting the revert deployment) view_bundle_revertWizard_getInfoStep_getNameFailure = Failed to get revert deployment name view_bundle_revertWizard_confirmStep_name = Revert Deployment Confirmation +view_bundle_revertWizard_confirmStep_noLiveDeployment_concise = No live deployment was found for the destination view_bundle_revertWizard_confirmStep_noLiveDeployment = No live deployment was found for the destination [{0}] +view_bundle_revertWizard_confirmStep_noPriorDeployment_concise = The live deployment cannot be reverted because there is no prior deployment view_bundle_revertWizard_confirmStep_noPriorDeployment = The live deployment [{0}] cannot be reverted because there is no prior deployment for the destination [{1}] view_bundle_revertWizard_confirmStep_failedToFindLiveDeployment = Failed to find live deployment; cannot revert view_bundle_revertWizard_confirmStep_liveDeployment = Live Deployment
commit 7f4a24bd14d2be5763837abab8e04ce35548ec93 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 17:46:26 2010 -0500
fix NPE
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java index 4053fae..4580301 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java @@ -151,54 +151,56 @@ public class ConfirmationStep extends AbstractWizardStep { prevHeader.setWidth100(); layout.addMember(prevHeader);
- final DynamicForm prevForm = new DynamicForm(); - prevForm.setNumCols(2); - - StaticTextItem prevNameItem = new StaticTextItem("prevName", MSG.common_title_name()); - prevNameItem.setTitleAlign(Alignment.LEFT); - prevNameItem.setAlign(Alignment.LEFT); - prevNameItem.setWrap(false); - prevNameItem.setWrapTitle(false); - prevNameItem.setValue(prev.getName()); - - StaticTextItem prevDescItem = new StaticTextItem("prevDesc", MSG.common_title_description()); - prevDescItem.setTitleAlign(Alignment.LEFT); - prevDescItem.setAlign(Alignment.LEFT); - prevDescItem.setWrap(false); - prevDescItem.setWrapTitle(false); - prevDescItem.setTitleVAlign(VerticalAlignment.TOP); - prevDescItem.setValue((null != prev.getDescription()) ? prev.getDescription() : MSG.common_val_none()); - - final StaticTextItem prevVersionItem = new StaticTextItem("prevVersion", MSG.view_bundle_bundleVersion()); - prevVersionItem.setTitleAlign(Alignment.LEFT); - prevVersionItem.setAlign(Alignment.LEFT); - prevVersionItem.setWrap(false); - prevVersionItem.setWrapTitle(false); - if (prev.getBundleVersion().getVersion() == null) { - BundleVersionCriteria c = new BundleVersionCriteria(); - c.addFilterId(prev.getBundleVersion().getId()); - bundleServer.findBundleVersionsByCriteria(c, new AsyncCallback<PageList<BundleVersion>>() { - - @Override - public void onSuccess(PageList<BundleVersion> result) { - if (result != null && result.size() == 1) { - prevVersionItem.setValue(result.get(0).getVersion()); + if (prev != null) { + final DynamicForm prevForm = new DynamicForm(); + prevForm.setNumCols(2); + + StaticTextItem prevNameItem = new StaticTextItem("prevName", MSG.common_title_name()); + prevNameItem.setTitleAlign(Alignment.LEFT); + prevNameItem.setAlign(Alignment.LEFT); + prevNameItem.setWrap(false); + prevNameItem.setWrapTitle(false); + prevNameItem.setValue(prev.getName()); + + StaticTextItem prevDescItem = new StaticTextItem("prevDesc", MSG.common_title_description()); + prevDescItem.setTitleAlign(Alignment.LEFT); + prevDescItem.setAlign(Alignment.LEFT); + prevDescItem.setWrap(false); + prevDescItem.setWrapTitle(false); + prevDescItem.setTitleVAlign(VerticalAlignment.TOP); + prevDescItem.setValue((null != prev.getDescription()) ? prev.getDescription() : MSG.common_val_none()); + + final StaticTextItem prevVersionItem = new StaticTextItem("prevVersion", MSG.view_bundle_bundleVersion()); + prevVersionItem.setTitleAlign(Alignment.LEFT); + prevVersionItem.setAlign(Alignment.LEFT); + prevVersionItem.setWrap(false); + prevVersionItem.setWrapTitle(false); + if (prev.getBundleVersion().getVersion() == null) { + BundleVersionCriteria c = new BundleVersionCriteria(); + c.addFilterId(prev.getBundleVersion().getId()); + bundleServer.findBundleVersionsByCriteria(c, new AsyncCallback<PageList<BundleVersion>>() { + + @Override + public void onSuccess(PageList<BundleVersion> result) { + if (result != null && result.size() == 1) { + prevVersionItem.setValue(result.get(0).getVersion()); + prevForm.markForRedraw(); + } + } + + @Override + public void onFailure(Throwable caught) { + prevVersionItem.setValue("?"); prevForm.markForRedraw(); } - } - - @Override - public void onFailure(Throwable caught) { - prevVersionItem.setValue("?"); - prevForm.markForRedraw(); - } - }); - } else { - prevVersionItem.setValue(prev.getBundleVersion().getVersion()); - } + }); + } else { + prevVersionItem.setValue(prev.getBundleVersion().getVersion()); + }
- prevForm.setItems(prevNameItem, prevDescItem, prevVersionItem); - layout.addMember(prevForm); + prevForm.setItems(prevNameItem, prevDescItem, prevVersionItem); + layout.addMember(prevForm); + }
Label confirmation = new Label(); confirmation.setContents("<b>" + MSG.view_bundle_revertWizard_confirmStep_confirmation() + "</b>");
commit fa3e4ecacf731ef96e116c6905c8ee1522ca4c6b Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 17:24:09 2010 -0500
we can now delete bundle destinations and deployments.
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 c7cc475..46b4e41 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 @@ -325,11 +325,12 @@ public class LinkManager { }
public static String getBundleVersionLink(int bundleId, int bundleVersionId) { - return "#Bundles/Bundle/" + bundleId + "/versions/" + bundleVersionId; + return "#Bundles/Bundle/" + bundleId + "/versions" + (bundleVersionId == 0 ? "" : ("/" + bundleVersionId)); }
public static String getBundleDestinationLink(int bundleId, int bundleDestinationId) { - return "#Bundles/Bundle/" + bundleId + "/destinations/" + bundleDestinationId; + return "#Bundles/Bundle/" + bundleId + "/destinations" + + (bundleDestinationId == 0 ? "" : ("/" + bundleDestinationId)); }
public static String getBundleDeploymentLink(int bundleId, int bundleDeploymentId) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index 393e4a6..94b216a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -32,9 +32,12 @@ import com.smartgwt.client.types.AnimationEffect; import com.smartgwt.client.types.AutoFitWidthApproach; import com.smartgwt.client.types.DateDisplayFormat; import com.smartgwt.client.types.ListGridFieldType; -import com.smartgwt.client.types.VerticalAlignment; +import com.smartgwt.client.util.BooleanCallback; +import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.form.fields.CanvasItem; import com.smartgwt.client.widgets.form.fields.LinkItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; @@ -76,6 +79,7 @@ import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; 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.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -134,7 +138,7 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("Summary")); form.setWidth100(); form.setAutoHeight(); - form.setNumCols(4); + form.setNumCols(5); form.setWrapItemTitles(false); form.setExtraSpace(10); form.setIsGroup(true); @@ -147,6 +151,12 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab bundleName.setLinkTitle(bundle.getName()); bundleName.setTarget("_self");
+ CanvasItem actionItem = new CanvasItem("actions"); + actionItem.setColSpan(1); + actionItem.setRowSpan(4); + actionItem.setShowTitle(false); + actionItem.setCanvas(getActionLayout(form.extendLocatorId("actions"))); + LinkItem bundleVersionName = new LinkItem("bundleVersion"); bundleVersionName.setTitle(MSG.view_bundle_bundleVersion()); bundleVersionName.setValue(LinkManager.getBundleVersionLink(bundle.getId(), deployment.getBundleVersion() @@ -172,7 +182,6 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab
StaticTextItem description = new StaticTextItem("description", MSG.common_title_description()); description.setValue(deployment.getDescription()); - description.setTitleVAlign(VerticalAlignment.TOP);
StaticTextItem status = new StaticTextItem("status", MSG.common_title_status()); status.setValue(deployment.getStatus().name()); @@ -192,12 +201,51 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab }); }
- form.setFields(bundleName, deployed, bundleVersionName, deployedBy, // - destinationGroup, path, description, status); + form.setFields(bundleName, deployed, actionItem, bundleVersionName, deployedBy, destinationGroup, path, + description, status);
return form; }
+ private Canvas getActionLayout(String locatorId) { + LocatableVLayout actionLayout = new LocatableVLayout(locatorId, 10); + IButton deleteButton = new LocatableIButton(actionLayout.extendLocatorId("Delete"), MSG.common_button_delete()); + deleteButton.setIcon("subsystems/bundle/BundleDeploymentAction_Delete_16.png"); + deleteButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + @Override + public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) { + SC.ask(MSG.view_bundle_deploy_deleteConfirm(), new BooleanCallback() { + public void execute(Boolean aBoolean) { + if (aBoolean) { + bundleService.deleteBundleDeployment(deployment.getId(), new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_deploy_deleteFailure(deployment.getName()), caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_deploy_deleteSuccessful(deployment.getName()), + Message.Severity.Info)); + // Bundle deployment is deleted, go back to main bundle destinations view + CoreGUI.goToView(LinkManager.getBundleDestinationLink(bundle.getId(), deployment + .getDestination().getId())); + } + }); + } + } + }); + } + }); + actionLayout.addMember(deleteButton); + + if (!canManageBundles) { + deleteButton.setDisabled(true); + } + + return actionLayout; + } + private TagEditorView createTagEditor() { boolean readOnly = !this.canManageBundles; TagEditorView tagEditor = new TagEditorView(extendLocatorId("tagEditor"), version.getTags(), readOnly, diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index ec1ca5e..91eaa34 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -27,6 +27,8 @@ import java.util.HashSet;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.util.BooleanCallback; +import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; @@ -192,9 +194,39 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka }); actionLayout.addMember(revertButton);
+ IButton deleteButton = new LocatableIButton(actionLayout.extendLocatorId("Delete"), MSG.common_button_delete()); + deleteButton.setIcon("subsystems/bundle/BundleDestinationAction_Delete_16.png"); + deleteButton.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + SC.ask(MSG.view_bundle_dest_deleteConfirm(), new BooleanCallback() { + public void execute(Boolean aBoolean) { + if (aBoolean) { + bundleService.deleteBundleDestination(destination.getId(), new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_dest_deleteFailure(destination.getName()), caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_dest_deleteSuccessful(destination.getName()), + Message.Severity.Info)); + // Bundle destination is deleted, go back to main bundle view + CoreGUI.goToView(LinkManager.getBundleDestinationLink(bundle.getId(), 0)); + } + }); + } + } + }); + } + }); + actionLayout.addMember(deleteButton); + if (!canManageBundles) { deployButton.setDisabled(true); revertButton.setDisabled(true); + deleteButton.setDisabled(true); }
return actionLayout; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java index cf4ab17..44f950c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java @@ -174,7 +174,7 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV new Message(MSG.view_bundle_version_deleteSuccessful(version.getVersion()), Message.Severity.Info)); // Bundle version is deleted, go back to main bundle view - CoreGUI.goToView(LinkManager.getBundleLink(version.getBundle().getId())); + CoreGUI.goToView(LinkManager.getBundleVersionLink(version.getBundle().getId(), 0)); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 4e12244..a34c71c 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -961,6 +961,9 @@ view_bundle_dest_loadFailureVersionInfo = Failed to load bundle destination depl view_bundle_dest_backToBundle = Back to Bundle view_bundle_dest_tagUpdateFailure = Failed to update bundle destination tags view_bundle_dest_tagUpdateSuccessful = You have successfully updated the bundle destination tags +view_bundle_dest_deleteConfirm = Are you sure you want to delete this bundle destination? +view_bundle_dest_deleteFailure = Failed to delete the bundle destination [{0}] +view_bundle_dest_deleteSuccessful = You successfully deleted the bundle destination [{0}] view_bundle_resDeployDS_loadFailure = Failed to load bundle resource deployments view_bundle_deploy_name = Deployment Name view_bundle_deploy_time = Deployment Time @@ -977,6 +980,9 @@ view_bundle_deploy_loadFailure = Failed to load bundle deployment view_bundle_deploy_loadBundleFailure = Failed to find bundle view_bundle_deploy_deployedBy = Deployed By view_bundle_deploy_clickForError = Click the icon for the error message +view_bundle_deploy_deleteConfirm = Are you sure you want to delete this bundle deployment? +view_bundle_deploy_deleteFailure = Failed to delete the bundle deployment [{0}] +view_bundle_deploy_deleteSuccessful = You successfully deleted the bundle deployment [{0}] view_bundle_createWizard_title = Create Bundle view_bundle_createWizard_windowTitle = Bundle Creation Wizard view_bundle_createWizard_cancelSuccessful = Canceled the creation of bundle [{0}], version = [{1}]
commit a87495b17c10e016084ef82af52959f4a4077a91 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 16:52:09 2010 -0500
don't show the deployment tree nodes if the user doesn't have permissions to see them
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 fd0bbe7..b66a340 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 @@ -71,6 +71,10 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView public void onPermissionsLoaded(Set<Permission> permissions) { // if we haven't done it yet, build the view components if (bundleTreeView == null) { + boolean canManageInventory = permissions != null + && permissions.contains(Permission.MANAGE_INVENTORY); + boolean canManageBundles = permissions != null && permissions.contains(Permission.MANAGE_BUNDLE); + SectionStack sectionStack = new LocatableSectionStack(getLocatorId()); sectionStack.setShowResizeBar(true); sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); @@ -78,12 +82,12 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView sectionStack.setHeight100();
SectionStackSection bundlesSection = new SectionStackSection(MSG.view_bundle_bundles()); - bundleTreeView = new BundleTreeView(extendLocatorId("BundleTree")); + bundleTreeView = new BundleTreeView(extendLocatorId("BundleTree"), canManageBundles); bundlesSection.addItem(bundleTreeView); sectionStack.addSection(bundlesSection);
// we only show repositories if the user has the global manage_inventory perms since that is required - if (permissions != null && permissions.contains(Permission.MANAGE_INVENTORY)) { + if (canManageInventory) { SectionStackSection repositoriesSection = new SectionStackSection(MSG .common_title_repositories()); ContentRepositoryTreeView repoTree = new ContentRepositoryTreeView(extendLocatorId("RepoTree")); 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 dadace4..61b29ce 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 @@ -56,9 +56,11 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; public class BundleTreeDataSource extends RPCDataSource {
private BundleGWTServiceAsync bundleService = GWTServiceLookup.getBundleService(); + private final boolean canManageBundles;
- public BundleTreeDataSource() { + public BundleTreeDataSource(boolean canManageBundles) { super(); + this.canManageBundles = canManageBundles; List<DataSourceField> fields = addDataSourceFields(); addFields(fields); } @@ -207,12 +209,14 @@ public class BundleTreeDataSource extends RPCDataSource { deploymentsNode.setName(MSG.view_bundle_destinations()); records.add(deploymentsNode); } else if (item instanceof BundleDestination) { - BundleDestination dest = (BundleDestination) item; + if (canManageBundles) { + BundleDestination dest = (BundleDestination) item;
- // each destination has 0, 1 or more deployments - if (dest.getDeployments() != null) { - for (BundleDeployment deploy : dest.getDeployments()) { - records.add(copyValuesForKnownBundle(deploy, bundleId)); + // each destination has 0, 1 or more deployments + if (dest.getDeployments() != null) { + for (BundleDeployment deploy : dest.getDeployments()) { + records.add(copyValuesForKnownBundle(deploy, bundleId)); + } } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java index 272841f..d692d60 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java @@ -40,7 +40,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; */ public class BundleTreeView extends LocatableTreeGrid {
- public BundleTreeView(String locatorId) { + public BundleTreeView(String locatorId, boolean canManageBundles) { super(locatorId); setWidth100(); setHeight100(); @@ -52,7 +52,7 @@ public class BundleTreeView extends LocatableTreeGrid { setSortField("name"); setShowHeader(false);
- setDataSource(new BundleTreeDataSource()); + setDataSource(new BundleTreeDataSource(canManageBundles));
addNodeClickHandler(new NodeClickHandler() { public void onNodeClick(NodeClickEvent event) {
commit 0105d3cb908d44b4156c8ce0f3c2709ea57101a3 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 16:31:52 2010 -0500
reorder some fields - description makes sense at bottom and if its a long description it won't push other fields down lower
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index 97b60af..393e4a6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -32,6 +32,7 @@ import com.smartgwt.client.types.AnimationEffect; import com.smartgwt.client.types.AutoFitWidthApproach; import com.smartgwt.client.types.DateDisplayFormat; import com.smartgwt.client.types.ListGridFieldType; +import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.fields.LinkItem; @@ -160,8 +161,18 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab StaticTextItem deployedBy = new StaticTextItem("deployedBy", MSG.view_bundle_deploy_deployedBy()); deployedBy.setValue(deployment.getSubjectName());
+ LinkItem destinationGroup = new LinkItem("group"); + destinationGroup.setTitle(MSG.common_title_resource_group()); + destinationGroup.setValue(LinkManager.getResourceGroupLink(deployment.getDestination().getGroup().getId())); + destinationGroup.setLinkTitle(deployment.getDestination().getGroup().getName()); + destinationGroup.setTarget("_self"); + + StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_deployDir()); + path.setValue(deployment.getDestination().getDeployDir()); + StaticTextItem description = new StaticTextItem("description", MSG.common_title_description()); description.setValue(deployment.getDescription()); + description.setTitleVAlign(VerticalAlignment.TOP);
StaticTextItem status = new StaticTextItem("status", MSG.common_title_status()); status.setValue(deployment.getStatus().name()); @@ -181,17 +192,9 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab }); }
- LinkItem destinationGroup = new LinkItem("group"); - destinationGroup.setTitle(MSG.common_title_resource_group()); - destinationGroup.setValue(LinkManager.getResourceGroupLink(deployment.getDestination().getGroup().getId())); - destinationGroup.setLinkTitle(deployment.getDestination().getGroup().getName()); - destinationGroup.setTarget("_self"); - - StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_deployDir()); - path.setValue(deployment.getDestination().getDeployDir()); - form.setFields(bundleName, deployed, bundleVersionName, deployedBy, // - description, status, destinationGroup, path); + destinationGroup, path, description, status); + return form; }
commit 4d770cf184501a7fa6dbf00741729e0e31dff122 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 15:48:09 2010 -0500
get the bundle list to sort properly on name column. can't currently sort on the composite fields "latest version" and "count"
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 c6a9cdc..643d13a 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 @@ -27,6 +27,7 @@ import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.widgets.events.DoubleClickEvent; import com.smartgwt.client.widgets.events.DoubleClickHandler; +import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -85,11 +86,15 @@ public class BundlesListView extends Table<RPCDataSource<BundleWithLatestVersion idField.setType(ListGridFieldType.INTEGER); idField.setWidth("50");
- ListGridField nameField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_NAMELINK, MSG + ListGridField nameField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_NAME, MSG .common_title_name()); - nameField.setType(ListGridFieldType.LINK); - nameField.setTarget("_self"); nameField.setWidth("33%"); + nameField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord record, int i, int i1) { + return "<a href="" + record.getAttribute(BundlesWithLatestVersionDataSource.FIELD_NAMELINK) + "">" + + String.valueOf(o) + "</a>"; + } + });
ListGridField descField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_DESCRIPTION, MSG .common_title_description()); @@ -99,12 +104,14 @@ public class BundlesListView extends Table<RPCDataSource<BundleWithLatestVersion MSG.view_bundle_latestVersion()); latestVersionField.setWidth("20%"); latestVersionField.setAlign(Alignment.CENTER); + latestVersionField.setCanSort(false); // need to figure out how we can sort on this projection field of the composite
ListGridField versionsCountField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_VERSIONS_COUNT, MSG.view_bundle_list_versionsCount()); versionsCountField.setType(ListGridFieldType.INTEGER); versionsCountField.setWidth("*"); versionsCountField.setAlign(Alignment.CENTER); + versionsCountField.setCanSort(false); // need to figure out how we can sort on this projection field of the composite
setListGridFields(idField, nameField, descField, latestVersionField, versionsCountField);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java index 0932620..16b48c7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java @@ -46,7 +46,7 @@ public class BundlesWithLatestVersionDataSource extends RPCDataSource<BundleWith public static final String FIELD_NAMELINK = "namelink"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_LATEST_VERSION = "latestVersion"; - public static final String FIELD_VERSIONS_COUNT = "versionsCount"; + public static final String FIELD_VERSIONS_COUNT = "deploymentCount";
private BundleGWTServiceAsync bundleService = GWTServiceLookup.getBundleService();
@@ -101,10 +101,7 @@ public class BundlesWithLatestVersionDataSource extends RPCDataSource<BundleWith
record.setAttribute(FIELD_ID, from.getBundleId()); record.setAttribute(FIELD_NAME, from.getBundleName()); - record.setAttribute(FIELD_NAMELINK, LinkManager.getBundleLink(from.getBundleId())); - record.setLinkText(from.getBundleName()); - record.setAttribute(FIELD_DESCRIPTION, from.getBundleDescription()); record.setAttribute(FIELD_LATEST_VERSION, from.getLatestVersion()); record.setAttribute(FIELD_VERSIONS_COUNT, Integer.valueOf(from.getVersionsCount().intValue())); // want int, not long
commit 3ddf5894f46a62d894a099d20db329e599fac42d Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 15:07:06 2010 -0500
BZ 606530 to avoid db deadlock during bundle deletion, add new "deletebundles" SLSB API that the client can use this enables the client to not have to do multiple async calls to the single "deletebundle" api.
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 e06b795..c6a9cdc 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.bundle.list;
+import java.util.ArrayList; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; @@ -44,6 +45,7 @@ import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableActionEnablement; import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; @@ -133,25 +135,37 @@ public class BundlesListView extends Table<RPCDataSource<BundleWithLatestVersion addTableAction(extendLocatorId("Delete"), MSG.common_button_delete(), MSG.common_msg_areYouSure(), new AbstractTableAction((hasAuth) ? TableActionEnablement.ANY : TableActionEnablement.NEVER) { public void executeAction(ListGridRecord[] selections, Object actionValue) { + if (selections == null || selections.length == 0) { + return; + } + BundlesWithLatestVersionDataSource ds = (BundlesWithLatestVersionDataSource) getDataSource(); + final ArrayList<String> doomedNames = new ArrayList<String>(selections.length); + int[] doomedIds = new int[selections.length]; + int i = 0; for (ListGridRecord selection : selections) { - BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); - final BundleWithLatestVersionComposite object = ds.copyValues(selection); - bundleManager.deleteBundle(object.getBundleId(), new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_list_deleteFailure(object.getBundleName()), caught); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_list_deleteSuccessful(object.getBundleName()), - Severity.Info)); - - CoreGUI.refresh(); - } - }); + BundleWithLatestVersionComposite object = ds.copyValues(selection); + doomedNames.add(object.getBundleName()); + doomedIds[i++] = object.getBundleId(); } + + BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); + bundleManager.deleteBundles(doomedIds, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + String names = doomedNames.toString(); + String error = ErrorHandler.getAllMessages(caught); + Message m = new Message(MSG.view_bundle_list_deletesFailure(), names + "<br/>\n" + + error, Severity.Error); + CoreGUI.getMessageCenter().notify(m); + } + + public void onSuccess(Void result) { + Message m = new Message(MSG.view_bundle_list_deletesSuccessful(), doomedNames + .toString(), Severity.Info); + CoreGUI.getMessageCenter().notify(m); + CoreGUI.refresh(); + } + }); } });
@@ -191,5 +205,4 @@ public class BundlesListView extends Table<RPCDataSource<BundleWithLatestVersion }
} - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java index ad56819..0f58c44 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/BundleGWTService.java @@ -55,6 +55,8 @@ public interface BundleGWTService extends RemoteService { BundleDestination createBundleDestination(int bundleId, String name, String description, String deployDir, int groupId) throws Exception;
+ void deleteBundles(int[] bundleIds) throws Exception; + void deleteBundle(int bundleId) throws Exception;
void deleteBundleDeployment(int bundleDeploymentId) throws Exception; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java index cfb8d18..103fcac 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/BundleGWTServiceImpl.java @@ -101,6 +101,14 @@ public class BundleGWTServiceImpl extends AbstractGWTServiceImpl implements Bund } }
+ public void deleteBundles(int[] bundleIds) throws Exception { + try { + bundleManager.deleteBundles(getSessionSubject(), bundleIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + public void deleteBundle(int bundleId) throws Exception { try { bundleManager.deleteBundle(getSessionSubject(), bundleId); diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 3ed25bb..4e12244 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -942,9 +942,11 @@ view_bundleVersion_loadFailure = Failed to load bundle version data view_bundle_list_backToAll = Back to All Bundles view_bundle_list_tagUpdateFailure = Failed to update bundle tags view_bundle_list_tagUpdateSuccessful = You have successfully updated the bundle tags -view_bundle_list_deleteConfirm = Are you sure you want to delete this bundle? +view_bundle_list_deleteConfirm = Are you sure you want to delete the selected bundles? +view_bundle_list_deletesFailure = Failed to delete the bundles +view_bundle_list_deletesSuccessful = You successfully deleted the bundles view_bundle_list_deleteFailure = Failed to delete the bundle [{0}] -view_bundle_list_deleteSuccessful = You successfully deleted the bundle named [{0}] +view_bundle_list_deleteSuccessful = You successfully deleted the bundle [{0}] view_bundle_list_error1 = Failed to load bundle to deploy [{0}] view_bundle_list_error2 = Failed to get a single bundle to deploy [{0}] view_bundle_list_error3 = Failed to load bundle diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java index b1f65cf..a57b618 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java @@ -1219,6 +1219,18 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot return results; }
+ // to avoid deadlocks, you cannot delete multiple bundles concurrently (see BZ 606530) + // instead, this simple method just loops over the given array and deletes them serially + // note they all get deleted in their own transaction; this method is never in a tx itself + @TransactionAttribute(TransactionAttributeType.NEVER) + public void deleteBundles(Subject subject, int[] bundleIds) throws Exception { + if (bundleIds != null) { + for (int bundleId : bundleIds) { + bundleManager.deleteBundle(subject, bundleId); + } + } + } + @SuppressWarnings("unchecked") @RequiredPermission(Permission.MANAGE_BUNDLE) public void deleteBundle(Subject subject, int bundleId) throws Exception { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java index 3ce410d..e8fdd8f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java @@ -210,6 +210,20 @@ public interface BundleManagerRemote { @WebParam(name = "distributionFileUrl") String distributionFileUrl) throws Exception;
/** + * Remove everything associated with the Bundles with the exception of files laid down by related deployments. + * Deployed files are left as is on the deployment platforms but the bundle mechanism will no longer track + * the deployment of all bundles that have been deleted. + * + * @param subject + * @param bundleIds IDs of all bundles to be deleted + * @throws Exception if any part of the removal fails. + */ + @WebMethod + void deleteBundles( // + @WebParam(name = "subject") Subject subject, // + @WebParam(name = "bundleIds") int[] bundleIds) throws Exception; + + /** * Remove everything associated with the Bundle with the exception of files laid down by related deployments. * Deployed files are left as is on the deployment platforms but the bundle mechanism will no longer track * the deployment. 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 6e4f1a6..484a751 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 @@ -105,6 +105,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.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.resource.CreateResourceHistory; import org.rhq.core.domain.resource.DeleteResourceHistory; import org.rhq.core.domain.resource.Resource; @@ -140,9 +142,7 @@ import org.rhq.enterprise.server.measurement.MeasurementDataManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementDefinitionManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementProblemManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementScheduleManagerLocal; -import org.rhq.core.domain.operation.bean.GroupOperationSchedule; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.resource.ResourceFactoryManagerLocal; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.ResourceNotFoundException; @@ -307,6 +307,10 @@ public class WebservicesManagerBean implements WebservicesRemote { return bundleManager.createBundleVersionViaURL(subject, distributionFileUrl); }
+ public void deleteBundles(Subject subject, int[] bundleIds) throws Exception { + bundleManager.deleteBundles(subject, bundleIds); + } + public void deleteBundle(Subject subject, int bundleId) throws Exception { bundleManager.deleteBundle(subject, bundleId); }
commit 5dc0d1c0aa10da93ea73bfda9bc9b642b5daf543 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 14:14:52 2010 -0500
BZ 612955 if we don't have the previous bundle version, get it async and set the field. this way the user knows the bundle version of the previous bundle this also fixes the description field which erroneously was the name field (cut-n-paste typo)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java index ce59914..4053fae 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client.bundle.revert;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.form.DynamicForm; @@ -27,7 +28,9 @@ import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.bundle.BundleDeployment; +import org.rhq.core.domain.bundle.BundleVersion; import org.rhq.core.domain.criteria.BundleDeploymentCriteria; +import org.rhq.core.domain.criteria.BundleVersionCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; @@ -104,8 +107,8 @@ public class ConfirmationStep extends AbstractWizardStep {
private void setLayout() {
- BundleDeployment live = this.wizard.getLiveDeployment(); - BundleDeployment prev = this.wizard.getPreviousDeployment(); + final BundleDeployment live = this.wizard.getLiveDeployment(); + final BundleDeployment prev = this.wizard.getPreviousDeployment();
Label liveHeader = new Label(); liveHeader.setContents("<b>" + MSG.view_bundle_revertWizard_confirmStep_liveDeployment() + ":<b>"); @@ -120,6 +123,7 @@ public class ConfirmationStep extends AbstractWizardStep { liveNameItem.setTitleAlign(Alignment.LEFT); liveNameItem.setAlign(Alignment.LEFT); liveNameItem.setWrap(false); + liveNameItem.setWrapTitle(false); liveNameItem.setValue(live.getName()); liveNameItem.setLeft(20);
@@ -127,12 +131,15 @@ public class ConfirmationStep extends AbstractWizardStep { liveDescItem.setTitleAlign(Alignment.LEFT); liveDescItem.setAlign(Alignment.LEFT); liveDescItem.setWrap(false); - liveDescItem.setValue((null != live.getName()) ? live.getName() : MSG.common_val_none()); + liveDescItem.setWrapTitle(false); + liveDescItem.setTitleVAlign(VerticalAlignment.TOP); + liveDescItem.setValue((null != live.getDescription()) ? live.getDescription() : MSG.common_val_none());
StaticTextItem liveVersionItem = new StaticTextItem("liveVersion", MSG.view_bundle_bundleVersion()); liveVersionItem.setTitleAlign(Alignment.LEFT); liveVersionItem.setAlign(Alignment.LEFT); liveVersionItem.setWrap(false); + liveVersionItem.setWrapTitle(false); liveVersionItem.setValue(live.getBundleVersion().getVersion());
liveForm.setItems(liveNameItem, liveDescItem, liveVersionItem); @@ -144,22 +151,53 @@ public class ConfirmationStep extends AbstractWizardStep { prevHeader.setWidth100(); layout.addMember(prevHeader);
- DynamicForm prevForm = new DynamicForm(); + final DynamicForm prevForm = new DynamicForm(); prevForm.setNumCols(2);
StaticTextItem prevNameItem = new StaticTextItem("prevName", MSG.common_title_name()); prevNameItem.setTitleAlign(Alignment.LEFT); prevNameItem.setAlign(Alignment.LEFT); prevNameItem.setWrap(false); + prevNameItem.setWrapTitle(false); prevNameItem.setValue(prev.getName());
StaticTextItem prevDescItem = new StaticTextItem("prevDesc", MSG.common_title_description()); prevDescItem.setTitleAlign(Alignment.LEFT); prevDescItem.setAlign(Alignment.LEFT); prevDescItem.setWrap(false); - prevDescItem.setValue((null != prev.getName()) ? prev.getName() : MSG.common_val_none()); + prevDescItem.setWrapTitle(false); + prevDescItem.setTitleVAlign(VerticalAlignment.TOP); + prevDescItem.setValue((null != prev.getDescription()) ? prev.getDescription() : MSG.common_val_none()); + + final StaticTextItem prevVersionItem = new StaticTextItem("prevVersion", MSG.view_bundle_bundleVersion()); + prevVersionItem.setTitleAlign(Alignment.LEFT); + prevVersionItem.setAlign(Alignment.LEFT); + prevVersionItem.setWrap(false); + prevVersionItem.setWrapTitle(false); + if (prev.getBundleVersion().getVersion() == null) { + BundleVersionCriteria c = new BundleVersionCriteria(); + c.addFilterId(prev.getBundleVersion().getId()); + bundleServer.findBundleVersionsByCriteria(c, new AsyncCallback<PageList<BundleVersion>>() { + + @Override + public void onSuccess(PageList<BundleVersion> result) { + if (result != null && result.size() == 1) { + prevVersionItem.setValue(result.get(0).getVersion()); + prevForm.markForRedraw(); + } + } + + @Override + public void onFailure(Throwable caught) { + prevVersionItem.setValue("?"); + prevForm.markForRedraw(); + } + }); + } else { + prevVersionItem.setValue(prev.getBundleVersion().getVersion()); + }
- prevForm.setItems(prevNameItem, prevDescItem); + prevForm.setItems(prevNameItem, prevDescItem, prevVersionItem); layout.addMember(prevForm);
Label confirmation = new Label();
commit 6bd6837302b3e8720bebcfa8c2ed60f8de1345a9 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 13:29:54 2010 -0500
use concise messages for message center. the exception's messages will be put into the details area in the popup by ErrorHandler
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java index 8a8baa6..ce59914 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/ConfirmationStep.java @@ -93,7 +93,8 @@ public class ConfirmationStep extends AbstractWizardStep { String message = MSG.view_bundle_revertWizard_confirmStep_failedToFindLiveDeployment() + ": " + caught.getMessage(); wizard.getView().showMessage(message); - CoreGUI.getErrorHandler().handleError(message, caught); + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_revertWizard_confirmStep_failedToFindLiveDeployment(), caught); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/RevertStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/RevertStep.java index 7724572..bfef06c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/RevertStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/revert/RevertStep.java @@ -88,8 +88,7 @@ public class RevertStep extends AbstractWizardStep { deployingImage.setSrc("/images/status_error.gif"); deployingMessage.setText(MSG.view_bundle_revertWizard_revertStep_scheduledFailure()); CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_revertWizard_revertStep_scheduledFailure() + ": " + caught.getMessage(), - caught); + MSG.view_bundle_revertWizard_revertStep_scheduledFailure(), caught); } }); }
commit 270a9782e2d2f71d6bbad09627e4d260bbe2d04b Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 13:58:09 2010 -0500
fix to filter by subjectId not the subject object
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index dd6d556..27d9dcd 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -215,7 +215,7 @@ public final class CriteriaQueryGenerator { + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + " FROM %alias% innerAlias " + NL // + " JOIN %innerAlias%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + NL // - + " WHERE crg.recursive = true AND s = %subjectId% )" + NL // + + " WHERE crg.recursive = true AND s.id = %subjectId% )" + NL // + " OR" + NL // + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id" + NL // + " FROM %alias% innerAlias " + NL //
commit e5003d37187cd75b7fa731824257003c082680b7 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 13:21:44 2010 -0500
BZ 616422 - the previous button now works. was hitting a NPE that we now protect against
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 6b90111..0423952 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 @@ -98,11 +98,13 @@ public class BundleUploadDataStep extends AbstractWizardStep { public boolean previousPage() { wizard.getView().hideMessage();
- for (BundleFileUploadForm uploadForm : this.uploadForms) { - if (uploadForm.isUploadInProgress()) { - handleUploadError("[" + uploadForm.getName() + "] " + MSG.view_bundle_createWizard_uploadInProgress(), - false); - return false; + if (this.uploadForms != null) { + for (BundleFileUploadForm uploadForm : this.uploadForms) { + if (uploadForm.isUploadInProgress()) { + handleUploadError("[" + uploadForm.getName() + "] " + + MSG.view_bundle_createWizard_uploadInProgress(), false); + return false; + } } }
commit 9dcbc0553d66f9c0031076aab6d4516cf1cd0565 Author: Ian Springer ian.springer@redhat.com Date: Mon Dec 20 13:15:42 2010 -0500
more work on operation schedule detail view
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java index 1e0d4a8..8450214 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java @@ -77,7 +77,7 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e idField.setCanEdit(false); fields.add(idField);
- DataSourceTextField operationNameField = createTextField(Field.OPERATION_NAME, "Operation", null, 100, true); + DataSourceTextField operationNameField = createTextField(Field.OPERATION_NAME, "Operation Name", null, 100, true); fields.add(operationNameField);
DataSourceTextField operationDisplayNameField = createTextField(Field.OPERATION_DISPLAY_NAME, "Operation", null, 100, true); @@ -88,7 +88,7 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e for (OperationDefinition operationDefinition : operationDefinitions) { valueMap.put(operationDefinition.getName(), operationDefinition.getDisplayName()); } - operationNameField.setValueMap(valueMap); + operationNameField.setValueMap(valueMap);
DataSourceTextField subjectField = createTextField(Field.SUBJECT, "Owner", null, 100, true); subjectField.setCanEdit(false); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java index 12df23e..263c3ae 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java @@ -20,12 +20,20 @@ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule;
import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Set;
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.TextAreaItem; +import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; +import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
+import org.rhq.core.domain.operation.OperationDefinition; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.form.AbstractRecordEditor; @@ -37,8 +45,21 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation */ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor {
+ private static final String FIELD_OPERATION_DESCRIPTION = "operationDescription"; + + private ResourceComposite resourceComposite; + private Map<String, String> operationNameToDescriptionMap = new HashMap<String, String>(); + private SelectItem operationNameItem; + private StaticTextItem operationDescriptionItem; + public ResourceOperationScheduleDetailsView(String locatorId, ResourceComposite resourceComposite, int scheduleId) { super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite), scheduleId, "Scheduled Operation", null); + this.resourceComposite = resourceComposite; + ResourceType resourceType = this.resourceComposite.getResource().getResourceType(); + Set<OperationDefinition> operationDefinitions = resourceType.getOperationDefinitions(); + for (OperationDefinition operationDefinition : operationDefinitions) { + this.operationNameToDescriptionMap.put(operationDefinition.getName(), operationDefinition.getDescription()); + } }
@Override @@ -54,19 +75,44 @@ public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { protected List<FormItem> createFormItems(EnhancedDynamicForm form) { List<FormItem> items = new ArrayList<FormItem>();
- SelectItem operationNameItem = new SelectItem(ResourceOperationScheduleDataSource.Field.OPERATION_NAME); - items.add(operationNameItem); + this.operationNameItem = new SelectItem(ResourceOperationScheduleDataSource.Field.OPERATION_NAME); + items.add(this.operationNameItem); + this.operationNameItem.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent event) { + updateOperationDescriptionItem(); + } + }); + + this.operationDescriptionItem = new StaticTextItem(FIELD_OPERATION_DESCRIPTION, "Operation Description"); + items.add(this.operationDescriptionItem);
- TextAreaItem descriptionItem = new TextAreaItem(ResourceOperationScheduleDataSource.Field.DESCRIPTION); - descriptionItem.setColSpan(form.getNumCols()); - items.add(descriptionItem); + TextAreaItem notesItem = new TextAreaItem(ResourceOperationScheduleDataSource.Field.DESCRIPTION, "Notes"); + notesItem.setColSpan(form.getNumCols()); + items.add(notesItem);
return items; }
@Override + protected void onDraw() { + super.onDraw(); + updateOperationDescriptionItem(); + } + + @Override protected String getTitleFieldName() { return ResourceOperationScheduleDataSource.Field.OPERATION_DISPLAY_NAME; } - + + private void updateOperationDescriptionItem() { + String operationName = this.operationNameItem.getValueAsString(); + String value; + if (operationName == null) { + value = "<i>Select an operation to view its description.</i>"; + } else { + value = this.operationNameToDescriptionMap.get(operationName); + } + this.operationDescriptionItem.setValue(value); + } + }
commit 8a242842c5e41f945cc3e0da64365b0a74fe5f6b Author: Ian Springer ian.springer@redhat.com Date: Mon Dec 20 10:51:59 2010 -0500
remove some faulty code that was trying to lookup an OperationScheduleEntity by its old primary key (https://bugzilla.redhat.com/show_bug.cgi?id=664350)
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java index 5d62695..b54dc27 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java @@ -1356,7 +1356,6 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan * the time this group operation was kicked off), the group operation was a success by definition */ groupHistory.setStatus(OperationRequestStatus.SUCCESS); - continue; } } catch (Throwable t) { LOG.warn("Failed to check for memberless group operations. Cause: " + t); @@ -1794,7 +1793,6 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan * @return a managed entity, attached to this bean's entity manager */ private OperationScheduleEntity findOperationScheduleEntity(ScheduleJobId jobId) { - OperationScheduleEntity entity = entityManager.find(OperationScheduleEntity.class, jobId); Query query = entityManager.createNamedQuery(OperationScheduleEntity.QUERY_FIND_BY_JOB_ID); String jobName = jobId.getJobName(); query.setParameter("jobName", jobName); @@ -1838,7 +1836,6 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan public List<OperationDefinition> findOperationDefinitionsByCriteria(Subject subject, OperationDefinitionCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ;
CriteriaQueryRunner<OperationDefinition> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); @@ -1849,7 +1846,6 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan public PageList<ResourceOperationHistory> findResourceOperationHistoriesByCriteria(Subject subject, ResourceOperationHistoryCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ; if (authorizationManager.isInventoryManager(subject) == false) { generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.RESOURCE, subject .getId()); @@ -1864,7 +1860,6 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan public PageList<GroupOperationHistory> findGroupOperationHistoriesByCriteria(Subject subject, GroupOperationHistoryCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ; if (authorizationManager.isInventoryManager(subject) == false) { generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.GROUP, subject .getId());
commit c49742d307ca90d6f27e92ecdb34396935b1fd1a Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 13:15:54 2010 -0500
use shorter innerAlias name to improve text-wrapping
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index ecce694..dd6d556 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -192,51 +192,40 @@ public final class CriteriaQueryGenerator {
private String getEnhancedResourceAuthorizationWhereFragment(String fragment, int subjectId) { String customAuthzFragment = "" // - + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " - + NL // - + " FROM %alias% innerAlias " - + NL // - + " JOIN %innerAliasWithFragment%.implicitGroups g JOIN g.roles r JOIN r.subjects s " - + NL // + + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAlias%.implicitGroups g JOIN g.roles r JOIN r.subjects s " + NL // + " WHERE s.id = %subjectId% ) )" + NL; // String aliasReplacement = criteria.getAlias() + (fragment != null ? "." + fragment : ""); String innerAliasReplacement = "innerAlias" + (fragment != null ? "." + fragment : ""); customAuthzFragment = customAuthzFragment.replace("%alias%", criteria.getAlias()); customAuthzFragment = customAuthzFragment.replace("%aliasWithFragment%", aliasReplacement); - customAuthzFragment = customAuthzFragment.replace("%innerAliasWithFragment%", innerAliasReplacement); + customAuthzFragment = customAuthzFragment.replace("%innerAlias%", innerAliasReplacement); customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId)); return customAuthzFragment; }
private String getEnhancedGroupAuthorizationWhereFragment(String fragment, int subjectId) { String customAuthzFragment = "" // - + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " - + NL // - + " FROM %alias% innerAlias " - + NL // - + " JOIN %innerAliasWithFragment%.roles r JOIN r.subjects s " - + NL // - + " WHERE s.id = %subjectId% )" - + NL // - + " OR" - + NL // - + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " - + NL // - + " FROM %alias% innerAlias " - + NL // - + " JOIN %innerAliasWithFragment%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " - + NL // + + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAlias%.roles r JOIN r.subjects s " + NL // + + " WHERE s.id = %subjectId% )" + NL // + + " OR" + NL // + + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAlias%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + NL // + " WHERE crg.recursive = true AND s = %subjectId% )" + NL // + " OR" + NL // + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id" + NL // + " FROM %alias% innerAlias " + NL // - + " JOIN %innerAliasWithFragment%.subject s" + NL // + + " JOIN %innerAlias%.subject s" + NL // + " WHERE s.id = %subjectId% ) ) " + NL; String aliasReplacement = criteria.getAlias() + (fragment != null ? "." + fragment : ""); String innerAliasReplacement = "innerAlias" + (fragment != null ? "." + fragment : ""); customAuthzFragment = customAuthzFragment.replace("%alias%", criteria.getAlias()); customAuthzFragment = customAuthzFragment.replace("%aliasWithFragment%", aliasReplacement); - customAuthzFragment = customAuthzFragment.replace("%innerAliasWithFragment%", innerAliasReplacement); + customAuthzFragment = customAuthzFragment.replace("%innerAlias%", innerAliasReplacement); customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId)); return customAuthzFragment; }
commit c720d98932c32174e0c3262eb7d9b6001372ccd4 Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 13:09:05 2010 -0500
update CriteriaQueryGenerator logic to generate 'WHERE' term appropriately
* basically, whenever ANY type of parameter is set on either the CriteriaQueryGenerator or the associated Criteria object, the 'WHERE' token needs to be generated into the query.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index ecf896e..ecce694 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -192,9 +192,12 @@ public final class CriteriaQueryGenerator {
private String getEnhancedResourceAuthorizationWhereFragment(String fragment, int subjectId) { String customAuthzFragment = "" // - + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // - + " FROM %alias% innerAlias " + NL // - + " JOIN %innerAliasWithFragment%.implicitGroups g JOIN g.roles r JOIN r.subjects s " + NL // + + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + + NL // + + " FROM %alias% innerAlias " + + NL // + + " JOIN %innerAliasWithFragment%.implicitGroups g JOIN g.roles r JOIN r.subjects s " + + NL // + " WHERE s.id = %subjectId% ) )" + NL; // String aliasReplacement = criteria.getAlias() + (fragment != null ? "." + fragment : ""); String innerAliasReplacement = "innerAlias" + (fragment != null ? "." + fragment : ""); @@ -207,14 +210,22 @@ public final class CriteriaQueryGenerator {
private String getEnhancedGroupAuthorizationWhereFragment(String fragment, int subjectId) { String customAuthzFragment = "" // - + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // - + " FROM %alias% innerAlias " + NL // - + " JOIN %innerAliasWithFragment%.roles r JOIN r.subjects s " + NL // - + " WHERE s.id = %subjectId% )" + NL // - + " OR" + NL // - + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // - + " FROM %alias% innerAlias " + NL // - + " JOIN %innerAliasWithFragment%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + NL // + + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + + NL // + + " FROM %alias% innerAlias " + + NL // + + " JOIN %innerAliasWithFragment%.roles r JOIN r.subjects s " + + NL // + + " WHERE s.id = %subjectId% )" + + NL // + + " OR" + + NL // + + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + + NL // + + " FROM %alias% innerAlias " + + NL // + + " JOIN %innerAliasWithFragment%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + + NL // + " WHERE crg.recursive = true AND s = %subjectId% )" + NL // + " OR" + NL // + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id" + NL // @@ -415,7 +426,8 @@ public final class CriteriaQueryGenerator { }
Map<String, Object> filterFields = getFilterFields(criteria); - if (filterFields.size() > 0 || searchExpressionWhereClause != null) { + if (filterFields.size() > 0 || authorizationPermsFragment != null + || authorizationCustomConditionFragment != null || searchExpressionWhereClause != null) { results.append("WHERE "); }
commit 8cdb554a592f02748fb1da9d0a850eead7120b5b Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 13:03:46 2010 -0500
remove 'authorizationJoinFragment', it's no longer used
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index afb1394..ecf896e 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -75,7 +75,6 @@ public final class CriteriaQueryGenerator { private String searchExpressionWhereClause;
private Subject subject; - private String authorizationJoinFragment; private String authorizationPermsFragment; private String authorizationCustomConditionFragment; private int authorizationSubjectId; @@ -356,9 +355,6 @@ public final class CriteriaQueryGenerator { } } } - if (authorizationJoinFragment != null) { - results.append(authorizationJoinFragment); - }
// figure out the 'LEFT JOIN's needed for 'ORDER BY' tokens PageControl pc = getPageControl(criteria); @@ -419,7 +415,7 @@ public final class CriteriaQueryGenerator { }
Map<String, Object> filterFields = getFilterFields(criteria); - if (filterFields.size() > 0 || authorizationJoinFragment != null || searchExpressionWhereClause != null) { + if (filterFields.size() > 0 || searchExpressionWhereClause != null) { results.append("WHERE "); }
@@ -463,17 +459,14 @@ public final class CriteriaQueryGenerator { }
// authorization - if (authorizationJoinFragment != null) { + if (authorizationPermsFragment != null) { if (firstCrit) { firstCrit = false; } else { // always want AND for security, regardless of conjunctiveFragment results.append(NL).append(" AND "); } - results.append("authSubject.id = " + authorizationSubjectId + " "); - if (null != this.authorizationPermsFragment) { - results.append(this.authorizationPermsFragment + " "); - } + results.append(this.authorizationPermsFragment + " "); }
if (authorizationCustomConditionFragment != null) {
commit ee2dbfd637f49f77e6dd3d4a0372b4591bee4a1b Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 12:51:28 2010 -0500
need to set the name of the user that did the deployment
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java index 00fe978..b1f65cf 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java @@ -255,6 +255,7 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot BundleDeployment deployment = new BundleDeployment(bundleVersion, bundleDestination, name); deployment.setDescription(description); deployment.setConfiguration(configuration); + deployment.setSubjectName(subject.getName());
entityManager.persist(deployment);
commit 29b93643a2f25a1a96db5d1ffb625c6aacf51c15 Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 12:48:24 2010 -0500
fix CriteriaQueryGenerator authorization token fragments
* need to use correlated sub-queries instead of joins to remove duplicate items in the result set. format for sub-queries may look odd, but are required to get hibernate to swallow / translate them properly into sql.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index ea4cf62..afb1394 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -165,24 +165,9 @@ public final class CriteriaQueryGenerator { public void setAuthorizationResourceFragment(AuthorizationTokenType type, String fragment, int subjectId) { this.authorizationSubjectId = subjectId; if (type == AuthorizationTokenType.RESOURCE) { - if (fragment == null) { - this.authorizationJoinFragment = "" // - + "JOIN " + alias + ".implicitGroups authGroup " + NL // - + "JOIN authGroup.roles authRole " + NL // - + "JOIN authRole.subjects authSubject " + NL; - } else { - this.authorizationJoinFragment = "" // - + "JOIN " + alias + "." + fragment + " authRes " + NL // - + "JOIN authRes.implicitGroups authGroup " + NL // - + "JOIN authGroup.roles authRole " + NL // - + "JOIN authRole.subjects authSubject " + NL; - } + setAuthorizationCustomConditionFragment(getEnhancedResourceAuthorizationWhereFragment(fragment, subjectId)); } else if (type == AuthorizationTokenType.GROUP) { - /* - * can no longer use JOIN-based filters for groups. need to support 3 completely separate authorization - * chains: 1) role-based for groups, 2) role-based for containing cluster groups, 3) private groups. - * so, we need to support group token authorization using a more complicated where-filter. - */ + // support for: 1) role-based for groups, 2) role-based for containing cluster groups, 3) private groups setAuthorizationCustomConditionFragment(getEnhancedGroupAuthorizationWhereFragment(fragment, subjectId)); } else { throw new IllegalArgumentException(this.getClass().getSimpleName() @@ -206,21 +191,42 @@ public final class CriteriaQueryGenerator { } }
+ private String getEnhancedResourceAuthorizationWhereFragment(String fragment, int subjectId) { + String customAuthzFragment = "" // + + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAliasWithFragment%.implicitGroups g JOIN g.roles r JOIN r.subjects s " + NL // + + " WHERE s.id = %subjectId% ) )" + NL; // + String aliasReplacement = criteria.getAlias() + (fragment != null ? "." + fragment : ""); + String innerAliasReplacement = "innerAlias" + (fragment != null ? "." + fragment : ""); + customAuthzFragment = customAuthzFragment.replace("%alias%", criteria.getAlias()); + customAuthzFragment = customAuthzFragment.replace("%aliasWithFragment%", aliasReplacement); + customAuthzFragment = customAuthzFragment.replace("%innerAliasWithFragment%", innerAliasReplacement); + customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId)); + return customAuthzFragment; + } + private String getEnhancedGroupAuthorizationWhereFragment(String fragment, int subjectId) { String customAuthzFragment = "" // - + "( %alias%.id IN ( SELECT %alias%.id " + NL // - + " FROM %alias%.roles r JOIN r.subjects s " + NL // + + "( %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAliasWithFragment%.roles r JOIN r.subjects s " + NL // + " WHERE s.id = %subjectId% )" + NL // + " OR" + NL // - + " %alias%.id IN ( SELECT %alias%.id " + NL // - + " FROM %alias%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + NL // + + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id " + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAliasWithFragment%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + NL // + " WHERE crg.recursive = true AND s = %subjectId% )" + NL // + " OR" + NL // - + " %alias%.id IN ( SELECT %alias%.id" + NL // - + " FROM %alias%.subject s" + NL // + + " %aliasWithFragment%.id IN ( SELECT %aliasWithFragment%.id" + NL // + + " FROM %alias% innerAlias " + NL // + + " JOIN %innerAliasWithFragment%.subject s" + NL // + " WHERE s.id = %subjectId% ) ) " + NL; - String aliasReplacement = (fragment != null ? fragment + "." : "") + criteria.getAlias(); - customAuthzFragment = customAuthzFragment.replace("%alias%", aliasReplacement); + String aliasReplacement = criteria.getAlias() + (fragment != null ? "." + fragment : ""); + String innerAliasReplacement = "innerAlias" + (fragment != null ? "." + fragment : ""); + customAuthzFragment = customAuthzFragment.replace("%alias%", criteria.getAlias()); + customAuthzFragment = customAuthzFragment.replace("%aliasWithFragment%", aliasReplacement); + customAuthzFragment = customAuthzFragment.replace("%innerAliasWithFragment%", innerAliasReplacement); customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId)); return customAuthzFragment; }
commit 706432d9a020332f355c8e00681ce4537d84d222 Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 10:54:20 2010 -0500
bump up timeout for deleting group definitions
* deletion of a group definition requires deleting all of its dynagroup children, and this could be hundreds or a few thousands groups against large inventories.
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 0f5fe93..b73b43b 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 @@ -100,7 +100,7 @@ public class GroupDefinitionListView extends TableSection { TableActionEnablement.ANY) { public void executeAction(ListGridRecord[] selection, Object actionValue) { final int[] groupDefinitionIds = TableUtility.getIds(selection); - ResourceGroupGWTServiceAsync groupManager = GWTServiceLookup.getResourceGroupService(); + ResourceGroupGWTServiceAsync groupManager = GWTServiceLookup.getResourceGroupService(60000); groupManager.deleteGroupDefinitions(groupDefinitionIds, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) {
commit a1413c63be98976785d38dc15d0c922a8cc42974 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 12:40:40 2010 -0500
make the error messages more concise so they don't expand the message center unnecessarily large. the popup message dialog will show the full exception details.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java index 90e3ea7..f16a071 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java @@ -121,7 +121,7 @@ public class BundleDeployWizard extends AbstractBundleDeployWizard {
public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_deployWizard_error_1(caught.getMessage()), caught); + MSG.view_bundle_deployWizard_error_1(), caught); } }); } @@ -130,8 +130,7 @@ public class BundleDeployWizard extends AbstractBundleDeployWizard {
public void onFailure(Throwable caught) { // should not really get here - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_deployWizard_error_1(caught.getMessage()), caught); + CoreGUI.getErrorHandler().handleError(MSG.view_bundle_deployWizard_error_1(), caught); deleteNewDestination(); } }); @@ -151,8 +150,7 @@ public class BundleDeployWizard extends AbstractBundleDeployWizard { }
public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_deployWizard_error_2(caught.getMessage()), caught); + CoreGUI.getErrorHandler().handleError(MSG.view_bundle_deployWizard_error_2(), caught); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java index 78a9bf9..615f0ab 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java @@ -145,8 +145,7 @@ public class GetDestinationStep extends AbstractWizardStep { }
public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_deployWizard_error_9(caught.getMessage()), caught); + CoreGUI.getErrorHandler().handleError(MSG.view_bundle_deployWizard_error_9(), caught); // try anyway and potentially fail again from there createDestination(); } @@ -179,7 +178,7 @@ public class GetDestinationStep extends AbstractWizardStep { public void onFailure(Throwable caught) { String message = MSG.view_bundle_deployWizard_error_10(); wizard.getView().showMessage(message); - CoreGUI.getErrorHandler().handleError(message + ": " + caught.getMessage(), caught); + CoreGUI.getErrorHandler().handleError(message, caught); createInProgress = false; wizard.getView().decrementStep(); } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index d98386e..3ed25bb 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -1009,15 +1009,15 @@ view_bundle_deployWizard_destinationCreatedDetail_concise = You have created the view_bundle_deployWizard_deploymentScheduled = Bundle Deployment Scheduled! view_bundle_deployWizard_deploymentScheduledDetail = You have scheduled the bundle deployment [{0}] to the destination group [{1}] view_bundle_deployWizard_deploymentScheduledDetail_concise = You have scheduled the bundle deployment -view_bundle_deployWizard_error_1 = Failed to delete new deployment on Cancel: {0} -view_bundle_deployWizard_error_2 = Failed to delete new destination on Cancel: {0} +view_bundle_deployWizard_error_1 = Failed to delete new deployment on Cancel +view_bundle_deployWizard_error_2 = Failed to delete new destination on Cancel view_bundle_deployWizard_error_3 = Failed to Schedule Deployment! view_bundle_deployWizard_error_4 = Failed to schedule deployment: {0} view_bundle_deployWizard_error_5 = Failed to Create Deployment! view_bundle_deployWizard_error_6 = Failed to create deployment: {0} view_bundle_deployWizard_error_7 = Failed to get deployment name. view_bundle_deployWizard_error_8 = You must select a valid resource group from the drop down -view_bundle_deployWizard_error_9 = Failed to delete new destination in nextPage: [{0}] +view_bundle_deployWizard_error_9 = Failed to delete new destination in nextPage view_bundle_deployWizard_error_10 = Failed to create destination, it may already exist. (Note, for an existing destination deploy from the Destination view) view_bundle_deployWizard_error_11 = Failed to find defined deployments. view_bundle_deployWizard_error_12 = Failed to find defined bundles.
commit 09bd655026d0e4e136850d87ff987c9daa4126a5 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 12:38:50 2010 -0500
errors should be at the error level, not fatal. rarely is an error actually fatal (where the definition of fatal means the software probably cannot go on any longer and a restart is usually necessary)
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 52971d7..f464421 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 @@ -37,7 +37,7 @@ public class ErrorHandler { }
public void handleError(String message, Throwable t) { - Message errorMessage = new Message(message, t, Message.Severity.Fatal); + Message errorMessage = new Message(message, t, Message.Severity.Error); CoreGUI.getMessageCenter().notify(errorMessage);
if (t != null) { @@ -81,5 +81,5 @@ public class ErrorHandler {
return list.toArray(new String[list.size()]); } - + }
commit 0716681d8453add414fe0acd4b705de75feb6ce7 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 12:19:59 2010 -0500
BZ 625198 - forgot to zero out the IDs in the default config
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java index 5c31961..736acba 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java @@ -64,7 +64,7 @@ public class GetDeploymentConfigStep extends AbstractWizardStep { if (defaultTemplate == null) { startingConfig = new Configuration(); } else { - startingConfig = defaultTemplate.getConfiguration(); + startingConfig = defaultTemplate.createConfiguration(); } } else { startingConfig = getNormalizedLiveConfig(configDef);
commit dffca6088e3b5e1b686bef0892e1bbb4082da523 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 12:18:34 2010 -0500
fix the loading icon
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java index bdc647a..576af53 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java @@ -23,6 +23,10 @@ public class ImageManager {
public static final String IMAGES_DIR = "images/";
+ public static String getLoadingIcon() { + return "ajax-loader.gif"; + } + /** * Returns a generic "upload" icon. */ diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java index 1c9dca9..619cd3e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java @@ -28,6 +28,7 @@ import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.bundle.BundleDeployment; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.ImageManager; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; @@ -62,7 +63,7 @@ public class DeployStep extends AbstractWizardStep { canvas.setHeight100(); canvas.setAlign(Alignment.CENTER);
- final Img deployingImage = new Img("/images/status-bar.gif"); + final Img deployingImage = new Img(ImageManager.getLoadingIcon()); deployingImage.setLayoutAlign(Alignment.CENTER); deployingImage.setWidth(50); deployingImage.setHeight(15);
commit 1e23b466af25ad9c62d26b3ac5048b6966b45784 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 11:54:56 2010 -0500
show concise error message along with details
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java index bdd818c..1c9dca9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java @@ -31,6 +31,7 @@ import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; 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.LocatableVLayout; @@ -94,6 +95,7 @@ public class DeployStep extends AbstractWizardStep { new Message(MSG.view_bundle_deployWizard_deploymentScheduledDetail_concise(), MSG.view_bundle_deployWizard_deploymentScheduledDetail(result.getName(), result.getDestination().getGroup().getName()), Severity.Info)); + wizard.getView().hideMessage(); CoreGUI.refresh(); wizard.setNewDeployment(result); } @@ -101,8 +103,12 @@ public class DeployStep extends AbstractWizardStep { public void onFailure(Throwable caught) { deployingImage.setSrc("/images/status_error.gif"); deployingMessage.setText(MSG.view_bundle_deployWizard_error_3()); - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_deployWizard_error_4(caught.getMessage()), caught); + String errMsg = MSG.view_bundle_deployWizard_error_4(ErrorHandler + .getAllMessages(caught)); + wizard.getView().showMessage(errMsg); + Message msg = new Message(MSG.view_bundle_deployWizard_error_3(), errMsg, + Severity.Error); + CoreGUI.getMessageCenter().notify(msg); } }); } @@ -110,8 +116,10 @@ public class DeployStep extends AbstractWizardStep { public void onFailure(Throwable caught) { deployingImage.setSrc("/images/status_error.gif"); deployingMessage.setText(MSG.view_bundle_deployWizard_error_5()); - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_deployWizard_error_6(caught.getMessage()), caught); + String errMsg = MSG.view_bundle_deployWizard_error_6(ErrorHandler.getAllMessages(caught)); + wizard.getView().showMessage(errMsg); + Message msg = new Message(MSG.view_bundle_deployWizard_error_5(), errMsg, Severity.Error); + CoreGUI.getMessageCenter().notify(msg); } }); }
commit 416e01daad0ff3fadefcfd260546d5f95285b848 Author: Heiko W. Rupp hwr@redhat.com Date: Mon Dec 20 15:15:06 2010 +0100
Availability3 never had its id set, so we can't compare it.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java index e59794a..37c5992 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java @@ -908,7 +908,9 @@ public class AvailabilityManagerTest extends AbstractEJB3Test { avail = availabilityManager.getCurrentAvailabilityForResource(overlord, theResource.getId());
// should have returned availability3 - assert avail.getId() == availability3.getId(); + // NOTE: availability3 never got an ID assigned, so we can't compare by id + // assert avail.getId() == availability3.getId(); + assert avail.getStartTime().equals(availability3.getStartTime()); assert avail.getAvailabilityType() == availability3.getAvailabilityType(); assert Math.abs(avail.getStartTime().getTime() - availability3.getStartTime().getTime()) < 1000; assert avail.getEndTime() == null;
commit 42b8ca52ac85b6d7e71b8786e2ff64037e7c566d Author: Heiko W. Rupp hwr@redhat.com Date: Mon Dec 20 11:58:42 2010 +0100
Better cleanup and introduce a sleep() call, as the previous mergeMeasurementReport is largely asynchronous inside. Sleep prevents random test failures.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java index 734f1df..2c3ab88 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java @@ -18,11 +18,15 @@ */ package org.rhq.enterprise.server.measurement.test;
+import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.Random;
import javax.persistence.EntityManager; +import javax.persistence.Query;
+import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
@@ -37,6 +41,7 @@ import org.rhq.core.domain.measurement.MeasurementScheduleRequest; import org.rhq.core.domain.measurement.MeasurementUnits; import org.rhq.core.domain.measurement.calltime.CallTimeData; import org.rhq.core.domain.measurement.calltime.CallTimeDataComposite; +import org.rhq.core.domain.measurement.calltime.CallTimeDataKey; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; @@ -55,6 +60,7 @@ import org.rhq.enterprise.server.util.LookupUtil;
public class MeasurementDataManagerTest extends AbstractEJB3Test {
+ private static final int DELTA = 20; private MeasurementDataManagerLocal measurementDataManager; private CallTimeDataManagerLocal callTimeDataManager;
@@ -63,6 +69,8 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { private Resource resource1,resource2; private MeasurementDefinition definitionCt1; private MeasurementDefinition definitionCt2; + private ResourceType theResourceType; + private Agent theAgent;
@BeforeMethod public void beforeMethod() { @@ -79,11 +87,60 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { }
+ @AfterMethod + public void afterMethod() { + + try { + // delete values + callTimeDataManager.purgeCallTimeData(new Date()); + + EntityManager em = beginTx(); + // delete keys + List<Integer> resourceIds = new ArrayList<Integer>(); + resourceIds.add(resource1.getId()); + resourceIds.add(resource2.getId()); + Query q = em.createNamedQuery(CallTimeDataKey.QUERY_DELETE_BY_RESOURCES); + q.setParameter("resourceIds",resourceIds); + q.executeUpdate(); + + resource1 = em.merge(resource1); + for (MeasurementSchedule sched : resource1.getSchedules()) { + em.remove(sched); + } + em.remove(resource1); + + resource2 = em.merge(resource2); + for (MeasurementSchedule sched : resource2.getSchedules()) { + em.remove(sched); + } + em.remove(resource2); + + definitionCt1 = em.merge(definitionCt1); + em.remove(definitionCt1); + definitionCt2 = em.merge(definitionCt2); + em.remove(definitionCt2); + + theResourceType = em.merge(theResourceType); + em.remove(theResourceType); + + theAgent = em.merge(theAgent); + em.remove(theAgent); + + commitAndClose(em); + } + catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + @Test public void bz658491() throws Exception { - EntityManager em = beginTx();
try { + EntityManager em = beginTx(); + setupResources(em);
MeasurementSchedule schedule1 = new MeasurementSchedule(definitionCt1,resource1); @@ -97,6 +154,7 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { resource2.addSchedule(schedule2);
em.flush(); + long now = System.currentTimeMillis();
MeasurementScheduleRequest request1 = new MeasurementScheduleRequest(schedule1); MeasurementScheduleRequest request2 = new MeasurementScheduleRequest(schedule2); @@ -111,14 +169,18 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { report.addData(data1); report.addData(data2);
+ commitAndClose(em); + measurementDataManager.mergeMeasurementReport(report);
- em.flush(); + // Do not remove this sleep -- the previous is is asynchronous + // and the sleep "guarantees" that data is actually hitting the db + Thread.sleep(1000);
PageList<CallTimeDataComposite> list1 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule1.getId(), - 0,System.currentTimeMillis(),new PageControl()); + now-DELTA,System.currentTimeMillis()+DELTA,new PageControl()); PageList<CallTimeDataComposite> list2 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule2.getId(), - 0,System.currentTimeMillis(),new PageControl()); + now-DELTA,System.currentTimeMillis()+DELTA,new PageControl());
assert list1 != null; assert list2 != null; @@ -130,19 +192,15 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { } catch (Exception e) { e.printStackTrace(); throw e; - } finally { - if (em != null) { - getTransactionManager().rollback(); - em.close(); - } } }
- @Test(enabled = false) + @Test public void bz658491OneResource() throws Exception { - EntityManager em = beginTx();
try { + EntityManager em = beginTx(); + setupResources(em);
MeasurementSchedule schedule1 = new MeasurementSchedule(definitionCt1,resource1); @@ -156,6 +214,7 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { resource2.addSchedule(schedule2);
em.flush(); + long now = System.currentTimeMillis();
MeasurementScheduleRequest request1 = new MeasurementScheduleRequest(schedule1); MeasurementScheduleRequest request2 = new MeasurementScheduleRequest(schedule2); @@ -170,14 +229,18 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { report.addData(data1); report.addData(data2);
+ commitAndClose(em); + measurementDataManager.mergeMeasurementReport(report);
- em.flush(); + // Do not remove this sleep -- the previous is is asynchronous + // and the sleep "guarantees" that data is actually hitting the db + Thread.sleep(1000);
PageList<CallTimeDataComposite> list1 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule1.getId(), - 0,System.currentTimeMillis(),new PageControl()); + now- DELTA,System.currentTimeMillis()+ DELTA,new PageControl()); PageList<CallTimeDataComposite> list2 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule2.getId(), - 0,System.currentTimeMillis(),new PageControl()); + now- DELTA,System.currentTimeMillis()+ DELTA,new PageControl());
assert list1 != null; assert list2 != null; @@ -189,11 +252,6 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { } catch (Exception e) { e.printStackTrace(); throw e; - } finally { - if (em != null) { - getTransactionManager().rollback(); - em.close(); - } } }
@@ -205,10 +263,10 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { * */ private void setupResources(EntityManager em) { - Agent theAgent = new Agent("testagent", "localhost", 1234, "", "randomToken"); + theAgent = new Agent("testagent", "localhost", 1234, "", "randomToken"); em.persist(theAgent);
- ResourceType theResourceType = new ResourceType("test-plat", "test-plugin", ResourceCategory.PLATFORM, null); + theResourceType = new ResourceType("test-plat", "test-plugin", ResourceCategory.PLATFORM, null); em.persist(theResourceType);
definitionCt1 = new MeasurementDefinition("CT-Def1", MeasurementCategory.PERFORMANCE, @@ -237,4 +295,10 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { EntityManager em = getEntityManager(); return em; } + + private void commitAndClose(EntityManager em) throws Exception { + em.flush(); + getTransactionManager().commit(); + em.close(); + } }
commit 6d4c02a946fe0117ba033b385a747b0a9d1e133b Author: Lukas Krejci lkrejci@redhat.com Date: Mon Dec 20 10:58:40 2010 +0100
BZ 656471 - adding missing index definition in db setup.
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml index 8108cb9..903f334 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml @@ -133,6 +133,10 @@ <field ref="TIME_STAMP"/> </primaryKey> </constraint> + + <index name="RHQ_MEAS_DATA_1D_TIME_IDX"> + <field ref="TIME_STAMP" /> + </index> </table>
commit 652d90efa3584115cf6c0747902e449e59a41038 Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 04:20:04 2010 -0500
append new lines to enhanced group authorization where fragment
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index 2ef27e2..ea4cf62 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -183,7 +183,7 @@ public final class CriteriaQueryGenerator { * chains: 1) role-based for groups, 2) role-based for containing cluster groups, 3) private groups. * so, we need to support group token authorization using a more complicated where-filter. */ - setAuthorizationCustomConditionFragment(getEnhancedGroupAuthorizationJoinFragment(fragment, subjectId)); + setAuthorizationCustomConditionFragment(getEnhancedGroupAuthorizationWhereFragment(fragment, subjectId)); } else { throw new IllegalArgumentException(this.getClass().getSimpleName() + " does not yet support generating queries for '" + type + "' token types"); @@ -206,19 +206,19 @@ public final class CriteriaQueryGenerator { } }
- private String getEnhancedGroupAuthorizationJoinFragment(String fragment, int subjectId) { + private String getEnhancedGroupAuthorizationWhereFragment(String fragment, int subjectId) { String customAuthzFragment = "" // - + "( %alias%.id IN ( SELECT %alias%.id " // - + " FROM %alias%.roles r JOIN r.subjects s " // - + " WHERE s.id = %subjectId% )" // - + " OR" // - + " %alias%.id IN ( SELECT %alias%.id " // - + " FROM %alias%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " // - + " WHERE crg.recursive = true AND s = %subjectId% )" // - + " OR" // - + " %alias%.id IN ( SELECT %alias%.id" // - + " FROM %alias%.subject s" // - + " WHERE s.id = %subjectId% )"; + + "( %alias%.id IN ( SELECT %alias%.id " + NL // + + " FROM %alias%.roles r JOIN r.subjects s " + NL // + + " WHERE s.id = %subjectId% )" + NL // + + " OR" + NL // + + " %alias%.id IN ( SELECT %alias%.id " + NL // + + " FROM %alias%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " + NL // + + " WHERE crg.recursive = true AND s = %subjectId% )" + NL // + + " OR" + NL // + + " %alias%.id IN ( SELECT %alias%.id" + NL // + + " FROM %alias%.subject s" + NL // + + " WHERE s.id = %subjectId% ) ) " + NL; String aliasReplacement = (fragment != null ? fragment + "." : "") + criteria.getAlias(); customAuthzFragment = customAuthzFragment.replace("%alias%", aliasReplacement); customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId));
commit 6183f641287c29b574b12b8a0615bf77a902ec8f Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 04:02:13 2010 -0500
enhance group authorization token fragment to account for all group types
* supported types are the 1) regular role-based joins, 2) role-based joins to the containing cluster group, 3) private / subject-owned groups
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java index 32c6950..2ef27e2 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java @@ -178,16 +178,12 @@ public final class CriteriaQueryGenerator { + "JOIN authRole.subjects authSubject " + NL; } } else if (type == AuthorizationTokenType.GROUP) { - if (fragment == null) { - this.authorizationJoinFragment = "" // - + "JOIN " + alias + ".roles authRole " + NL // - + "JOIN authRole.subjects authSubject " + NL; - } else { - this.authorizationJoinFragment = "" // - + "JOIN " + alias + "." + fragment + " authGroup " + NL // - + "JOIN authGroup.roles authRole " + NL // - + "JOIN authRole.subjects authSubject " + NL; - } + /* + * can no longer use JOIN-based filters for groups. need to support 3 completely separate authorization + * chains: 1) role-based for groups, 2) role-based for containing cluster groups, 3) private groups. + * so, we need to support group token authorization using a more complicated where-filter. + */ + setAuthorizationCustomConditionFragment(getEnhancedGroupAuthorizationJoinFragment(fragment, subjectId)); } else { throw new IllegalArgumentException(this.getClass().getSimpleName() + " does not yet support generating queries for '" + type + "' token types"); @@ -210,6 +206,25 @@ public final class CriteriaQueryGenerator { } }
+ private String getEnhancedGroupAuthorizationJoinFragment(String fragment, int subjectId) { + String customAuthzFragment = "" // + + "( %alias%.id IN ( SELECT %alias%.id " // + + " FROM %alias%.roles r JOIN r.subjects s " // + + " WHERE s.id = %subjectId% )" // + + " OR" // + + " %alias%.id IN ( SELECT %alias%.id " // + + " FROM %alias%.clusterResourceGroup crg JOIN crg.roles r JOIN r.subjects s " // + + " WHERE crg.recursive = true AND s = %subjectId% )" // + + " OR" // + + " %alias%.id IN ( SELECT %alias%.id" // + + " FROM %alias%.subject s" // + + " WHERE s.id = %subjectId% )"; + String aliasReplacement = (fragment != null ? fragment + "." : "") + criteria.getAlias(); + customAuthzFragment = customAuthzFragment.replace("%alias%", aliasReplacement); + customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId)); + return customAuthzFragment; + } + public String getParameterReplacedQuery(boolean countQuery) { String query = getQueryString(countQuery);
commit de53f73d84df7e7815cfff2d15d86f5f7a4748c7 Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 03:58:48 2010 -0500
add commented out debugging parameters to rhq-server.sh
diff --git a/modules/enterprise/server/container/src/main/bin-resources/bin/rhq-server.sh b/modules/enterprise/server/container/src/main/bin-resources/bin/rhq-server.sh index bbef0bf..b08ceaa 100644 --- a/modules/enterprise/server/container/src/main/bin-resources/bin/rhq-server.sh +++ b/modules/enterprise/server/container/src/main/bin-resources/bin/rhq-server.sh @@ -54,6 +54,7 @@ # is mainly used to augment the Server's # default set of options. This can be # left unset if it is not needed. +#RHQ_SERVER_ADDITIONAL_JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n # # RHQ_SERVER_CMDLINE_OPTS - If this is defined, these are the command line # arguments that will be passed to the RHQ Server
commit 9ba744a9f8089930ade0def90731ae0456f13af2 Author: Joseph Marques joseph@redhat.com Date: Mon Dec 20 02:20:37 2010 -0500
up the timeout for recalculating group definitions - it could be expensive
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 981fadc..d675373 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 @@ -62,6 +62,10 @@ public class GWTServiceLookup { return secure(ResourceGroupGWTServiceAsync.Util.getInstance()); }
+ public static ResourceGroupGWTServiceAsync getResourceGroupService(int timeout) { + return secure(ResourceGroupGWTServiceAsync.Util.getInstance(), timeout); + } + public static ResourceTypeGWTServiceAsync getResourceTypeGWTService() { return secure(ResourceTypeGWTServiceAsync.Util.getInstance()); } 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 9ab4029..7ad448a 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 @@ -150,7 +150,7 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm form.saveData(new DSCallback() { @Override public void execute(DSResponse response, Object rawData, DSRequest request) { - GWTServiceLookup.getResourceGroupService().recalculateGroupDefinitions( + GWTServiceLookup.getResourceGroupService(600000).recalculateGroupDefinitions( new int[] { groupDefinitionId }, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) {
commit a803ca2fd91ee10ccabe5d398e981db8977caf59 Author: John Mazzitelli mazz@redhat.com Date: Mon Dec 20 00:22:30 2010 -0500
fix help text
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 f924d00..5948154 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 @@ -1662,15 +1662,15 @@ public interface AgentI18NResourceKeys { String LISTDATA_HELP = "PromptCommand.listdata.help";
@I18NMessage("Lists files found in the data directory, optionally deleting them.\n\\n" - + "\This is an advanced command for adminstrators use only. You should not\n\\n" - + "\delete data files unless you know what you are doing. You could render\n\\n" - + "\the agent useless if you delete files that you should not.\n\\n" - + "\ -v, --verbose={true|false} : enables/disables more detailed file lists\n\\n" - + "\ -r, --recurse: recurse down subdirectories\n\\n" + + "This is an advanced command for administrators use only. You should not\n\\n" + + "delete data files unless you know what you are doing. You could render\n\\n" + + "the agent useless if you delete files that you should not.\n\\n" + + "\ -v, --verbose : enables more detailed file lists\n\\n" + + "\ -r, --recurse : recurse into subdirectories\n\\n" + "\ -d, --delete : delete the files that are listed\n\\n" - + "\ 'bundles'|path_name : the relative path under the data directory to list\n\\n" - + "\ If 'bundle', will list data files from the bundle\n\\n" - + "\ subsystem") + + "\ 'bundles'|path_name : the relative path under the data directory to list.\n\\n" + + "\ If 'bundles', will list data files from the bundle\n\\n" + + "\ subsystem.") String LISTDATA_DETAILED_HELP = "PromptCommand.listdata.detailed-help";
@I18NMessage("You cannot use .. in the path - you can only list files within the data directory")
commit e2992dff3266c2985ed2b077d3b8fe6b66350460 Author: John Mazzitelli mazz@redhat.com Date: Sun Dec 19 23:56:33 2010 -0500
BZ 648579 - type - fix the help constant
diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java index 762ebad..c36fd81 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java @@ -63,7 +63,7 @@ public class ListDataPromptCommand implements AgentPromptCommand { }
public String getDetailedHelp() { - return MSG.getMsg(AgentI18NResourceKeys.GC_DETAILED_HELP); + return MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DETAILED_HELP); }
private void processArguments(AgentMain agent, String[] args) {
commit 438e904d526a280acafc0a8fc1892269ceaef1ae Author: John Mazzitelli mazz@redhat.com Date: Sun Dec 19 23:51:46 2010 -0500
BZ 648579 add ability to view bundle tmp files and optionally delete them. this adds a general command that lets you peek in the agent data directory and subdirectories
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 43c2ba5..1ffa079 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 @@ -115,6 +115,7 @@ import org.rhq.enterprise.agent.promptcmd.GetConfigPromptCommand; import org.rhq.enterprise.agent.promptcmd.HelpPromptCommand; import org.rhq.enterprise.agent.promptcmd.IdentifyPromptCommand; import org.rhq.enterprise.agent.promptcmd.InventoryPromptCommand; +import org.rhq.enterprise.agent.promptcmd.ListDataPromptCommand; import org.rhq.enterprise.agent.promptcmd.LogPromptCommand; import org.rhq.enterprise.agent.promptcmd.MetricsPromptCommand; import org.rhq.enterprise.agent.promptcmd.NativePromptCommand; @@ -1628,7 +1629,7 @@ public class AgentMain { //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; }
@@ -3036,7 +3037,7 @@ public class AgentMain { new LogPromptCommand(), new TimerPromptCommand(), new PingPromptCommand(), new DownloadPromptCommand(), new DumpSpoolPromptCommand(), new SenderPromptCommand(), new FailoverPromptCommand(), new UpdatePromptCommand(), new DebugPromptCommand(), new SleepPromptCommand(), new GCPromptCommand(), - new SchedulesPromptCommand() }; + new SchedulesPromptCommand(), new ListDataPromptCommand() };
// hold the conflicts StringBuilder conflicts = new StringBuilder(); @@ -3412,15 +3413,16 @@ public class AgentMain { try { InventoryManager inventoryManager = PluginContainer.getInstance().getInventoryManager(); if (inventoryManager != null && inventoryManager.hasUpgradeMergeFailed()) { - m_output.println(MSG.getMsg(AgentI18NResourceKeys.RESTARTING_PLUGIN_CONTAINER_AFTER_UPGRADE_MERGE_FAILURE)); + 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."); + LOG.error("Failed to restart the plugin container when server connection established."); } return true; } @@ -3430,7 +3432,7 @@ public class AgentMain { 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 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 c28349c..f924d00 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 @@ -1652,6 +1652,57 @@ public interface AgentI18NResourceKeys { @I18NMessage("days") String UNITS_DAYS = "units.days";
+ @I18NMessage("listdata") + String LISTDATA = "PromptCommand.listdata"; + + @I18NMessage("listdata [--delete] [--recurse] [--verbose] <'bundles'|path_name>") + String LISTDATA_SYNTAX = "PromptCommand.listdata.syntax"; + + @I18NMessage("Lists and optionally deletes agent data files. USE WITH CAUTION!") + String LISTDATA_HELP = "PromptCommand.listdata.help"; + + @I18NMessage("Lists files found in the data directory, optionally deleting them.\n\\n" + + "\This is an advanced command for adminstrators use only. You should not\n\\n" + + "\delete data files unless you know what you are doing. You could render\n\\n" + + "\the agent useless if you delete files that you should not.\n\\n" + + "\ -v, --verbose={true|false} : enables/disables more detailed file lists\n\\n" + + "\ -r, --recurse: recurse down subdirectories\n\\n" + + "\ -d, --delete : delete the files that are listed\n\\n" + + "\ 'bundles'|path_name : the relative path under the data directory to list\n\\n" + + "\ If 'bundle', will list data files from the bundle\n\\n" + + "\ subsystem") + String LISTDATA_DETAILED_HELP = "PromptCommand.listdata.detailed-help"; + + @I18NMessage("You cannot use .. in the path - you can only list files within the data directory") + String LISTDATA_DOTDOT_NOT_ALLOWED = "PromptCommand.listdata.dotdot-not-allowed"; + + @I18NMessage("You can only list files within the data directory - no absolute paths allowed") + String LISTDATA_ABSOLUTE_NOT_ALLOWED = "PromptCommand.listdata.absolute-not-allowed"; + + @I18NMessage("Agent data directory: [{0}]") + String LISTDATA_DATA_DIR = "PromptCommand.listdata.data_dir"; + + @I18NMessage("File not found: [{0}]") + String LISTDATA_FILE_NOT_FOUND = "PromptCommand.listdata.file_not_found"; + + @I18NMessage("Deleted: [{0}]") + String LISTDATA_DELETED = "PromptCommand.listdata.deleted"; + + @I18NMessage("Delete failed: [{0}]") + String LISTDATA_DELETED_FAILED = "PromptCommand.listdata.deleted_failed"; + + @I18NMessage("{0}") + String LISTDATA_FILE_INFO = "PromptCommand.listdata.file_info"; + + @I18NMessage("{1,date,short} {1,time,short}\t{2} bytes\t{0}") + String LISTDATA_FILE_INFO_VERBOSE = "PromptCommand.listdata.file_info_verbose"; + + @I18NMessage("{0}") + String LISTDATA_DIR_INFO = "PromptCommand.listdata.dir_info"; + + @I18NMessage("{1,date,short} {1,time,short}\t{2} files\t{0}") + String LISTDATA_DIR_INFO_VERBOSE = "PromptCommand.listdata.dir_info_verbose"; + @I18NMessage("gc") String GC = "PromptCommand.gc";
diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java new file mode 100644 index 0000000..762ebad --- /dev/null +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/ListDataPromptCommand.java @@ -0,0 +1,207 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.agent.promptcmd; + +import gnu.getopt.Getopt; +import gnu.getopt.LongOpt; + +import java.io.File; +import java.io.PrintWriter; +import java.util.Date; + +import mazz.i18n.Msg; + +import org.rhq.enterprise.agent.AgentMain; +import org.rhq.enterprise.agent.i18n.AgentI18NFactory; +import org.rhq.enterprise.agent.i18n.AgentI18NResourceKeys; + +/** + * Allows you to peek into the agent's data directory. This also provides + * a way to delete files in the data directory and its subdirectories, allowing + * you to clean up temporary or unused data files that may be bloating the agent. + * + * @author John Mazzitelli + */ +public class ListDataPromptCommand implements AgentPromptCommand { + private static final Msg MSG = AgentI18NFactory.getMsg(); + + public String getPromptCommandString() { + return MSG.getMsg(AgentI18NResourceKeys.LISTDATA); + } + + public boolean execute(AgentMain agent, String[] args) { + // strip the first argument, which is the name of our prompt command + String[] realArgs = new String[args.length - 1]; + System.arraycopy(args, 1, realArgs, 0, args.length - 1); + + processArguments(agent, realArgs); + return true; + } + + public String getSyntax() { + return MSG.getMsg(AgentI18NResourceKeys.LISTDATA_SYNTAX); + } + + public String getHelp() { + return MSG.getMsg(AgentI18NResourceKeys.LISTDATA_HELP); + } + + public String getDetailedHelp() { + return MSG.getMsg(AgentI18NResourceKeys.GC_DETAILED_HELP); + } + + private void processArguments(AgentMain agent, String[] args) { + PrintWriter out = agent.getOut(); + + String sopts = "-dvr"; + LongOpt[] lopts = { new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v'), + new LongOpt("recurse", LongOpt.NO_ARGUMENT, null, 'r'), + new LongOpt("delete", LongOpt.NO_ARGUMENT, null, 'd') }; + + Getopt getopt = new Getopt(getPromptCommandString(), args, sopts, lopts); + int code; + boolean verbose = false; + boolean recurse = false; + boolean delete = false; + String pathname = null; + + while ((pathname == null) && (code = getopt.getopt()) != -1) { + switch (code) { + case ':': + case '?': { + out.println(MSG.getMsg(AgentI18NResourceKeys.HELP_SYNTAX_LABEL, getSyntax())); + break; + } + + case 1: { + // we found the path name - stop processing arguments + pathname = getopt.getOptarg(); + break; + } + + case 'v': { + verbose = true; + break; + } + + case 'r': { + recurse = true; + break; + } + + case 'd': { + delete = true; + break; + } + } + } + + if (getopt.getOptind() < args.length || pathname == null) { + // we got too many arguments on the command line + out.println(MSG.getMsg(AgentI18NResourceKeys.HELP_SYNTAX_LABEL, getSyntax())); + return; + } + + // sneaky sneaky - do not allow the user to attempt to go up to parent directories + if (pathname.indexOf("..") != -1) { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DOTDOT_NOT_ALLOWED)); + return; + } + + // sneaky sneaky - do not allow the user to attempt to go to any absolute path + if (new File(pathname).isAbsolute()) { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_ABSOLUTE_NOT_ALLOWED)); + return; + } + + String dataDir = agent.getConfiguration().getDataDirectory().getAbsolutePath(); + + if (verbose) { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DATA_DIR, dataDir)); + } + + if ("bundles".equals(pathname)) { + pathname = "tmp/bundle-versions"; + } + + list(out, dataDir, new File(dataDir, pathname), verbose, recurse, delete); + + return; + } + + private void list(PrintWriter out, String dataDir, File file, boolean verbose, boolean recurse, boolean delete) { + String relativePath = getRelativePath(dataDir, file); + + if (file.isFile()) { + printFileInfo(out, dataDir, file, verbose); + } else if (file.isDirectory()) { + printDirInfo(out, dataDir, file, verbose); + File[] dirFiles = file.listFiles(); + if (recurse) { + for (File dirFile : dirFiles) { + list(out, dataDir, dirFile, verbose, recurse, delete); + } + } + } else { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_FILE_NOT_FOUND, relativePath)); + return; + + } + + if (delete) { + boolean ok = file.delete(); + if (ok) { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DELETED, relativePath)); + } else { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DELETED_FAILED, relativePath)); + } + } + } + + private void printFileInfo(PrintWriter out, String dataDir, File file, boolean verbose) { + String name = getRelativePath(dataDir, file); + if (verbose) { + long filesize = file.length(); + Date lastModified = new Date(file.lastModified()); + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_FILE_INFO_VERBOSE, name, lastModified, filesize)); + } else { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_FILE_INFO, name)); + } + } + + private void printDirInfo(PrintWriter out, String dataDir, File dir, boolean verbose) { + String name = getRelativePath(dataDir, dir); + if (verbose) { + int filecount = dir.listFiles().length; + Date lastModified = new Date(dir.lastModified()); + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DIR_INFO_VERBOSE, name, lastModified, filecount)); + } else { + out.println(MSG.getMsg(AgentI18NResourceKeys.LISTDATA_DIR_INFO, name)); + } + } + + private String getRelativePath(String dataDir, File file) { + try { + return file.getAbsolutePath().substring(dataDir.length()); + } catch (Exception e) { + // something weird happened, just show the path + return file.getPath(); + } + } +}
commit bb0b69b2a1a0169269f0e2f3189dfc89a6f03fdc Author: Joseph Marques joseph@redhat.com Date: Sun Dec 19 23:06:22 2010 -0500
add core/client-api module to 'coregui' profile
* some bundle classes in server/jar refer to client-api classes
diff --git a/modules/pom.xml b/modules/pom.xml index 35040d3..f760f66 100644 --- a/modules/pom.xml +++ b/modules/pom.xml @@ -87,6 +87,7 @@ </activation> <modules> <module>core/domain</module> + <module>core/client-api</module> <module>enterprise/server/jar</module> <module>enterprise/gui/coregui</module> </modules>
commit 2a8710a5d7c0a1780ec77208d1d71afb5630b4c7 Author: Joseph Marques joseph@redhat.com Date: Sun Dec 19 22:52:26 2010 -0500
remove offset so SearchBar sits in line properly
diff --git a/modules/enterprise/gui/coregui/src/main/webapp/css/search.css b/modules/enterprise/gui/coregui/src/main/webapp/css/search.css index 2f96535..45b13f3 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/css/search.css +++ b/modules/enterprise/gui/coregui/src/main/webapp/css/search.css @@ -59,7 +59,6 @@ div {
/* - * * search container elements */
@@ -74,8 +73,6 @@ div {
.searchBarBackgroundContainer { position: absolute; - top: 5px; - left: 5px; background-color: white; border-style: inset; border-color: gray;
commit 38b76483415e7644a0fa7b4a7e3c4f4180358d9c Author: Joseph Marques joseph@redhat.com Date: Thu Dec 16 02:54:13 2010 -0500
fix SearchBar styling to eliminate JSF-style color border and correct inset
diff --git a/modules/enterprise/gui/coregui/src/main/webapp/css/search.css b/modules/enterprise/gui/coregui/src/main/webapp/css/search.css index cd75fbc..2f96535 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/css/search.css +++ b/modules/enterprise/gui/coregui/src/main/webapp/css/search.css @@ -61,13 +61,12 @@ div { /* * * search container elements - * */
.searchBarContainer { width: 800px; position: relative; - background-color: rgb(233, 230, 225); + background-color: white; height: 34px; vertical-align: bottom; z-index: 999999; @@ -79,10 +78,7 @@ div { left: 5px; background-color: white; border-style: inset; - border-top-color: rgb(222, 222, 222); - border-left-color: rgb(222, 222, 222); - border-bottom-color: white; - border-right-color: white; + border-color: gray; border-width: 1px 1px 1px 1px; padding: 0; width: 785px;
commit cbeb637f476b69ba543bc283246f60bdbc6fd517 Author: Joseph Marques joseph@redhat.com Date: Thu Dec 16 02:28:27 2010 -0500
get rid of unused methods
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java index 23d9626..9e3e6eb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java @@ -193,11 +193,6 @@ public class FlexSearchBar extends AbstractSearchBar { // presume the enclosing page logic loads results without a button click }
- public static native String getUserAgent() - /*-{ - return navigator.userAgent.toLowerCase(); - }-*/; - public SavedSearchManager getSavedSearchManager() { return savedSearchManager; } 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 9ce630b..b421132 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 @@ -184,11 +184,6 @@ public class SearchBar extends AbstractSearchBar { // presume the enclosing page logic loads results without a button click }
- public static native String getUserAgent() - /*-{ - return navigator.userAgent.toLowerCase(); - }-*/; - public SavedSearchManager getSavedSearchManager() { return savedSearchManager; }
commit c69e48b06bd5ba26ba91aeb4be8b3be726cb1564 Author: Joseph Marques joseph@redhat.com Date: Thu Dec 16 02:26:14 2010 -0500
welcome msg redundant with SearchBar label, delete it and accompanying logic
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/AbstractSearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/AbstractSearchBar.java index ac4a874..a0d44db 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/AbstractSearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/AbstractSearchBar.java @@ -32,8 +32,6 @@ public abstract class AbstractSearchBar extends Composite {
public abstract SearchSubsystem getSearchSubsystem();
- public abstract String getWelcomeMessage(); - public abstract String getSelectedTab();
public abstract void activateSavedSearch(String savedSearchName); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java index 172bd13..23d9626 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java @@ -62,8 +62,6 @@ public class FlexSearchBar extends AbstractSearchBar {
private static final Messages MSG = CoreGUI.getMessages();
- public String welcomeMessage; - public static final String DEFAULT_PATTERN_NAME = MSG.view_searchBar_defaultPattern();
private static final String IMAGE_DIR = "/coregui/images/search/"; @@ -106,7 +104,7 @@ public class FlexSearchBar extends AbstractSearchBar {
if (event.getNativeEvent().getEventTarget().equals(searchButton) && event.getTypeInt() == Event.ONMOUSEDOWN) { - prepareSearchExecution(); + //prepareSearchExecution(); } } } @@ -150,20 +148,6 @@ public class FlexSearchBar extends AbstractSearchBar { savedSearchManager = new SavedSearchManager(this); }
- private Element createDiv(Element parentDiv, String className, String id) { - Element div = DOM.createDiv(); - if (parentDiv != null) { - parentDiv.appendChild(div); - } - if (className != null) { - div.addClassName(className); - } - if (id != null) { - div.setId(id); - } - return div; - } - private HorizontalPanel createHPanel(Panel parent, String className, String id) { HorizontalPanel panel = new HorizontalPanel(); if (parent != null) { @@ -179,15 +163,6 @@ public class FlexSearchBar extends AbstractSearchBar { }
public void onSavedSearchManagerLoaded() { - /* - RootPanel.get("patternFieldContainer").add(autoCompletePatternField); - RootPanel.get("patternNameFieldContainer").add(patternNameField); - RootPanel.get("patternNameLabelContainer").add(patternNameLabel); - RootPanel.get("starImageContainer").add(starImage); - RootPanel.get("arrowImageContainer").add(arrowImage); - RootPanel.get("savedSearchesContainer").add(savedSearchesPanel); - */ - sbc_sbbgc_sbcc_sbclhs_pfc.add(autoCompletePatternField); sbc_sbbgc_sbcc_sbcrhs_pnfc.add(patternNameField); sbc_sbbgc_sbcc_sbcrhs_pnlc.add(patternNameLabel); @@ -202,7 +177,6 @@ public class FlexSearchBar extends AbstractSearchBar { setupArrowImage(); setupSavedSearches();
- // if (defaultSearchText != null) { this.autoCompletePatternField.setText(defaultSearchText); click(searchButton); // execute the search with this default search expression @@ -230,10 +204,6 @@ public class FlexSearchBar extends AbstractSearchBar {
public void setSearchSubsystem(SearchSubsystem searchSubsystem) { this.searchSubsystem = searchSubsystem; - - this.welcomeMessage = MSG.view_searchBar_welcomeMessage(this.searchSubsystem.getName()); - - this.autoCompletePatternField.setText(welcomeMessage); }
public SearchSubsystem getSearchSubsystem() { @@ -264,17 +234,6 @@ public class FlexSearchBar extends AbstractSearchBar { return defaultSavedSearchPatternId; }
- public String getWelcomeMessage() { - return welcomeMessage; - } - - public void prepareSearchExecution() { - String searchTerms = autoCompletePatternField.getText().toLowerCase().trim(); - if (searchTerms.equals(welcomeMessage)) { - autoCompletePatternField.setText(""); - } - } - private void setupAutoCompletingPatternField() { autoCompletePatternField.getElement().setId("patternField"); autoCompletePatternField.setStyleName("patternField"); @@ -397,18 +356,11 @@ public class FlexSearchBar extends AbstractSearchBar { }
public void onFocus(FocusEvent event) { - // clear default search text if necessary - if (autoCompletePatternField.getText().equals(welcomeMessage)) { - autoCompletePatternField.setValue("", true); - } autoCompletePatternField.showSuggestionList(); savedSearchesPanel.hide(); }
public void onBlur(BlurEvent event) { - if (autoCompletePatternField.getText().equals("")) { - autoCompletePatternField.setValue(welcomeMessage, true); - } savedSearchesPanel.hide(); } } 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 8be4f47..9ce630b 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 @@ -61,8 +61,6 @@ public class SearchBar extends AbstractSearchBar {
private static final Messages MSG = CoreGUI.getMessages();
- public String welcomeMessage; - public static final String DEFAULT_PATTERN_NAME = MSG.view_searchBar_defaultPattern();
private static final String IMAGE_DIR = "/coregui/images/search/"; @@ -118,7 +116,7 @@ public class SearchBar extends AbstractSearchBar {
if (event.getNativeEvent().getEventTarget().equals(searchButton) && event.getTypeInt() == Event.ONMOUSEDOWN) { - prepareSearchExecution(); + //prepareSearchExecution(); } } } @@ -197,10 +195,6 @@ public class SearchBar extends AbstractSearchBar {
public void setSearchSubsystem(SearchSubsystem searchSubsystem) { this.searchSubsystem = searchSubsystem; - - this.welcomeMessage = MSG.view_searchBar_welcomeMessage(this.searchSubsystem.getName()); - - this.autoCompletePatternField.setText(welcomeMessage); }
public SearchSubsystem getSearchSubsystem() { @@ -235,17 +229,6 @@ public class SearchBar extends AbstractSearchBar { return defaultSavedSearchPatternId; }
- public String getWelcomeMessage() { - return welcomeMessage; - } - - public void prepareSearchExecution() { - String searchTerms = autoCompletePatternField.getText().toLowerCase().trim(); - if (searchTerms.equals(welcomeMessage)) { - autoCompletePatternField.setText(""); - } - } - private void setupAutoCompletingPatternField() { autoCompletePatternField.getElement().setId("patternField"); autoCompletePatternField.setStyleName("patternField"); @@ -368,18 +351,11 @@ public class SearchBar extends AbstractSearchBar { }
public void onFocus(FocusEvent event) { - // clear default search text if necessary - if (autoCompletePatternField.getText().equals(welcomeMessage)) { - autoCompletePatternField.setValue("", true); - } autoCompletePatternField.showSuggestionList(); savedSearchesPanel.hide(); }
public void onBlur(BlurEvent event) { - if (autoCompletePatternField.getText().equals("")) { - autoCompletePatternField.setValue(welcomeMessage, true); - } savedSearchesPanel.hide(); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java index f2dab2f..454b8a1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java @@ -700,11 +700,6 @@ public class SuggestTextBox_v3 extends Composite implements HasText, HasAllFocus SearchSuggestion searchSuggestion = extraSearchSuggestion(suggestion); String currentText = getText().toLowerCase();
- if (searchBar.getWelcomeMessage().equals(currentText)) { - setValue("", true); - return; - } - if (searchSuggestion.getKind() == SearchSuggestion.Kind.GlobalSavedSearch || searchSuggestion.getKind() == SearchSuggestion.Kind.UserSavedSearch) { // execute saved searches immediately, since they presumably constitute complete expressions
commit 0e90bc94eb626e05b55fd5f2f1a2eeaac7e25c4e Author: John Mazzitelli mazz@redhat.com Date: Sun Dec 19 18:42:38 2010 -0500
BZ 625198 the bundle deploy wizard needs to show the default values for the config properties if defaults have been set in the recipe this code is agnostic to the kind of bundle type it is. checked in fixes to both filetemplate and ant bundle types (file template now supports setting default values in configdef command)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java index a28845c..5c31961 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java @@ -23,6 +23,7 @@ import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.enterprise.gui.coregui.client.components.HeaderLabel; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; @@ -57,8 +58,17 @@ public class GetDeploymentConfigStep extends AbstractWizardStep { editor.addMember(label); } else { // otherwise, pop up the config editor to get the needed config - Configuration startingConfig = (null == wizard.getLiveDeployment()) ? new Configuration() - : getNormalizedLiveConfig(configDef); + Configuration startingConfig; + if (wizard.getLiveDeployment() == null) { + ConfigurationTemplate defaultTemplate = configDef.getDefaultTemplate(); + if (defaultTemplate == null) { + startingConfig = new Configuration(); + } else { + startingConfig = defaultTemplate.getConfiguration(); + } + } else { + startingConfig = getNormalizedLiveConfig(configDef); + } editor = new ConfigurationEditor("BundleDeploymentConfig", configDef, startingConfig); } }
commit 2c87326ad0fa9449ef0e351e0f241d36ec4566da Author: John Mazzitelli mazz@redhat.com Date: Sun Dec 19 18:40:53 2010 -0500
BZ 625198 the bundle deploy wizard needs to show the default values for the config properties if defaults have been set in the recipe this code is agnostic to the kind of bundle type it is. checked in fixes to both filetemplate and ant bundle types (file template now supports setting default values in configdef command)
diff --git a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/InputPropertyType.java b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/InputPropertyType.java index 2b44a3a..070f02c 100644 --- a/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/InputPropertyType.java +++ b/modules/common/ant-bundle/src/main/java/org/rhq/bundle/ant/type/InputPropertyType.java @@ -19,6 +19,7 @@ package org.rhq.bundle.ant.type;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; + import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; @@ -48,7 +49,8 @@ public class InputPropertyType extends AbstractBundleType { ConfigurationDefinition configDef = getProject().getConfigurationDefinition(); PropertySimpleType propType = PropertySimpleType.fromXmlName(this.type); PropertyDefinitionSimple propDef = new PropertyDefinitionSimple(this.name, this.description, this.required, - propType); + propType); + propDef.setDefaultValue(this.defaultValue); configDef.put(propDef);
String value = getProject().getProperty(this.name); @@ -61,7 +63,7 @@ public class InputPropertyType extends AbstractBundleType { if (!parseOnly) { if (value == null && this.required) { throw new BuildException("No value was specified for required input property '" + this.name - + "', and no default is defined for the property."); + + "', and no default is defined for the property."); } validateValue(value, propType); String valueString = (value != null) ? "'" + value + "'" : "<null>"; @@ -74,7 +76,7 @@ public class InputPropertyType extends AbstractBundleType {
return; } - + public String getDescription() { return description; } @@ -145,7 +147,7 @@ public class InputPropertyType extends AbstractBundleType { validateValue(this.defaultValue, propType); } catch (RuntimeException e) { throw new BuildException("Default value '" + this.defaultValue - + "' is not valid according to 'type' attribute: " + this.type, e); + + "' is not valid according to 'type' attribute: " + this.type, e); } } } @@ -154,28 +156,28 @@ public class InputPropertyType extends AbstractBundleType { if (value != null) { try { switch (propType) { - case BOOLEAN: - if (!value.equals(Boolean.TRUE.toString()) && !value.equals(Boolean.FALSE.toString())) { - throw new RuntimeException("Illegal value for boolean property - value must be 'true' or 'false'." - + value); - } - break; - case DOUBLE: - Double.valueOf(value); - break; - case FLOAT: - Float.valueOf(value); - break; - case INTEGER: - Integer.valueOf(value); - break; - case LONG: - Long.valueOf(value); - break; + case BOOLEAN: + if (!value.equals(Boolean.TRUE.toString()) && !value.equals(Boolean.FALSE.toString())) { + throw new RuntimeException( + "Illegal value for boolean property - value must be 'true' or 'false'." + value); + } + break; + case DOUBLE: + Double.valueOf(value); + break; + case FLOAT: + Float.valueOf(value); + break; + case INTEGER: + Integer.valueOf(value); + break; + case LONG: + Long.valueOf(value); + break; } } catch (RuntimeException e) { throw new BuildException("'" + value + "' is not a legal value for input property '" + this.name - + "', which has type '" + this.type + "'.", e); + + "', which has type '" + this.type + "'.", e); } } } diff --git a/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/ConfigDefRecipeCommand.java b/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/ConfigDefRecipeCommand.java index 54f297c..59a0984 100644 --- a/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/ConfigDefRecipeCommand.java +++ b/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/ConfigDefRecipeCommand.java @@ -36,10 +36,12 @@ public class ConfigDefRecipeCommand implements RecipeCommand { }
public void parse(RecipeParser parser, RecipeContext context, String[] args) { - String sopts = ":n:"; - LongOpt[] lopts = { new LongOpt("name", LongOpt.REQUIRED_ARGUMENT, null, 'n') }; + String sopts = ":n:d:"; + LongOpt[] lopts = { new LongOpt("default", LongOpt.REQUIRED_ARGUMENT, null, 'd'), + new LongOpt("name", LongOpt.REQUIRED_ARGUMENT, null, 'n') };
String replacementVariableName = null; + String defaultValue = null;
Getopt getopt = new Getopt(getName(), args, sopts, lopts); int code; @@ -60,6 +62,11 @@ public class ConfigDefRecipeCommand implements RecipeCommand { break; }
+ case 'd': { + defaultValue = getopt.getOptarg(); + break; + } + default: { throw new IllegalArgumentException("Unexpected error in recipe command"); } @@ -75,6 +82,9 @@ public class ConfigDefRecipeCommand implements RecipeCommand { Set<String> replacementVariableNames = new HashSet<String>(1); replacementVariableNames.add(replacementVariableName); context.addReplacementVariables(replacementVariableNames); + if (defaultValue != null) { + context.assignDefaultValueToReplacementVariable(replacementVariableName, defaultValue); + }
return; } diff --git a/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/RecipeContext.java b/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/RecipeContext.java index e147e45..f6824a1 100644 --- a/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/RecipeContext.java +++ b/modules/common/filetemplate-bundle/src/main/java/org/rhq/bundle/filetemplate/recipe/RecipeContext.java @@ -49,6 +49,7 @@ public class RecipeContext { private final Map<String, String> files; private final Set<String> realizedFiles; private final Set<String> replacementVariables; + private final Map<String, String> replacementVariableDefaultValues; private Configuration replacementVariableValues; private final List<Script> scripts; private final List<Command> commands; @@ -62,6 +63,7 @@ public class RecipeContext { this.files = new HashMap<String, String>(); this.realizedFiles = new HashSet<String>(); this.replacementVariables = new HashSet<String>(); + this.replacementVariableDefaultValues = new HashMap<String, String>(); this.scripts = new ArrayList<Script>(); this.commands = new ArrayList<Command>(); this.deploymentProperties = new DeploymentProperties(); @@ -172,6 +174,29 @@ public class RecipeContext { }
/** + * If a replacement varaible is known to have a default value, call this + * to set that default value. + * + * @param replacementVariable the variable whose default is being set + * @param defaultValue the value of the default for the given replacement variable + */ + public void assignDefaultValueToReplacementVariable(String replacementVariable, String defaultValue) { + this.replacementVariableDefaultValues.put(replacementVariable, defaultValue); + } + + /** + * Returns a map keyed on replacement variables whose values are the default + * values for the replacement variables. Note that not all replacement variables + * found in {@link #getReplacementVariables()} will have an associated entry + * in the returned map (that is, not all variables have a default value). + * + * @return the map of all known default values for replacement variables + */ + public Map<String, String> getReplacementVariableDefaultValues() { + return this.replacementVariableDefaultValues; + } + + /** * If known, the returned value will contain values that are to be used to replace * replacement variables found in the recipe. * @@ -287,6 +312,15 @@ public class RecipeContext { } str.append("\n");
+ str.append("Replacement Default Values: "); + Map<String, String> defaults = getReplacementVariableDefaultValues(); + if (defaults == null) { + str.append("<none>"); + } else { + str.append(defaults); + } + str.append("\n"); + str.append("Script Files: ").append(getScriptFiles()).append("\n"); for (Script script : this.scripts) { str.append("* ").append(script.getExecutable()).append(" ").append(script.getArguments()).append("\n"); diff --git a/modules/common/filetemplate-bundle/src/test/java/org/rhq/bundle/filetemplate/recipe/RecipeParserTest.java b/modules/common/filetemplate-bundle/src/test/java/org/rhq/bundle/filetemplate/recipe/RecipeParserTest.java index 16054e0..cc277f1 100644 --- a/modules/common/filetemplate-bundle/src/test/java/org/rhq/bundle/filetemplate/recipe/RecipeParserTest.java +++ b/modules/common/filetemplate-bundle/src/test/java/org/rhq/bundle/filetemplate/recipe/RecipeParserTest.java @@ -156,6 +156,20 @@ public class RecipeParserTest { assert vars.size() == 2 : vars; assert vars.contains("my.first.property"); assert vars.contains("custom.prop"); + assert context.getReplacementVariableDefaultValues().isEmpty(); + + cleanRecipe(); + addRecipeCommand("configdef -n custom.prop -d 8080"); + addRecipeCommand("configdef --name another.prop --default some.default.value"); + parser = new RecipeParser(); + context = new RecipeContext(getRecipe()); + parser.parseRecipe(context); + vars = context.getReplacementVariables(); + assert vars.size() == 2 : vars; + assert vars.contains("custom.prop"); + assert vars.contains("another.prop"); + assert context.getReplacementVariableDefaultValues().containsKey("another.prop"); + assert context.getReplacementVariableDefaultValues().get("another.prop").equals("some.default.value"); }
public void testRealizeRecipe() throws Exception { diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtility.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtility.java index 74a864e..62b5377 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtility.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtility.java @@ -1,30 +1,31 @@ - /* - * 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.clientapi.agent.configuration;
import java.util.ArrayList; import java.util.List; import java.util.Map; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
@@ -36,6 +37,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.PropertyDefinitionList; import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; @@ -47,6 +49,57 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; * @author Ian Springer */ public abstract class ConfigurationUtility { + + /** + * This will populate the given configuration definition with a default template. + * A default template will only be created if one or more properties are required + * or have default values. If no property definition is required or has a default value, + * the default template will remain <code>null</code> in the given config definition. + * + * Note that if the given configuration definition already has a default template defined + * for it, this method is a no-op and will return immediately. + * + * @param configDef the configuration definition whose default template is to be created and set + */ + public static void initializeDefaultTemplate(ConfigurationDefinition configDef) { + ConfigurationTemplate defaultTemplate = configDef.getDefaultTemplate(); + if (defaultTemplate == null) { + Configuration defaultConfig = createDefaultConfiguration(configDef); + // not everything should have a default template - only stuff that has default values + if (!defaultConfig.getProperties().isEmpty()) { + defaultTemplate = new ConfigurationTemplate(ConfigurationTemplate.DEFAULT_TEMPLATE_NAME, + ConfigurationTemplate.DEFAULT_TEMPLATE_NAME); + defaultTemplate.setDefault(true); + defaultTemplate.setConfiguration(defaultConfig); + configDef.putTemplate(defaultTemplate); + } + } + return; + } + + /** + * Given a configuration definition, this will build and return a "default configuration" that + * can be validated with the definition. All required properties are set and all properties + * that define a default value are also set. If a required property does not have a default + * value defined in the definition, the property value will be set to <code>null</code>. + * + * Use this to help create the definition's default template. + * + * @param configurationDefinition the configuration definition whose default configuration is to be created + * @return configuration the default configuration + */ + public static Configuration createDefaultConfiguration(ConfigurationDefinition configurationDefinition) { + if (configurationDefinition == null) { + throw new IllegalArgumentException("configurationDefinition == null"); + } + Configuration defaultConfig = new Configuration(); + Map<String, PropertyDefinition> childPropertyDefinitions = configurationDefinition.getPropertyDefinitions(); + for (PropertyDefinition childPropertyDefinition : childPropertyDefinitions.values()) { + createDefaultProperty(childPropertyDefinition, defaultConfig); + } + return defaultConfig; + } + /** * "Normalize" the given configuration according to the given configuration definition. That is, for any optional * properties that are not defined in the top-level configuration Map or any sub-Maps, set them. Simple properties @@ -55,9 +108,8 @@ public abstract class ConfigurationUtility { * @param configuration the configuration to be normalized * @param configurationDefinition the configuration definition to normalize the configuration against */ - public static void normalizeConfiguration(@NotNull - Configuration configuration, @Nullable - ConfigurationDefinition configurationDefinition) { + public static void normalizeConfiguration(@NotNull Configuration configuration, + @Nullable ConfigurationDefinition configurationDefinition) { //noinspection ConstantConditions if (configuration == null) { throw new IllegalArgumentException("Configuration parameter is null."); @@ -82,9 +134,8 @@ public abstract class ConfigurationUtility { * @return a list of messages describing any errors that were found */ @NotNull - public static List<String> validateConfiguration(@NotNull - Configuration configuration, @Nullable - ConfigurationDefinition configurationDefinition) { + public static List<String> validateConfiguration(@NotNull Configuration configuration, + @Nullable ConfigurationDefinition configurationDefinition) { List<String> errorMessages = new ArrayList<String>(); if (configurationDefinition != null) { Map<String, PropertyDefinition> childPropertyDefinitions = configurationDefinition.getPropertyDefinitions(); @@ -95,6 +146,60 @@ public abstract class ConfigurationUtility { return errorMessages; }
+ private static void createDefaultProperty(PropertyDefinition propertyDefinition, + AbstractPropertyMap parentPropertyMap) { + + Property property = null; + + if (propertyDefinition instanceof PropertyDefinitionSimple) { + String defaultValue = ((PropertyDefinitionSimple) propertyDefinition).getDefaultValue(); + if (defaultValue != null || propertyDefinition.isRequired()) { + property = new PropertySimple(propertyDefinition.getName(), defaultValue); + } + } else if (propertyDefinition.isRequired()) { + if (propertyDefinition instanceof PropertyDefinitionMap) { + property = new PropertyMap(propertyDefinition.getName()); + Map<String, PropertyDefinition> childPropertyDefinitions = ((PropertyDefinitionMap) propertyDefinition) + .getPropertyDefinitions(); + for (PropertyDefinition childPropertyDefinition : childPropertyDefinitions.values()) { + createDefaultProperty(childPropertyDefinition, (PropertyMap) property); + } + } else if (propertyDefinition instanceof PropertyDefinitionList) { + property = new PropertyList(propertyDefinition.getName()); + PropertyDefinition listMemberPropertyDefinition = ((PropertyDefinitionList) propertyDefinition) + .getMemberDefinition(); + if (listMemberPropertyDefinition.isRequired()) { + if (listMemberPropertyDefinition instanceof PropertyDefinitionMap) { + // member property is a list-o-maps, create a default child map if appropriate + PropertyDefinitionMap listMemberDefinitionMap = (PropertyDefinitionMap) listMemberPropertyDefinition; + PropertyMap listMap = new PropertyMap(listMemberDefinitionMap.getName()); + createDefaultProperty(listMemberDefinitionMap, listMap); + ((PropertyList) property).add(listMap); + } else if (listMemberPropertyDefinition instanceof PropertyDefinitionSimple) { + // member property is a simple, create a single list entry as its default if appropriate + PropertyDefinitionSimple listMemberDefinitionSimple = (PropertyDefinitionSimple) listMemberPropertyDefinition; + String defaultValue = listMemberDefinitionSimple.getDefaultValue(); + if (defaultValue != null || listMemberDefinitionSimple.isRequired()) { + PropertySimple listSimple = new PropertySimple(listMemberDefinitionSimple.getName(), + defaultValue); + ((PropertyList) property).add(listSimple); + } + } + } + } else if (propertyDefinition instanceof PropertyDefinitionDynamic) { + // Dynamic property values should simply be stored as simple + property = new PropertySimple(propertyDefinition.getName(), null); + } else { + throw new IllegalStateException("Unsupported PropertyDefinition subclass: " + + propertyDefinition.getClass().getName()); + } + } + + if (property != null) { + parentPropertyMap.put(property); + } + } + private static void normalizeProperty(PropertyDefinition propertyDefinition, AbstractPropertyMap parentPropertyMap) { if (parentPropertyMap.getMap().keySet().contains(propertyDefinition.getName())) // property is already set { diff --git a/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtilityTest.java b/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtilityTest.java new file mode 100644 index 0000000..3f3dccd --- /dev/null +++ b/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/configuration/ConfigurationUtilityTest.java @@ -0,0 +1,322 @@ +/* + * 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.configuration; + +import org.testng.annotations.Test; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertyList; +import org.rhq.core.domain.configuration.PropertyMap; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; +import org.rhq.core.domain.configuration.definition.PropertySimpleType; + +@Test +public class ConfigurationUtilityTest { + public void testCreateDefaultNone() { + // no defaults, no required props - returned config should be empty + ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); + + PropertyDefinitionSimple simple = new PropertyDefinitionSimple("simple", null, false, PropertySimpleType.STRING); + PropertyDefinitionMap map = new PropertyDefinitionMap("map", null, false, simple); + PropertyDefinitionList list = new PropertyDefinitionList("list", null, false, simple); + + configDef.put(simple); + configDef.put(map); + configDef.put(list); + + Configuration config = ConfigurationUtility.createDefaultConfiguration(configDef); + assert config != null; + assert config.getProperties().size() == 0; + } + + public void testCreateDefaultSimple() { + ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); + + PropertyDefinitionSimple simple = new PropertyDefinitionSimple("simple", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple simpleRequired = new PropertyDefinitionSimple("simpleRequired", null, true, + PropertySimpleType.STRING); + PropertyDefinitionSimple simpleDefault = new PropertyDefinitionSimple("simpleDefault", null, false, + PropertySimpleType.STRING); + PropertyDefinitionSimple simpleRequiredDefault = new PropertyDefinitionSimple("simpleRequiredDefault", null, + true, PropertySimpleType.STRING); + + simpleDefault.setDefaultValue("!!simpleDefaultValue!!"); + simpleRequiredDefault.setDefaultValue("!!simpleRequiredDefaultValue!!"); + + configDef.put(simple); + configDef.put(simpleRequired); + configDef.put(simpleDefault); + configDef.put(simpleRequiredDefault); + + Configuration config = ConfigurationUtility.createDefaultConfiguration(configDef); + assert config != null; + assert config.getProperties().size() == 3; // simple is not required with no default - its not in the config + assert config.getSimple(simple.getName()) == null; + assert config.getSimpleValue(simpleRequired.getName(), null) == null; + assert config.getSimpleValue(simpleDefault.getName(), null).equals("!!simpleDefaultValue!!"); + assert config.getSimpleValue(simpleRequiredDefault.getName(), null).equals("!!simpleRequiredDefaultValue!!"); + } + + public void testCreateDefaultMap() { + ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); + + // a=not required, no default; c=not required, has default; d=required, has default + PropertyDefinitionSimple a = new PropertyDefinitionSimple("a", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple b = new PropertyDefinitionSimple("b", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple c = new PropertyDefinitionSimple("c", null, true, PropertySimpleType.STRING); + b.setDefaultValue("!!bDefaultValue!!"); + c.setDefaultValue("!!cDefaultValue!!"); + + PropertyDefinitionMap map1 = new PropertyDefinitionMap("map1", null, false, a, b, c); + PropertyDefinitionMap mapRequired1 = new PropertyDefinitionMap("mapRequired1", null, true, a, b, c); + PropertyDefinitionMap mapRequiredDefault1 = new PropertyDefinitionMap("mapRequiredDefault1", null, true, a, b, + c); + + configDef.put(map1); + configDef.put(mapRequired1); + configDef.put(mapRequiredDefault1); + + Configuration config = ConfigurationUtility.createDefaultConfiguration(configDef); + assert config != null; + assert config.getProperties().size() == 2; // map is not required with no default - its not in the config + assert config.getMap(map1.getName()) == null; + + // the two required maps have the same definitions - a,b,c as above. since a isn't required with no default, its not there + PropertyMap mapProp1 = config.getMap(mapRequired1.getName()); + assert mapProp1 != null; + assert mapProp1.getSimple(a.getName()) == null; + assert mapProp1.getSimpleValue(b.getName(), null).equals("!!bDefaultValue!!"); + assert mapProp1.getSimpleValue(c.getName(), null).equals("!!cDefaultValue!!"); + + mapProp1 = config.getMap(mapRequiredDefault1.getName()); + assert mapProp1 != null; + assert mapProp1.getSimple(a.getName()) == null; + assert mapProp1.getSimpleValue(b.getName(), null).equals("!!bDefaultValue!!"); + assert mapProp1.getSimpleValue(c.getName(), null).equals("!!cDefaultValue!!"); + } + + public void testCreateDefaultList() { + ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); + + // a=not required, no default, b=required, has default + PropertyDefinitionSimple a = new PropertyDefinitionSimple("a", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple c = new PropertyDefinitionSimple("c", null, true, PropertySimpleType.STRING); + c.setDefaultValue("!!cDefaultValue!!"); + + PropertyDefinitionList list1 = new PropertyDefinitionList("list1", null, false, a); + PropertyDefinitionList listRequired1 = new PropertyDefinitionList("listRequired1", null, true, a); + PropertyDefinitionList listRequiredDefault1 = new PropertyDefinitionList("listRequiredDefault1", null, true, c); + + configDef.put(list1); + configDef.put(listRequired1); + configDef.put(listRequiredDefault1); + + Configuration config = ConfigurationUtility.createDefaultConfiguration(configDef); + assert config != null; + assert config.getProperties().size() == 2; // list is not required with no default - its not in the config + assert config.getList(list1.getName()) == null; + + PropertyList listProp1 = config.getList(listRequired1.getName()); + assert listProp1 != null; + assert listProp1.getList().isEmpty(); // has "a" definition, which is not required and has no default + + listProp1 = config.getList(listRequiredDefault1.getName()); + assert listProp1 != null; + assert listProp1.getList().get(0).getName().equals(c.getName()); + assert ((PropertySimple) listProp1.getList().get(0)).getStringValue().equals("!!cDefaultValue!!"); + } + + public void testCreateDefaultListOMaps() { + ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); + + // a=not required, no default; c=not required, has default; d=required, has default + PropertyDefinitionSimple a = new PropertyDefinitionSimple("a", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple b = new PropertyDefinitionSimple("b", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple c = new PropertyDefinitionSimple("c", null, true, PropertySimpleType.STRING); + b.setDefaultValue("!!bDefaultValue!!"); + c.setDefaultValue("!!cDefaultValue!!"); + + PropertyDefinitionMap map2 = new PropertyDefinitionMap("map2", null, false, a, b, c); + PropertyDefinitionMap mapRequired2 = new PropertyDefinitionMap("mapRequired2", null, true, a, b, c); + PropertyDefinitionMap mapRequiredDefault2 = new PropertyDefinitionMap("mapRequiredDefault2", null, true, a, b, + c); + + PropertyDefinitionList listX = new PropertyDefinitionList("listX", null, true, map2); + PropertyDefinitionList listY = new PropertyDefinitionList("listY", null, true, mapRequired2); + PropertyDefinitionList listZ = new PropertyDefinitionList("listZ", null, true, mapRequiredDefault2); + + configDef.put(listX); + configDef.put(listY); + configDef.put(listZ); + + Configuration config = ConfigurationUtility.createDefaultConfiguration(configDef); + + assert config != null; + assert config.getProperties().size() == 3; + + PropertyList listPropTest = config.getList(listX.getName()); + assert listPropTest != null; + assert listPropTest.getList().isEmpty(); + + listPropTest = config.getList(listY.getName()); + assert listPropTest != null; + PropertyMap childMap2 = (PropertyMap) listPropTest.getList().get(0); + + listPropTest = config.getList(listZ.getName()); + assert listPropTest != null; + PropertyMap childMap3 = (PropertyMap) listPropTest.getList().get(0); + + assert childMap2.getName().equals(mapRequired2.getName()); + assert childMap3.getName().equals(mapRequiredDefault2.getName()); + } + + public void testCreateDefaultAllSimpleMapList() { + // tests a big config def that has simples, lists, maps - combination of the other individual tests + ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); + + // SETUP SIMPLE + + PropertyDefinitionSimple simple = new PropertyDefinitionSimple("simple", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple simpleRequired = new PropertyDefinitionSimple("simpleRequired", null, true, + PropertySimpleType.STRING); + PropertyDefinitionSimple simpleDefault = new PropertyDefinitionSimple("simpleDefault", null, false, + PropertySimpleType.STRING); + PropertyDefinitionSimple simpleRequiredDefault = new PropertyDefinitionSimple("simpleRequiredDefault", null, + true, PropertySimpleType.STRING); + + simpleDefault.setDefaultValue("!!simpleDefaultValue!!"); + simpleRequiredDefault.setDefaultValue("!!simpleRequiredDefaultValue!!"); + + configDef.put(simple); + configDef.put(simpleRequired); + configDef.put(simpleDefault); + configDef.put(simpleRequiredDefault); + + // SETUP MAP + + // a=not required, no default; c=not required, has default; d=required, has default + PropertyDefinitionSimple a = new PropertyDefinitionSimple("a", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple b = new PropertyDefinitionSimple("b", null, false, PropertySimpleType.STRING); + PropertyDefinitionSimple c = new PropertyDefinitionSimple("c", null, true, PropertySimpleType.STRING); + b.setDefaultValue("!!bDefaultValue!!"); + c.setDefaultValue("!!cDefaultValue!!"); + + PropertyDefinitionMap map1 = new PropertyDefinitionMap("map1", null, false, a, b, c); + PropertyDefinitionMap mapRequired1 = new PropertyDefinitionMap("mapRequired1", null, true, a, b, c); + PropertyDefinitionMap mapRequiredDefault1 = new PropertyDefinitionMap("mapRequiredDefault1", null, true, a, b, + c); + + configDef.put(map1); + configDef.put(mapRequired1); + configDef.put(mapRequiredDefault1); + + // SETUP LIST + + PropertyDefinitionList list1 = new PropertyDefinitionList("list1", null, false, a); + PropertyDefinitionList listRequired1 = new PropertyDefinitionList("listRequired1", null, true, a); + PropertyDefinitionList listRequiredDefault1 = new PropertyDefinitionList("listRequiredDefault1", null, true, c); + + configDef.put(list1); + configDef.put(listRequired1); + configDef.put(listRequiredDefault1); + + // SETUP LIST-O-MAPS + + PropertyDefinitionMap map2 = new PropertyDefinitionMap("map2", null, false, a, b, c); + PropertyDefinitionMap mapRequired2 = new PropertyDefinitionMap("mapRequired2", null, true, a, b, c); + PropertyDefinitionMap mapRequiredDefault2 = new PropertyDefinitionMap("mapRequiredDefault2", null, true, a, b, + c); + + PropertyDefinitionList listX = new PropertyDefinitionList("listX", null, true, map2); + PropertyDefinitionList listY = new PropertyDefinitionList("listY", null, true, mapRequired2); + PropertyDefinitionList listZ = new PropertyDefinitionList("listZ", null, true, mapRequiredDefault2); + + configDef.put(listX); + configDef.put(listY); + configDef.put(listZ); + + // get the default config + Configuration config = ConfigurationUtility.createDefaultConfiguration(configDef); + assert config != null; + assert config.getProperties().size() == 10; + + // ASSERT SIMPLE + + assert config.getSimple(simple.getName()) == null; + assert config.getSimpleValue(simpleRequired.getName(), null) == null; + assert config.getSimpleValue(simpleDefault.getName(), null).equals("!!simpleDefaultValue!!"); + assert config.getSimpleValue(simpleRequiredDefault.getName(), null).equals("!!simpleRequiredDefaultValue!!"); + + // ASSERT MAP + + assert config.getMap(map1.getName()) == null; + + // the two required maps have the same definitions - a,b,c as above. since a isn't required with no default, its not there + PropertyMap mapProp1 = config.getMap(mapRequired1.getName()); + assert mapProp1 != null; + assert mapProp1.getSimple(a.getName()) == null; + assert mapProp1.getSimpleValue(b.getName(), null).equals("!!bDefaultValue!!"); + assert mapProp1.getSimpleValue(c.getName(), null).equals("!!cDefaultValue!!"); + + mapProp1 = config.getMap(mapRequiredDefault1.getName()); + assert mapProp1 != null; + assert mapProp1.getSimple(a.getName()) == null; + assert mapProp1.getSimpleValue(b.getName(), null).equals("!!bDefaultValue!!"); + assert mapProp1.getSimpleValue(c.getName(), null).equals("!!cDefaultValue!!"); + + // ASSERT LIST + + assert config.getList(list1.getName()) == null; + + PropertyList listProp1 = config.getList(listRequired1.getName()); + assert listProp1 != null; + assert listProp1.getList().isEmpty(); // has "a" definition, which is not required and has no default + + listProp1 = config.getList(listRequiredDefault1.getName()); + assert listProp1 != null; + assert listProp1.getList().get(0).getName().equals(c.getName()); + assert ((PropertySimple) listProp1.getList().get(0)).getStringValue().equals("!!cDefaultValue!!"); + + // ASSERT LIST-O-MAPS + + PropertyList listPropTest = config.getList(listX.getName()); + assert listPropTest != null; + assert listPropTest.getList().isEmpty(); + + listPropTest = config.getList(listY.getName()); + assert listPropTest != null; + PropertyMap childMap2 = (PropertyMap) listPropTest.getList().get(0); + + listPropTest = config.getList(listZ.getName()); + assert listPropTest != null; + PropertyMap childMap3 = (PropertyMap) listPropTest.getList().get(0); + + assert childMap2.getName().equals(mapRequired2.getName()); + assert childMap3.getName().equals(mapRequiredDefault2.getName()); + } +} 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 174aa8e..b77b4e6 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 @@ -83,10 +83,11 @@ public class PropertyDefinitionSimple extends PropertyDefinition { * This property's default value. This field should have a non-null value for properties whose * {@link PropertyDefinition#required} field is <code>false</code> (i.e. for optional properties). Conversely, this * field should be null for properties whose {@link PropertyDefinition#required} field is <code>true</code> (i.e. for - * required properties). - * @deprecated Use the (default) template instead + * required properties). + * + * This field is mainly used to help build default templates. You usually do not want to use this + * default value member variable directly - consider using the configuration definition's default template. */ - @Deprecated @Column(name = "DEFAULT_VALUE", length = 2000) private String defaultValue;
@@ -201,12 +202,29 @@ public class PropertyDefinitionSimple extends PropertyDefinition { this.allowCustomEnumeratedValue = allowCustomEnumValue; }
- @Deprecated + /** + * Returns the default value that this property definition defines for its + * value. Note, however, you rarely want to use this directly. Under most + * circumstances, you should be using the configuration definition's + * {@link ConfigurationDefinition#getDefaultTemplate() default template}. + * + * For an example of where this method is useful, see + * org.rhq.core.clientapi.agent.configuration.ConfigurationUtility.initializeDefaultTemplate(ConfigurationDefinition) + * + * @return property default value + */ public String getDefaultValue() { return defaultValue; }
- @Deprecated + /** + * Sets the default value for this property. Note that you normally call this + * only at times when you plan on building default templates with this + * property definition later. See {@link #getDefaultValue()} for more details + * on this default value. + * + * @param defaultValue + */ public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/RecipeParseResults.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/RecipeParseResults.java index 108c097..5c42f9b 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/RecipeParseResults.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/RecipeParseResults.java @@ -1,6 +1,6 @@ /* * RHQ 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 @@ -21,6 +21,7 @@ package org.rhq.enterprise.server.bundle;
import java.util.Set;
+import org.rhq.core.clientapi.agent.configuration.ConfigurationUtility; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.util.updater.DeploymentProperties;
@@ -28,7 +29,8 @@ import org.rhq.core.util.updater.DeploymentProperties; * This class is general to all Bundle handling server side plugins. It is returned by the SSP when parsing * a bundle's recipe and contains all of the information neded to create a bundle version. * - * @author jay shaughnessy + * @author Jay Shaughnessy + * @author John Mazzitelli */ public class RecipeParseResults {
@@ -43,9 +45,9 @@ public class RecipeParseResults {
public RecipeParseResults(DeploymentProperties bundleMetadata, ConfigurationDefinition configDef, Set<String> bundleFileNames) { - this.bundleMetadata = bundleMetadata; - this.configDef = configDef; - this.bundleFileNames = bundleFileNames; + setBundleMetadata(bundleMetadata); + setConfigurationDefinition(configDef); + setBundleFiles(bundleFileNames); }
public DeploymentProperties getBundleMetadata() { @@ -60,8 +62,9 @@ public class RecipeParseResults { return configDef; }
- public void setConfigDef(ConfigurationDefinition configDef) { + public void setConfigurationDefinition(ConfigurationDefinition configDef) { this.configDef = configDef; + ConfigurationUtility.initializeDefaultTemplate(this.configDef); }
public Set<String> getBundleFileNames() { @@ -71,5 +74,4 @@ public class RecipeParseResults { public void setBundleFiles(Set<String> bundleFileNames) { this.bundleFileNames = bundleFileNames; } - } diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java index ab55bac..968d5cd 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/bundle/BundleManagerBeanTest.java @@ -57,6 +57,7 @@ import org.rhq.core.domain.bundle.composite.BundleWithLatestVersionComposite; 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.ConfigurationTemplate; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; import org.rhq.core.domain.content.Architecture; @@ -300,9 +301,30 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { bundleDescription);
ConfigurationDefinition configDef = new ConfigurationDefinition("foo", null); - String propName = "prop1"; - String propDescription = "prop1desc"; - configDef.put(new PropertyDefinitionSimple(propName, propDescription, true, PropertySimpleType.INTEGER)); + int propDefaultValue1 = 998877; + String propDefaultValue4 = "this.is.the.default"; + String propName1 = "prop1requiredWithDefault"; + String propName2 = "prop2"; + String propName3 = "prop3requiredWithNoDefault"; + String propName4 = "prop4notRequiredWithDefault"; + String propDesc1 = "prop1desc"; + String propDesc2 = "prop2desc"; + String propDesc3 = "prop3desc"; + String propDesc4 = "prop4desc"; + PropertyDefinitionSimple propdef1requiredWithDefault = new PropertyDefinitionSimple(propName1, propDesc1, + true, PropertySimpleType.INTEGER); + PropertyDefinitionSimple propdef2 = new PropertyDefinitionSimple(propName2, propDesc2, false, + PropertySimpleType.STRING); + PropertyDefinitionSimple propdef3requiredWithNoDefault = new PropertyDefinitionSimple(propName3, propDesc3, + true, PropertySimpleType.STRING); + PropertyDefinitionSimple propdef4notRequiredWithDefault = new PropertyDefinitionSimple(propName4, + propDesc4, false, PropertySimpleType.STRING); + propdef1requiredWithDefault.setDefaultValue(String.valueOf(propDefaultValue1)); + propdef4notRequiredWithDefault.setDefaultValue(propDefaultValue4); + configDef.put(propdef1requiredWithDefault); + configDef.put(propdef2); + configDef.put(propdef3requiredWithNoDefault); + configDef.put(propdef4notRequiredWithDefault);
Map<String, File> bundleFiles = new HashMap<String, File>(3); bundleFiles.put(bundleFile1, new File(tmpDir, bundleFile1)); @@ -358,12 +380,41 @@ public class BundleManagerBeanTest extends UpdateSubsytemTestBase { assert bundleFileNames.contains(bundleFile2) : bv; assert bundleFileNames.contains(bundleFile3) : bv; assert bv.getBundleDeployments().isEmpty() : bv; - assert bv.getConfigurationDefinition().getPropertyDefinitions().size() == 1; - assert bv.getConfigurationDefinition().get(propName) != null; - assert bv.getConfigurationDefinition().get(propName).getDescription().equals(propDescription); - assert bv.getConfigurationDefinition().get(propName).isRequired(); - assert bv.getConfigurationDefinition().getPropertyDefinitionSimple(propName).getType() == PropertySimpleType.INTEGER; + assert bv.getConfigurationDefinition().getPropertyDefinitions().size() == 4; + assert bv.getConfigurationDefinition().get(propName1) != null; + assert bv.getConfigurationDefinition().get(propName1).getDescription().equals(propDesc1); + assert bv.getConfigurationDefinition().get(propName1).isRequired() == true; + assert bv.getConfigurationDefinition().getPropertyDefinitionSimple(propName1).getType() == PropertySimpleType.INTEGER; + assert bv.getConfigurationDefinition().get(propName2) != null; + assert bv.getConfigurationDefinition().get(propName2).getDescription().equals(propDesc2); + assert bv.getConfigurationDefinition().get(propName2).isRequired() == false; + assert bv.getConfigurationDefinition().getPropertyDefinitionSimple(propName2).getType() == PropertySimpleType.STRING; + assert bv.getConfigurationDefinition().get(propName3) != null; + assert bv.getConfigurationDefinition().get(propName3).getDescription().equals(propDesc3); + assert bv.getConfigurationDefinition().get(propName3).isRequired() == true; + assert bv.getConfigurationDefinition().getPropertyDefinitionSimple(propName3).getType() == PropertySimpleType.STRING; + assert bv.getConfigurationDefinition().get(propName4) != null; + assert bv.getConfigurationDefinition().get(propName4).getDescription().equals(propDesc4); + assert bv.getConfigurationDefinition().get(propName4).isRequired() == false; + assert bv.getConfigurationDefinition().getPropertyDefinitionSimple(propName4).getType() == PropertySimpleType.STRING; assert bv.getRecipe().equals(recipe); + + // make sure the default template is correct + ConfigurationTemplate defaultTemplate = bv.getConfigurationDefinition().getDefaultTemplate(); + Configuration defaultConfig = defaultTemplate.getConfiguration(); + assert defaultConfig.getProperties().size() == 3; // prop2 is not required and has no default, thus is missing + PropertySimple prop1 = defaultConfig.getSimple(propName1); + PropertySimple prop2 = defaultConfig.getSimple(propName2); + PropertySimple prop3 = defaultConfig.getSimple(propName3); + PropertySimple prop4 = defaultConfig.getSimple(propName4); + assert prop1 != null; + assert prop2 == null : "prop2 was not required and has no default, it should not be in the default template config"; + assert prop3 != null; + assert prop4 != null; + assert prop1.getIntegerValue() != null; + assert prop1.getIntegerValue().intValue() == propDefaultValue1; + assert prop3.getStringValue() == null : "prop3 was required but had no default, its template value should have been null"; + assert prop4.getStringValue().equals(propDefaultValue4); } } finally { FileUtil.purge(tmpDir, true); diff --git a/modules/enterprise/server/plugins/filetemplate-bundle/src/main/java/org/rhq/enterprise/server/plugins/filetemplate/BundleServerPluginComponent.java b/modules/enterprise/server/plugins/filetemplate-bundle/src/main/java/org/rhq/enterprise/server/plugins/filetemplate/BundleServerPluginComponent.java index 4db9de9..cdb855a 100644 --- a/modules/enterprise/server/plugins/filetemplate-bundle/src/main/java/org/rhq/enterprise/server/plugins/filetemplate/BundleServerPluginComponent.java +++ b/modules/enterprise/server/plugins/filetemplate-bundle/src/main/java/org/rhq/enterprise/server/plugins/filetemplate/BundleServerPluginComponent.java @@ -111,6 +111,7 @@ public class BundleServerPluginComponent implements ServerPluginComponent, Bundl PropertyDefinitionSimple prop = new PropertyDefinitionSimple(replacementVar, "Needed by bundle recipe.", false, PropertySimpleType.STRING); prop.setDisplayName(replacementVar); + prop.setDefaultValue(recipeContext.getReplacementVariableDefaultValues().get(replacementVar)); configDef.put(prop); } }
commit ebbeac6c225768c858efeb2a6c95037e67ef3d72 Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 16:03:34 2010 -0500
support deleting bundle versions
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index 2d40a23..ec1ca5e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -111,6 +111,7 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka form.setWidth100(); form.setColWidths("20%", "40%", "40%"); form.setNumCols(3); + form.setAutoHeight(); form.setWrapItemTitles(false); form.setExtraSpace(10); form.setIsGroup(true); 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 e0bd7e9..e4ff4d3 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 @@ -168,6 +168,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { form.setWidth100(); form.setColWidths("20%", "40%", "40%"); form.setNumCols(3); + form.setAutoHeight(); form.setWrapItemTitles(false); form.setExtraSpace(10); form.setIsGroup(true); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java index 284ef3c..cf4ab17 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java @@ -26,7 +26,13 @@ import java.util.HashSet;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.util.BooleanCallback; +import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; +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.CanvasItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; @@ -49,9 +55,11 @@ import org.rhq.enterprise.gui.coregui.client.components.HeaderLabel; import org.rhq.enterprise.gui.coregui.client.components.buttons.BackButton; 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.BundleGWTServiceAsync; 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.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTab; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTabSet; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; @@ -61,6 +69,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class BundleVersionView extends LocatableVLayout implements BookmarkableView {
+ private BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); private BundleVersion version; private boolean canManageBundles = false;
@@ -111,16 +120,24 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV }
private LocatableDynamicForm createSummaryForm() { + LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("Summary")); form.setWidth100(); + form.setColWidths("20%", "40%", "40%"); + form.setNumCols(3); form.setAutoHeight(); - form.setNumCols(2); form.setWrapItemTitles(false); form.setExtraSpace(10); form.setIsGroup(true); form.setGroupTitle(MSG.common_title_summary()); form.setPadding(5);
+ CanvasItem actionItem = new CanvasItem("actions"); + actionItem.setColSpan(1); + actionItem.setRowSpan(4); + actionItem.setShowTitle(false); + actionItem.setCanvas(getActionLayout(form.extendLocatorId("actions"))); + StaticTextItem versionItem = new StaticTextItem("version", MSG.common_title_version()); versionItem.setValue(version.getVersion());
@@ -133,10 +150,47 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); descriptionItem.setValue(version.getDescription());
- form.setFields(versionItem, liveDeploymentsItem, filesItems, descriptionItem); + form.setFields(versionItem, actionItem, liveDeploymentsItem, filesItems, descriptionItem); return form; }
+ private Canvas getActionLayout(String locatorId) { + LocatableVLayout actionLayout = new LocatableVLayout(locatorId, 10); + IButton deleteButton = new LocatableIButton(extendLocatorId("Delete"), MSG.common_button_delete()); + deleteButton.setIcon("subsystems/bundle/BundleVersionAction_Delete_16.png"); + deleteButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + SC.ask(MSG.view_bundle_version_deleteConfirm(), new BooleanCallback() { + public void execute(Boolean aBoolean) { + if (aBoolean) { + bundleManager.deleteBundleVersion(version.getId(), false, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_version_deleteFailure(version.getVersion()), caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_version_deleteSuccessful(version.getVersion()), + Message.Severity.Info)); + // Bundle version is deleted, go back to main bundle view + CoreGUI.goToView(LinkManager.getBundleLink(version.getBundle().getId())); + } + }); + } + } + }); + } + }); + actionLayout.addMember(deleteButton); + + if (!canManageBundles) { + deleteButton.setDisabled(true); + } + + return actionLayout; + } + private TagEditorView createTagEditor() { boolean readOnly = !this.canManageBundles; TagEditorView tagEditor = new TagEditorView(extendLocatorId("Tags"), version.getTags(), readOnly, @@ -213,17 +267,16 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV criteria.fetchConfigurationDefinition(true); criteria.fetchTags(true);
- GWTServiceLookup.getBundleService().findBundleVersionsByCriteria(criteria, - new AsyncCallback<PageList<BundleVersion>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_bundle_version_loadFailure(), caught); - } + bundleManager.findBundleVersionsByCriteria(criteria, new AsyncCallback<PageList<BundleVersion>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_bundle_version_loadFailure(), caught); + }
- public void onSuccess(PageList<BundleVersion> result) { - BundleVersion version = result.get(0); - ViewId nextPath = viewPath.next().getCurrent(); - viewBundleVersion(version, nextPath); - } - }); + public void onSuccess(PageList<BundleVersion> result) { + BundleVersion version = result.get(0); + ViewId nextPath = viewPath.next().getCurrent(); + viewBundleVersion(version, nextPath); + } + }); } } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 0009db8..d98386e 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -908,6 +908,9 @@ view_bundle_fileListView_loadFailure = Failed to load bundle file data view_bundle_version_backToBundle = Back to Bundle view_bundle_version_bundleVersionTagUpdateFailure = Failed to update bundle version tags view_bundle_version_bundleVersionTagUpdateSuccessful = You have successfully updated the bundle version tags +view_bundle_version_deleteConfirm = Are you sure you want to delete this bundle version? +view_bundle_version_deleteFailure = Failed to delete the bundle version [{0}] +view_bundle_version_deleteSuccessful = You successfully deleted the bundle version [{0}] view_bundle_version_loadFailure = Failed to load bundle version view_bundle_tree_loadFailure = Failed to load bundle data view_bundle_revertWizard_title = Bundle Revert diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16.png new file mode 100644 index 0000000..f4d69d8 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16_Disabled.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16_Disabled.png new file mode 100644 index 0000000..c8b5750 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDeploymentAction_Delete_16_Disabled.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16.png new file mode 100644 index 0000000..7c528ef Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16_Disabled.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16_Disabled.png new file mode 100644 index 0000000..b76504b Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleDestinationAction_Delete_16_Disabled.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16.png new file mode 100644 index 0000000..3f5cce4 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16_Disabled.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16_Disabled.png new file mode 100644 index 0000000..049b3c1 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleVersionAction_Delete_16_Disabled.png differ
commit 504bd1c6af214f3bacd3a7c894a0f1926bcc9fdb Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 12:41:27 2010 -0500
add todo - need to remember this is where the selection fails if tree is not loaded
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java index 74c78ad..272841f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java @@ -64,9 +64,9 @@ public class BundleTreeView extends LocatableTreeGrid { }
public void selectPath(ViewPath viewPath) { - Tree theTree = getTree();
+ // TODO: how do we get the tree to load its nodes if they aren't loaded yet? if (viewPath.viewsLeft() > 0) { String key = ""; for (ViewId view : viewPath.getViewPath().subList(2, viewPath.getViewPath().size())) { @@ -89,7 +89,6 @@ public class BundleTreeView extends LocatableTreeGrid { final String finalKey = key; GWT.runAsync(new RunAsyncCallback() { public void onFailure(Throwable reason) { - }
public void onSuccess() {
commit 95b92ea3d6b6b8640761ca3081d63c3e50b8606e Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 12:34:07 2010 -0500
I'm always confused what these do. adding javadoc so I can remember in the future
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 81f9882..122f032 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 @@ -61,7 +61,21 @@ public class Message { };
public enum Option { - Transient, Sticky, BackgroundJobResult + /** + * The message will not be persisted in the message center list. + */ + Transient, + + /** + * The message will not auto-clear after a delay - it remains on the screen until you navigate away. + */ + Sticky, + + /** + * The message will be persisted in the message center list, + * but will not show up in the main screen message area. + */ + BackgroundJobResult };
public Message(String conciseMessage) {
commit 529f4c4431f6a315b8721e11d36a8185d00e6312 Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 11:22:53 2010 -0500
make sure the tree folders are open when selected. this only partially works. if the tree is not loaded yet, it won't load on its own
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 4bad6b9..dadace4 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 @@ -226,40 +226,45 @@ public class BundleTreeDataSource extends RPCDataSource { }
public ListGridRecord copyValuesForKnownBundle(Object from, Integer bundleId) { + String parentID; TreeNode node = new TreeNode(); if (from instanceof Bundle) { Bundle bundle = (Bundle) from; + node.setIsFolder(true); + node.setIcon("subsystems/bundle/Bundle_16.png"); node.setID(String.valueOf(bundle.getId())); node.setName(bundle.getName()); - node.setIcon("subsystems/bundle/Bundle_16.png");
} else if (from instanceof BundleVersion) { BundleVersion version = (BundleVersion) from; - node.setName(version.getVersion()); - node.setID(version.getBundle().getId() + "_versions_" + version.getId()); - node.setParentID(version.getBundle().getId() + "_versions"); node.setIsFolder(false); node.setIcon("subsystems/bundle/BundleVersion_16.png"); + parentID = version.getBundle().getId() + "_versions"; + node.setParentID(parentID); + node.setID(parentID + '_' + version.getId()); + node.setName(version.getVersion());
} else if (from instanceof BundleDeployment) { BundleDeployment deployment = (BundleDeployment) from; + node.setIsFolder(false); + node.setIcon("subsystems/bundle/BundleDeployment_16.png"); + parentID = bundleId + "_destinations_" + deployment.getDestination().getId(); + node.setParentID(parentID); + node.setID(bundleId + "_deployments_" + deployment.getId()); if (deployment.isLive()) { node.setName("<span style="color: green; font-weight: bold">(live)</span> " + deployment.getName()); } else { node.setName(deployment.getName()); } - node.setID(bundleId + "_deployments_" + deployment.getId()); - node.setParentID(bundleId + "_destinations_" + deployment.getDestination().getId()); - node.setIsFolder(false); - node.setIcon("subsystems/bundle/BundleDeployment_16.png");
} else if (from instanceof BundleDestination) { BundleDestination destination = (BundleDestination) from; - node.setName(destination.getName()); - node.setID(destination.getBundle().getId() + "_destinations_" + destination.getId()); - node.setParentID(destination.getBundle().getId() + "_destinations"); node.setIsFolder(true); node.setIcon("subsystems/bundle/BundleDestination_16.png"); + parentID = destination.getBundle().getId() + "_destinations"; + node.setParentID(parentID); + node.setID(parentID + '_' + destination.getId()); + node.setName(destination.getName()); }
return node; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java index 9f3a5be..74c78ad 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java @@ -26,6 +26,7 @@ import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.RunAsyncCallback; import com.google.gwt.user.client.History; import com.smartgwt.client.types.SelectionStyle; +import com.smartgwt.client.widgets.tree.Tree; import com.smartgwt.client.widgets.tree.TreeNode; import com.smartgwt.client.widgets.tree.events.NodeClickEvent; import com.smartgwt.client.widgets.tree.events.NodeClickHandler; @@ -55,7 +56,8 @@ public class BundleTreeView extends LocatableTreeGrid {
addNodeClickHandler(new NodeClickHandler() { public void onNodeClick(NodeClickEvent event) { - String path = event.getNode().getAttribute("id").replaceAll("_", "/"); + TreeNode node = event.getNode(); + String path = node.getAttribute("id").replaceAll("_", "/"); History.newItem("Bundles/Bundle/" + path); } }); @@ -63,6 +65,8 @@ public class BundleTreeView extends LocatableTreeGrid {
public void selectPath(ViewPath viewPath) {
+ Tree theTree = getTree(); + if (viewPath.viewsLeft() > 0) { String key = ""; for (ViewId view : viewPath.getViewPath().subList(2, viewPath.getViewPath().size())) { @@ -71,9 +75,14 @@ public class BundleTreeView extends LocatableTreeGrid {
key += view.getPath();
- TreeNode node = getTree().findById(key); + TreeNode node = theTree.findById(key); if (node != null) { - getTree().openFolder(node); + // make sure all its parents are open as well as itself + TreeNode parentNode = node; // prime the pump + while (parentNode != null) { + theTree.openFolder(parentNode); + parentNode = theTree.getParent(parentNode); + } } }
commit 3a351ac8dd9d8657b04ac024d379db4dec90af49 Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 10:13:00 2010 -0500
the separator for our custom keys is underscore, not colon
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java index 12b8e23..9f3a5be 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java @@ -67,7 +67,7 @@ public class BundleTreeView extends LocatableTreeGrid { String key = ""; for (ViewId view : viewPath.getViewPath().subList(2, viewPath.getViewPath().size())) { if (key.length() > 0) - key += ":"; + key += "_";
key += view.getPath();
commit 7f771252b7e95536c474bad025d458d0ed5bd438 Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 07:32:49 2010 -0500
add a third tree level - under destinations, you can now see all deployments made to that dest. if the deployment is live, you'll see a green, bold string "(live)" next to the name of the deployment
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 f90d8b3..e0bd7e9 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 @@ -312,7 +312,11 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } } else if (viewPath.getCurrent().getPath().equals("deployments")) { if (viewPath.isEnd()) { - // TODO: where to go? I don't think this is a valid url right now + // today we do not have an uber-view showing all deployments for a bundle. + // if we did, it would show all deployments to all destinations for all bundle versions. + // because that would be a very large list with a lot of stuff to show, it was deemed + // too complex to be useful for users. thus, we have no uber-deployments view. If we did, + // we would render it here. } else { // a specific deployment //removeMembers(getMembers()); 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 7dd1e65..4bad6b9 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 @@ -86,10 +86,11 @@ public class BundleTreeDataSource extends RPCDataSource { protected void executeFetch(final DSRequest request, final DSResponse response) {
String p = request.getCriteria().getAttribute("parentId"); - // load the bundles
if (p == null) {
+ // there is no parent - we are at the root of the tree + // get the top nodes (the bundles) BundleCriteria criteria = new BundleCriteria(); criteria.fetchDestinations(true); criteria.setPageControl(getPageControl(request)); @@ -107,7 +108,10 @@ public class BundleTreeDataSource extends RPCDataSource { processResponse(request.getRequestId(), response); } }); + } else { + + // we are at an inner node, being asked to get the children of it if (p.endsWith("_versions")) { int bundleId = Integer.parseInt(p.substring(0, p.indexOf("_"))); BundleVersionCriteria criteria = new BundleVersionCriteria(); @@ -125,6 +129,7 @@ public class BundleTreeDataSource extends RPCDataSource { processResponse(request.getRequestId(), response); } }); + } else if (p.endsWith("_deployments")) { int bundleId = Integer.parseInt(p.substring(0, p.indexOf("_"))); BundleDeploymentCriteria criteria = new BundleDeploymentCriteria(); @@ -141,10 +146,12 @@ public class BundleTreeDataSource extends RPCDataSource { processResponse(request.getRequestId(), response); } }); + } else if (p.endsWith("_destinations")) { - int bundleId = Integer.parseInt(p.substring(0, p.indexOf("_"))); + final int bundleId = Integer.parseInt(p.substring(0, p.indexOf("_"))); BundleDestinationCriteria criteria = new BundleDestinationCriteria(); criteria.addFilterBundleId(bundleId); + criteria.fetchDeployments(true); bundleService.findBundleDestinationsByCriteria(criteria, new AsyncCallback<PageList<BundleDestination>>() { public void onFailure(Throwable caught) { @@ -152,7 +159,7 @@ public class BundleTreeDataSource extends RPCDataSource { }
public void onSuccess(PageList<BundleDestination> result) { - response.setData(buildRecords(result)); + response.setData(buildRecordsForKnownBundle(result, bundleId)); processResponse(request.getRequestId(), response); } }); @@ -162,22 +169,31 @@ public class BundleTreeDataSource extends RPCDataSource {
@Override public Object copyValues(Record from) { - return null; // TODO: Implement this method. + return null; // don't need this method. }
@Override public ListGridRecord[] buildRecords(Collection dataObjects) { + return buildRecordsForKnownBundle(dataObjects, null); + } + + public ListGridRecord[] buildRecordsForKnownBundle(Collection dataObjects, Integer bundleId) { if (dataObjects == null) { return null; }
- List<ListGridRecord> records = new ArrayList<ListGridRecord>(); + final List<ListGridRecord> records = new ArrayList<ListGridRecord>();
for (Object item : dataObjects) { + + // the resultant item is a direct node to build records.add(copyValues(item)); + + // now build the children of the node if (item instanceof Bundle) { Bundle bundle = (Bundle) item;
+ // each bundle has two direct children - the versions and destinations folders TreeNode versionNode = new TreeNode(MSG.view_bundle_versions()); versionNode.setID(bundle.getId() + "_versions"); versionNode.setParentID(String.valueOf(bundle.getId())); @@ -190,6 +206,15 @@ public class BundleTreeDataSource extends RPCDataSource { deploymentsNode.setParentID(String.valueOf(bundle.getId())); deploymentsNode.setName(MSG.view_bundle_destinations()); records.add(deploymentsNode); + } else if (item instanceof BundleDestination) { + BundleDestination dest = (BundleDestination) item; + + // each destination has 0, 1 or more deployments + if (dest.getDeployments() != null) { + for (BundleDeployment deploy : dest.getDeployments()) { + records.add(copyValuesForKnownBundle(deploy, bundleId)); + } + } } } return records.toArray(new ListGridRecord[records.size()]); @@ -197,6 +222,10 @@ public class BundleTreeDataSource extends RPCDataSource {
@Override public ListGridRecord copyValues(Object from) { + return copyValuesForKnownBundle(from, null); + } + + public ListGridRecord copyValuesForKnownBundle(Object from, Integer bundleId) { TreeNode node = new TreeNode(); if (from instanceof Bundle) { Bundle bundle = (Bundle) from; @@ -214,19 +243,25 @@ public class BundleTreeDataSource extends RPCDataSource {
} else if (from instanceof BundleDeployment) { BundleDeployment deployment = (BundleDeployment) from; - node.setName(deployment.getName() + " (" + deployment.getBundleVersion().getVersion() + ")"); - node.setID(deployment.getBundleVersion().getBundle().getId() + "_deployments_" + deployment.getId()); - node.setParentID(deployment.getBundleVersion().getBundle().getId() + "_deployments"); + if (deployment.isLive()) { + node.setName("<span style="color: green; font-weight: bold">(live)</span> " + deployment.getName()); + } else { + node.setName(deployment.getName()); + } + node.setID(bundleId + "_deployments_" + deployment.getId()); + node.setParentID(bundleId + "_destinations_" + deployment.getDestination().getId()); node.setIsFolder(false); node.setIcon("subsystems/bundle/BundleDeployment_16.png"); + } else if (from instanceof BundleDestination) { BundleDestination destination = (BundleDestination) from; node.setName(destination.getName()); node.setID(destination.getBundle().getId() + "_destinations_" + destination.getId()); node.setParentID(destination.getBundle().getId() + "_destinations"); - node.setIsFolder(false); + node.setIsFolder(true); node.setIcon("subsystems/bundle/BundleDestination_16.png"); } + return node; } }
commit f97b16484480fee641d73e80e1b9b9b711651cb4 Author: John Mazzitelli mazz@redhat.com Date: Sat Dec 18 06:15:58 2010 -0500
add description, rearrange buttons and description field to be consistent across pages.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index 548037b..2d40a23 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -42,6 +42,7 @@ import org.rhq.core.domain.tagging.Tag; 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.bundle.deploy.BundleDeployWizard; @@ -118,13 +119,13 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka
LinkItem bundleName = new LinkItem("bundle"); bundleName.setTitle(MSG.view_bundle_bundle()); - bundleName.setValue("#Bundles/Bundle/" + bundle.getId()); + bundleName.setValue(LinkManager.getBundleLink(bundle.getId())); bundleName.setLinkTitle(bundle.getName()); bundleName.setTarget("_self");
CanvasItem actionItem = new CanvasItem("actions"); actionItem.setColSpan(1); - actionItem.setRowSpan(4); + actionItem.setRowSpan(5); actionItem.setShowTitle(false); actionItem.setCanvas(getActionLayout(form.extendLocatorId("actions")));
@@ -133,14 +134,17 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka
LinkItem destinationGroup = new LinkItem("group"); destinationGroup.setTitle(MSG.view_bundle_dest_group()); - destinationGroup.setValue("#ResourceGroup/" + destination.getGroup().getId()); + destinationGroup.setValue(LinkManager.getResourceGroupLink(destination.getGroup().getId())); destinationGroup.setLinkTitle(destination.getGroup().getName()); destinationGroup.setTarget("_self");
StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_dest_deployDir()); path.setValue(destination.getDeployDir());
- form.setFields(bundleName, actionItem, created, destinationGroup, path); + StaticTextItem description = new StaticTextItem("description", MSG.common_title_description()); + description.setValue(destination.getDescription()); + + form.setFields(bundleName, actionItem, created, destinationGroup, path, description); return form; }
@@ -176,9 +180,6 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka new BundleDeployWizard(destination).startWizard(); } }); - if (!canManageBundles) { - deployButton.setDisabled(true); - } actionLayout.addMember(deployButton);
IButton revertButton = new LocatableIButton(actionLayout.extendLocatorId("Revert"), MSG.view_bundle_revert()); @@ -188,10 +189,13 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka new BundleRevertWizard(destination).startWizard(); } }); + actionLayout.addMember(revertButton); + if (!canManageBundles) { + deployButton.setDisabled(true); revertButton.setDisabled(true); } - actionLayout.addMember(revertButton); + return actionLayout; }
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 1c9dc47..f90d8b3 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 @@ -27,6 +27,7 @@ import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.util.BooleanCallback; import com.smartgwt.client.util.SC; +import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; @@ -173,8 +174,11 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { form.setGroupTitle(MSG.common_title_summary()); form.setPadding(5);
- StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); - descriptionItem.setValue(bundle.getDescription()); + CanvasItem actionItem = new CanvasItem("actions"); + actionItem.setColSpan(1); + actionItem.setRowSpan(3); + actionItem.setShowTitle(false); + actionItem.setCanvas(getActionCanvas());
StaticTextItem versionCountItem = new StaticTextItem("versionCount", MSG.view_bundle_list_versionsCount()); versionCountItem.setValue(bundle.getBundleVersions() != null ? bundle.getBundleVersions().size() : 0); @@ -183,40 +187,17 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { .view_bundle_list_destinationsCount()); destinationsCountItem.setValue(bundle.getDestinations() != null ? bundle.getDestinations().size() : 0);
- form.setFields(descriptionItem, getActionItem(), versionCountItem, destinationsCountItem); + StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); + descriptionItem.setValue(bundle.getDescription()); + + form.setFields(versionCountItem, actionItem, destinationsCountItem, descriptionItem);
return form; }
- private CanvasItem getActionItem() { + private Canvas getActionCanvas() { VLayout layout = new LocatableVLayout(form.extendLocatorId("Actions"), 10);
- IButton deleteButton = new LocatableIButton(form.extendLocatorId("Delete"), MSG.common_button_delete()); - deleteButton.setIcon("subsystems/bundle/BundleAction_Delete_16.png"); - deleteButton.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - SC.ask(MSG.view_bundle_list_deleteConfirm(), new BooleanCallback() { - public void execute(Boolean aBoolean) { - if (aBoolean) { - bundleManager.deleteBundle(bundleBeingViewed, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_list_deleteFailure(bundle.getName()), caught); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_list_deleteSuccessful(bundle.getName()), - Message.Severity.Info)); - History.newItem("Bundles"); // Bundle is deleted, go back to all bundles view - } - }); - } - } - }); - } - }); - IButton deployButton = new LocatableIButton(form.extendLocatorId("Deploy"), MSG.view_bundle_deploy()); deployButton.setIcon("subsystems/bundle/BundleAction_Deploy_16.png"); deployButton.addClickHandler(new ClickHandler() { @@ -244,21 +225,41 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { }); } }); + layout.addMember(deployButton); + + IButton deleteButton = new LocatableIButton(form.extendLocatorId("Delete"), MSG.common_button_delete()); + deleteButton.setIcon("subsystems/bundle/BundleAction_Delete_16.png"); + deleteButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + SC.ask(MSG.view_bundle_list_deleteConfirm(), new BooleanCallback() { + public void execute(Boolean aBoolean) { + if (aBoolean) { + bundleManager.deleteBundle(bundleBeingViewed, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_list_deleteFailure(bundle.getName()), caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_list_deleteSuccessful(bundle.getName()), + Message.Severity.Info)); + History.newItem("Bundles"); // Bundle is deleted, go back to all bundles view + } + }); + } + } + }); + } + }); + layout.addMember(deleteButton);
if (!canManageBundles) { - deleteButton.setDisabled(true); deployButton.setDisabled(true); + deleteButton.setDisabled(true); }
- layout.addMember(deleteButton); - layout.addMember(deployButton); - - CanvasItem actionItem = new CanvasItem("actions"); - actionItem.setColSpan(1); - actionItem.setRowSpan(3); - actionItem.setShowTitle(false); - actionItem.setCanvas(layout); - return actionItem; + return layout; }
public void renderView(final ViewPath viewPath) { @@ -311,8 +312,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } } else if (viewPath.getCurrent().getPath().equals("deployments")) { if (viewPath.isEnd()) { - // TODO: go to deployments tab for the bundle - // deployments list screen + // TODO: where to go? I don't think this is a valid url right now } else { // a specific deployment //removeMembers(getMembers()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java index 2985f06..284ef3c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java @@ -124,16 +124,16 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV StaticTextItem versionItem = new StaticTextItem("version", MSG.common_title_version()); versionItem.setValue(version.getVersion());
- StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); - descriptionItem.setValue(version.getDescription()); - StaticTextItem liveDeploymentsItem = new StaticTextItem("deployments", MSG.view_bundle_deployments()); liveDeploymentsItem.setValue(version.getBundleDeployments().size());
StaticTextItem filesItems = new StaticTextItem("files", MSG.view_bundle_files()); filesItems.setValue(version.getBundleFiles().size());
- form.setFields(versionItem, descriptionItem, liveDeploymentsItem, filesItems); + StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); + descriptionItem.setValue(version.getDescription()); + + form.setFields(versionItem, liveDeploymentsItem, filesItems, descriptionItem); return form; }
commit 930cd482ebf00702f399b8faa10b504b5ce4a35a Author: Ian Springer ian.springer@redhat.com Date: Fri Dec 17 18:08:58 2010 -0500
start of details view for Resource operation schedules (view and new modes)
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 e30a6bb..199ca19 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 @@ -74,8 +74,12 @@ public class EnhancedDynamicForm extends LocatableDynamicForm { setWrapItemTitles(false);
// Other Display Settings - setHiliteRequiredFields(true); - setRequiredTitleSuffix(" <span class='requiredFieldMarker'>*</span> :"); + if (readOnly) { + setHiliteRequiredFields(false); + } else { + setHiliteRequiredFields(true); + setRequiredTitleSuffix(" <span class='requiredFieldMarker'>*</span> :"); + }
// DataSource Settings setUseAllDataSourceFields(false); @@ -106,6 +110,7 @@ public class EnhancedDynamicForm extends LocatableDynamicForm { StaticTextItem staticItem = new StaticTextItem(item.getName(), item.getTitle()); staticItem.setTooltip(item.getTooltip()); staticItem.setValue(item.getValue()); + staticItem.setColSpan(item.getAttribute("colSpan")); // TODO: Any other fields we should copy? icons?
if (item instanceof BooleanItem) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java index 06e68e5..1e0d4a8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java @@ -19,7 +19,9 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule;
+import java.util.LinkedHashMap; import java.util.List; +import java.util.Set;
import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.Record; @@ -30,7 +32,9 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.JobTrigger; import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.bean.OperationSchedule; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.OperationGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; @@ -38,7 +42,7 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; /** * @author Ian Springer */ -public abstract class OperationScheduleDataSource<T extends OperationSchedule> extends RPCDataSource<T> { +public abstract class OperationScheduleDataSource<T extends OperationSchedule> extends RPCDataSource<T> {
public static abstract class Field { public static final String ID = "id"; @@ -54,8 +58,11 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e
protected OperationGWTServiceAsync operationService = GWTServiceLookup.getOperationService();
- public OperationScheduleDataSource() { + private ResourceType resourceType; + + public OperationScheduleDataSource(ResourceType resourceType) { super(); + this.resourceType = resourceType; List<DataSourceField> fields = addDataSourceFields(); addFields(fields); } @@ -70,13 +77,24 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e idField.setCanEdit(false); fields.add(idField);
+ DataSourceTextField operationNameField = createTextField(Field.OPERATION_NAME, "Operation", null, 100, true); + fields.add(operationNameField); + DataSourceTextField operationDisplayNameField = createTextField(Field.OPERATION_DISPLAY_NAME, "Operation", null, 100, true); fields.add(operationDisplayNameField);
+ Set<OperationDefinition> operationDefinitions = this.resourceType.getOperationDefinitions(); + LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>(); + for (OperationDefinition operationDefinition : operationDefinitions) { + valueMap.put(operationDefinition.getName(), operationDefinition.getDisplayName()); + } + operationNameField.setValueMap(valueMap); + DataSourceTextField subjectField = createTextField(Field.SUBJECT, "Owner", null, 100, true); + subjectField.setCanEdit(false); fields.add(subjectField);
- DataSourceTextField descriptionField = createTextField(Field.DESCRIPTION, "Description", null, 100, true); + DataSourceTextField descriptionField = createTextField(Field.DESCRIPTION, "Notes", null, 100, false); fields.add(descriptionField);
DataSourceTextField jobTriggerField = createTextField(Field.JOB_TRIGGER, "Schedule", null, 100, true); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java index d658acc..d615316 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java @@ -58,7 +58,7 @@ public abstract class OperationScheduleListView extends TableSection<OperationSc }
public void executeAction(ListGridRecord[] selection, Object actionValue) { - // TODO: wizard or details view + newDetails(); } });
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java new file mode 100644 index 0000000..12df23e --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/ResourceOperationScheduleDetailsView.java @@ -0,0 +1,72 @@ +/* + * 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.inventory.common.detail.operation.schedule; + +import java.util.ArrayList; +import java.util.List; + +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.TextAreaItem; + +import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.enterprise.gui.coregui.client.ViewPath; +import org.rhq.enterprise.gui.coregui.client.components.form.AbstractRecordEditor; +import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleDataSource; + +/** + * @author Ian Springer + */ +public class ResourceOperationScheduleDetailsView extends AbstractRecordEditor { + + public ResourceOperationScheduleDetailsView(String locatorId, ResourceComposite resourceComposite, int scheduleId) { + super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite), scheduleId, "Scheduled Operation", null); + } + + @Override + public void renderView(ViewPath viewPath) { + super.renderView(viewPath); + + // Existing schedules are not editable. This may change in the future. + boolean isReadOnly = (getRecordId() != 0); + init(isReadOnly); + } + + @Override + protected List<FormItem> createFormItems(EnhancedDynamicForm form) { + List<FormItem> items = new ArrayList<FormItem>(); + + SelectItem operationNameItem = new SelectItem(ResourceOperationScheduleDataSource.Field.OPERATION_NAME); + items.add(operationNameItem); + + TextAreaItem descriptionItem = new TextAreaItem(ResourceOperationScheduleDataSource.Field.DESCRIPTION); + descriptionItem.setColSpan(form.getNumCols()); + items.add(descriptionItem); + + return items; + } + + @Override + protected String getTitleFieldName() { + return ResourceOperationScheduleDataSource.Field.OPERATION_DISPLAY_NAME; + } + +} 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 9cbf3e2..ffc4ca5 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 @@ -347,8 +347,8 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.operationsTab, this.operationsHistory, new ResourceOperationHistoryListView(operationsTab .extendLocatorId("HistoryView"), this.resourceComposite), true, true);
- updateSubTab(this.operationsTab, this.operationsSchedule,new ResourceOperationScheduleListView(operationsTab.extendLocatorId("SchedulesView"), this.resourceComposite), - true, true); + updateSubTab(this.operationsTab, this.operationsSchedule,new ResourceOperationScheduleListView( + operationsTab.extendLocatorId("SchedulesView"), this.resourceComposite), true, true); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java index e044f51..6e9c744 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java @@ -28,6 +28,7 @@ import com.smartgwt.client.data.Record;
import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationScheduleDataSource;
/** @@ -37,10 +38,11 @@ import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.s */ public class ResourceOperationScheduleDataSource extends OperationScheduleDataSource<ResourceOperationSchedule> {
- private int resourceId; + private ResourceComposite resourceComposite;
- public ResourceOperationScheduleDataSource(int resourceId) { - this.resourceId = resourceId; + public ResourceOperationScheduleDataSource(ResourceComposite resourceComposite) { + super(resourceComposite.getResource().getResourceType()); + this.resourceComposite = resourceComposite; }
@Override @@ -50,7 +52,7 @@ public class ResourceOperationScheduleDataSource extends OperationScheduleDataSo
@Override protected void executeFetch(final DSRequest request, final DSResponse response) { - operationService.findScheduledResourceOperations(this.resourceId, + operationService.findScheduledResourceOperations(this.resourceComposite.getResource().getId(), new AsyncCallback<List<ResourceOperationSchedule>>() { public void onSuccess(List<ResourceOperationSchedule> result) { Record[] records = buildRecords(result); @@ -59,8 +61,8 @@ public class ResourceOperationScheduleDataSource extends OperationScheduleDataSo }
public void onFailure(Throwable caught) { - throw new RuntimeException("Failed to find scheduled operations for Resource with id [" - + resourceId + "].", caught); + throw new RuntimeException("Failed to find scheduled operations for " + + resourceComposite.getResource() + ".", caught); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java index 03de2a6..14bb294 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java @@ -22,8 +22,8 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operatio import com.smartgwt.client.widgets.Canvas;
import org.rhq.core.domain.resource.composite.ResourceComposite; -import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationScheduleDataSource; import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationScheduleListView; +import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.ResourceOperationScheduleDetailsView;
/** * @author Ian Springer @@ -35,7 +35,7 @@ public class ResourceOperationScheduleListView extends OperationScheduleListView private ResourceComposite resourceComposite;
public ResourceOperationScheduleListView(String locatorId, ResourceComposite resourceComposite) { - super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite.getResource().getId()), TITLE); + super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite), TITLE); this.resourceComposite = resourceComposite; }
@@ -45,8 +45,9 @@ public class ResourceOperationScheduleListView extends OperationScheduleListView }
@Override - public Canvas getDetailsView(int id) { - return new Canvas(); // TODO + public Canvas getDetailsView(int scheduleId) { + return new ResourceOperationScheduleDetailsView(extendLocatorId("DetailsView"), + this.resourceComposite, scheduleId); }
}
commit 28b070f78cac12c2c2f58194361133d3cc0b2e2d Author: Ian Springer ian.springer@redhat.com Date: Fri Dec 17 15:52:12 2010 -0500
add ID field to RHQ_OPERATION_SCHEDULE and make it the primary key
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index c6bdebd..2d8d1fc 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.101</db.schema.version> + <db.schema.version>2.102</db.schema.version> </properties>
<dependencies> diff --git a/modules/core/dbutils/src/main/java/org/rhq/core/db/upgrade/OperationScheduleIdSetterUpgradeTask.java b/modules/core/dbutils/src/main/java/org/rhq/core/db/upgrade/OperationScheduleIdSetterUpgradeTask.java new file mode 100644 index 0000000..58692c9 --- /dev/null +++ b/modules/core/dbutils/src/main/java/org/rhq/core/db/upgrade/OperationScheduleIdSetterUpgradeTask.java @@ -0,0 +1,60 @@ +/* + * 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.db.upgrade; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.rhq.core.db.DatabaseType; + +/** + * Sets values on the id column for all rows in RHQ_OPERATION_SCHEDULE. The id's are set, starting at 10001, in the + * order that the rows were created. This is done by parsing the value of the JOB_NAME column, which includes the + * creation time. + * + * @author Ian Springer + */ +public class OperationScheduleIdSetterUpgradeTask implements DatabaseUpgradeTask { + + @Override + public void execute(DatabaseType databaseType, Connection connection) throws SQLException { + String selectSQL = "SELECT job_name FROM rhq_operation_schedule;"; + System.out.println("Executing: " + selectSQL); + List<Object[]> results = databaseType.executeSelectSql(connection, selectSQL); + Map<Long, String> sortedJobNames = new TreeMap<Long, String>(); + for (Object[] result : results) { + String jobName = (String)result[0]; // e.g.: rhq-resource-10001--121207376-1292542028679 + // last portion is the job's creation time, e.g.: 1292542028679 + Long ctime = Long.valueOf(jobName.substring(jobName.lastIndexOf('-') + 1)); + sortedJobNames.put(ctime, jobName); + } + int id = 10001; + for (String jobName : sortedJobNames.values()) { + String updateSQL = "UPDATE rhq_operation_schedule SET id = " + (id++) + " WHERE job_name = '" + jobName + + "';"; + System.out.println("Executing: " + updateSQL); + databaseType.executeSql(connection, updateSQL); + } + } + +} diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/operation-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/operation-schema.xml index 2e34094..68b3274 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/operation-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/operation-schema.xml @@ -71,6 +71,8 @@ code special conditions into the session bean, we'll allow a short-lived NULL next fire time row. --> <table name="RHQ_OPERATION_SCHEDULE"> + <column name="ID" type="INTEGER" required="true" default="sequence-only" initial="10001" primarykey="true"/> + <column name="JOB_NAME" type="VARCHAR2" required="true" size="100"/> <column name="JOB_GROUP" type="VARCHAR2" required="true" size="100"/> <column name="DTYPE" type="VARCHAR2" required="true" size="8"/> @@ -83,16 +85,15 @@ <column name="GROUP_ID" type="INTEGER" required="false" references="RHQ_RESOURCE_GROUP"/>
<!-- - Note that this is the same primary key that Quartz uses for its schedules (RHQ_qrtz_job_details). - We do not need to add DTYPE to the key, because we ensure the name/group are unique - across resource/group schedules + Note, this is the same as the primary key that Quartz uses for its schedules (RHQ_QRTZ_JOB_DETAILS). + We do not need to add DTYPE to the key, because we ensure the name/group are unique across resource/group + schedules --> - <constraint name="RHQ_OPERATION_SCHEDULE_KEY"> - <primaryKey> - <field ref="JOB_NAME"/> - <field ref="JOB_GROUP"/> - </primaryKey> - </constraint> + <!-- === business key (JOB_NAME + JOB_GROUP) === --> + <index name="RHQ_OPERATION_SCHEDULE_KEY_IDX" unique="true"> + <field ref="JOB_NAME"/> + <field ref="JOB_GROUP"/> + </index> </table>
</dbsetup> diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index d9f63c0..975c778 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3277,6 +3277,25 @@ </schema-directSQL> <schema-alterColumn table="RHQ_RESOURCE_TYPE" column="DELETED" nullable="FALSE" /> </schemaSpec> + + <schemaSpec version="2.102"> + <!-- Create the ID column nullable. --> + <schema-addColumn table="RHQ_OPERATION_SCHEDULE" column="ID" columnType="INTEGER" /> + <!-- Set values for ID column on all existing rows. --> + <schema-javaTask className="OperationScheduleIdSetterUpgradeTask" /> + <!-- Now that all existing rows have IDs, switch the column to non-nullable. --> + <schema-alterColumn table="RHQ_OPERATION_SCHEDULE" column="ID" nullable="FALSE" /> + <!-- Finally, make ID the primary key, rather than (JOB_NAME, JOB_GROUP), and make + (JOB_NAME, JOB_GROUP) a unique index instead. --> + <schema-directSQL> + <statement desc="Changing primary key of RHQ_OPERATION_SCHEDULE to ID..."> + ALTER TABLE RHQ_OPERATION_SCHEDULE DROP CONSTRAINT RHQ_OPERATION_SCHEDULE_KEY; + ALTER TABLE RHQ_OPERATION_SCHEDULE ADD PRIMARY KEY (ID); + CREATE UNIQUE INDEX RHQ_OPERATION_SCHEDULE_KEY_IDX ON RHQ_OPERATION_SCHEDULE (JOB_NAME, JOB_GROUP); + </statement> + </schema-directSQL> + </schemaSpec> + </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/GroupOperationScheduleEntity.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/GroupOperationScheduleEntity.java index 39f85d2..3f545bd 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/GroupOperationScheduleEntity.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/GroupOperationScheduleEntity.java @@ -36,6 +36,7 @@ import org.rhq.core.domain.resource.group.ResourceGroup; @NamedQueries( { @NamedQuery(name = GroupOperationScheduleEntity.QUERY_FIND_BY_GROUP_ID, query = "SELECT s " + " FROM GroupOperationScheduleEntity s " + " WHERE s.group.id = :groupId ") }) public class GroupOperationScheduleEntity extends OperationScheduleEntity { + public static final String QUERY_FIND_BY_GROUP_ID = "GroupOperationScheduleEntity.findByGroupId";
private static final long serialVersionUID = 1L; @@ -68,4 +69,5 @@ public class GroupOperationScheduleEntity extends OperationScheduleEntity { str.append("]"); return str.toString(); } + } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationScheduleEntity.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationScheduleEntity.java index 7da39d1..6eea462 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationScheduleEntity.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationScheduleEntity.java @@ -28,12 +28,14 @@ import java.util.Date; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.IdClass; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; +import javax.persistence.SequenceGenerator; import javax.persistence.Table;
/** @@ -45,10 +47,8 @@ import javax.persistence.Table; * * @author John Mazzitelli */ - @DiscriminatorColumn(name = "DTYPE") @Entity -@IdClass(ScheduleJobId.class) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @NamedQueries( { @NamedQuery(name = OperationScheduleEntity.QUERY_FIND_BY_JOB_ID, query = "" // @@ -58,6 +58,7 @@ import javax.persistence.Table; + " AND s.jobGroup = :jobGroup "), @NamedQuery(name = OperationScheduleEntity.QUERY_GET_SCHEDULE_RESOURCE_ADMIN, query = "" // + "SELECT DISTINCT new org.rhq.core.domain.operation.composite.ResourceOperationScheduleComposite( " + + " ro.id, " // + " ro.jobName, " // + " ro.jobGroup, " // + " '', " // @@ -69,6 +70,7 @@ import javax.persistence.Table; + " WHERE ro.nextFireTime IS NOT NULL "), // @NamedQuery(name = OperationScheduleEntity.QUERY_GET_SCHEDULE_RESOURCE, query = "" // + "SELECT DISTINCT new org.rhq.core.domain.operation.composite.ResourceOperationScheduleComposite( " + + " ro.id, " // + " ro.jobName, " // + " ro.jobGroup, " // + " '', " // @@ -84,6 +86,7 @@ import javax.persistence.Table; + " AND s = :subject "), // @NamedQuery(name = OperationScheduleEntity.QUERY_GET_SCHEDULE_GROUP_ADMIN, query = "" // + "SELECT DISTINCT new org.rhq.core.domain.operation.composite.GroupOperationScheduleComposite( " + + " go.id, " // + " go.jobName, " // + " go.jobGroup, " // + " '', " // @@ -95,6 +98,7 @@ import javax.persistence.Table; + " WHERE go.nextFireTime IS NOT NULL "), // @NamedQuery(name = OperationScheduleEntity.QUERY_GET_SCHEDULE_GROUP, query = "" // + "SELECT DISTINCT new org.rhq.core.domain.operation.composite.GroupOperationScheduleComposite( " + + " go.id, " // + " go.jobName, " // + " go.jobGroup, " // + " '', " // @@ -108,8 +112,10 @@ import javax.persistence.Table; + " JOIN r.subjects s " // + " WHERE go.nextFireTime IS NOT NULL " // + " AND s = :subject ") }) +@SequenceGenerator(name = "id", sequenceName = "RHQ_OPERATION_SCHEDULE_ID_SEQ") @Table(name = "RHQ_OPERATION_SCHEDULE") public abstract class OperationScheduleEntity implements Serializable { + public static final String QUERY_FIND_BY_JOB_ID = "OperationScheduleEntity.findByJobId"; public static final String QUERY_GET_SCHEDULE_RESOURCE = "OperationScheduleEntity.getScheduleResource"; public static final String QUERY_GET_SCHEDULE_RESOURCE_ADMIN = "OperationScheduleEntity.getScheduleResource_admin"; @@ -118,10 +124,15 @@ public abstract class OperationScheduleEntity implements Serializable {
private static final long serialVersionUID = 1L;
+ @Column(name = "ID", nullable = false) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "id") @Id + private int id; + + @Column(name = "JOB_NAME", nullable = false) private String jobName;
- @Id + @Column(name = "JOB_GROUP", nullable = false) private String jobGroup;
@Column(name = "NEXT_FIRE_TIME", nullable = true) @@ -136,6 +147,10 @@ public abstract class OperationScheduleEntity implements Serializable { this.nextFireTime = (nextFireTime == null) ? null : nextFireTime.getTime(); }
+ public int getId() { + return id; + } + /** * The single job ID which identifies this specific schedule. It can later be parsed via * {@link ScheduleJobId#ScheduleJobId(String)}. @@ -184,9 +199,10 @@ public abstract class OperationScheduleEntity implements Serializable { @Override public String toString() { StringBuilder buf = new StringBuilder(); - buf.append("job-name=[" + jobName); - buf.append("], job-group=[" + jobGroup); - buf.append("], next-fire-time=[" + ((nextFireTime == null) ? "never" : new Date(nextFireTime))); + buf.append("id=" + id); + buf.append(", jobName=" + jobName); + buf.append(", jobGroup=" + jobGroup); + buf.append(", nextFireTime=" + ((nextFireTime == null) ? "never" : new Date(nextFireTime)));
return buf.toString(); } @@ -210,4 +226,5 @@ public abstract class OperationScheduleEntity implements Serializable {
return this.getJobId().equals(other.getJobId()); } + } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationScheduleEntity.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationScheduleEntity.java index b7be10a..46dc63e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationScheduleEntity.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationScheduleEntity.java @@ -34,11 +34,10 @@ import javax.persistence.NamedQuery; import org.rhq.core.domain.resource.Resource;
/** - * Information on a specific operation schedule on a particular resource. + * Information on a specific operation schedule on a particular Resource. * * @author John Mazzitelli */ - @DiscriminatorValue("resource") @Entity @NamedQueries( { @@ -47,6 +46,7 @@ import org.rhq.core.domain.resource.Resource; @NamedQuery(name = ResourceOperationScheduleEntity.QUERY_DELETE_BY_RESOURCES, query = "DELETE FROM ResourceOperationScheduleEntity s " + " WHERE s.resource.id IN ( :resourceIds ) )") }) public class ResourceOperationScheduleEntity extends OperationScheduleEntity { + public static final String QUERY_DELETE_BY_RESOURCES = "ResourceOperationScheduleEntity.QUERY_DELETE_BY_RESOURCES"; public static final String QUERY_FIND_BY_RESOURCE_ID = "ResourceOperationScheduleEntity.findByResourceId";
@@ -80,4 +80,5 @@ public class ResourceOperationScheduleEntity extends OperationScheduleEntity { str.append("]"); return str.toString(); } + } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ScheduleJobId.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ScheduleJobId.java index 0d29a76..bc6641b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ScheduleJobId.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ScheduleJobId.java @@ -23,8 +23,10 @@ package org.rhq.core.domain.operation;
/** - * This class is a mutable version of {@link JobId} and is used as the primary key to the - * {@link OperationScheduleEntity} entities. + * This class is a mutable version of {@link JobId}, which represents the unique identifier of the Quartz job + * for a scheduled RHQ operation. + * + * NOTE: It is no longer used as the primary key to the {@link OperationScheduleEntity} entities. * * @author John Mazzitelli */ diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java index c638b31..70f6a36 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java @@ -41,6 +41,7 @@ import org.rhq.core.domain.operation.JobId; public abstract class OperationSchedule implements Serializable { private static final long serialVersionUID = 1L;
+ private int id; private String jobName; private String jobGroup; private String operationName; @@ -53,6 +54,14 @@ public abstract class OperationSchedule implements Serializable { public OperationSchedule() { }
+ public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + public String getJobGroup() { return jobGroup; } 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 b5fba55..1107b06 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 @@ -22,8 +22,6 @@ */ package org.rhq.core.domain.operation.composite;
-import org.rhq.core.domain.operation.ScheduleJobId; - /** * Provides some information on a compatible group's scheduled operation. * @@ -31,15 +29,15 @@ import org.rhq.core.domain.operation.ScheduleJobId; */ public class GroupOperationScheduleComposite extends OperationScheduleComposite {
- private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2L;
private final int groupId; private final String groupName; private final String groupResourceTypeName;
- public GroupOperationScheduleComposite(String jobName, String jobGroup, String operationName, + public GroupOperationScheduleComposite(int id, String jobName, String jobGroup, String operationName, long operationNextFireTime, int groupId, String groupName, String groupResourceTypeName) { - super(new ScheduleJobId(jobName, jobGroup), operationName, operationNextFireTime); + super(id, jobName, jobGroup, operationName, operationNextFireTime); this.groupId = groupId; this.groupName = groupName; this.groupResourceTypeName = groupResourceTypeName; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/OperationScheduleComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/OperationScheduleComposite.java index dc99113..f80811a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/OperationScheduleComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/composite/OperationScheduleComposite.java @@ -25,31 +25,37 @@ package org.rhq.core.domain.operation.composite; import java.io.Serializable; import java.util.Date;
-import org.rhq.core.domain.operation.ScheduleJobId; +import org.rhq.core.domain.operation.JobId;
public abstract class OperationScheduleComposite implements Serializable {
- private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2L;
- private ScheduleJobId operationJobId; + private int id; + private JobId jobId; private String operationName; private long operationNextFireTime;
//no args constructor for serialization purposes not to be used. protected OperationScheduleComposite() { this.operationNextFireTime = -1; - this.operationJobId = null; + this.id = 0; this.operationName = "(uninitialized)"; }
- public OperationScheduleComposite(ScheduleJobId operationJobId, String operationName, long operationNextFireTime) { - this.operationJobId = operationJobId; + public OperationScheduleComposite(int id, String jobName, String jobGroup, String operationName, long operationNextFireTime) { + this.id = id; + this.jobId = new JobId(jobName, jobGroup); this.operationName = operationName; this.operationNextFireTime = operationNextFireTime; }
- public ScheduleJobId getOperationJobId() { - return operationJobId; + public int getId() { + return id; + } + + public JobId getJobId() { + return jobId; }
public String getOperationName() { @@ -72,7 +78,7 @@ public abstract class OperationScheduleComposite implements Serializable { @Override public String toString() { StringBuilder str = new StringBuilder(); - str.append("operation-job-id=[" + operationJobId); + str.append("operation-job-id=[" + id); str.append("], operation-name=[" + operationName); str.append("], operation-next-fire-time=[" + new Date(operationNextFireTime)); str.append("]"); 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 a0996a7..7ddd0d1 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 @@ -22,11 +22,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 static final long serialVersionUID = 2L;
private int resourceId; private String resourceName; @@ -40,9 +38,9 @@ public class ResourceOperationScheduleComposite extends OperationScheduleComposi this.resourceId = 0; }
- public ResourceOperationScheduleComposite(String jobName, String jobGroup, String operationName, + public ResourceOperationScheduleComposite(int id, String jobName, String jobGroup, String operationName, long operationNextFireTime, int resourceId, String resourceName, String resourceTypeName) { - super(new ScheduleJobId(jobName, jobGroup), operationName, operationNextFireTime); + super(id, jobName, jobGroup, operationName, operationNextFireTime); this.resourceId = resourceId; this.resourceName = resourceName; this.resourceTypeName = resourceTypeName; diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/operation/test/JobIdTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/operation/test/JobIdTest.java index 48ff284..8cb8ca7 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/operation/test/JobIdTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/operation/test/JobIdTest.java @@ -22,13 +22,17 @@ */ package org.rhq.core.domain.operation.test;
+import org.rhq.core.domain.operation.ScheduleJobId; import org.testng.annotations.Test; import org.rhq.core.domain.operation.HistoryJobId; import org.rhq.core.domain.operation.JobId; -import org.rhq.core.domain.operation.ScheduleJobId;
+ /** + * Test the equals() and hashCode() methods on {@link JobId}, {@link HistoryJobId}, and {@link ScheduleJobId}. + */ @Test public class JobIdTest { + public void testJobIdEquals() { JobId one; JobId two; @@ -170,4 +174,5 @@ public class JobIdTest { assert !one.equals(two); assert one.hashCode() != two.hashCode(); } + } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java index 65fe51f..06e68e5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java @@ -23,6 +23,7 @@ import java.util.List;
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.widgets.grid.ListGridRecord;
@@ -40,6 +41,7 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; public abstract class OperationScheduleDataSource<T extends OperationSchedule> extends RPCDataSource<T> {
public static abstract class Field { + public static final String ID = "id"; public static final String JOB_NAME = "jobName"; public static final String JOB_GROUP = "jobGroup"; public static final String OPERATION_NAME = "operationName"; @@ -63,6 +65,11 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e protected List<DataSourceField> addDataSourceFields() { List<DataSourceField> fields = super.addDataSourceFields();
+ DataSourceIntegerField idField = new DataSourceIntegerField(Field.ID, "ID"); + idField.setPrimaryKey(true); + idField.setCanEdit(false); + fields.add(idField); + DataSourceTextField operationDisplayNameField = createTextField(Field.OPERATION_DISPLAY_NAME, "Operation", null, 100, true); fields.add(operationDisplayNameField);
@@ -84,14 +91,15 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e public T copyValues(Record from) { T to = createOperationSchedule();
+ to.setId(from.getAttributeAsInt(Field.ID)); to.setJobName(from.getAttribute(Field.JOB_NAME)); to.setJobGroup(from.getAttribute(Field.JOB_GROUP)); to.setJobTrigger((JobTrigger)from.getAttributeAsObject(Field.JOB_TRIGGER)); - to.setDescription(from.getAttribute(Field.DESCRIPTION)); - to.setOperationDisplayName(from.getAttribute(Field.OPERATION_DISPLAY_NAME)); - to.setOperationName(from.getAttribute(Field.OPERATION_NAME)); - to.setParameters((Configuration)from.getAttributeAsObject(Field.PARAMETERS)); to.setSubject((Subject)from.getAttributeAsObject(Field.SUBJECT)); + to.setParameters((Configuration)from.getAttributeAsObject(Field.PARAMETERS)); + to.setOperationName(from.getAttribute(Field.OPERATION_NAME)); + to.setOperationDisplayName(from.getAttribute(Field.OPERATION_DISPLAY_NAME)); + to.setDescription(from.getAttribute(Field.DESCRIPTION));
return to; } @@ -100,14 +108,15 @@ public abstract class OperationScheduleDataSource<T extends OperationSchedule> e public ListGridRecord copyValues(T from) { ListGridRecord to = new ListGridRecord();
+ to.setAttribute(Field.ID, from.getId()); to.setAttribute(Field.JOB_NAME, from.getJobName()); to.setAttribute(Field.JOB_GROUP, from.getJobGroup()); to.setAttribute(Field.JOB_TRIGGER, from.getJobTrigger()); - to.setAttribute(Field.OPERATION_DISPLAY_NAME, from.getOperationDisplayName()); - to.setAttribute(Field.OPERATION_NAME, from.getOperationName()); to.setAttribute(Field.SUBJECT, from.getSubject()); - to.setAttribute(Field.DESCRIPTION, from.getDescription()); to.setAttribute(Field.PARAMETERS, from.getParameters()); + to.setAttribute(Field.OPERATION_NAME, from.getOperationName()); + to.setAttribute(Field.OPERATION_DISPLAY_NAME, from.getOperationDisplayName()); + to.setAttribute(Field.DESCRIPTION, from.getDescription());
return to; } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java index f5988e3..db58484 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java @@ -39,6 +39,8 @@ public abstract class OperationJob implements Job { public static final String DATAMAP_STRING_OPERATION_DISPLAY_NAME = "operationDisplayName"; public static final String DATAMAP_INT_PARAMETERS_ID = "parametersId"; // the configuration ID public static final String DATAMAP_INT_SUBJECT_ID = "subjectId"; + // id of the associated OperationScheduleEntity - may be null for jobs created prior to upgrading to RHQ 4.0 + public static final String DATAMAP_INT_ENTITY_ID = "entityId";
/** * For security purposes, we need to provide a subject with a valid login session. This creates such a subject by diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java index a1fc704..5d62695 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java @@ -203,13 +203,16 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan trigger.setJobName(jobDetail.getName()); trigger.setJobGroup(jobDetail.getGroup());
- // we need to create our own schedule tracking entity + // We need to create our own schedule tracking entity. ResourceOperationScheduleEntity schedule; schedule = new ResourceOperationScheduleEntity(jobDetail.getName(), jobDetail.getGroup(), trigger .getStartTime(), resource); entityManager.persist(schedule);
- // now actually schedule it + // Add the id of the entity bean, so we can easily map the Quartz job to the associated entity bean. + jobDataMap.put(ResourceOperationJob.DATAMAP_INT_ENTITY_ID, String.valueOf(schedule.getId())); + + // Now actually schedule it. Date next = scheduler.scheduleJob(jobDetail, trigger); ResourceOperationSchedule newSchedule = getResourceOperationSchedule(subject, jobDetail);
@@ -283,6 +286,9 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan group); entityManager.persist(schedule);
+ // Add the id of the entity bean, so we can easily map the Quartz job to the associated entity bean. + jobDataMap.put(ResourceOperationJob.DATAMAP_INT_ENTITY_ID, String.valueOf(schedule.getId())); + // now actually schedule it Date next = scheduler.scheduleJob(jobDetail, trigger); GroupOperationSchedule newSchedule = getGroupOperationSchedule(subject, jobDetail); @@ -424,6 +430,8 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan public ResourceOperationSchedule getResourceOperationSchedule(Subject whoami, JobDetail jobDetail) { JobDataMap jobDataMap = jobDetail.getJobDataMap();
+ String jobName = jobDetail.getName(); + String jobGroup = jobDetail.getGroup(); String description = jobDetail.getDescription(); String operationName = jobDataMap.getString(ResourceOperationJob.DATAMAP_STRING_OPERATION_NAME); String displayName = jobDataMap.getString(ResourceOperationJob.DATAMAP_STRING_OPERATION_DISPLAY_NAME); @@ -438,6 +446,8 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan int resourceId = jobDataMap.getIntFromString(ResourceOperationJob.DATAMAP_INT_RESOURCE_ID); Resource resource = getResourceIfAuthorized(whoami, resourceId);
+ Integer entityId = getOperationScheduleEntityId(jobDetail); + // note that we throw an exception if the subject does not exist! // this is by design to avoid a malicious user creating a dummy subject in the database, // scheduling a very bad operation, and deleting that subject thus removing all traces @@ -445,8 +455,9 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan // will need to be deleted and rescheduled.
ResourceOperationSchedule sched = new ResourceOperationSchedule(); - sched.setJobName(jobDetail.getName()); - sched.setJobGroup(jobDetail.getGroup()); + sched.setId(entityId); + sched.setJobName(jobName); + sched.setJobGroup(jobGroup); sched.setResource(resource); sched.setOperationName(operationName); sched.setOperationDisplayName(displayName); @@ -461,6 +472,25 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan return sched; }
+ private int getOperationScheduleEntityId(JobDetail jobDetail) { + JobDataMap jobDataMap = jobDetail.getJobDataMap(); + Object entityIdObj = jobDataMap.get(ResourceOperationJob.DATAMAP_INT_ENTITY_ID); + int entityId; + if (entityIdObj != null) { + // for jobs created using RHQ 4.0 or later, the map will contain an entityId entry + entityId = Integer.valueOf((String)entityIdObj); + } else { + // for jobs created prior to upgrading to RHQ 4.0, the map will not contain an entityId entry, + // so we'll need to lookup the entity id from the DB. + String jobName = jobDetail.getName(); + String jobGroup = jobDetail.getGroup(); + ScheduleJobId jobId = new ScheduleJobId(jobName, jobGroup); + OperationScheduleEntity operationScheduleEntity = findOperationScheduleEntity(jobId); + entityId = operationScheduleEntity.getId(); + } + return entityId; + } + public ResourceOperationSchedule getResourceOperationSchedule(Subject subject, String jobId) throws SchedulerException { JobId jobIdObject = new JobId(jobId); @@ -1430,7 +1460,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan Subject overlord = subjectManager.getOverlord(); for (ResourceOperationScheduleComposite composite : results) { try { - ResourceOperationSchedule sched = getResourceOperationSchedule(subject, composite.getOperationJobId() + ResourceOperationSchedule sched = getResourceOperationSchedule(subject, composite.getJobId() .toString()); OperationDefinition def = getSupportedResourceOperation(overlord, composite.getResourceId(), sched .getOperationName(), false); @@ -1484,7 +1514,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan Subject overlord = subjectManager.getOverlord(); for (GroupOperationScheduleComposite composite : results) { try { - GroupOperationSchedule sched = getGroupOperationSchedule(subject, composite.getOperationJobId() + GroupOperationSchedule sched = getGroupOperationSchedule(subject, composite.getJobId() .toString()); OperationDefinition def = getSupportedGroupOperation(overlord, composite.getGroupId(), sched .getOperationName(), false); @@ -1765,7 +1795,13 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan */ private OperationScheduleEntity findOperationScheduleEntity(ScheduleJobId jobId) { OperationScheduleEntity entity = entityManager.find(OperationScheduleEntity.class, jobId); - return entity; + Query query = entityManager.createNamedQuery(OperationScheduleEntity.QUERY_FIND_BY_JOB_ID); + String jobName = jobId.getJobName(); + query.setParameter("jobName", jobName); + String jobGroup = jobId.getJobGroup(); + query.setParameter("jobGroup", jobGroup); + OperationScheduleEntity operationScheduleEntity = (OperationScheduleEntity)query.getSingleResult(); + return operationScheduleEntity; }
public GroupOperationSchedule scheduleGroupOperation(Subject subject, int groupId, int[] executionOrderResourceIds,
commit 1b25505eb944dd6fe0edb1706e1ff65b6a585461 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 15:35:53 2010 -0500
exposing error messages
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ErrorMessageWindow.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ErrorMessageWindow.java new file mode 100644 index 0000000..bd90b9f --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ErrorMessageWindow.java @@ -0,0 +1,78 @@ +/* + * 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.smartgwt.client.widgets.Canvas; +import com.smartgwt.client.widgets.events.CloseClickHandler; +import com.smartgwt.client.widgets.events.CloseClientEvent; + +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHTMLPane; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow; + +/** + * This is a convienence component that is a simple modal dialog box used to display + * things like error messages/stack traces. + * + * Call {@link #show()} on the instantiated window to display it. + * + * @author John Mazzitelli + */ +public class ErrorMessageWindow extends LocatableWindow { + public ErrorMessageWindow(String locatorId, String title, String message) { + super(locatorId); + + LocatableHTMLPane htmlPane = new LocatableHTMLPane(extendLocatorId("winDetailsPane")); + htmlPane.setMargin(10); + htmlPane.setDefaultWidth(500); + htmlPane.setDefaultHeight(400); + htmlPane.setContents(message); + + setupWindow(title, htmlPane); + } + + public ErrorMessageWindow(String locatorId, String title, Canvas item) { + super(locatorId); + setupWindow(title, item); + } + + private void setupWindow(String title, Canvas item) { + setTitle(title); + setShowMinimizeButton(false); + setShowMaximizeButton(true); + setIsModal(true); + setShowModalMask(true); + setAutoSize(true); + setAutoCenter(true); + setShowResizer(true); + setCanDragResize(true); + centerInPage(); + addCloseClickHandler(new CloseClickHandler() { + @Override + public void onCloseClick(CloseClientEvent event) { + markForDestroy(); + } + }); + addItem(item); + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java index 5e94e47..917b13d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java @@ -53,6 +53,7 @@ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment> public static final String FIELD_DEPLOY_DIR = "deployDir"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_DEPLOY_TIME = "deploymentTime"; + public static final String FIELD_ERROR_MESSAGE = "errorMessage"; public static final String FIELD_CONFIG = "configuration"; public static final String FIELD_STATUS = "status"; public static final String FIELD_DEPLOYER = "deployer"; // a user name @@ -153,6 +154,7 @@ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment> record.setAttribute(FIELD_NAME, from.getName()); record.setAttribute(FIELD_DEPLOY_DIR, from.getDestination().getDeployDir()); record.setAttribute(FIELD_DESCRIPTION, from.getDescription()); + record.setAttribute(FIELD_ERROR_MESSAGE, from.getErrorMessage()); record.setAttribute(FIELD_DEPLOY_TIME, new Date(from.getCtime())); record.setAttribute(FIELD_CONFIG, from.getConfiguration()); record.setAttribute(FIELD_STATUS, from.getStatus().name()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java index a0658b0..9cb3f58 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java @@ -33,10 +33,13 @@ 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.grid.events.RecordClickEvent; +import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import org.rhq.core.domain.bundle.BundleDeployment; import org.rhq.core.domain.bundle.BundleDeploymentStatus; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.ErrorMessageWindow; import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.bundle.list.BundleVersionDataSource; import org.rhq.enterprise.gui.coregui.client.components.table.Table; @@ -105,6 +108,16 @@ public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployme statusField.setValueIcons(statusIcons); statusField.setValueIconWidth(11); statusField.setValueIconHeight(11); + statusField.addRecordClickHandler(new RecordClickHandler() { + @Override + public void onRecordClick(RecordClickEvent event) { + String err = event.getRecord().getAttribute(BundleDeploymentDataSource.FIELD_ERROR_MESSAGE); + if (err != null && err.length() > 0) { + err = "<pre>" + err + "</pre>"; + new ErrorMessageWindow(extendLocatorId("errWin"), MSG.common_title_error(), err).show(); + } + } + });
idField.setWidth(50); nameField.setWidth("30%"); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index f64edda..97b60af 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -30,11 +30,14 @@ import java.util.HashSet; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.AnimationEffect; import com.smartgwt.client.types.AutoFitWidthApproach; +import com.smartgwt.client.types.DateDisplayFormat; import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.form.fields.LinkItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.events.ClickEvent; +import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; @@ -58,6 +61,7 @@ import org.rhq.core.domain.tagging.Tag; 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.ErrorMessageWindow; import org.rhq.enterprise.gui.coregui.client.ImageManager; import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.ViewId; @@ -86,12 +90,21 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab private VLayout detail; private boolean canManageBundles;
+ private final HashMap<String, String> statusIcons; + public BundleDeploymentView(String locatorId, boolean canManageBundles) { super(locatorId); this.canManageBundles = canManageBundles; setWidth100(); setHeight100(); //setMargin(10); // do not set margin, we already have our margin set outside of us + + statusIcons = new HashMap<String, String>(); + statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); + statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); + statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); }
private void viewBundleDeployment(BundleDeployment bundleDeployment, ViewId current) { @@ -141,8 +154,33 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab bundleVersionName.setTarget("_self");
StaticTextItem deployed = new StaticTextItem("deployed", MSG.view_bundle_deployed()); + deployed.setDateFormatter(DateDisplayFormat.TOLOCALESTRING); deployed.setValue(new Date(deployment.getCtime()));
+ StaticTextItem deployedBy = new StaticTextItem("deployedBy", MSG.view_bundle_deploy_deployedBy()); + deployedBy.setValue(deployment.getSubjectName()); + + StaticTextItem description = new StaticTextItem("description", MSG.common_title_description()); + description.setValue(deployment.getDescription()); + + StaticTextItem status = new StaticTextItem("status", MSG.common_title_status()); + status.setValue(deployment.getStatus().name()); + status.setValueIcons(statusIcons); + status.setValueIconHeight(11); + status.setValueIconWidth(11); + status.setShowValueIconOnly(true); + if (deployment.getErrorMessage() != null) { + status.setTooltip(MSG.view_bundle_deploy_clickForError()); + status.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + ErrorMessageWindow win = new ErrorMessageWindow(extendLocatorId("errWin"), + MSG.common_title_error(), "<pre>" + deployment.getErrorMessage() + "</pre>"); + win.show(); + } + }); + } + LinkItem destinationGroup = new LinkItem("group"); destinationGroup.setTitle(MSG.common_title_resource_group()); destinationGroup.setValue(LinkManager.getResourceGroupLink(deployment.getDestination().getGroup().getId())); @@ -152,7 +190,8 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_deployDir()); path.setValue(deployment.getDestination().getDeployDir());
- form.setFields(bundleName, bundleVersionName, deployed, destinationGroup, path); + form.setFields(bundleName, deployed, bundleVersionName, deployedBy, // + description, status, destinationGroup, path); return form; }
@@ -214,12 +253,6 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab
// status icon field ListGridField status = new ListGridField("status", MSG.common_title_status()); - HashMap<String, String> statusIcons = new HashMap<String, String>(); - statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); - statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); - statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); status.setValueIcons(statusIcons); status.setValueIconHeight(11); status.setValueIconWidth(11); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java index 6093083..972e618 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java @@ -34,8 +34,6 @@ import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.types.VerticalAlignment; 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.form.DynamicForm; @@ -51,10 +49,10 @@ import com.smartgwt.client.widgets.grid.events.RecordClickHandler; import org.rhq.core.domain.bundle.BundleDeploymentStatus; import org.rhq.core.domain.bundle.BundleResourceDeployment; import org.rhq.core.domain.bundle.BundleResourceDeploymentHistory; +import org.rhq.enterprise.gui.coregui.client.ErrorMessageWindow; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableListGrid; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
/** * @author Greg Hinkle @@ -170,24 +168,10 @@ public class BundleResourceDeploymentHistoryListView extends LocatableVLayout { form.setItems(timestamp, action, category, user, status, info, message, detail); form.editRecord(record);
- final Window window = new LocatableWindow(extendLocatorId("detailsWin")); - window.setTitle(MSG.view_bundle_deploy_installDetails()); - window.setAutoSize(true); - window.setWidth(500); - window.setAutoCenter(true); - window.setIsModal(true); - window.setShowModalMask(true); - window.setCanDragResize(true); - window.addItem(form); - window.setShowMinimizeButton(false); - window.setShowMaximizeButton(true); - window.addCloseClickHandler(new CloseClickHandler() { - @Override - public void onCloseClick(CloseClientEvent event) { - window.destroy(); - } - }); - window.show(); + Window win = new ErrorMessageWindow(extendLocatorId("detailsWin"), MSG.view_bundle_deploy_installDetails(), + form); + win.setWidth(500); + win.show(); }
public ListGridRecord[] buildRecords() { diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index b0ceaf9..0009db8 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -970,6 +970,8 @@ view_bundle_deploy_selectARow = Select a row to show installation details view_bundle_deploy_operatingSystem = Operating System view_bundle_deploy_loadFailure = Failed to load bundle deployment view_bundle_deploy_loadBundleFailure = Failed to find bundle +view_bundle_deploy_deployedBy = Deployed By +view_bundle_deploy_clickForError = Click the icon for the error message view_bundle_createWizard_title = Create Bundle view_bundle_createWizard_windowTitle = Bundle Creation Wizard view_bundle_createWizard_cancelSuccessful = Canceled the creation of bundle [{0}], version = [{1}]
commit f65d0fc2c63453daf2af4eb21d7afdcc171b464a Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 14:08:52 2010 -0500
fix up the deployment details list, add more data like user and timestamp
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java index 9073dc9..6093083 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleResourceDeploymentHistoryListView.java @@ -23,17 +23,24 @@ package org.rhq.enterprise.gui.coregui.client.bundle.deployment;
import java.util.ArrayList; +import java.util.Date; import java.util.HashMap;
+import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.types.AutoFitWidthApproach; +import com.smartgwt.client.types.DateDisplayFormat; import com.smartgwt.client.types.ExpansionMode; -import com.smartgwt.client.types.TitleOrientation; +import com.smartgwt.client.types.ListGridFieldType; +import com.smartgwt.client.types.SelectionStyle; +import com.smartgwt.client.types.VerticalAlignment; 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.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.AutoFitTextAreaItem; -import com.smartgwt.client.widgets.form.fields.ButtonItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; -import com.smartgwt.client.widgets.form.fields.events.ClickEvent; -import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; @@ -44,8 +51,10 @@ import com.smartgwt.client.widgets.grid.events.RecordClickHandler; import org.rhq.core.domain.bundle.BundleDeploymentStatus; import org.rhq.core.domain.bundle.BundleResourceDeployment; import org.rhq.core.domain.bundle.BundleResourceDeploymentHistory; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableListGrid; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
/** * @author Greg Hinkle @@ -53,44 +62,60 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; public class BundleResourceDeploymentHistoryListView extends LocatableVLayout {
private BundleResourceDeployment resourceDeployment; + private HashMap<String, String> statusIcons;
public BundleResourceDeploymentHistoryListView(String locatorId, BundleResourceDeployment resourceDeployment) { super(locatorId); - setWidth100(); setHeight100(); this.resourceDeployment = resourceDeployment;
+ statusIcons = new HashMap<String, String>(); + statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); + statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); + statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); }
@Override protected void onInit() { super.onInit();
- ListGrid grid = new LocatableListGrid(this.getLocatorId()); + final ListGrid grid = new LocatableListGrid(this.getLocatorId()); grid.setWidth100(); grid.setHeight100(); + grid.setSelectionType(SelectionStyle.SINGLE); + grid.setCanExpandRecords(true); + grid.setExpansionMode(ExpansionMode.DETAIL_FIELD); + grid.setDetailField("message");
ListGridField action = new ListGridField("action", MSG.view_bundle_deploy_action()); + action.setAutoFitWidth(true); + action.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH); + ListGridField message = new ListGridField("info", MSG.common_title_info()); - ListGridField status = new ListGridField("status", MSG.common_title_status()); + message.setWidth("60%");
- HashMap<String, String> icons = new HashMap<String, String>(); - icons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); - icons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Warning_11.png"); - icons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - icons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); - icons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); - status.setValueIcons(icons); - status.setValueIconHeight(11); - status.setWidth(80); + ListGridField user = new ListGridField("user", MSG.common_title_user()); + user.setHidden(true);
- grid.setCanExpandRecords(true); - grid.setExpansionMode(ExpansionMode.DETAIL_FIELD); - grid.setDetailField("message"); + ListGridField timestamp = new ListGridField("timestamp", MSG.common_title_timestamp()); + timestamp.setWidth("40%"); + + ListGridField status = new ListGridField("status", MSG.common_title_status()); + status.setValueIcons(statusIcons); + status.setValueIconHeight(11); + status.setValueIconWidth(11); + status.setAutoFitWidth(true); + status.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH);
ListGridField details = new ListGridField("attachment", MSG.common_title_details()); details.setWidth(50); + details.setAlign(Alignment.CENTER); + details.setType(ListGridFieldType.ICON); + details.setIconHeight(11); + details.setIconWidth(11); details.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { return "<img src="images/subsystems/bundle/Details_11.png"/>"; @@ -102,47 +127,67 @@ public class BundleResourceDeploymentHistoryListView extends LocatableVLayout { } });
- grid.setFields(action, message, status, details); + grid.setFields(action, message, timestamp, status, user, details); grid.setData(buildRecords()); - addMember(grid);
+ grid.addDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + showDetails(grid.getSelectedRecord()); + } + }); + + addMember(grid); }
private void showDetails(ListGridRecord record) { + DynamicForm form = new LocatableDynamicForm(extendLocatorId("detailsForm")); + form.setHeight100(); + form.setWidth100(); + form.setPadding(20); + + StaticTextItem status = new StaticTextItem("status", MSG.common_title_status()); + status.setValueIcons(statusIcons); + status.setValueIconHeight(11); + status.setValueIconWidth(11); + status.setShowValueIconOnly(true); + + StaticTextItem user = new StaticTextItem("user", MSG.common_title_user());
- DynamicForm form = new DynamicForm(); + StaticTextItem timestamp = new StaticTextItem("timestamp", MSG.common_title_timestamp()); + timestamp.setDateFormatter(DateDisplayFormat.TOLOCALESTRING);
StaticTextItem action = new StaticTextItem("action", MSG.view_bundle_deploy_action()); StaticTextItem info = new StaticTextItem("info", MSG.common_title_info()); StaticTextItem category = new StaticTextItem("category", MSG.common_title_category()); - StaticTextItem message = new StaticTextItem("message", MSG.common_title_message()); - - AutoFitTextAreaItem detail = new AutoFitTextAreaItem("attachement", MSG.common_title_details()); - detail.setTitleOrientation(TitleOrientation.TOP); - detail.setColSpan(2);
- ButtonItem close = new ButtonItem("close", MSG.common_button_close()); + StaticTextItem message = new StaticTextItem("message", MSG.common_title_message()); + message.setTitleVAlign(VerticalAlignment.TOP);
- form.setItems(action, info, category, message, detail, close); + AutoFitTextAreaItem detail = new AutoFitTextAreaItem("attachment", MSG.common_title_details()); + detail.setTitleVAlign(VerticalAlignment.TOP);
+ form.setItems(timestamp, action, category, user, status, info, message, detail); form.editRecord(record);
- final Window window = new Window(); + final Window window = new LocatableWindow(extendLocatorId("detailsWin")); window.setTitle(MSG.view_bundle_deploy_installDetails()); - window.setWidth(800); - window.setHeight(600); + window.setAutoSize(true); + window.setWidth(500); + window.setAutoCenter(true); window.setIsModal(true); window.setShowModalMask(true); window.setCanDragResize(true); - window.centerInPage(); window.addItem(form); - window.show(); - - close.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { + window.setShowMinimizeButton(false); + window.setShowMaximizeButton(true); + window.addCloseClickHandler(new CloseClickHandler() { + @Override + public void onCloseClick(CloseClientEvent event) { window.destroy(); } }); + window.show(); }
public ListGridRecord[] buildRecords() { @@ -161,10 +206,11 @@ public class BundleResourceDeploymentHistoryListView extends LocatableVLayout { record.setAttribute("message", step.getMessage()); record.setAttribute("attachment", step.getAttachment()); record.setAttribute("status", step.getStatus().name()); + record.setAttribute("timestamp", new Date(step.getAuditTime())); + record.setAttribute("user", step.getSubjectName()); records.add(record); }
return records.toArray(new ListGridRecord[records.size()]); - } }
commit 0c02640cca3054b976af857ec585a46d07a5cc54 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 12:35:41 2010 -0500
add authz check to see deployment info. clean up the ui a bit to make it have a consistent l&f like the other bundle views
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index 0bb149c..f64edda 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -29,12 +29,14 @@ import java.util.HashSet;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.AnimationEffect; +import com.smartgwt.client.types.AutoFitWidthApproach; +import com.smartgwt.client.types.ListGridFieldType; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; -import com.smartgwt.client.widgets.form.fields.CanvasItem; import com.smartgwt.client.widgets.form.fields.LinkItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; 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.grid.events.SelectionChangedHandler; @@ -49,6 +51,8 @@ import org.rhq.core.domain.bundle.BundleVersion; import org.rhq.core.domain.criteria.BundleCriteria; import org.rhq.core.domain.criteria.BundleDeploymentCriteria; import org.rhq.core.domain.criteria.BundleResourceDeploymentCriteria; +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; @@ -80,12 +84,14 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab private Bundle bundle;
private VLayout detail; + private boolean canManageBundles;
- public BundleDeploymentView(String locatorId) { + public BundleDeploymentView(String locatorId, boolean canManageBundles) { super(locatorId); + this.canManageBundles = canManageBundles; setWidth100(); setHeight100(); - setMargin(10); + //setMargin(10); // do not set margin, we already have our margin set outside of us }
private void viewBundleDeployment(BundleDeployment bundleDeployment, ViewId current) { @@ -97,23 +103,62 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab this.bundle = bundleDeployment.getBundleVersion().getBundle();
addMember(new BackButton(extendLocatorId("BackButton"), MSG.view_bundle_deploy_backButton() + ": " - + deployment.getDestination().getName(), "Bundles/Bundle/" + version.getBundle().getId() + "/destinations/" - + deployment.getDestination().getId())); - + + deployment.getDestination().getName(), LinkManager.getBundleDestinationLink(version.getBundle().getId(), + deployment.getDestination().getId()))); addMember(new HeaderLabel(Canvas.getImgURL("subsystems/bundle/BundleDeployment_24.png"), deployment.getName())); + addMember(createTagEditor()); + addMember(createSummaryForm()); + addMemberDeploymentsTable();
+ detail = new VLayout(); + detail.setAutoHeight(); + detail.hide(); + addMember(detail); + } + + private LocatableDynamicForm createSummaryForm() { LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("Summary")); + form.setWidth100(); + form.setAutoHeight(); form.setNumCols(4); + form.setWrapItemTitles(false); + form.setExtraSpace(10); + form.setIsGroup(true); + form.setGroupTitle(MSG.common_title_summary()); + form.setPadding(5);
LinkItem bundleName = new LinkItem("bundle"); bundleName.setTitle(MSG.view_bundle_bundle()); - bundleName.setValue("#Bundles/Bundle/" + bundle.getId()); + bundleName.setValue(LinkManager.getBundleLink(bundle.getId())); bundleName.setLinkTitle(bundle.getName()); bundleName.setTarget("_self");
- CanvasItem tagItem = new CanvasItem("tag"); - tagItem.setShowTitle(false); - TagEditorView tagEditor = new TagEditorView(form.getLocatorId(), version.getTags(), false, + LinkItem bundleVersionName = new LinkItem("bundleVersion"); + bundleVersionName.setTitle(MSG.view_bundle_bundleVersion()); + bundleVersionName.setValue(LinkManager.getBundleVersionLink(bundle.getId(), deployment.getBundleVersion() + .getId())); + bundleVersionName.setLinkTitle(deployment.getBundleVersion().getVersion()); + bundleVersionName.setTarget("_self"); + + StaticTextItem deployed = new StaticTextItem("deployed", MSG.view_bundle_deployed()); + deployed.setValue(new Date(deployment.getCtime())); + + LinkItem destinationGroup = new LinkItem("group"); + destinationGroup.setTitle(MSG.common_title_resource_group()); + destinationGroup.setValue(LinkManager.getResourceGroupLink(deployment.getDestination().getGroup().getId())); + destinationGroup.setLinkTitle(deployment.getDestination().getGroup().getName()); + destinationGroup.setTarget("_self"); + + StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_deployDir()); + path.setValue(deployment.getDestination().getDeployDir()); + + form.setFields(bundleName, bundleVersionName, deployed, destinationGroup, path); + return form; + } + + private TagEditorView createTagEditor() { + boolean readOnly = !this.canManageBundles; + TagEditorView tagEditor = new TagEditorView(extendLocatorId("tagEditor"), version.getTags(), readOnly, new TagsChangedCallback() { public void tagsChanged(HashSet<Tag> tags) { GWTServiceLookup.getTagService().updateBundleDeploymentTags(deployment.getId(), tags, @@ -130,32 +175,9 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab }); } }); - tagEditor.setVertical(true); - tagItem.setCanvas(tagEditor); - tagItem.setRowSpan(4); - - StaticTextItem deployed = new StaticTextItem("deployed", MSG.view_bundle_deployed()); - deployed.setValue(new Date(deployment.getCtime())); - - LinkItem destinationGroup = new LinkItem("group"); - destinationGroup.setTitle(MSG.common_title_resource_group()); - destinationGroup.setValue(LinkManager.getResourceGroupLink(deployment.getDestination().getGroup().getId())); - destinationGroup.setLinkTitle(deployment.getDestination().getGroup().getName()); - destinationGroup.setTarget("_self"); - - StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_deployDir()); - path.setValue(deployment.getDestination().getDeployDir()); - - form.setFields(bundleName, tagItem, deployed, destinationGroup, path); - - addMember(form); - - addMemberDeploymentsTable(); - - detail = new VLayout(); - detail.setAutoHeight(); - detail.hide(); - addMember(detail); + tagEditor.setAutoHeight(); + tagEditor.setExtraSpace(10); + return tagEditor; }
private Table addMemberDeploymentsTable() { @@ -163,20 +185,20 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab
table.setTitleComponent(new HTMLFlow(MSG.view_bundle_deploy_selectARow()));
- ListGridField resourceIcon = new ListGridField("resourceAvailability", ""); + // resource icon field + ListGridField resourceIcon = new ListGridField("resourceAvailability"); HashMap<String, String> icons = new HashMap<String, String>(); - icons.put("UP", ImageManager.getResourceIcon(ResourceCategory.PLATFORM, Boolean.TRUE)); - icons.put("DOWN", ImageManager.getResourceIcon(ResourceCategory.PLATFORM, Boolean.FALSE)); + icons.put(AvailabilityType.UP.name(), ImageManager.getResourceIcon(ResourceCategory.PLATFORM, Boolean.TRUE)); + icons.put(AvailabilityType.DOWN.name(), ImageManager.getResourceIcon(ResourceCategory.PLATFORM, Boolean.FALSE)); resourceIcon.setValueIcons(icons); resourceIcon.setValueIconSize(16); - resourceIcon.setCellFormatter(new CellFormatter() { - public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - return ""; - } - }); - resourceIcon.setWidth(30); + resourceIcon.setType(ListGridFieldType.ICON); + resourceIcon.setWidth(40);
+ // resource field ListGridField resource = new ListGridField("resource", MSG.common_title_platform()); + resource.setAutoFitWidth(true); + resource.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH); resource.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { return "<a href="" + LinkManager.getResourceLink(listGridRecord.getAttributeAsInt("resourceId")) @@ -184,49 +206,55 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab
} }); + + // resource version field ListGridField resourceVersion = new ListGridField("resourceVersion", MSG.view_bundle_deploy_operatingSystem()); + resourceVersion.setAutoFitWidth(true); + resourceVersion.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH); + + // status icon field ListGridField status = new ListGridField("status", MSG.common_title_status()); HashMap<String, String> statusIcons = new HashMap<String, String>(); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); - statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); status.setValueIcons(statusIcons); status.setValueIconHeight(11); - status.setWidth(80); + status.setValueIconWidth(11); + status.setWidth("*");
ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>(); for (BundleResourceDeployment rd : deployment.getResourceDeployments()) { ListGridRecord record = new ListGridRecord(); - record.setAttribute("resource", rd.getResource().getName()); - - record.setAttribute("resourceAvailability", rd.getResource().getCurrentAvailability().getAvailabilityType() - .name()); - record.setAttribute("resourceId", rd.getResource().getId()); - record.setAttribute("resourceVersion", rd.getResource().getVersion()); + Resource rr = rd.getResource(); + record.setAttribute("resource", rr.getName()); + record.setAttribute("resourceAvailability", rr.getCurrentAvailability().getAvailabilityType().name()); + record.setAttribute("resourceId", rr.getId()); + record.setAttribute("resourceVersion", rr.getVersion()); record.setAttribute("status", rd.getStatus().name()); record.setAttribute("id", rd.getId()); - record.setAttribute("entity", rd); + record.setAttribute("object", rd); records.add(record); }
// To get the ListGrid the Table must be initialized (via onInit()) by adding to the Canvas table.setHeight("30%"); + table.setWidth100(); table.setShowResizeBar(true); table.setResizeBarTarget("next"); addMember(table);
- table.getListGrid().setFields(resourceIcon, resource, resourceVersion, status); - - table.getListGrid().setData(records.toArray(new ListGridRecord[records.size()])); - - table.getListGrid().addSelectionChangedHandler(new SelectionChangedHandler() { + ListGrid listGrid = table.getListGrid(); + listGrid.setFields(resourceIcon, resource, resourceVersion, status); + listGrid.setData(records.toArray(new ListGridRecord[records.size()])); + listGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { if (selectionEvent.getState()) {
BundleResourceDeployment bundleResourceDeployment = (BundleResourceDeployment) selectionEvent - .getRecord().getAttributeAsObject("entity"); + .getRecord().getAttributeAsObject("object"); BundleResourceDeploymentHistoryListView detailView = new BundleResourceDeploymentHistoryListView( "Detail", bundleResourceDeployment);
@@ -234,24 +262,6 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab detail.addMember(detailView); detail.setHeight("50%"); detail.animateShow(AnimationEffect.SLIDE); - - /* - BundleResourceDeploymentCriteria criteria = new BundleResourceDeploymentCriteria(); - criteria.addFilterId(selectionEvent.getRecord().getAttributeAsInt("id")); - criteria.fetchHistories(true); - criteria.fetchResource(true); - criteria.fetchBundleDeployment(true); - bundleService.findBundleResourceDeploymentsByCriteria(criteria, new AsyncCallback<PageList<BundleResourceDeployment>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load resource deployment history details",caught); - } - - public void onSuccess(PageList<BundleResourceDeployment> result) { - - } - }); - */ - } else { detail.animateHide(AnimationEffect.SLIDE); } @@ -264,8 +274,6 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab public void renderView(final ViewPath viewPath) { int bundleDeploymentId = Integer.parseInt(viewPath.getCurrent().getPath());
- final ViewId viewId = viewPath.getCurrent(); - BundleDeploymentCriteria criteria = new BundleDeploymentCriteria(); criteria.addFilterId(bundleDeploymentId); criteria.fetchBundleVersion(true); @@ -281,9 +289,7 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab }
public void onSuccess(PageList<BundleDeployment> result) { - final BundleDeployment deployment = result.get(0); - BundleCriteria bundleCriteria = new BundleCriteria(); bundleCriteria.addFilterId(deployment.getBundleVersion().getBundle().getId()); bundleService.findBundlesByCriteria(bundleCriteria, new AsyncCallback<PageList<Bundle>>() { @@ -292,11 +298,8 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab }
public void onSuccess(PageList<Bundle> result) { - final Bundle bundle = result.get(0); - deployment.getBundleVersion().setBundle(bundle); - BundleResourceDeploymentCriteria criteria = new BundleResourceDeploymentCriteria(); criteria.addFilterBundleDeploymentId(deployment.getId()); criteria.fetchHistories(true); @@ -304,7 +307,6 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab criteria.fetchBundleDeployment(true); bundleService.findBundleResourceDeploymentsByCriteria(criteria, new AsyncCallback<PageList<BundleResourceDeployment>>() { - public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.view_bundle_deploy_loadFailure(), caught); } @@ -314,13 +316,10 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab viewBundleDeployment(deployment, viewPath.getCurrent()); } }); - } }); - } }); - }
} 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 15ebed4..1c9dc47 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 @@ -316,7 +316,8 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } else { // a specific deployment //removeMembers(getMembers()); - BundleDeploymentView view = new BundleDeploymentView(extendLocatorId("Deployment")); + BundleDeploymentView view = new BundleDeploymentView(extendLocatorId("Deployment"), + canManageBundles); addMember(view); view.renderView(viewPath.next()); }
commit 61056623da28a88d5055a2ca6bf4261de018f1fd Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 11:28:30 2010 -0500
refactor the bundle version view. add authz checks.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java index a2412d5..a0658b0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java @@ -115,18 +115,20 @@ public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployme
setListGridFields(idField, nameField, descriptionField, bundleVersionField, deployTimeField, statusField);
- setListGridDoubleClickHandler(new DoubleClickHandler() { - @Override - public void onDoubleClick(DoubleClickEvent event) { - ListGrid listGrid = (ListGrid) event.getSource(); - ListGridRecord[] selectedRows = listGrid.getSelection(); - if (selectedRows != null && selectedRows.length == 1) { - String selectedId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_BUNDLE_ID); - String selectedVersionId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_ID); - CoreGUI.goToView(LinkManager.getBundleDeploymentLink(Integer.valueOf(selectedId), Integer - .valueOf(selectedVersionId))); + if (canManageBundles) { + setListGridDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + ListGrid listGrid = (ListGrid) event.getSource(); + ListGridRecord[] selectedRows = listGrid.getSelection(); + if (selectedRows != null && selectedRows.length == 1) { + String selectedId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_BUNDLE_ID); + String selectedVersionId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_ID); + CoreGUI.goToView(LinkManager.getBundleDeploymentLink(Integer.valueOf(selectedId), Integer + .valueOf(selectedVersionId))); + } } - } - }); + }); + } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index c298b35..548037b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -163,6 +163,7 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka } }); tagEditor.setAutoHeight(); + tagEditor.setExtraSpace(10); return tagEditor; }
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 b567a0a..15ebed4 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 @@ -140,6 +140,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } }); tagEditor.setAutoHeight(); + tagEditor.setExtraSpace(10); return tagEditor; }
@@ -304,7 +305,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { if (viewPath.getCurrent().getPath().equals("versions")) { if (!viewPath.isEnd()) { // a specific version - BundleVersionView view = new BundleVersionView(extendLocatorId("Version")); + BundleVersionView view = new BundleVersionView(extendLocatorId("Version"), canManageBundles); addMember(view); view.renderView(viewPath.next()); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java index ad55799..2985f06 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java @@ -26,11 +26,11 @@ import java.util.HashSet;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; -import com.smartgwt.client.types.TitleOrientation; import com.smartgwt.client.widgets.Canvas; -import com.smartgwt.client.widgets.form.fields.CanvasItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; +import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; +import com.smartgwt.client.widgets.form.fields.events.ChangeHandler; import com.smartgwt.client.widgets.tab.Tab; import com.smartgwt.client.widgets.tab.TabSet;
@@ -40,6 +40,7 @@ import org.rhq.core.domain.tagging.Tag; 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.bundle.deployment.BundleDeploymentListView; @@ -61,63 +62,84 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; public class BundleVersionView extends LocatableVLayout implements BookmarkableView {
private BundleVersion version; + private boolean canManageBundles = false;
- public BundleVersionView(String locatorId) { + public BundleVersionView(String locatorId, boolean canManageBundles) { super(locatorId); + this.canManageBundles = canManageBundles; setWidth100(); setHeight100(); + //setMargin(10); // do not set margin, we already have our margin set outside of us }
- public void viewBundleVersion(BundleVersion version, ViewId nextViewId) { + private void viewBundleVersion(BundleVersion version, ViewId nextViewId) { // Whenever a new view request comes in, make sure to clean house to avoid ID conflicts for sub-widgets this.destroyMembers();
this.version = version;
- TabSet tabs = new LocatableTabSet(getLocatorId()); - tabs.addTab(createSummaryTab()); - - tabs.addTab(createLiveDeploymentsTab()); - - tabs.addTab(createFilesTab()); - - // tabs.addTab(createUpdateHistoryTab()); - addMember(new BackButton(extendLocatorId("BackButton"), MSG.view_bundle_version_backToBundle() + ": " - + version.getBundle().getName(), "Bundles/Bundle/" + version.getBundle().getId())); + + version.getBundle().getName(), LinkManager.getBundleLink(version.getBundle().getId())));
addMember(new HeaderLabel(Canvas.getImgURL("subsystems/bundle/BundleVersion_24.png"), version.getName() + ": " + version.getVersion()));
+ addMember(createTagEditor()); + + addMember(createSummaryForm()); + + TabSet tabs = new LocatableTabSet(extendLocatorId("Tabs")); + tabs.addTab(createRecipeTab()); + tabs.addTab(createLiveDeploymentsTab()); + tabs.addTab(createFilesTab()); addMember(tabs);
if (nextViewId != null) { - if (nextViewId.getPath().equals("deployments")) { + if (nextViewId.getPath().equals("recipe")) { + tabs.selectTab(0); + } else if (nextViewId.getPath().equals("deployments")) { tabs.selectTab(1); } else if (nextViewId.getPath().equals("files")) { tabs.selectTab(2); - } else if (nextViewId.getPath().equals("history")) { - tabs.selectTab(3); + } else { + // should we throw an exception? someone gave a bad URL; just bring them to first tab + tabs.selectTab(0); } }
markForRedraw(); }
- private Tab createSummaryTab() { - LocatableTab tab = new LocatableTab(extendLocatorId("Summary"), MSG.common_title_summary()); - - LocatableDynamicForm form = new LocatableDynamicForm(tab.getLocatorId()); + private LocatableDynamicForm createSummaryForm() { + LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("Summary")); form.setWidth100(); - form.setHeight100(); - form.setNumCols(4); + form.setAutoHeight(); + form.setNumCols(2); + form.setWrapItemTitles(false); + form.setExtraSpace(10); + form.setIsGroup(true); + form.setGroupTitle(MSG.common_title_summary()); + form.setPadding(5);
StaticTextItem versionItem = new StaticTextItem("version", MSG.common_title_version()); versionItem.setValue(version.getVersion());
- CanvasItem tagItem = new CanvasItem("tag"); - tagItem.setShowTitle(false); - TagEditorView tagEditor = new TagEditorView(form.getLocatorId(), version.getTags(), false, + StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); + descriptionItem.setValue(version.getDescription()); + + StaticTextItem liveDeploymentsItem = new StaticTextItem("deployments", MSG.view_bundle_deployments()); + liveDeploymentsItem.setValue(version.getBundleDeployments().size()); + + StaticTextItem filesItems = new StaticTextItem("files", MSG.view_bundle_files()); + filesItems.setValue(version.getBundleFiles().size()); + + form.setFields(versionItem, descriptionItem, liveDeploymentsItem, filesItems); + return form; + } + + private TagEditorView createTagEditor() { + boolean readOnly = !this.canManageBundles; + TagEditorView tagEditor = new TagEditorView(extendLocatorId("Tags"), version.getTags(), readOnly, new TagsChangedCallback() { public void tagsChanged(HashSet<Tag> tags) { GWTServiceLookup.getTagService().updateBundleVersionTags(version.getId(), tags, @@ -135,61 +157,54 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV }); } }); - tagEditor.setVertical(true); - tagItem.setCanvas(tagEditor); - tagItem.setRowSpan(4); - - StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); - descriptionItem.setValue(version.getDescription()); - - StaticTextItem liveDeploymentsItem = new StaticTextItem("deployments", MSG.view_bundle_deployments()); - liveDeploymentsItem.setValue(version.getBundleDeployments().size()); - - StaticTextItem filesItems = new StaticTextItem("files", MSG.view_bundle_files()); - filesItems.setValue(version.getBundleFiles().size()); - - TextAreaItem recipeItem = new TextAreaItem("recipe", MSG.view_bundle_recipe()); - recipeItem.setDisabled(true); - recipeItem.setTitleOrientation(TitleOrientation.TOP); - recipeItem.setColSpan(4); - recipeItem.setWidth("*"); - recipeItem.setHeight("*"); - recipeItem.setValue(version.getRecipe()); + tagEditor.setAutoHeight(); + tagEditor.setExtraSpace(10); + return tagEditor; + }
- form.setFields(versionItem, tagItem, descriptionItem, liveDeploymentsItem, filesItems, recipeItem); + private Tab createRecipeTab() { + LocatableTab tab = new LocatableTab(extendLocatorId("Recipe"), MSG.view_bundle_recipe()); + LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("RecipeForm")); + + TextAreaItem recipeCanvas = new TextAreaItem("recipe", MSG.view_bundle_recipe()); + recipeCanvas.setShowTitle(false); + recipeCanvas.setColSpan(2); + recipeCanvas.setWidth("100%"); + recipeCanvas.setHeight("100%"); + recipeCanvas.setValue(version.getRecipe()); + recipeCanvas.addChangeHandler(new ChangeHandler() { + @Override + public void onChange(ChangeEvent event) { + // makes this read-only; however, since its not disabled, user can still select/copy the text + event.cancel(); + } + });
+ form.setHeight100(); + form.setWidth100(); + form.setItems(recipeCanvas); tab.setPane(form); - return tab; }
private Tab createLiveDeploymentsTab() { LocatableTab tab = new LocatableTab(extendLocatorId("Deployments"), MSG.view_bundle_deployments()); - Criteria criteria = new Criteria(); criteria.setAttribute("bundleVersionId", version.getId()); - - // TODO: get user perm, if has manage_bundle, pass true - tab.setPane(new BundleDeploymentListView(tab.getLocatorId(), criteria, false)); - + tab.setPane(new BundleDeploymentListView(tab.getLocatorId(), criteria, this.canManageBundles)); return tab; }
private Tab createFilesTab() { LocatableTab tab = new LocatableTab(extendLocatorId("Files"), MSG.view_bundle_files()); - FileListView filesView = new FileListView(tab.getLocatorId(), version.getId()); - tab.setPane(filesView); - return tab; }
public void renderView(final ViewPath viewPath) { int bundleVersionId = Integer.parseInt(viewPath.getCurrent().getPath());
- final ViewId viewId = viewPath.getCurrent(); - BundleVersionCriteria criteria = new BundleVersionCriteria(); criteria.addFilterId(bundleVersionId); criteria.fetchBundle(true); @@ -206,9 +221,9 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV
public void onSuccess(PageList<BundleVersion> result) { BundleVersion version = result.get(0); - viewBundleVersion(version, viewPath.getCurrent()); + ViewId nextPath = viewPath.next().getCurrent(); + viewBundleVersion(version, nextPath); } }); - } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/file/FileListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/file/FileListView.java index 31fce59..5b33200 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/file/FileListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/file/FileListView.java @@ -25,10 +25,13 @@ package org.rhq.enterprise.gui.coregui.client.bundle.version.file; import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.types.AutoFitWidthApproach; +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.bundle.BundleFile; +import org.rhq.core.domain.content.PackageVersion; import org.rhq.core.domain.criteria.BundleFileCriteria; import org.rhq.core.domain.measurement.MeasurementUnits; import org.rhq.core.domain.util.PageList; @@ -43,6 +46,13 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class FileListView extends LocatableVLayout {
+ private static final String ID = "id"; + private static final String NAME = "name"; + private static final String FILESIZE = "fileSize"; + private static final String MD5 = "md5"; + private static final String SHA256 = "sha256"; + private static final String VERSION = "version"; + private int bundleVersionId;
public FileListView(String locatorId, int bundleVersionId) { @@ -54,20 +64,32 @@ public class FileListView extends LocatableVLayout {
Table table = new Table(extendLocatorId("BundleFiles"), MSG.view_bundle_bundleFiles());
- ListGridField id = new ListGridField("id", MSG.common_title_id()); - id.setWidth("20%"); - - ListGridField name = new ListGridField("name", MSG.common_title_name()); - name.setWidth("60%"); + ListGridField id = new ListGridField(ID, MSG.common_title_id()); + ListGridField name = new ListGridField(NAME, MSG.common_title_name()); + ListGridField size = new ListGridField(FILESIZE, MSG.view_bundle_fileListView_fileSize()); + //ListGridField md5 = new ListGridField(MD5, MSG.view_bundle_fileListView_md5()); + ListGridField sha256 = new ListGridField(SHA256, MSG.view_bundle_fileListView_sha256()); + ListGridField version = new ListGridField(VERSION, MSG.common_title_version());
- ListGridField size = new ListGridField("size", MSG.view_bundle_fileListView_fileSize()); - name.setWidth("20%"); + id.setWidth("50"); + setAutoFitOnField(name); + setAutoFitOnField(size); + //setAutoFitOnField(md5); + setAutoFitOnField(sha256); + setAutoFitOnField(version);
// To get the ListGrid the Table must be initialized (via onInit()) by adding to the Canvas addMember(table); - table.getListGrid().setFields(id, name, size); - table.getListGrid().setData(buildRecords(files));
+ ListGrid listGrid = table.getListGrid(); + listGrid.setFields(id, name, size, /*md5,*/sha256, version); // today, we don't set md5, no sense showing it + listGrid.setData(buildRecords(files)); + table.setTableActionDisableOverride(true); + } + + private void setAutoFitOnField(ListGridField field) { + field.setAutoFitWidth(true); + field.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH); }
@Override @@ -96,17 +118,27 @@ public class FileListView extends LocatableVLayout { int i = 0; for (BundleFile file : files) { ListGridRecord record = new ListGridRecord(); - record.setAttribute("id", file.getId()); - record.setAttribute("name", file.getPackageVersion().getFileName()); + PackageVersion packageVersion = file.getPackageVersion(); + + record.setAttribute(ID, file.getId()); + record.setAttribute(NAME, returnValueOrUnknown(packageVersion.getFileName())); + record.setAttribute(MD5, returnValueOrUnknown(packageVersion.getMD5())); + record.setAttribute(SHA256, returnValueOrUnknown(packageVersion.getSHA256())); + record.setAttribute(VERSION, returnValueOrUnknown(packageVersion.getVersion()));
- Long size = file.getPackageVersion().getFileSize(); + Long size = packageVersion.getFileSize(); if (size != null) { - record.setAttribute("size", MeasurementConverterClient.format(size.doubleValue(), + record.setAttribute(FILESIZE, MeasurementConverterClient.format(size.doubleValue(), MeasurementUnits.BYTES, true)); + } else { + record.setAttribute(FILESIZE, MSG.common_val_na()); } records[i++] = record; } return records; }
+ private String returnValueOrUnknown(String val) { + return (val != null && val.length() > 0) ? val : MSG.common_val_na(); + } } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index de1ef89..b0ceaf9 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -902,6 +902,8 @@ view_bundle_versions = Versions
# individual bundle views/wizards view_bundle_fileListView_fileSize = File Size +view_bundle_fileListView_md5 = MD5 +view_bundle_fileListView_sha256 = SHA256 view_bundle_fileListView_loadFailure = Failed to load bundle file data view_bundle_version_backToBundle = Back to Bundle view_bundle_version_bundleVersionTagUpdateFailure = Failed to update bundle version tags
commit 9a7672945dc3c4890b2d491e91a6c36fc633b37a Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 17 17:25:26 2010 +0100
BZ 658491. Keep the direct path insert for the values as there is no reading from the same table involved.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java index 0c38451..25778fd 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java @@ -88,7 +88,7 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi + "(schedule_id, call_destination) " + "SELECT ?, ? FROM RHQ_numbers WHERE i = 42 " + "AND NOT EXISTS (SELECT * FROM " + DATA_KEY_TABLE_NAME + " WHERE schedule_id = ? AND call_destination = ?)";
- private static final String CALLTIME_VALUE_INSERT_STATEMENT = "INSERT INTO " + DATA_VALUE_TABLE_NAME + private static final String CALLTIME_VALUE_INSERT_STATEMENT = "INSERT /*+ APPEND */ INTO " + DATA_VALUE_TABLE_NAME + "(id, key_id, begin_time, end_time, minimum, maximum, total, count) " + "SELECT %s, key.id, ?, ?, ?, ?, ?, ? FROM RHQ_numbers num, RHQ_calltime_data_key key WHERE num.i = 42 " + "AND key.id = (SELECT id FROM " + DATA_KEY_TABLE_NAME + " WHERE schedule_id = ? AND call_destination = ?)";
commit 19c306bc1906f6777a5273e61ec20c7ed4c3b9a7 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 17 17:18:05 2010 +0100
Do a flush() to force writing stuff to the DB.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java index 6a09934..734f1df 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementDataManagerTest.java @@ -22,11 +22,7 @@ import java.util.Date; import java.util.Random;
import javax.persistence.EntityManager; -import javax.transaction.Status;
-import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
@@ -49,7 +45,6 @@ import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.measurement.CallTimeDataManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementDataManagerLocal; -import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.util.LookupUtil;
@@ -60,23 +55,18 @@ import org.rhq.enterprise.server.util.LookupUtil;
public class MeasurementDataManagerTest extends AbstractEJB3Test {
- private final Log log = LogFactory.getLog(MeasurementDataManagerTest.class); - - private ResourceManagerLocal resourceManager; private MeasurementDataManagerLocal measurementDataManager; private CallTimeDataManagerLocal callTimeDataManager;
private Subject overlord;
private Resource resource1,resource2; - private ResourceType theResourceType; - private Agent theAgent; - private MeasurementDefinition theDefinition; + private MeasurementDefinition definitionCt1; + private MeasurementDefinition definitionCt2;
@BeforeMethod public void beforeMethod() { try { - this.resourceManager = LookupUtil.getResourceManager(); this.measurementDataManager = LookupUtil.getMeasurementDataManager(); this.callTimeDataManager = LookupUtil.getCallTimeDataManager(); this.overlord = LookupUtil.getSubjectManager().getOverlord(); @@ -96,8 +86,18 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { try { setupResources(em);
- MeasurementSchedule schedule1 = resource1.getSchedules().iterator().next(); - MeasurementSchedule schedule2 = resource2.getSchedules().iterator().next(); + MeasurementSchedule schedule1 = new MeasurementSchedule(definitionCt1,resource1); + em.persist(schedule1); + definitionCt1.addSchedule(schedule1); + resource1.addSchedule(schedule1); + + MeasurementSchedule schedule2 = new MeasurementSchedule(definitionCt1,resource2); + em.persist(schedule2); + definitionCt1.addSchedule(schedule2); + resource2.addSchedule(schedule2); + + em.flush(); + MeasurementScheduleRequest request1 = new MeasurementScheduleRequest(schedule1); MeasurementScheduleRequest request2 = new MeasurementScheduleRequest(schedule2);
@@ -113,6 +113,66 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test {
measurementDataManager.mergeMeasurementReport(report);
+ em.flush(); + + PageList<CallTimeDataComposite> list1 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule1.getId(), + 0,System.currentTimeMillis(),new PageControl()); + PageList<CallTimeDataComposite> list2 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule2.getId(), + 0,System.currentTimeMillis(),new PageControl()); + + assert list1 != null; + assert list2 != null; + + assert list1.size() == 1 : "List 1 returned " + list1.size() + " entries, expected was 1"; + assert list2.size() == 1 : "List 2 returned " + list2.size() + " entries, expected was 1"; + + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + if (em != null) { + getTransactionManager().rollback(); + em.close(); + } + } + } + + @Test(enabled = false) + public void bz658491OneResource() throws Exception { + EntityManager em = beginTx(); + + try { + setupResources(em); + + MeasurementSchedule schedule1 = new MeasurementSchedule(definitionCt1,resource1); + em.persist(schedule1); + definitionCt1.addSchedule(schedule1); + resource1.addSchedule(schedule1); + + MeasurementSchedule schedule2 = new MeasurementSchedule(definitionCt2,resource1); + em.persist(schedule2); + definitionCt1.addSchedule(schedule2); + resource2.addSchedule(schedule2); + + em.flush(); + + MeasurementScheduleRequest request1 = new MeasurementScheduleRequest(schedule1); + MeasurementScheduleRequest request2 = new MeasurementScheduleRequest(schedule2); + + CallTimeData data1 = new CallTimeData(request1); + CallTimeData data2 = new CallTimeData(request2); + + data1.addCallData("/foo", new Date(),100); + data2.addCallData("/bar", new Date(),200); + + MeasurementReport report = new MeasurementReport(); + report.addData(data1); + report.addData(data2); + + measurementDataManager.mergeMeasurementReport(report); + + em.flush();
PageList<CallTimeDataComposite> list1 = callTimeDataManager.findCallTimeDataForResource(overlord,schedule1.getId(), 0,System.currentTimeMillis(),new PageControl()); @@ -139,23 +199,27 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test {
/** - * Just set up a resource where we can attach the availabilities to + * Just set up two resources plus measurement definitions * * @param em The EntityManager to use * - * @return A Resource ready to use */ private void setupResources(EntityManager em) { - theAgent = new Agent("testagent", "localhost", 1234, "", "randomToken"); + Agent theAgent = new Agent("testagent", "localhost", 1234, "", "randomToken"); em.persist(theAgent);
- theResourceType = new ResourceType("test-plat", "test-plugin", ResourceCategory.PLATFORM, null); + ResourceType theResourceType = new ResourceType("test-plat", "test-plugin", ResourceCategory.PLATFORM, null); em.persist(theResourceType);
- theDefinition = new MeasurementDefinition("CT-Def", MeasurementCategory.PERFORMANCE, + definitionCt1 = new MeasurementDefinition("CT-Def1", MeasurementCategory.PERFORMANCE, + MeasurementUnits.MILLISECONDS, DataType.CALLTIME,true,60000, DisplayType.SUMMARY); + definitionCt1.setResourceType(theResourceType); + em.persist(definitionCt1); + + definitionCt2 = new MeasurementDefinition("CT-Def2", MeasurementCategory.PERFORMANCE, MeasurementUnits.MILLISECONDS, DataType.CALLTIME,true,60000, DisplayType.SUMMARY); - theDefinition.setResourceType(theResourceType); - em.persist(theDefinition); + definitionCt2.setResourceType(theResourceType); + em.persist(definitionCt2);
resource1 = new Resource("test-platform-key1", "test-platform-name", theResourceType); @@ -166,18 +230,6 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { resource2.setUuid("" + new Random().nextInt()); resource2.setAgent(theAgent); em.persist(resource2); - - MeasurementSchedule schedule1 = new MeasurementSchedule(theDefinition,resource1); - em.persist(schedule1); - theDefinition.addSchedule(schedule1); - resource1.addSchedule(schedule1); - - MeasurementSchedule schedule2 = new MeasurementSchedule(theDefinition,resource2); - em.persist(schedule2); - theDefinition.addSchedule(schedule2); - resource2.addSchedule(schedule2); - - em.flush(); }
private EntityManager beginTx() throws Exception { @@ -185,5 +237,4 @@ public class MeasurementDataManagerTest extends AbstractEJB3Test { EntityManager em = getEntityManager(); return em; } - }
commit f37a519a58108a372062745ff4b9d10b01cce7e7 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 17 16:38:12 2010 +0100
Revert previous change and remove the direct path inserts.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java index 2c76232..0c38451 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java @@ -80,7 +80,7 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi private static final String DATA_VALUE_TABLE_NAME = "RHQ_CALLTIME_DATA_VALUE"; private static final String DATA_KEY_TABLE_NAME = "RHQ_CALLTIME_DATA_KEY";
- private static final String CALLTIME_KEY_INSERT_STATEMENT = "INSERT /*+ APPEND */ INTO " + DATA_KEY_TABLE_NAME + private static final String CALLTIME_KEY_INSERT_STATEMENT = "INSERT INTO " + DATA_KEY_TABLE_NAME + "(id, schedule_id, call_destination) " + "SELECT %s, ?, ? FROM RHQ_numbers WHERE i = 42 " + "AND NOT EXISTS (SELECT * FROM " + DATA_KEY_TABLE_NAME + " WHERE schedule_id = ? AND call_destination = ?)";
@@ -88,7 +88,7 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi + "(schedule_id, call_destination) " + "SELECT ?, ? FROM RHQ_numbers WHERE i = 42 " + "AND NOT EXISTS (SELECT * FROM " + DATA_KEY_TABLE_NAME + " WHERE schedule_id = ? AND call_destination = ?)";
- private static final String CALLTIME_VALUE_INSERT_STATEMENT = "INSERT /*+ APPEND */ INTO " + DATA_VALUE_TABLE_NAME + private static final String CALLTIME_VALUE_INSERT_STATEMENT = "INSERT INTO " + DATA_VALUE_TABLE_NAME + "(id, key_id, begin_time, end_time, minimum, maximum, total, count) " + "SELECT %s, key.id, ?, ?, ?, ?, ?, ? FROM RHQ_numbers num, RHQ_calltime_data_key key WHERE num.i = 42 " + "AND key.id = (SELECT id FROM " + DATA_KEY_TABLE_NAME + " WHERE schedule_id = ? AND call_destination = ?)"; @@ -316,26 +316,25 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi for (String callDestination : callDestinations) { ps.setString(2, callDestination); ps.setString(4, callDestination); -// ps.addBatch(); - ps.execute(); + ps.addBatch(); } }
-// results = ps.executeBatch(); + results = ps.executeBatch();
int insertedRowCount = 0; -// for (int i = 0; i < results.length; i++) { -// if (((results[i] < 0) || (results[i] > 1)) && (results[i] != -2)) // oracle returns -2 because it can't count updated rows -// { -// throw new MeasurementStorageException("Failed to insert call-time data key rows - result [" -// + results[i] + "] for batch command [" + i + "] is less than 0 or greater than 1."); -// } -// -// insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row -// } - -// log.debug("Inserted new call-time data key rows for " + ((insertedRowCount >= 0) ? insertedRowCount : "?") -// + " out of " + results.length + " reported key-value pairs."); + for (int i = 0; i < results.length; i++) { + if (((results[i] < 0) || (results[i] > 1)) && (results[i] != -2)) // oracle returns -2 because it can't count updated rows + { + throw new MeasurementStorageException("Failed to insert call-time data key rows - result [" + + results[i] + "] for batch command [" + i + "] is less than 0 or greater than 1."); + } + + insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row + } + + log.debug("Inserted new call-time data key rows for " + ((insertedRowCount >= 0) ? insertedRowCount : "?") + + " out of " + results.length + " reported key-value pairs."); } catch (SQLException e) { logSQLException("Failed to persist call-time data keys", e); } catch (Throwable t) { @@ -393,23 +392,22 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi ps.setDouble(5, callTimeDataValue.getTotal()); ps.setLong(6, callTimeDataValue.getCount()); ps.setString(8, callDestination); -// ps.addBatch(); - ps.execute(); + ps.addBatch(); } }
-// results = ps.executeBatch(); + results = ps.executeBatch();
int insertedRowCount = 0; -// for (int i = 0; i < results.length; i++) { -// if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts -// { -// throw new MeasurementStorageException("Failed to insert call-time data value rows - result [" -// + results[i] + "] for batch command [" + i + "] does not equal 1."); -// } -// -// insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row; -// } + for (int i = 0; i < results.length; i++) { + if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts + { + throw new MeasurementStorageException("Failed to insert call-time data value rows - result [" + + results[i] + "] for batch command [" + i + "] does not equal 1."); + } + + insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row; + }
notifyAlertConditionCacheManager("insertCallTimeDataValues", callTimeDataSet .toArray(new CallTimeData[callTimeDataSet.size()]));
commit 2bbb4cf551c52288216a1d6ad3e1a43d44c320e3 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 17 15:30:53 2010 +0100
Replace batching by individual statements. Related to BZ 658491
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java index df8fbd2..2c76232 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/CallTimeDataManagerBean.java @@ -316,25 +316,26 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi for (String callDestination : callDestinations) { ps.setString(2, callDestination); ps.setString(4, callDestination); - ps.addBatch(); +// ps.addBatch(); + ps.execute(); } }
- results = ps.executeBatch(); +// results = ps.executeBatch();
int insertedRowCount = 0; - for (int i = 0; i < results.length; i++) { - if (((results[i] < 0) || (results[i] > 1)) && (results[i] != -2)) // oracle returns -2 because it can't count updated rows - { - throw new MeasurementStorageException("Failed to insert call-time data key rows - result [" - + results[i] + "] for batch command [" + i + "] is less than 0 or greater than 1."); - } - - insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row - } - - log.debug("Inserted new call-time data key rows for " + ((insertedRowCount >= 0) ? insertedRowCount : "?") - + " out of " + results.length + " reported key-value pairs."); +// for (int i = 0; i < results.length; i++) { +// if (((results[i] < 0) || (results[i] > 1)) && (results[i] != -2)) // oracle returns -2 because it can't count updated rows +// { +// throw new MeasurementStorageException("Failed to insert call-time data key rows - result [" +// + results[i] + "] for batch command [" + i + "] is less than 0 or greater than 1."); +// } +// +// insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row +// } + +// log.debug("Inserted new call-time data key rows for " + ((insertedRowCount >= 0) ? insertedRowCount : "?") +// + " out of " + results.length + " reported key-value pairs."); } catch (SQLException e) { logSQLException("Failed to persist call-time data keys", e); } catch (Throwable t) { @@ -392,22 +393,23 @@ public class CallTimeDataManagerBean implements CallTimeDataManagerLocal, CallTi ps.setDouble(5, callTimeDataValue.getTotal()); ps.setLong(6, callTimeDataValue.getCount()); ps.setString(8, callDestination); - ps.addBatch(); +// ps.addBatch(); + ps.execute(); } }
- results = ps.executeBatch(); +// results = ps.executeBatch();
int insertedRowCount = 0; - for (int i = 0; i < results.length; i++) { - if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts - { - throw new MeasurementStorageException("Failed to insert call-time data value rows - result [" - + results[i] + "] for batch command [" + i + "] does not equal 1."); - } - - insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row; - } +// for (int i = 0; i < results.length; i++) { +// if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts +// { +// throw new MeasurementStorageException("Failed to insert call-time data value rows - result [" +// + results[i] + "] for batch command [" + i + "] does not equal 1."); +// } +// +// insertedRowCount += results[i]==-2 ? 1 : results[i] ; // If Oracle returns -2, just count 1 row; +// }
notifyAlertConditionCacheManager("insertCallTimeDataValues", callTimeDataSet .toArray(new CallTimeData[callTimeDataSet.size()]));
commit a3ff39c9c4a1a1e751ce951723d3d04192ab5d21 Merge: b5a1378... aa14f1b... Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 17 13:57:01 2010 +0100
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit b5a137896221a3f6980d31ed35fe9d09ffbd21f1 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 17 13:44:26 2010 +0100
Provide less aggressive settings.
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 df3cdbc..2975ccd 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 @@ -314,9 +314,9 @@ <metric property="metric002" defaultOn="true" displayType="summary" defaultInterval="720000"/> <metric property="metric003" defaultOn="true" displayType="summary" defaultInterval="600000"/> <metric property="metric004" defaultOn="true" displayType="summary" defaultInterval="600000"/> - <metric property="trait001" defaultOn="true" dataType="trait" displayType="summary" defaultInterval="1200000"/> - <metric property="trait002" defaultOn="true" dataType="trait" displayType="summary" defaultInterval="1440000"/> - <metric displayName="CallTime" property="calltime" defaultOn="true" dataType="calltime" defaultInterval="1200000" units="milliseconds"/> + <metric property="trait001" defaultOn="true" dataType="trait" displayType="summary" defaultInterval="3600000"/> + <metric property="trait002" defaultOn="true" dataType="trait" displayType="summary" defaultInterval="2400000"/> + <metric displayName="CallTime" property="calltime" defaultOn="true" dataType="calltime" defaultInterval="2400000" units="milliseconds"/> <event name="PerfTestEventType" description="a test event type"/> </service> </server> diff --git a/modules/plugins/perftest/src/main/resources/configurable-5.xml b/modules/plugins/perftest/src/main/resources/configurable-5.xml index c3f68b4..889b2b2 100644 --- a/modules/plugins/perftest/src/main/resources/configurable-5.xml +++ b/modules/plugins/perftest/src/main/resources/configurable-5.xml @@ -23,9 +23,9 @@ <simpleNumericMeasurementGenerator/> <simpleTraitMeasurementGenerator/> <ConfigurableCallTimeDataGenerator - minMsgCount="1" maxMsgCount="500" + minMsgCount="1" maxMsgCount="100" minDuration="10" maxDuration="500" - numberSubPaths="100"/> + numberSubPaths="10"/> </resource>
</scenario>
commit aa14f1b66731c4a3c4af55be772c8a0da611ad73 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 03:51:13 2010 -0500
get more perms so non-auth user can't get to deployments
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java index 147aaf0..a2412d5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java @@ -47,8 +47,11 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; */ public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployment>> {
- public BundleDeploymentListView(String locatorId, Criteria criteria) { + private final boolean canManageBundles; + + public BundleDeploymentListView(String locatorId, Criteria criteria, boolean canManageBundles) { super(locatorId, MSG.view_bundle_bundleDeployments(), criteria); + this.canManageBundles = canManageBundles; setDataSource(new BundleDeploymentDataSource()); setHeaderIcon("subsystems/bundle/BundleDeployment_24.png"); } @@ -70,14 +73,18 @@ public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployme deployTimeField.setType(ListGridFieldType.DATE); deployTimeField.setDateFormatter(DateDisplayFormat.TOLOCALESTRING);
- nameField.setCellFormatter(new CellFormatter() { - public String format(Object o, ListGridRecord record, int i, int i1) { - return "<a href="" - + LinkManager.getBundleDeploymentLink(record - .getAttributeAsInt(BundleDeploymentDataSource.FIELD_BUNDLE_ID), record - .getAttributeAsInt(BundleDeploymentDataSource.FIELD_ID)) + "">" + String.valueOf(o) + "</a>"; - } - }); + // only users that are authorized can see deployments + if (canManageBundles) { + nameField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord record, int i, int i1) { + return "<a href="" + + LinkManager.getBundleDeploymentLink(record + .getAttributeAsInt(BundleDeploymentDataSource.FIELD_BUNDLE_ID), record + .getAttributeAsInt(BundleDeploymentDataSource.FIELD_ID)) + "">" + String.valueOf(o) + + "</a>"; + } + }); + }
bundleVersionField.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord record, int i, int i1) { @@ -116,7 +123,7 @@ public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployme if (selectedRows != null && selectedRows.length == 1) { String selectedId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_BUNDLE_ID); String selectedVersionId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_ID); - CoreGUI.goToView(LinkManager.getBundleDestinationLink(Integer.valueOf(selectedId), Integer + CoreGUI.goToView(LinkManager.getBundleDeploymentLink(Integer.valueOf(selectedId), Integer .valueOf(selectedVersionId))); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index b4aaba8..c298b35 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -197,7 +197,8 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka private Table createDeploymentsTable() { Criteria criteria = new Criteria(); criteria.addCriteria("bundleDestinationId", destination.getId()); - BundleDeploymentListView deployments = new BundleDeploymentListView(extendLocatorId("Deployments"), criteria); + BundleDeploymentListView deployments = new BundleDeploymentListView(extendLocatorId("Deployments"), criteria, + canManageBundles); deployments.setHeight100(); deployments.setShowResizeBar(true); return deployments; 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 36968e8..b567a0a 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 @@ -100,10 +100,10 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { BundleTopView.VIEW_ID.getTitle()); headerLabel = new HeaderLabel("subsystems/bundle/Bundle_24.png", bundle.getName()); tabs = new LocatableTabSet(getLocatorId()); - destinationsTab = createDestinationsTab(); versionsTab = createVersionsTab(); - tabs.addTab(destinationsTab); + destinationsTab = createDestinationsTab(); tabs.addTab(versionsTab); + tabs.addTab(destinationsTab);
addMember(backButton); addMember(headerLabel); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java index e3e8567..ad55799 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java @@ -169,7 +169,8 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV Criteria criteria = new Criteria(); criteria.setAttribute("bundleVersionId", version.getId());
- tab.setPane(new BundleDeploymentListView(tab.getLocatorId(), criteria)); + // TODO: get user perm, if has manage_bundle, pass true + tab.setPane(new BundleDeploymentListView(tab.getLocatorId(), criteria, false));
return tab; } 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 7192f94..2517d3e 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 @@ -110,7 +110,9 @@ public class TaggedView extends LocatableVLayout implements BookmarkableView { tab.setPane(bundleVersionListView); container.addTab(tab);
- BundleDeploymentListView bundleDeploymentListView = new BundleDeploymentListView(getLocatorId(), criteria); + // TODO: get manage_bundle perm, if user has it pass true + BundleDeploymentListView bundleDeploymentListView = new BundleDeploymentListView(getLocatorId(), criteria, + false); viewsWithTags.add(bundleDeploymentListView); tab = new LocatableTab(extendLocatorId("bundleDeploymentsList"), MSG.view_bundle_bundleDeployments()); tab.setPane(bundleDeploymentListView);
commit cb37fdd5b2b814f32b0f92f9e7782f13cce9ee89 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 03:27:07 2010 -0500
more cleanup of the bundle views
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 49395c0..c7cc475 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 @@ -323,4 +323,16 @@ public class LinkManager { public static String getBundleLink(int bundleId) { return "#Bundles/Bundle/" + bundleId; } + + public static String getBundleVersionLink(int bundleId, int bundleVersionId) { + return "#Bundles/Bundle/" + bundleId + "/versions/" + bundleVersionId; + } + + public static String getBundleDestinationLink(int bundleId, int bundleDestinationId) { + return "#Bundles/Bundle/" + bundleId + "/destinations/" + bundleDestinationId; + } + + public static String getBundleDeploymentLink(int bundleId, int bundleDeploymentId) { + return "#Bundles/Bundle/" + bundleId + "/deployments/" + bundleDeploymentId; + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java index 48f6849..5e94e47 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentDataSource.java @@ -48,6 +48,18 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; */ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment> {
+ public static final String FIELD_ID = "id"; + public static final String FIELD_NAME = "name"; + public static final String FIELD_DEPLOY_DIR = "deployDir"; + public static final String FIELD_DESCRIPTION = "description"; + public static final String FIELD_DEPLOY_TIME = "deploymentTime"; + public static final String FIELD_CONFIG = "configuration"; + public static final String FIELD_STATUS = "status"; + public static final String FIELD_DEPLOYER = "deployer"; // a user name + public static final String FIELD_BUNDLE_VERSION_VERSION = "bundleVersionVersion"; + public static final String FIELD_BUNDLE_VERSION_ID = "bundleVersionId"; + public static final String FIELD_BUNDLE_ID = "bundleId"; + private BundleGWTServiceAsync bundleService = GWTServiceLookup.getBundleService();
public BundleDeploymentDataSource() { @@ -60,24 +72,24 @@ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment> protected List<DataSourceField> addDataSourceFields() { List<DataSourceField> fields = super.addDataSourceFields();
- DataSourceIntegerField id = new DataSourceIntegerField("id", MSG.common_title_id()); + DataSourceIntegerField id = new DataSourceIntegerField(FIELD_ID, MSG.common_title_id()); id.setPrimaryKey(true); fields.add(id);
- DataSourceTextField name = new DataSourceTextField("name", MSG.view_bundle_deploy_name()); + DataSourceTextField name = new DataSourceTextField(FIELD_NAME, MSG.view_bundle_deploy_name()); fields.add(name);
- DataSourceTextField bundleVersion = new DataSourceTextField("bundleVersionVersion", MSG + DataSourceTextField bundleVersion = new DataSourceTextField(FIELD_BUNDLE_VERSION_VERSION, MSG .view_bundle_bundleVersion()); fields.add(bundleVersion);
- DataSourceTextField description = new DataSourceTextField("description", MSG.common_title_description()); + DataSourceTextField description = new DataSourceTextField(FIELD_DESCRIPTION, MSG.common_title_description()); fields.add(description);
- DataSourceTextField status = new DataSourceTextField("status", MSG.common_title_status()); + DataSourceTextField status = new DataSourceTextField(FIELD_STATUS, MSG.common_title_status()); fields.add(status);
- DataSourceDateTimeField created = new DataSourceDateTimeField("deploymentTime", MSG.view_bundle_deploy_time()); + DataSourceDateTimeField created = new DataSourceDateTimeField(FIELD_DEPLOY_TIME, MSG.view_bundle_deploy_time()); fields.add(created);
return fields; @@ -88,12 +100,13 @@ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment> BundleDeploymentCriteria criteria = new BundleDeploymentCriteria(); criteria.fetchBundleVersion(true);
- if (request.getCriteria().getValues().containsKey("bundleId")) { - criteria.addFilterBundleId(Integer.parseInt(request.getCriteria().getAttribute("bundleId"))); + if (request.getCriteria().getValues().containsKey(FIELD_BUNDLE_ID)) { + criteria.addFilterBundleId(Integer.parseInt(request.getCriteria().getAttribute(FIELD_BUNDLE_ID))); }
- if (request.getCriteria().getValues().containsKey("bundleVersionId")) { - criteria.addFilterBundleVersionId(Integer.parseInt(request.getCriteria().getAttribute("bundleVersionId"))); + if (request.getCriteria().getValues().containsKey(FIELD_BUNDLE_VERSION_ID)) { + criteria.addFilterBundleVersionId(Integer.parseInt(request.getCriteria().getAttribute( + FIELD_BUNDLE_VERSION_ID))); }
if (request.getCriteria().getValues().containsKey("bundleDestinationId")) { @@ -128,7 +141,7 @@ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment>
@Override public BundleDeployment copyValues(Record from) { - return null; // TODO: Implement this method. + return (BundleDeployment) from.getAttributeAsObject("object"); }
@Override @@ -136,24 +149,26 @@ public class BundleDeploymentDataSource extends RPCDataSource<BundleDeployment>
ListGridRecord record = new ListGridRecord();
- record.setAttribute("id", from.getId()); - record.setAttribute("name", from.getName()); - record.setAttribute("deployDir", from.getDestination().getDeployDir()); - record.setAttribute("description", from.getDescription()); - record.setAttribute("deploymentTime", new Date(from.getCtime())); - record.setAttribute("configuration", from.getConfiguration()); - record.setAttribute("status", from.getStatus().name()); - record.setAttribute("deployer", from.getSubjectName()); + record.setAttribute(FIELD_ID, from.getId()); + record.setAttribute(FIELD_NAME, from.getName()); + record.setAttribute(FIELD_DEPLOY_DIR, from.getDestination().getDeployDir()); + record.setAttribute(FIELD_DESCRIPTION, from.getDescription()); + record.setAttribute(FIELD_DEPLOY_TIME, new Date(from.getCtime())); + record.setAttribute(FIELD_CONFIG, from.getConfiguration()); + record.setAttribute(FIELD_STATUS, from.getStatus().name()); + record.setAttribute(FIELD_DEPLOYER, from.getSubjectName());
if (from.getBundleVersion() != null) { - record.setAttribute("bundleVersionVersion", from.getBundleVersion().getVersion()); - record.setAttribute("bundleVersionId", from.getBundleVersion().getId()); + record.setAttribute(FIELD_BUNDLE_VERSION_VERSION, from.getBundleVersion().getVersion()); + record.setAttribute(FIELD_BUNDLE_VERSION_ID, from.getBundleVersion().getId());
if (from.getBundleVersion().getBundle() != null) { - record.setAttribute("bundleId", from.getBundleVersion().getBundle().getId()); + record.setAttribute(FIELD_BUNDLE_ID, from.getBundleVersion().getBundle().getId()); } }
+ record.setAttribute("object", from); + return record; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java index 93a55a1..147aaf0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentListView.java @@ -25,17 +25,27 @@ package org.rhq.enterprise.gui.coregui.client.bundle.deployment; import java.util.HashMap;
import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.types.DateDisplayFormat; +import com.smartgwt.client.types.ListGridFieldType; +import com.smartgwt.client.widgets.events.DoubleClickEvent; +import com.smartgwt.client.widgets.events.DoubleClickHandler; import com.smartgwt.client.widgets.grid.CellFormatter; +import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
+import org.rhq.core.domain.bundle.BundleDeployment; import org.rhq.core.domain.bundle.BundleDeploymentStatus; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; +import org.rhq.enterprise.gui.coregui.client.bundle.list.BundleVersionDataSource; import org.rhq.enterprise.gui.coregui.client.components.table.Table; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource;
/** * @author Greg Hinkle */ -public class BundleDeploymentListView extends Table { +public class BundleDeploymentListView extends Table<RPCDataSource<BundleDeployment>> {
public BundleDeploymentListView(String locatorId, Criteria criteria) { super(locatorId, MSG.view_bundle_bundleDeployments(), criteria); @@ -45,37 +55,71 @@ public class BundleDeploymentListView extends Table {
@Override protected void configureTable() { - getListGrid().getField("id").setWidth("60"); - getListGrid().getField("name").setWidth("25%"); - getListGrid().getField("name").setCellFormatter(new CellFormatter() { + ListGridField idField = new ListGridField(BundleDeploymentDataSource.FIELD_ID, MSG.common_title_id()); + ListGridField nameField = new ListGridField(BundleDeploymentDataSource.FIELD_NAME, MSG + .view_bundle_deploy_name()); + ListGridField descriptionField = new ListGridField(BundleDeploymentDataSource.FIELD_DESCRIPTION, MSG + .common_title_description()); + ListGridField bundleVersionField = new ListGridField(BundleDeploymentDataSource.FIELD_BUNDLE_VERSION_VERSION, + MSG.view_bundle_bundleVersion()); + ListGridField statusField = new ListGridField(BundleDeploymentDataSource.FIELD_STATUS, MSG + .common_title_status()); + ListGridField deployTimeField = new ListGridField(BundleDeploymentDataSource.FIELD_DEPLOY_TIME, MSG + .view_bundle_deploy_time()); + + deployTimeField.setType(ListGridFieldType.DATE); + deployTimeField.setDateFormatter(DateDisplayFormat.TOLOCALESTRING); + + nameField.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord record, int i, int i1) { - return "<a href="#Bundles/Bundle/" + record.getAttribute("bundleId") + "/deployments/" - + record.getAttribute("id") + "">" + String.valueOf(o) + "</a>"; + return "<a href="" + + LinkManager.getBundleDeploymentLink(record + .getAttributeAsInt(BundleDeploymentDataSource.FIELD_BUNDLE_ID), record + .getAttributeAsInt(BundleDeploymentDataSource.FIELD_ID)) + "">" + String.valueOf(o) + "</a>"; } });
- getListGrid().getField("bundleVersionVersion").setWidth("80"); - getListGrid().getField("bundleVersionVersion").setCellFormatter(new CellFormatter() { - public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - return "<a href="#Bundles/Bundle/" + listGridRecord.getAttribute("bundleId") + "/versions/" - + listGridRecord.getAttribute("bundleVersionId") + "">" + o + "</a>"; + bundleVersionField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord record, int i, int i1) { + return "<a href="" + + LinkManager.getBundleVersionLink(record + .getAttributeAsInt(BundleDeploymentDataSource.FIELD_BUNDLE_ID), record + .getAttributeAsInt(BundleDeploymentDataSource.FIELD_BUNDLE_VERSION_ID)) + "">" + + String.valueOf(o) + "</a>"; } });
- getListGrid().getField("description").setWidth("25%"); - getListGrid().getField("deploymentTime").setWidth("20%"); - getListGrid().getField("status").setWidth("25%"); - ListGridField status = getListGrid().getField("status"); HashMap<String, String> statusIcons = new HashMap<String, String>(); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); - statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); - status.setValueIcons(statusIcons); - status.setValueIconHeight(11); - status.setWidth(80); + statusField.setValueIcons(statusIcons); + statusField.setValueIconWidth(11); + statusField.setValueIconHeight(11);
+ idField.setWidth(50); + nameField.setWidth("30%"); + descriptionField.setWidth("40%"); + bundleVersionField.setWidth("15%"); + deployTimeField.setWidth("15%"); + statusField.setWidth(80);
+ setListGridFields(idField, nameField, descriptionField, bundleVersionField, deployTimeField, statusField); + + setListGridDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + ListGrid listGrid = (ListGrid) event.getSource(); + ListGridRecord[] selectedRows = listGrid.getSelection(); + if (selectedRows != null && selectedRows.length == 1) { + String selectedId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_BUNDLE_ID); + String selectedVersionId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_ID); + CoreGUI.goToView(LinkManager.getBundleDestinationLink(Integer.valueOf(selectedId), Integer + .valueOf(selectedVersionId))); + } + } + }); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationDataSource.java index d52538c..1a6f3dc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationDataSource.java @@ -49,6 +49,19 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; */ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination> {
+ public static final String FIELD_ID = "id"; + public static final String FIELD_NAME = "name"; + public static final String FIELD_DESCRIPTION = "description"; + public static final String FIELD_BUNDLE_ID = "bundleId"; + public static final String FIELD_BUNDLE_NAME = "bundleName"; + public static final String FIELD_GROUP_ID = "groupId"; + public static final String FIELD_GROUP_NAME = "groupName"; + public static final String FIELD_DEPLOY_DIR = "deployDir"; + public static final String FIELD_LATEST_DEPLOY_VERSION = "latestDeploymentVersion"; + public static final String FIELD_LATEST_DEPLOY_DATE = "latestDeploymentDate"; + public static final String FIELD_LATEST_DEPLOY_STATUS = "latestDeploymentStatus"; + public static final String FIELD_LATEST_DEPLOY = "latestDeployment"; + public BundleDestinationDataSource() { super(); List<DataSourceField> fields = addDataSourceFields(); @@ -59,34 +72,34 @@ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination protected List<DataSourceField> addDataSourceFields() { List<DataSourceField> fields = super.addDataSourceFields();
- DataSourceIntegerField idField = new DataSourceIntegerField("id", MSG.common_title_id()); + DataSourceIntegerField idField = new DataSourceIntegerField(FIELD_ID, MSG.common_title_id()); idField.setPrimaryKey(true); fields.add(idField);
- DataSourceTextField name = new DataSourceTextField("name", MSG.common_title_name()); + DataSourceTextField name = new DataSourceTextField(FIELD_NAME, MSG.common_title_name()); fields.add(name);
- DataSourceTextField description = new DataSourceTextField("description", MSG.common_title_description()); + DataSourceTextField description = new DataSourceTextField(FIELD_DESCRIPTION, MSG.common_title_description()); fields.add(description);
- DataSourceTextField bundle = new DataSourceTextField("bundleName", MSG.view_bundle_bundle()); + DataSourceTextField bundle = new DataSourceTextField(FIELD_BUNDLE_NAME, MSG.view_bundle_bundle()); fields.add(bundle);
- DataSourceTextField group = new DataSourceTextField("groupName", MSG.view_bundle_dest_group()); + DataSourceTextField group = new DataSourceTextField(FIELD_GROUP_NAME, MSG.view_bundle_dest_group()); fields.add(group);
- DataSourceTextField deployDir = new DataSourceTextField("deployDir", MSG.view_bundle_dest_deployDir()); + DataSourceTextField deployDir = new DataSourceTextField(FIELD_DEPLOY_DIR, MSG.view_bundle_dest_deployDir()); fields.add(deployDir);
- DataSourceTextField latestDeploymentVersion = new DataSourceTextField("latestDeploymentVersion", MSG + DataSourceTextField latestDeploymentVersion = new DataSourceTextField(FIELD_LATEST_DEPLOY_VERSION, MSG .view_bundle_dest_lastDeployedVersion()); fields.add(latestDeploymentVersion);
- DataSourceTextField latestDeploymentDate = new DataSourceTextField("latestDeploymentDate", MSG + DataSourceTextField latestDeploymentDate = new DataSourceTextField(FIELD_LATEST_DEPLOY_DATE, MSG .view_bundle_dest_lastDeploymentDate()); fields.add(latestDeploymentDate);
- DataSourceTextField latestDeploymentStatus = new DataSourceTextField("latestDeploymentStatus", MSG + DataSourceTextField latestDeploymentStatus = new DataSourceTextField(FIELD_LATEST_DEPLOY_STATUS, MSG .view_bundle_dest_lastDeploymentStatus()); fields.add(latestDeploymentStatus);
@@ -97,8 +110,8 @@ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination protected void executeFetch(final DSRequest request, final DSResponse response) { BundleDestinationCriteria criteria = new BundleDestinationCriteria();
- if (request.getCriteria().getValues().containsKey("bundleId")) { - criteria.addFilterBundleId(Integer.parseInt(request.getCriteria().getAttributeAsString("bundleId"))); + if (request.getCriteria().getValues().containsKey(FIELD_BUNDLE_ID)) { + criteria.addFilterBundleId(Integer.parseInt(request.getCriteria().getAttributeAsString(FIELD_BUNDLE_ID))); }
if (request.getCriteria().getValues().get("tagNamespace") != null) { @@ -125,11 +138,10 @@ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination }
public void onSuccess(final PageList<BundleDestination> result) { - BundleVersionCriteria versionCriteria = new BundleVersionCriteria(); - if (request.getCriteria().getValues().containsKey("bundleId")) { + if (request.getCriteria().getValues().containsKey(FIELD_BUNDLE_ID)) { versionCriteria.addFilterBundleId(Integer.parseInt(request.getCriteria().getAttributeAsString( - "bundleId"))); + FIELD_BUNDLE_ID))); } GWTServiceLookup.getBundleService().findBundleVersionsByCriteria(versionCriteria, new AsyncCallback<PageList<BundleVersion>>() { @@ -139,11 +151,8 @@ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination }
public void onSuccess(PageList<BundleVersion> versions) { - for (BundleDestination dest : result) { - for (BundleDeployment dep : dest.getDeployments()) { - for (BundleVersion version : versions) { if (dep.getBundleVersion().getId() == version.getId()) { dep.setBundleVersion(version); @@ -151,10 +160,8 @@ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination } } } - response.setData(buildRecords(result)); processResponse(request.getRequestId(), response); - } }); } @@ -163,35 +170,32 @@ public class BundleDestinationDataSource extends RPCDataSource<BundleDestination
@Override public BundleDestination copyValues(Record from) { - return null; + return (BundleDestination) from.getAttributeAsObject("object"); }
@Override public ListGridRecord copyValues(BundleDestination from) { ListGridRecord record = new ListGridRecord();
- record.setAttribute("id", from.getId()); - record.setAttribute("name", from.getName()); - record.setAttribute("description", from.getDescription()); - record.setAttribute("bundleId", from.getBundle().getId()); - record.setAttribute("bundleName", from.getBundle().getName()); - - record.setAttribute("groupId", from.getGroup().getId()); - record.setAttribute("groupName", from.getGroup().getName()); + record.setAttribute(FIELD_ID, from.getId()); + record.setAttribute(FIELD_NAME, from.getName()); + record.setAttribute(FIELD_DESCRIPTION, from.getDescription()); + record.setAttribute(FIELD_BUNDLE_ID, from.getBundle().getId()); + record.setAttribute(FIELD_BUNDLE_NAME, from.getBundle().getName()); + record.setAttribute(FIELD_GROUP_ID, from.getGroup().getId()); + record.setAttribute(FIELD_GROUP_NAME, from.getGroup().getName()); + record.setAttribute(FIELD_DEPLOY_DIR, from.getDeployDir());
- record.setAttribute("deployDir", from.getDeployDir()); - record.setAttribute("entity", from); + record.setAttribute("object", from);
long last = 0; for (BundleDeployment dep : from.getDeployments()) { if (last < dep.getCtime()) { last = dep.getCtime(); - - record.setAttribute("latestDeployment", dep); - record.setAttribute("latestDeploymentVersion", dep.getBundleVersion().getVersion()); - record.setAttribute("latestDeploymentDate", new Date(dep.getCtime())); - record.setAttribute("latestDeploymentStatus", dep.getStatus().name()); - + record.setAttribute(FIELD_LATEST_DEPLOY, dep); + record.setAttribute(FIELD_LATEST_DEPLOY_VERSION, dep.getBundleVersion().getVersion()); + record.setAttribute(FIELD_LATEST_DEPLOY_DATE, new Date(dep.getCtime())); + record.setAttribute(FIELD_LATEST_DEPLOY_STATUS, dep.getStatus().name()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java index f4052f7..5bfc174 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationListView.java @@ -25,17 +25,26 @@ package org.rhq.enterprise.gui.coregui.client.bundle.destination; import java.util.HashMap;
import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.types.DateDisplayFormat; +import com.smartgwt.client.types.ListGridFieldType; +import com.smartgwt.client.widgets.events.DoubleClickEvent; +import com.smartgwt.client.widgets.events.DoubleClickHandler; import com.smartgwt.client.widgets.grid.CellFormatter; +import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.bundle.BundleDeploymentStatus; +import org.rhq.core.domain.bundle.BundleDestination; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.components.table.Table; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource;
/** * @author Greg Hinkle */ -public class BundleDestinationListView extends Table { +public class BundleDestinationListView extends Table<RPCDataSource<BundleDestination>> {
public BundleDestinationListView(String locatorId) { this(locatorId, null); @@ -49,32 +58,84 @@ public class BundleDestinationListView extends Table {
@Override protected void configureTable() { - getListGrid().getField("id").setWidth(45); - getListGrid().getField("name").setWidth("20%"); - getListGrid().getField("name").setCellFormatter(new CellFormatter() { + ListGridField idField = new ListGridField(BundleDestinationDataSource.FIELD_ID, MSG.common_title_id()); + ListGridField nameField = new ListGridField(BundleDestinationDataSource.FIELD_NAME, MSG.common_title_name()); + ListGridField descriptionField = new ListGridField(BundleDestinationDataSource.FIELD_DESCRIPTION, MSG + .common_title_description()); + ListGridField bundleNameField = new ListGridField(BundleDestinationDataSource.FIELD_BUNDLE_NAME, MSG + .view_bundle_bundle()); + ListGridField groupNameField = new ListGridField(BundleDestinationDataSource.FIELD_GROUP_NAME, MSG + .view_bundle_dest_group()); + ListGridField deployDirField = new ListGridField(BundleDestinationDataSource.FIELD_DEPLOY_DIR, MSG + .view_bundle_dest_deployDir()); + ListGridField latestDeploymentVersionField = new ListGridField( + BundleDestinationDataSource.FIELD_LATEST_DEPLOY_VERSION, MSG.view_bundle_dest_lastDeployedVersion()); + ListGridField latestDeploymentDateField = new ListGridField( + BundleDestinationDataSource.FIELD_LATEST_DEPLOY_DATE, MSG.view_bundle_dest_lastDeploymentDate()); + ListGridField latestDeploymentStatusField = new ListGridField( + BundleDestinationDataSource.FIELD_LATEST_DEPLOY_STATUS, MSG.view_bundle_dest_lastDeploymentStatus()); + + latestDeploymentDateField.setType(ListGridFieldType.DATE); + latestDeploymentDateField.setDateFormatter(DateDisplayFormat.TOLOCALESTRING); + + nameField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { + Integer bundleId = listGridRecord.getAttributeAsInt(BundleDestinationDataSource.FIELD_BUNDLE_ID); + Integer bundleDestId = listGridRecord.getAttributeAsInt(BundleDestinationDataSource.FIELD_ID); + return "<a href="" + LinkManager.getBundleDestinationLink(bundleId, bundleDestId) + "">" + o + "</a>"; + } + }); + + groupNameField.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - return "<a href="#Bundles/Bundles/" + listGridRecord.getAttribute("bundleId") + "/destinations/" - + listGridRecord.getAttribute("id") + "">" + o + "</a>"; + Integer groupId = listGridRecord.getAttributeAsInt(BundleDestinationDataSource.FIELD_GROUP_ID); + return "<a href="" + LinkManager.getResourceGroupLink(groupId) + "">" + o + "</a>"; } });
- getListGrid().getField("description").setWidth("15%"); - //getListGrid().getField("bundleName").setWidth("20%"); - getListGrid().hideField("bundleName"); - getListGrid().getField("groupName").setWidth("15%"); - getListGrid().getField("deployDir").setWidth("15%"); + bundleNameField.setCellFormatter(new CellFormatter() { + public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { + Integer bid = listGridRecord.getAttributeAsInt(BundleDestinationDataSource.FIELD_BUNDLE_ID); + return "<a href="" + LinkManager.getBundleLink(bid) + "">" + o + "</a>"; + } + });
- ListGridField status = getListGrid().getField("latestDeploymentStatus"); HashMap<String, String> statusIcons = new HashMap<String, String>(); statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); - statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Warning_11.png"); + statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Error_11.png"); statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); - status.setValueIcons(statusIcons); - status.setValueIconHeight(11); - status.setWidth(80); + latestDeploymentStatusField.setValueIcons(statusIcons); + latestDeploymentStatusField.setValueIconHeight(11); + latestDeploymentStatusField.setValueIconWidth(11);
+ idField.setWidth(50); + nameField.setWidth("20%"); + descriptionField.setWidth("25%"); + bundleNameField.setHidden(true); + groupNameField.setWidth("15%"); + deployDirField.setWidth("20%"); + latestDeploymentVersionField.setWidth("10%"); + latestDeploymentDateField.setWidth("10%"); + latestDeploymentStatusField.setWidth(80);
+ // XXX there seems to be a bug here - i want to hide the bundle column, but setHidden(true) causes the entire rendering to fail + setListGridFields(idField, nameField, descriptionField, /*bundleNameField, */groupNameField, deployDirField, + latestDeploymentVersionField, latestDeploymentDateField, latestDeploymentStatusField); + + setListGridDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + ListGrid listGrid = (ListGrid) event.getSource(); + ListGridRecord[] selectedRows = listGrid.getSelection(); + if (selectedRows != null && selectedRows.length == 1) { + String selectedId = selectedRows[0].getAttribute(BundleDestinationDataSource.FIELD_BUNDLE_ID); + String selectedDestId = selectedRows[0].getAttribute(BundleDestinationDataSource.FIELD_ID); + CoreGUI.goToView(LinkManager.getBundleDestinationLink(Integer.valueOf(selectedId), Integer + .valueOf(selectedDestId))); + } + } + }); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index 601c0c8..b4aaba8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -77,7 +77,7 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka this.canManageBundles = canManageBundles; setWidth100(); setHeight100(); - setMargin(10); + //setMargin(10); // do not set margin, we already have our margin set outside of us }
private void viewBundleDestination(BundleDestination bundleDestination, ViewId current) { @@ -87,15 +87,34 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka this.destination = bundleDestination; this.bundle = bundleDestination.getBundle();
- addMember(new BackButton(extendLocatorId("BackButton"), MSG.view_bundle_dest_backToBundle() + ": " - + bundle.getName(), "Bundles/Bundle/" + bundle.getId())); + BackButton backButton = new BackButton(extendLocatorId("BackButton"), MSG.view_bundle_dest_backToBundle() + + ": " + bundle.getName(), "Bundles/Bundle/" + bundle.getId());
- addMember(new HeaderLabel(Canvas.getImgURL("subsystems/bundle/BundleDestination_24.png"), destination.getName())); + HeaderLabel header = new HeaderLabel(Canvas.getImgURL("subsystems/bundle/BundleDestination_24.png"), + destination.getName());
- LocatableDynamicForm form = new LocatableDynamicForm(getLocatorId()); + detail = new Canvas(); + detail.setHeight("50%"); + detail.hide(); + + addMember(backButton); + addMember(header); + addMember(createTagEditor()); + addMember(createSummaryForm()); + addMember(createDeploymentsTable()); + addMember(detail); + } + + private LocatableDynamicForm createSummaryForm() { + LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("Summary")); form.setWidth100(); - form.setNumCols(4); - form.setColWidths("20%", "30%", "25%", "25%"); + form.setColWidths("20%", "40%", "40%"); + form.setNumCols(3); + form.setWrapItemTitles(false); + form.setExtraSpace(10); + form.setIsGroup(true); + form.setGroupTitle(MSG.common_title_summary()); + form.setPadding(5);
LinkItem bundleName = new LinkItem("bundle"); bundleName.setTitle(MSG.view_bundle_bundle()); @@ -103,32 +122,11 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka bundleName.setLinkTitle(bundle.getName()); bundleName.setTarget("_self");
- CanvasItem tagItem = new CanvasItem("tag"); - tagItem.setShowTitle(false); - TagEditorView tagEditor = new TagEditorView(form.extendLocatorId("Tags"), destination.getTags(), - !canManageBundles, new TagsChangedCallback() { - public void tagsChanged(HashSet<Tag> tags) { - GWTServiceLookup.getTagService().updateBundleDestinationTags(destination.getId(), tags, - new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_bundle_dest_tagUpdateFailure(), caught); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_dest_tagUpdateSuccessful(), Message.Severity.Info)); - } - }); - } - }); - tagEditor.setVertical(true); - tagItem.setCanvas(tagEditor); - tagItem.setRowSpan(4); - CanvasItem actionItem = new CanvasItem("actions"); + actionItem.setColSpan(1); + actionItem.setRowSpan(4); actionItem.setShowTitle(false); actionItem.setCanvas(getActionLayout(form.extendLocatorId("actions"))); - actionItem.setRowSpan(4);
StaticTextItem created = new StaticTextItem("created", MSG.view_bundle_dest_created()); created.setValue(new Date(destination.getCtime())); @@ -142,24 +140,34 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka StaticTextItem path = new StaticTextItem("path", MSG.view_bundle_dest_deployDir()); path.setValue(destination.getDeployDir());
- form.setFields(bundleName, tagItem, actionItem, created, destinationGroup, path); - - addMember(form); + form.setFields(bundleName, actionItem, created, destinationGroup, path); + return form; + }
- Table deployments = createDeploymentsTable(); - deployments.setHeight100(); - deployments.setShowResizeBar(true); - addMember(createDeploymentsTable()); + private TagEditorView createTagEditor() { + boolean readOnly = !this.canManageBundles; + TagEditorView tagEditor = new TagEditorView(extendLocatorId("Tags"), destination.getTags(), readOnly, + new TagsChangedCallback() { + public void tagsChanged(HashSet<Tag> tags) { + GWTServiceLookup.getTagService().updateBundleDestinationTags(destination.getId(), tags, + new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_bundle_dest_tagUpdateFailure(), caught); + }
- detail = new Canvas(); - detail.setHeight("50%"); - detail.hide(); - addMember(detail); + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_dest_tagUpdateSuccessful(), Message.Severity.Info)); + } + }); + } + }); + tagEditor.setAutoHeight(); + return tagEditor; }
private Canvas getActionLayout(String locatorId) { - LocatableVLayout actionLayout = new LocatableVLayout(locatorId); - actionLayout.setMembersMargin(10); + LocatableVLayout actionLayout = new LocatableVLayout(locatorId, 10); IButton deployButton = new LocatableIButton(actionLayout.extendLocatorId("Deploy"), MSG.view_bundle_deploy()); deployButton.setIcon("subsystems/bundle/BundleAction_Deploy_16.png"); deployButton.addClickHandler(new ClickHandler() { @@ -189,7 +197,10 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka private Table createDeploymentsTable() { Criteria criteria = new Criteria(); criteria.addCriteria("bundleDestinationId", destination.getId()); - return new BundleDeploymentListView(extendLocatorId("Deployments"), criteria); + BundleDeploymentListView deployments = new BundleDeploymentListView(extendLocatorId("Deployments"), criteria); + deployments.setHeight100(); + deployments.setShowResizeBar(true); + return deployments; }
public void renderView(final ViewPath viewPath) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleVersionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleVersionDataSource.java index cc21796..11edfdf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleVersionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleVersionDataSource.java @@ -42,6 +42,13 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; */ public class BundleVersionDataSource extends RPCDataSource<BundleVersion> {
+ public static final String FIELD_ID = "id"; + public static final String FIELD_BUNDLE_ID = "bundleId"; + public static final String FIELD_VERSION = "version"; + public static final String FIELD_NAME = "name"; + public static final String FIELD_DESCRIPTION = "description"; + public static final String FIELD_FILECOUNT = "fileCount"; + private BundleGWTServiceAsync bundleService = GWTServiceLookup.getBundleService();
public BundleVersionDataSource() { @@ -54,22 +61,23 @@ public class BundleVersionDataSource extends RPCDataSource<BundleVersion> { protected List<DataSourceField> addDataSourceFields() { List<DataSourceField> fields = super.addDataSourceFields();
- DataSourceIntegerField idField = new DataSourceIntegerField("id", MSG.common_title_id()); + DataSourceIntegerField idField = new DataSourceIntegerField(FIELD_ID, MSG.common_title_id()); idField.setPrimaryKey(true); fields.add(idField);
- DataSourceTextField latestVersionField = new DataSourceTextField("version", MSG.common_title_version()); - fields.add(latestVersionField); + DataSourceTextField versionField = new DataSourceTextField(FIELD_VERSION, MSG.common_title_version()); + fields.add(versionField);
- DataSourceTextField nameField = new DataSourceTextField("name", MSG.common_title_name()); + DataSourceTextField nameField = new DataSourceTextField(FIELD_NAME, MSG.common_title_name()); fields.add(nameField);
- DataSourceTextField descriptionField = new DataSourceTextField("description", MSG.common_title_description()); + DataSourceTextField descriptionField = new DataSourceTextField(FIELD_DESCRIPTION, MSG + .common_title_description()); fields.add(descriptionField);
- DataSourceIntegerField deploymentCountField = new DataSourceIntegerField("fileCount", MSG + DataSourceIntegerField fileCountField = new DataSourceIntegerField(FIELD_FILECOUNT, MSG .view_bundle_bundleFiles()); - fields.add(deploymentCountField); + fields.add(fileCountField);
return fields; } @@ -124,12 +132,12 @@ public class BundleVersionDataSource extends RPCDataSource<BundleVersion> { public ListGridRecord copyValues(BundleVersion from) { ListGridRecord record = new ListGridRecord();
- record.setAttribute("id", from.getId()); - record.setAttribute("bundleId", from.getBundle().getId()); - record.setAttribute("name", from.getName()); - record.setAttribute("description", from.getDescription()); - record.setAttribute("version", from.getVersion()); - record.setAttribute("fileCount", Integer.valueOf(from.getBundleFiles().size())); + record.setAttribute(FIELD_ID, from.getId()); + record.setAttribute(FIELD_BUNDLE_ID, from.getBundle().getId()); + record.setAttribute(FIELD_NAME, from.getName()); + record.setAttribute(FIELD_DESCRIPTION, from.getDescription()); + record.setAttribute(FIELD_VERSION, from.getVersion()); + record.setAttribute(FIELD_FILECOUNT, Integer.valueOf(from.getBundleFiles().size()));
record.setAttribute("object", from);
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 c1e4ccc..36968e8 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 @@ -78,9 +78,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { private Tab destinationsTab;
private BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); - private Bundle bundle; - private final boolean canManageBundles;
public BundleView(String locatorId, Set<Permission> perms) { @@ -88,39 +86,32 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { this.canManageBundles = (perms != null) ? perms.contains(Permission.MANAGE_BUNDLE) : false; setWidth100(); setHeight100(); - setPadding(10); + setMargin(10); setOverflow(Overflow.AUTO); }
- @Override - protected void onInit() { - super.onInit(); - } - public void viewBundle(Bundle bundle, ViewId nextViewId) { // Whenever a new view request comes in, make sure to clean house to avoid ID conflicts for sub-widgets this.destroyMembers();
this.bundle = bundle;
- addMember(new BackButton(extendLocatorId("BackButton"), MSG.view_bundle_list_backToAll(), BundleTopView.VIEW_ID - .getTitle())); - + BackButton backButton = new BackButton(extendLocatorId("BackButton"), MSG.view_bundle_list_backToAll(), + BundleTopView.VIEW_ID.getTitle()); headerLabel = new HeaderLabel("subsystems/bundle/Bundle_24.png", bundle.getName()); - - addMember(headerLabel); - - addMember(createSummaryForm()); - tabs = new LocatableTabSet(getLocatorId()); - versionsTab = createVersionsTab(); - tabs.addTab(versionsTab); - destinationsTab = createDestinationsTab(); + versionsTab = createVersionsTab(); tabs.addTab(destinationsTab); + tabs.addTab(versionsTab);
+ addMember(backButton); + addMember(headerLabel); + addMember(createTagEditor()); + addMember(createSummaryForm()); addMember(tabs);
+ // select the correct tab based on what URL the user is going to (based on what tree node was selected) if ((null == nextViewId) || (nextViewId.getPath().equals("versions"))) { tabs.selectTab(versionsTab); } else if (nextViewId.getPath().equals("destinations")) { @@ -130,27 +121,42 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { markForRedraw(); }
+ private TagEditorView createTagEditor() { + boolean readOnly = !this.canManageBundles; + TagEditorView tagEditor = new TagEditorView(extendLocatorId("TagEditor"), bundle.getTags(), readOnly, + new TagsChangedCallback() { + public void tagsChanged(HashSet<Tag> tags) { + GWTServiceLookup.getTagService().updateBundleTags(bundleBeingViewed, tags, + new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_bundle_list_tagUpdateFailure(), caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_list_tagUpdateSuccessful(), Message.Severity.Info)); + } + }); + } + }); + tagEditor.setAutoHeight(); + return tagEditor; + } + private Tab createDestinationsTab() { LocatableTab destinationsTab = new LocatableTab(extendLocatorId("Destinations"), MSG.view_bundle_destinations()); - Criteria criteria = new Criteria(); criteria.addCriteria("bundleId", bundle.getId()); - destinationsTab.setPane(new BundleDestinationListView(destinationsTab.getLocatorId(), criteria)); - return destinationsTab; }
private Tab createVersionsTab() { LocatableTab versionsTab = new LocatableTab(extendLocatorId("Versions"), MSG.view_bundle_versions()); - Criteria criteria = new Criteria(); criteria.addCriteria("bundleId", bundleBeingViewed); - bundleVersionsTable = new BundleVersionListView(versionsTab.getLocatorId(), criteria); - versionsTab.setPane(bundleVersionsTable); - return versionsTab; }
@@ -158,13 +164,15 @@ public class BundleView extends LocatableVLayout implements BookmarkableView {
form = new LocatableDynamicForm(extendLocatorId("Summary")); form.setWidth100(); - form.setColWidths("20%", "30%", "25%", "25%"); - form.setNumCols(4); + form.setColWidths("20%", "40%", "40%"); + form.setNumCols(3); form.setWrapItemTitles(false); - form.setPadding(10); + form.setExtraSpace(10); + form.setIsGroup(true); + form.setGroupTitle(MSG.common_title_summary()); + form.setPadding(5);
StaticTextItem descriptionItem = new StaticTextItem("description", MSG.common_title_description()); - descriptionItem.setWrap(false); descriptionItem.setValue(bundle.getDescription());
StaticTextItem versionCountItem = new StaticTextItem("versionCount", MSG.view_bundle_list_versionsCount()); @@ -174,41 +182,11 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { .view_bundle_list_destinationsCount()); destinationsCountItem.setValue(bundle.getDestinations() != null ? bundle.getDestinations().size() : 0);
- form.setFields(descriptionItem, getTagItem(), getActionItem(), versionCountItem, destinationsCountItem); + form.setFields(descriptionItem, getActionItem(), versionCountItem, destinationsCountItem);
return form; }
- private CanvasItem getTagItem() { - - boolean readOnly = !this.canManageBundles; - - TagEditorView tagEditor = new TagEditorView(form.extendLocatorId("TagEditor"), bundle.getTags(), readOnly, - new TagsChangedCallback() { - public void tagsChanged(HashSet<Tag> tags) { - GWTServiceLookup.getTagService().updateBundleTags(bundleBeingViewed, tags, - new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_bundle_list_tagUpdateFailure(), caught); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_list_tagUpdateSuccessful(), Message.Severity.Info)); - } - }); - } - }); - tagEditor.setVertical(true); - - CanvasItem tagItem = new CanvasItem("tags"); - tagItem.setShowTitle(false); - tagItem.setRowSpan(3); - tagItem.setCanvas(tagEditor); - - return tagItem; - } - private CanvasItem getActionItem() { VLayout layout = new LocatableVLayout(form.extendLocatorId("Actions"), 10);
@@ -275,6 +253,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { layout.addMember(deployButton);
CanvasItem actionItem = new CanvasItem("actions"); + actionItem.setColSpan(1); actionItem.setRowSpan(3); actionItem.setShowTitle(false); actionItem.setCanvas(layout); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionListView.java index 6e8f401..247907a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionListView.java @@ -23,18 +23,25 @@ package org.rhq.enterprise.gui.coregui.client.bundle.version;
import com.smartgwt.client.data.Criteria; -import com.smartgwt.client.types.SelectionAppearance; import com.smartgwt.client.types.SelectionStyle; +import com.smartgwt.client.widgets.events.DoubleClickEvent; +import com.smartgwt.client.widgets.events.DoubleClickHandler; import com.smartgwt.client.widgets.grid.CellFormatter; +import com.smartgwt.client.widgets.grid.ListGrid; +import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
+import org.rhq.core.domain.bundle.BundleVersion; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.bundle.list.BundleVersionDataSource; import org.rhq.enterprise.gui.coregui.client.components.table.Table; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource;
/** * @author Greg Hinkle */ -public class BundleVersionListView extends Table { +public class BundleVersionListView extends Table<RPCDataSource<BundleVersion>> {
public BundleVersionListView(String locatorId) { this(locatorId, null); @@ -43,28 +50,56 @@ public class BundleVersionListView extends Table { public BundleVersionListView(String locatorId, Criteria criteria) { super(locatorId, MSG.view_bundle_bundleVersions(), criteria); setHeaderIcon("subsystems/bundle/BundleVersion_24.png"); - BundleVersionDataSource bundleVersionsDataSource = new BundleVersionDataSource(); - setDataSource(bundleVersionsDataSource); + setDataSource(new BundleVersionDataSource()); + } + + @Override + protected SelectionStyle getDefaultSelectionStyle() { + return SelectionStyle.SINGLE; }
@Override protected void configureTable() { - getListGrid().getField("id").setWidth("60"); - getListGrid().getField("name").setWidth("25%"); - getListGrid().getField("name").setCellFormatter(new CellFormatter() { + ListGridField idField = new ListGridField(FIELD_ID, MSG.common_title_id()); + + ListGridField versionField = new ListGridField(BundleVersionDataSource.FIELD_VERSION, MSG + .common_title_version()); + versionField.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - return "<a href="#Bundles/Bundle/" + listGridRecord.getAttribute("bundleId") + "/versions/" - + listGridRecord.getAttribute("id") + "">" + o + "</a>"; + Integer _bundleId = listGridRecord.getAttributeAsInt("bundleId"); + Integer _bvId = listGridRecord.getAttributeAsInt("id"); + return "<a href="" + LinkManager.getBundleVersionLink(_bundleId, _bvId) + "">" + o + "</a>"; } });
- getListGrid().getField("version").setWidth("10%"); - getListGrid().getField("fileCount").setWidth("10%"); - getListGrid().getField("description").setWidth("*"); + ListGridField nameField = new ListGridField(BundleVersionDataSource.FIELD_NAME, MSG.common_title_name());
- getListGrid().setSelectionType(SelectionStyle.NONE); - getListGrid().setSelectionAppearance(SelectionAppearance.ROW_STYLE); + ListGridField descriptionField = new ListGridField(BundleVersionDataSource.FIELD_DESCRIPTION, MSG + .common_title_description());
+ ListGridField fileCountField = new ListGridField(BundleVersionDataSource.FIELD_FILECOUNT, MSG + .view_bundle_bundleFiles());
+ idField.setWidth(50); + versionField.setWidth("20%"); + nameField.setWidth("25%"); + descriptionField.setWidth("*"); + fileCountField.setWidth("10%"); + + setListGridFields(idField, versionField, nameField, descriptionField, fileCountField); + + setListGridDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + ListGrid listGrid = (ListGrid) event.getSource(); + ListGridRecord[] selectedRows = listGrid.getSelection(); + if (selectedRows != null && selectedRows.length == 1) { + String selectedId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_BUNDLE_ID); + String selectedVersionId = selectedRows[0].getAttribute(BundleVersionDataSource.FIELD_ID); + CoreGUI.goToView(LinkManager.getBundleVersionLink(Integer.valueOf(selectedId), Integer + .valueOf(selectedVersionId))); + } + } + }); } } diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/Error_11.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/Error_11.png new file mode 100644 index 0000000..371298c Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/Error_11.png differ
commit 6656ed9ffacd62f03eec1c34d1536356706c771b Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 00:13:20 2010 -0500
disable deploy/revert buttons if user doesn't have perms
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index dd65070..601c0c8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -70,8 +70,11 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka
private Canvas detail;
- public BundleDestinationView(String locatorId) { + private boolean canManageBundles; + + public BundleDestinationView(String locatorId, boolean canManageBundles) { super(locatorId); + this.canManageBundles = canManageBundles; setWidth100(); setHeight100(); setMargin(10); @@ -102,8 +105,8 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka
CanvasItem tagItem = new CanvasItem("tag"); tagItem.setShowTitle(false); - TagEditorView tagEditor = new TagEditorView(form.extendLocatorId("Tags"), destination.getTags(), false, - new TagsChangedCallback() { + TagEditorView tagEditor = new TagEditorView(form.extendLocatorId("Tags"), destination.getTags(), + !canManageBundles, new TagsChangedCallback() { public void tagsChanged(HashSet<Tag> tags) { GWTServiceLookup.getTagService().updateBundleDestinationTags(destination.getId(), tags, new AsyncCallback<Void>() { @@ -164,6 +167,9 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka new BundleDeployWizard(destination).startWizard(); } }); + if (!canManageBundles) { + deployButton.setDisabled(true); + } actionLayout.addMember(deployButton);
IButton revertButton = new LocatableIButton(actionLayout.extendLocatorId("Revert"), MSG.view_bundle_revert()); @@ -173,69 +179,22 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka new BundleRevertWizard(destination).startWizard(); } }); + if (!canManageBundles) { + revertButton.setDisabled(true); + } actionLayout.addMember(revertButton); return actionLayout; }
private Table createDeploymentsTable() { - Criteria criteria = new Criteria(); criteria.addCriteria("bundleDestinationId", destination.getId()); - return new BundleDeploymentListView(extendLocatorId("Deployments"), criteria); - - /* Table table = new Table("Deployment History"); - - ListGridField name = new ListGridField("name", "Name"); - name.setCellFormatter(new CellFormatter() { - public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - return "<a href="#Bundles/Bundle/" + bundle.getId() + "/deployments/" - + listGridRecord.getAttribute("id") + "">" + o + "</a>"; - } - }); - - ListGridField version = new ListGridField("version", "Version"); - ListGridField description = new ListGridField("description", "Description"); - ListGridField installDate = new ListGridField("installDate", "Install Date"); - ListGridField status = new ListGridField("status", "Status"); - HashMap<String, String> statusIcons = new HashMap<String, String>(); - statusIcons.put(BundleDeploymentStatus.IN_PROGRESS.name(), "subsystems/bundle/install-loader.gif"); - statusIcons.put(BundleDeploymentStatus.FAILURE.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.MIXED.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.WARN.name(), "subsystems/bundle/Warning_11.png"); - statusIcons.put(BundleDeploymentStatus.SUCCESS.name(), "subsystems/bundle/Ok_11.png"); - status.setValueIcons(statusIcons); - status.setValueIconHeight(11); - status.setWidth(80); - - - table.getListGrid().setFields(name, version, description, installDate, status); - - ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>(); - for (BundleDeployment rd : destination.getDeployments()) { - ListGridRecord record = new ListGridRecord(); - - record.setAttribute("name", rd.getName()); - record.setAttribute("description", rd.getDescription()); - record.setAttribute("bundleId", bundle.getId()); - record.setAttribute("version", rd.getBundleVersion().getName()); - record.setAttribute("status", rd.getStatus().name()); - record.setAttribute("id", rd.getId()); - record.setAttribute("entity", rd); - record.setAttribute("installDate", new Date(rd.getCtime())); - records.add(record); - } - - table.getListGrid().setData(records.toArray(new ListGridRecord[records.size()])); - - return table;*/ }
public void renderView(final ViewPath viewPath) { int bundleDestinationId = Integer.parseInt(viewPath.getCurrent().getPath());
- final ViewId viewId = viewPath.getCurrent(); - BundleDestinationCriteria criteria = new BundleDestinationCriteria(); criteria.addFilterId(bundleDestinationId); criteria.fetchBundle(true); @@ -253,7 +212,6 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka viewBundleDestination(destination, viewPath.getCurrent()); } }); - }
} \ No newline at end of file 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 a94b133..c1e4ccc 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 @@ -343,7 +343,8 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } else if (viewPath.getCurrent().getPath().equals("destinations")) { if (!viewPath.isEnd()) { // a specific destination - BundleDestinationView view = new BundleDestinationView(extendLocatorId("Destination")); + BundleDestinationView view = new BundleDestinationView(extendLocatorId("Destination"), + canManageBundles); addMember(view); view.renderView(viewPath.next()); }
commit 5f8c0d6c2b969ffcf88ed311afc9d561e81022f4 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 17 00:01:05 2010 -0500
the detail messages are too long for the message center -make them details and provide shorter concise messages
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java index bef5d91..bdd818c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/DeployStep.java @@ -79,8 +79,9 @@ public class DeployStep extends AbstractWizardStep { deployingImage.setSrc("/images/status_complete.gif"); deployingMessage.setText(MSG.view_bundle_deployWizard_deploymentCreated()); CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_deployWizard_deploymentCreatedDetail(result.getName(), result - .getDescription()), Severity.Info)); + new Message(MSG.view_bundle_deployWizard_deploymentCreatedDetail_concise(result.getName()), + MSG.view_bundle_deployWizard_deploymentCreatedDetail(result.getName(), result + .getDescription()), Severity.Info)); wizard.setNewDeployment(result);
bundleServer.scheduleBundleDeployment(wizard.getNewDeployment().getId(), wizard @@ -90,8 +91,9 @@ public class DeployStep extends AbstractWizardStep { deployingImage.setSrc("/images/status_complete.gif"); deployingMessage.setText(MSG.view_bundle_deployWizard_deploymentScheduled()); CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_deployWizard_deploymentScheduledDetail(result - .getName(), result.getDestination().getGroup().getName()), Severity.Info)); + new Message(MSG.view_bundle_deployWizard_deploymentScheduledDetail_concise(), + MSG.view_bundle_deployWizard_deploymentScheduledDetail(result.getName(), + result.getDestination().getGroup().getName()), Severity.Info)); CoreGUI.refresh(); wizard.setNewDeployment(result); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java index ee0122e..78a9bf9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java @@ -169,8 +169,9 @@ public class GetDestinationStep extends AbstractWizardStep { wizard.setDestination(result); wizard.setNewDestination(true); CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_deployWizard_destinationCreatedDetail(result.getName(), result - .getDescription()), Severity.Info)); + new Message(MSG.view_bundle_deployWizard_destinationCreatedDetail_concise(result.getName()), + MSG.view_bundle_deployWizard_destinationCreatedDetail(result.getName(), result + .getDescription()), Severity.Info)); createInProgress = false; wizard.getView().incrementStep(); } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 69803a3..de1ef89 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -995,10 +995,13 @@ view_bundle_createWizard_createSuccessful = You have successfully created a bund view_bundle_deployWizard_deploying = Deploying... view_bundle_deployWizard_deployStep = Deploy Bundle to Destination Platforms view_bundle_deployWizard_deploymentCreated = Created Deployment... -view_bundle_deployWizard_deploymentCreatedDetail = Created deployment [{0}] description [{1}] -view_bundle_deployWizard_destinationCreatedDetail = Created destination [{0}] description [{1}] +view_bundle_deployWizard_deploymentCreatedDetail = You have created the deployment [{0}] with the description [{1}] +view_bundle_deployWizard_deploymentCreatedDetail_concise = You have created the deployment [{0}] +view_bundle_deployWizard_destinationCreatedDetail = You have created the destination [{0}] with the description [{1}] +view_bundle_deployWizard_destinationCreatedDetail_concise = You have created the destination [{0}] view_bundle_deployWizard_deploymentScheduled = Bundle Deployment Scheduled! -view_bundle_deployWizard_deploymentScheduledDetail = Scheduled bundle deployment [{0}] destination group [{1}] +view_bundle_deployWizard_deploymentScheduledDetail = You have scheduled the bundle deployment [{0}] to the destination group [{1}] +view_bundle_deployWizard_deploymentScheduledDetail_concise = You have scheduled the bundle deployment view_bundle_deployWizard_error_1 = Failed to delete new deployment on Cancel: {0} view_bundle_deployWizard_error_2 = Failed to delete new destination on Cancel: {0} view_bundle_deployWizard_error_3 = Failed to Schedule Deployment!
commit 515cd7359131215bee54396c2043766cdf9e6ff7 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 23:18:13 2010 -0500
disable buttons when a user doesn't have perms
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 c8f9261..fd0bbe7 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 @@ -120,7 +120,7 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView } else { if (!viewPath.getNext().equals(currentNextPath)) { currentNextPath = viewPath.getNext(); - bundleView = new BundleView(extendLocatorId("Bundle")); + bundleView = new BundleView(extendLocatorId("Bundle"), permissions); setContent(bundleView); bundleView.renderView(viewPath.next()); } else { 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 1d64b7a..a94b133 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 @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.bundle.list;
import java.util.HashSet; +import java.util.Set;
import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; @@ -36,6 +37,7 @@ import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.tab.Tab; import com.smartgwt.client.widgets.tab.TabSet;
+import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.bundle.Bundle; import org.rhq.core.domain.criteria.BundleCriteria; import org.rhq.core.domain.tagging.Tag; @@ -79,8 +81,11 @@ public class BundleView extends LocatableVLayout implements BookmarkableView {
private Bundle bundle;
- public BundleView(String locatorId) { + private final boolean canManageBundles; + + public BundleView(String locatorId, Set<Permission> perms) { super(locatorId); + this.canManageBundles = (perms != null) ? perms.contains(Permission.MANAGE_BUNDLE) : false; setWidth100(); setHeight100(); setPadding(10); @@ -176,7 +181,9 @@ public class BundleView extends LocatableVLayout implements BookmarkableView {
private CanvasItem getTagItem() {
- TagEditorView tagEditor = new TagEditorView(form.extendLocatorId("TagEditor"), bundle.getTags(), false, + boolean readOnly = !this.canManageBundles; + + TagEditorView tagEditor = new TagEditorView(form.extendLocatorId("TagEditor"), bundle.getTags(), readOnly, new TagsChangedCallback() { public void tagsChanged(HashSet<Tag> tags) { GWTServiceLookup.getTagService().updateBundleTags(bundleBeingViewed, tags, @@ -259,6 +266,11 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } });
+ if (!canManageBundles) { + deleteButton.setDisabled(true); + deployButton.setDisabled(true); + } + layout.addMember(deleteButton); layout.addMember(deployButton);
@@ -271,7 +283,6 @@ public class BundleView extends LocatableVLayout implements BookmarkableView {
public void renderView(final ViewPath viewPath) { int bundleId = Integer.parseInt(viewPath.getCurrent().getPath()); - final ViewId viewId = viewPath.getCurrent();
viewPath.next(); if (viewPath.isEnd() || viewPath.isNextEnd()) { diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Delete_16_Disabled.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Delete_16_Disabled.png new file mode 100644 index 0000000..b8b8468 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Delete_16_Disabled.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Deploy_16_Disabled.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Deploy_16_Disabled.png new file mode 100644 index 0000000..fcbd9c4 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Deploy_16_Disabled.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Revert_16_Disabled.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Revert_16_Disabled.png new file mode 100644 index 0000000..b851d16 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/bundle/BundleAction_Revert_16_Disabled.png differ
commit e7fb3d8b0e17089282e53c6a9e6d6690bb3286fd Merge: 0496649... c761fd5... Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 21:56:07 2010 -0500
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq.git
commit 049664958db392c360a6b9969241d9dad6dbd032 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 21:55:48 2010 -0500
modifying bundle tags requires MANAGE_BUNDLE perm
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/tagging/TagManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/tagging/TagManagerBean.java index a66166f..a7e05a2 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/tagging/TagManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/tagging/TagManagerBean.java @@ -69,12 +69,8 @@ public class TagManagerBean implements TagManagerLocal, TagManagerRemote { private AuthorizationManagerLocal authorizationManager;
public PageList<Tag> findTagsByCriteria(Subject subject, TagCriteria criteria) { - CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ; - CriteriaQueryRunner<Tag> queryRunner = new CriteriaQueryRunner<Tag>(criteria, generator, entityManager); - return queryRunner.execute(); }
@@ -145,8 +141,7 @@ public class TagManagerBean implements TagManagerLocal, TagManagerRemote { } }
- @RequiredPermission(Permission.MANAGE_INVENTORY) - // todo verify + @RequiredPermission(Permission.MANAGE_BUNDLE) public void updateBundleTags(Subject subject, int bundleId, Set<Tag> tags) {
Set<Tag> definedTags = addTags(subject, tags); @@ -163,8 +158,7 @@ public class TagManagerBean implements TagManagerLocal, TagManagerRemote { } }
- @RequiredPermission(Permission.MANAGE_INVENTORY) - // todo verify + @RequiredPermission(Permission.MANAGE_BUNDLE) public void updateBundleVersionTags(Subject subject, int bundleVersionId, Set<Tag> tags) {
Set<Tag> definedTags = addTags(subject, tags); @@ -181,8 +175,7 @@ public class TagManagerBean implements TagManagerLocal, TagManagerRemote { } }
- @RequiredPermission(Permission.MANAGE_INVENTORY) - // todo verify + @RequiredPermission(Permission.MANAGE_BUNDLE) public void updateBundleDeploymentTags(Subject subject, int bundleDeploymentId, Set<Tag> tags) {
Set<Tag> definedTags = addTags(subject, tags); @@ -199,8 +192,7 @@ public class TagManagerBean implements TagManagerLocal, TagManagerRemote { } }
- @RequiredPermission(Permission.MANAGE_INVENTORY) - // todo verify + @RequiredPermission(Permission.MANAGE_BUNDLE) public void updateBundleDestinationTags(Subject subject, int bundleDestinationId, Set<Tag> tags) {
Set<Tag> definedTags = addTags(subject, tags);
commit c761fd50323d94e0a4d717ef885464c86959dfc8 Author: Ian Springer ian.springer@redhat.com Date: Thu Dec 16 19:55:54 2010 -0500
first rough cut of GWT-based resource Operations>Schedule subtab
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/common/JobTrigger.java b/modules/core/domain/src/main/java/org/rhq/core/domain/common/JobTrigger.java new file mode 100644 index 0000000..b3a8b48 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/common/JobTrigger.java @@ -0,0 +1,298 @@ +/* + * 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.common; + +import java.io.Serializable; +import java.util.Date; + +/** + * Indicates when a particular job (e.g. invocation of an RHQ Agent plugin operation) should execute. + * Note, all constructors of this class are private - the create*Trigger() static factory methods + * must be used to create instances. + * + * @author Ian Springer + */ +public class JobTrigger implements Serializable { + + private static final long serialVersionUID = 1L; + + // Together, the startType, recurrenceType, and endType define what type of trigger this is. + // For the remaining fields in this class, only those that apply to the trigger's type will have non-null values. + private StartType startType; + private RecurrenceType recurrenceType; + // Note, this field will be null when recurrenceType=NONE, since it's not applicable in that case. + private EndType endType; + + // Fields used by startType=DATETIME triggers + private Date startDate; + + // Fields used by recurrenceType=REPEAT_INTERVAL triggers + private Long repeatInterval; + // endDate and repeatCount are mutually exclusive - only one can have a non-null value; + // if both are null, the repetition is indefinite. + private Date endDate; + private Integer repeatCount; + + // Fields used by recurrenceType=CRON_EXPRESSION triggers + private String cronExpression; + + public enum StartType { + /** + * Start the initial run now. + */ + NOW, + /** + * Start the initial run at a specified date-time in the future. + */ + DATETIME; + } + + public enum RecurrenceType { + /** + * No recurrence - just run once. + */ + NONE, + /** + * Run every n seconds, starting at the start time of the initial run. + */ + REPEAT_INTERVAL, + /** + * Run on a schedule based on the specified cron expression. The expression must follow + * <a href="http://www.quartz-scheduler.org/docs/tutorials/crontrigger.html">Quartz + * cron expression syntax</a>, which is a bit different than Unix cron expression syntax. + */ + CRON_EXPRESSION; + } + + public enum EndType { + /** + * No end - recurrence is indefinite. + */ + NEVER, + /** + * End recurrence at a specified date/time in the future. + */ + DATETIME, + /** + * End recurrence after n repetitions. + */ + REPEAT_COUNT; + } + + public StartType getStartType() { + return startType; + } + + public EndType getEndType() { + return endType; + } + + public RecurrenceType getRecurrenceType() { + return recurrenceType; + } + + public Date getStartDate() { + return startDate; + } + + public Long getRepeatInterval() { + return repeatInterval; + } + + public String getCronExpression() { + return cronExpression; + } + + public Date getEndDate() { + return endDate; + } + + public Integer getRepeatCount() { + return repeatCount; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append("Trigger"); + sb.append("[cronExpression='").append(cronExpression).append('''); + sb.append(", startType=").append(startType); + sb.append(", recurrenceType=").append(recurrenceType); + sb.append(", endType=").append(endType); + sb.append(", startDate=").append(startDate); + sb.append(", repeatInterval=").append(repeatInterval); + sb.append(", endDate=").append(endDate); + sb.append(", repeatCount=").append(repeatCount); + sb.append(']'); + return sb.toString(); + } + + /** + * Create a trigger that will run now, once. + * + * @return a trigger that will run now, once + */ + public static JobTrigger createNowTrigger() { + return new JobTrigger(); + } + + /** + * Create a trigger that will run now and repeat on interval indefinitely. + * + * @return a trigger that will run now and repeat on interval indefinitely + */ + public static JobTrigger createNowAndRepeatTrigger(long repeatInterval) { + return new JobTrigger(repeatInterval); + } + + /** + * Create a trigger that will run now and repeat on interval until end date/time. + * + * @return a trigger that will run now and repeat on interval until end date/time + */ + public static JobTrigger createNowAndRepeatTrigger(long repeatInterval, Date endDate) { + return new JobTrigger(repeatInterval, endDate); + } + + /** + * Create a trigger that will run now and repeat on interval n times. + * + * @return a trigger that will run now and repeat on interval n times + */ + public static JobTrigger createNowAndRepeatTrigger(long repeatInterval, int repeatCount) { + return new JobTrigger(repeatInterval, repeatCount); + } + + /** + * Create a trigger that will run at specified date/time, once. + * + * @return a trigger that will run at specified date/time, once + */ + public static JobTrigger createLaterTrigger(Date startDate) { + return new JobTrigger(startDate); + } + + /** + * Create a trigger that will run at specified date/time and then repeat on interval indefinitely. + * + * @return a trigger that will run at specified date/time and then repeat on interval indefinitely + */ + public static JobTrigger createLaterAndRepeatTrigger(Date startDate, long repeatInterval) { + return new JobTrigger(startDate, repeatInterval); + } + + /** + * Create a trigger that will run at specified date/time and then repeat on interval until end date/time. + * + * @return a trigger that will run at specified date/time and then repeat on interval until end date/time + */ + public static JobTrigger createLaterAndRepeatTrigger(Date startDate, long repeatInterval, Date endDate) { + return new JobTrigger(startDate, repeatInterval, endDate); + } + + /** + * Create a trigger that will run at specified date/time and then repeat on interval n times. + * + * @return a trigger that will run at specified date/time and then repeat on interval n times + */ + public static JobTrigger createLaterAndRepeatTrigger(Date startDate, long repeatInterval, int repeatCount) { + return new JobTrigger(startDate, repeatInterval, repeatCount); + } + + /** + * Create a trigger that will run on the schedule specified by a cron expression. The expression must follow + * <a href="http://www.quartz-scheduler.org/docs/tutorials/crontrigger.html">Quartz + * cron expression syntax</a>, which is a bit different than Unix cron expression syntax. + * + * @return a trigger that will run on the schedule specified by a cron expression + */ + public static JobTrigger createCronTrigger(String cronExpression) { + return new JobTrigger(cronExpression); + } + + + private JobTrigger(StartType startType, RecurrenceType recurrenceType, EndType endType) { + this.startType = startType; + this.recurrenceType = recurrenceType; + this.endType = endType; + } + + // run now, once + private JobTrigger() { + this(StartType.NOW, RecurrenceType.NONE, null); + } + + // run now and repeat on interval indefinitely + private JobTrigger(long repeatInterval) { + this(StartType.NOW, RecurrenceType.REPEAT_INTERVAL, EndType.REPEAT_COUNT); + this.repeatInterval = repeatInterval; + } + + // run now and repeat on interval until end date/time + private JobTrigger(long repeatInterval, Date endDate) { + this(StartType.NOW, RecurrenceType.REPEAT_INTERVAL, EndType.DATETIME); + this.repeatInterval = repeatInterval; + this.endDate = endDate; + } + + // run now and repeat on interval n times + private JobTrigger(long repeatInterval, int repeatCount) { + this(StartType.NOW, RecurrenceType.REPEAT_INTERVAL, EndType.REPEAT_COUNT); + this.repeatInterval = repeatInterval; + this.repeatCount = repeatCount; + } + + // run at specified date/time, once + private JobTrigger(Date startDate) { + this(StartType.DATETIME, RecurrenceType.NONE, EndType.REPEAT_COUNT); + this.startDate = startDate; + this.repeatCount = 1; + } + + // run at specified date/time and then repeat on interval indefinitely + private JobTrigger(Date startDate, long repeatInterval) { + this(StartType.DATETIME, RecurrenceType.REPEAT_INTERVAL, EndType.NEVER); + this.startDate = startDate; + this.repeatInterval = repeatInterval; + } + + // run at specified date/time and then repeat on interval until end date/time + private JobTrigger(Date startDate, long repeatInterval, Date endDate) { + this(StartType.DATETIME, RecurrenceType.REPEAT_INTERVAL, EndType.DATETIME); + this.startDate = startDate; + this.repeatInterval = repeatInterval; + this.endDate = endDate; + } + + // run at specified date/time and then repeat on interval n times + private JobTrigger(Date startDate, long repeatInterval, int repeatCount) { + this(StartType.DATETIME, RecurrenceType.REPEAT_INTERVAL, EndType.REPEAT_COUNT); + this.startDate = startDate; + this.repeatInterval = repeatInterval; + this.repeatCount = repeatCount; + } + + // run on the schedule specified by cron expression + private JobTrigger(String cronExpression) { + this(StartType.NOW, RecurrenceType.CRON_EXPRESSION, EndType.NEVER); + this.cronExpression = cronExpression; + } + +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java b/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java deleted file mode 100644 index da58047..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java +++ /dev/null @@ -1,298 +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.core.domain.common; - -import java.io.Serializable; -import java.util.Date; - -/** - * Indicates when a particular job (e.g. invocation of an RHQ Agent plugin operation) should execute. - * Note, all constructors of this class are private - the create*Trigger() static factory methods - * must be used to create instances. - * - * @author Ian Springer - */ -public class Trigger implements Serializable { - - private static final long serialVersionUID = 1L; - - // Together, the startType, recurrenceType, and endType define what type of trigger this is. - // For the remaining fields in this class, only those that apply to the trigger's type will have non-null values. - private StartType startType; - private RecurrenceType recurrenceType; - // Note, this field will be null when recurrenceType=NONE, since it's not applicable in that case. - private EndType endType; - - // Fields used by startType=DATETIME triggers - private Date startDate; - - // Fields used by recurrenceType=REPEAT_INTERVAL triggers - private Long repeatInterval; - // endDate and repeatCount are mutually exclusive - only one can have a non-null value; - // if both are null, the repetition is indefinite. - private Date endDate; - private Integer repeatCount; - - // Fields used by recurrenceType=CRON_EXPRESSION triggers - private String cronExpression; - - public enum StartType { - /** - * Start the initial run now. - */ - NOW, - /** - * Start the initial run at a specified date-time in the future. - */ - DATETIME; - } - - public enum RecurrenceType { - /** - * No recurrence - just run once. - */ - NONE, - /** - * Run every n seconds, starting at the start time of the initial run. - */ - REPEAT_INTERVAL, - /** - * Run on a schedule based on the specified cron expression. The expression must follow - * <a href="http://www.quartz-scheduler.org/docs/tutorials/crontrigger.html">Quartz - * cron expression syntax</a>, which is a bit different than Unix cron expression syntax. - */ - CRON_EXPRESSION; - } - - public enum EndType { - /** - * No end - recurrence is indefinite. - */ - NEVER, - /** - * End recurrence at a specified date/time in the future. - */ - DATETIME, - /** - * End recurrence after n repetitions. - */ - REPEAT_COUNT; - } - - public StartType getStartType() { - return startType; - } - - public EndType getEndType() { - return endType; - } - - public RecurrenceType getRecurrenceType() { - return recurrenceType; - } - - public Date getStartDate() { - return startDate; - } - - public Long getRepeatInterval() { - return repeatInterval; - } - - public String getCronExpression() { - return cronExpression; - } - - public Date getEndDate() { - return endDate; - } - - public Integer getRepeatCount() { - return repeatCount; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("Trigger"); - sb.append("[cronExpression='").append(cronExpression).append('''); - sb.append(", startType=").append(startType); - sb.append(", recurrenceType=").append(recurrenceType); - sb.append(", endType=").append(endType); - sb.append(", startDate=").append(startDate); - sb.append(", repeatInterval=").append(repeatInterval); - sb.append(", endDate=").append(endDate); - sb.append(", repeatCount=").append(repeatCount); - sb.append(']'); - return sb.toString(); - } - - /** - * Create a trigger that will run now, once. - * - * @return a trigger that will run now, once - */ - public static Trigger createNowTrigger() { - return new Trigger(); - } - - /** - * Create a trigger that will run now and repeat on interval indefinitely. - * - * @return a trigger that will run now and repeat on interval indefinitely - */ - public static Trigger createNowAndRepeatTrigger(long repeatInterval) { - return new Trigger(repeatInterval); - } - - /** - * Create a trigger that will run now and repeat on interval until end date/time. - * - * @return a trigger that will run now and repeat on interval until end date/time - */ - public static Trigger createNowAndRepeatTrigger(long repeatInterval, Date endDate) { - return new Trigger(repeatInterval, endDate); - } - - /** - * Create a trigger that will run now and repeat on interval n times. - * - * @return a trigger that will run now and repeat on interval n times - */ - public static Trigger createNowAndRepeatTrigger(long repeatInterval, int repeatCount) { - return new Trigger(repeatInterval, repeatCount); - } - - /** - * Create a trigger that will run at specified date/time, once. - * - * @return a trigger that will run at specified date/time, once - */ - public static Trigger createLaterTrigger(Date startDate) { - return new Trigger(startDate); - } - - /** - * Create a trigger that will run at specified date/time and then repeat on interval indefinitely. - * - * @return a trigger that will run at specified date/time and then repeat on interval indefinitely - */ - public static Trigger createLaterAndRepeatTrigger(Date startDate, long repeatInterval) { - return new Trigger(startDate, repeatInterval); - } - - /** - * Create a trigger that will run at specified date/time and then repeat on interval until end date/time. - * - * @return a trigger that will run at specified date/time and then repeat on interval until end date/time - */ - public static Trigger createLaterAndRepeatTrigger(Date startDate, long repeatInterval, Date endDate) { - return new Trigger(startDate, repeatInterval, endDate); - } - - /** - * Create a trigger that will run at specified date/time and then repeat on interval n times. - * - * @return a trigger that will run at specified date/time and then repeat on interval n times - */ - public static Trigger createLaterAndRepeatTrigger(Date startDate, long repeatInterval, int repeatCount) { - return new Trigger(startDate, repeatInterval, repeatCount); - } - - /** - * Create a trigger that will run on the schedule specified by a cron expression. The expression must follow - * <a href="http://www.quartz-scheduler.org/docs/tutorials/crontrigger.html">Quartz - * cron expression syntax</a>, which is a bit different than Unix cron expression syntax. - * - * @return a trigger that will run on the schedule specified by a cron expression - */ - public static Trigger createCronTrigger(String cronExpression) { - return new Trigger(cronExpression); - } - - - private Trigger(StartType startType, RecurrenceType recurrenceType, EndType endType) { - this.startType = startType; - this.recurrenceType = recurrenceType; - this.endType = endType; - } - - // run now, once - private Trigger() { - this(StartType.NOW, RecurrenceType.NONE, null); - } - - // run now and repeat on interval indefinitely - private Trigger(long repeatInterval) { - this(StartType.NOW, RecurrenceType.REPEAT_INTERVAL, EndType.REPEAT_COUNT); - this.repeatInterval = repeatInterval; - } - - // run now and repeat on interval until end date/time - private Trigger(long repeatInterval, Date endDate) { - this(StartType.NOW, RecurrenceType.REPEAT_INTERVAL, EndType.DATETIME); - this.repeatInterval = repeatInterval; - this.endDate = endDate; - } - - // run now and repeat on interval n times - private Trigger(long repeatInterval, int repeatCount) { - this(StartType.NOW, RecurrenceType.REPEAT_INTERVAL, EndType.REPEAT_COUNT); - this.repeatInterval = repeatInterval; - this.repeatCount = repeatCount; - } - - // run at specified date/time, once - private Trigger(Date startDate) { - this(StartType.DATETIME, RecurrenceType.NONE, EndType.REPEAT_COUNT); - this.startDate = startDate; - this.repeatCount = 1; - } - - // run at specified date/time and then repeat on interval indefinitely - private Trigger(Date startDate, long repeatInterval) { - this(StartType.DATETIME, RecurrenceType.REPEAT_INTERVAL, EndType.NEVER); - this.startDate = startDate; - this.repeatInterval = repeatInterval; - } - - // run at specified date/time and then repeat on interval until end date/time - private Trigger(Date startDate, long repeatInterval, Date endDate) { - this(StartType.DATETIME, RecurrenceType.REPEAT_INTERVAL, EndType.DATETIME); - this.startDate = startDate; - this.repeatInterval = repeatInterval; - this.endDate = endDate; - } - - // run at specified date/time and then repeat on interval n times - private Trigger(Date startDate, long repeatInterval, int repeatCount) { - this(StartType.DATETIME, RecurrenceType.REPEAT_INTERVAL, EndType.REPEAT_COUNT); - this.startDate = startDate; - this.repeatInterval = repeatInterval; - this.repeatCount = repeatCount; - } - - // run on the schedule specified by cron expression - private Trigger(String cronExpression) { - this(StartType.NOW, RecurrenceType.CRON_EXPRESSION, EndType.NEVER); - this.cronExpression = cronExpression; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java index f92f3d0..c638b31 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java @@ -26,6 +26,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;
import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.common.JobTrigger; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.operation.HistoryJobId; import org.rhq.core.domain.operation.JobId; @@ -47,6 +48,7 @@ public abstract class OperationSchedule implements Serializable { private Configuration parameters; private Subject subject; private String description; + private JobTrigger jobTrigger;
public OperationSchedule() { } @@ -124,6 +126,14 @@ public abstract class OperationSchedule implements Serializable { this.description = description; }
+ public JobTrigger getJobTrigger() { + return jobTrigger; + } + + public void setJobTrigger(JobTrigger jobTrigger) { + this.jobTrigger = jobTrigger; + } + /** * The single job ID which identifies the operation. It can later be parsed via {@link JobId#JobId(String)}. Note * that this job ID only identifies the scheduled operation; it does not identify any specific invocation of that diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java index 58d02ee..badd227 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/OperationGWTService.java @@ -27,10 +27,13 @@ import org.rhq.core.domain.criteria.GroupOperationHistoryCriteria; import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria; import org.rhq.core.domain.operation.GroupOperationHistory; import org.rhq.core.domain.operation.ResourceOperationHistory; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; import org.rhq.core.domain.operation.composite.ResourceOperationScheduleComposite; import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.exception.ThrowableUtil;
/** * @author Greg Hinkle @@ -46,10 +49,14 @@ public interface OperationGWTService extends RemoteService {
List<DisambiguationReport<ResourceOperationScheduleComposite>> findScheduledOperations(int pageSize);
- public void invokeResourceOperation(int resourceId, String operationName, Configuration parameters, + void invokeResourceOperation(int resourceId, String operationName, Configuration parameters, String description, int timeout) throws RuntimeException;
- public void scheduleResourceOperation(int resourceId, String operationName, Configuration parameters, + void scheduleResourceOperation(int resourceId, String operationName, Configuration parameters, String description, int timeout, String cronString) throws RuntimeException;
+ List<ResourceOperationSchedule> findScheduledResourceOperations(int resourceId) throws RuntimeException; + + List<GroupOperationSchedule> findScheduledGroupOperations(int groupId) throws RuntimeException; + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleCompositeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleCompositeDataSource.java deleted file mode 100644 index 88df113..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleCompositeDataSource.java +++ /dev/null @@ -1,74 +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.inventory.common.detail.operation.schedule; - -import java.util.List; - -import com.smartgwt.client.data.DataSourceField; -import com.smartgwt.client.data.fields.DataSourceIntegerField; -import com.smartgwt.client.data.fields.DataSourceTextField; - -import org.rhq.core.domain.operation.composite.OperationScheduleComposite; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.gwt.OperationGWTServiceAsync; -import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; - -/** - * @author Ian Springer - */ -public abstract class OperationScheduleCompositeDataSource extends RPCDataSource<OperationScheduleComposite> { - - public static abstract class Field { - - public static final String OPERATION_JOB_ID = "operationJobId"; - public static final String OPERATION_NAME = "operationName"; - public static final String OPERATION_NEXT_FIRE_TIME = "operationNextFireTime"; - } - - protected OperationGWTServiceAsync operationService = GWTServiceLookup.getOperationService(); - - public OperationScheduleCompositeDataSource() { - super(); - List<DataSourceField> fields = addDataSourceFields(); - addFields(fields); - } - - @Override - protected List<DataSourceField> addDataSourceFields() { - List<DataSourceField> fields = super.addDataSourceFields(); - - // TODO: i18n - DataSourceIntegerField idField = new DataSourceIntegerField(Field.OPERATION_JOB_ID, "ID"); - idField.setPrimaryKey(true); - idField.setCanEdit(false); - fields.add(idField); - - DataSourceTextField nameField = createTextField(Field.OPERATION_NAME, MSG.common_title_name(), 3, 100, true); - fields.add(nameField); - - // TODO: i18n - DataSourceTextField nextFireTimeField = createTextField(Field.OPERATION_NEXT_FIRE_TIME, "Next Fire Time", null, - 100, false); - fields.add(nextFireTimeField); - - return fields; - } - -} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java new file mode 100644 index 0000000..65fe51f --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleDataSource.java @@ -0,0 +1,115 @@ +/* + * 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.inventory.common.detail.operation.schedule; + +import java.util.List; + +import com.smartgwt.client.data.DataSourceField; +import com.smartgwt.client.data.Record; +import com.smartgwt.client.data.fields.DataSourceTextField; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.common.JobTrigger; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.operation.bean.OperationSchedule; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.gwt.OperationGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +/** + * @author Ian Springer + */ +public abstract class OperationScheduleDataSource<T extends OperationSchedule> extends RPCDataSource<T> { + + public static abstract class Field { + public static final String JOB_NAME = "jobName"; + public static final String JOB_GROUP = "jobGroup"; + public static final String OPERATION_NAME = "operationName"; + public static final String OPERATION_DISPLAY_NAME = "operationDisplayName"; + public static final String PARAMETERS = "parameters"; + public static final String SUBJECT = "subject"; + public static final String DESCRIPTION = "description"; + public static final String JOB_TRIGGER = "jobTrigger"; + } + + protected OperationGWTServiceAsync operationService = GWTServiceLookup.getOperationService(); + + public OperationScheduleDataSource() { + super(); + List<DataSourceField> fields = addDataSourceFields(); + addFields(fields); + } + + // TODO: i18n + @Override + protected List<DataSourceField> addDataSourceFields() { + List<DataSourceField> fields = super.addDataSourceFields(); + + DataSourceTextField operationDisplayNameField = createTextField(Field.OPERATION_DISPLAY_NAME, "Operation", null, 100, true); + fields.add(operationDisplayNameField); + + DataSourceTextField subjectField = createTextField(Field.SUBJECT, "Owner", null, 100, true); + fields.add(subjectField); + + DataSourceTextField descriptionField = createTextField(Field.DESCRIPTION, "Description", null, 100, true); + fields.add(descriptionField); + + DataSourceTextField jobTriggerField = createTextField(Field.JOB_TRIGGER, "Schedule", null, 100, true); + fields.add(jobTriggerField); + + return fields; + } + + protected abstract T createOperationSchedule(); + + @Override + public T copyValues(Record from) { + T to = createOperationSchedule(); + + to.setJobName(from.getAttribute(Field.JOB_NAME)); + to.setJobGroup(from.getAttribute(Field.JOB_GROUP)); + to.setJobTrigger((JobTrigger)from.getAttributeAsObject(Field.JOB_TRIGGER)); + to.setDescription(from.getAttribute(Field.DESCRIPTION)); + to.setOperationDisplayName(from.getAttribute(Field.OPERATION_DISPLAY_NAME)); + to.setOperationName(from.getAttribute(Field.OPERATION_NAME)); + to.setParameters((Configuration)from.getAttributeAsObject(Field.PARAMETERS)); + to.setSubject((Subject)from.getAttributeAsObject(Field.SUBJECT)); + + return to; + } + + @Override + public ListGridRecord copyValues(T from) { + ListGridRecord to = new ListGridRecord(); + + to.setAttribute(Field.JOB_NAME, from.getJobName()); + to.setAttribute(Field.JOB_GROUP, from.getJobGroup()); + to.setAttribute(Field.JOB_TRIGGER, from.getJobTrigger()); + to.setAttribute(Field.OPERATION_DISPLAY_NAME, from.getOperationDisplayName()); + to.setAttribute(Field.OPERATION_NAME, from.getOperationName()); + to.setAttribute(Field.SUBJECT, from.getSubject()); + to.setAttribute(Field.DESCRIPTION, from.getDescription()); + to.setAttribute(Field.PARAMETERS, from.getParameters()); + + return to; + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java index 29d0136..d658acc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/OperationScheduleListView.java @@ -28,15 +28,12 @@ import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; /** * @author Ian Springer */ -public abstract class OperationScheduleListView extends TableSection<OperationScheduleCompositeDataSource> { +public abstract class OperationScheduleListView extends TableSection<OperationScheduleDataSource> {
- private static final String HEADER_ICON = "subsystems/control/Operation_24.png"; - - public OperationScheduleListView(String locatorId, OperationScheduleCompositeDataSource dataSource, String title) { + public OperationScheduleListView(String locatorId, OperationScheduleDataSource dataSource, String title) { super(locatorId, title);
setDataSource(dataSource); - setHeaderIcon(HEADER_ICON); }
protected abstract boolean hasControlPermission(); @@ -45,11 +42,15 @@ public abstract class OperationScheduleListView extends TableSection<OperationSc protected void configureTable() { super.configureTable();
- ListGridField nameField = new ListGridField(OperationScheduleCompositeDataSource.Field.OPERATION_NAME, 150); + ListGridField operationField = new ListGridField(OperationScheduleDataSource.Field.OPERATION_DISPLAY_NAME, 150); + + //ListGridField subjectField = new ListGridField(OperationScheduleDataSource.Field.SUBJECT, 150); + + //ListGridField jobTriggerField = new ListGridField(OperationScheduleDataSource.Field.JOB_TRIGGER, 300);
- ListGridField nextFireTimeField = new ListGridField(OperationScheduleCompositeDataSource.Field.OPERATION_NEXT_FIRE_TIME); + ListGridField descriptionField = new ListGridField(OperationScheduleDataSource.Field.DESCRIPTION);
- setListGridFields(nameField, nextFireTimeField); + setListGridFields(operationField, descriptionField);
addTableAction(extendLocatorId("New"), MSG.common_button_new(), new TableAction() { public boolean isEnabled(ListGridRecord[] selection) { 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 de120f5..9cbf3e2 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 @@ -61,6 +61,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory 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.history.ResourceOperationHistoryListView; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary.ActivityView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.util.message.Message; @@ -243,7 +244,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateAlertsTabContent(resourceComposite); updateMonitoringTabContent(resource, facets); updateEventsTabContent(resourceComposite, facets); - updateOperationsTabContent(resource, facets); + updateOperationsTabContent(facets); updateConfigurationTabContent(resourceComposite, resource, resourcePermissions, facets); updateContentTabContent(resource, facets);
@@ -334,7 +335,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo } }
- private void updateOperationsTabContent(Resource resource, Set<ResourceTypeFacet> facets) { + private void updateOperationsTabContent(Set<ResourceTypeFacet> facets) { 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 @@ -342,11 +343,12 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo // 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.operationsHistory, new ResourceOperationHistoryListView(operationsTab .extendLocatorId("HistoryView"), this.resourceComposite), true, true);
- updateSubTab(this.operationsTab, this.operationsSchedule, new FullHTMLPane(this.operationsSchedule.extendLocatorId("View"), - "/rhq/resource/operation/resourceOperationSchedules-plain.xhtml?id=" + resource.getId()), true, true); + updateSubTab(this.operationsTab, this.operationsSchedule,new ResourceOperationScheduleListView(operationsTab.extendLocatorId("SchedulesView"), this.resourceComposite), + true, true); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java new file mode 100644 index 0000000..e044f51 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDataSource.java @@ -0,0 +1,68 @@ +/* + * 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.inventory.resource.detail.operation.schedule; + +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.Record; + +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; +import org.rhq.core.domain.resource.Resource; +import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationScheduleDataSource; + +/** + * A DataSource for {@link ResourceOperationSchedule}s for a given {@link Resource}. + * + * @author Ian Springer + */ +public class ResourceOperationScheduleDataSource extends OperationScheduleDataSource<ResourceOperationSchedule> { + + private int resourceId; + + public ResourceOperationScheduleDataSource(int resourceId) { + this.resourceId = resourceId; + } + + @Override + protected ResourceOperationSchedule createOperationSchedule() { + return new ResourceOperationSchedule(); + } + + @Override + protected void executeFetch(final DSRequest request, final DSResponse response) { + operationService.findScheduledResourceOperations(this.resourceId, + new AsyncCallback<List<ResourceOperationSchedule>>() { + public void onSuccess(List<ResourceOperationSchedule> result) { + Record[] records = buildRecords(result); + response.setData(records); + processResponse(request.getRequestId(), response); + } + + public void onFailure(Throwable caught) { + throw new RuntimeException("Failed to find scheduled operations for Resource with id [" + + resourceId + "].", caught); + } + }); + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java new file mode 100644 index 0000000..03de2a6 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleListView.java @@ -0,0 +1,52 @@ +/* + * 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.inventory.resource.detail.operation.schedule; + +import com.smartgwt.client.widgets.Canvas; + +import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationScheduleDataSource; +import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationScheduleListView; + +/** + * @author Ian Springer + */ +public class ResourceOperationScheduleListView extends OperationScheduleListView { + + private static final String TITLE = null; + + private ResourceComposite resourceComposite; + + public ResourceOperationScheduleListView(String locatorId, ResourceComposite resourceComposite) { + super(locatorId, new ResourceOperationScheduleDataSource(resourceComposite.getResource().getId()), TITLE); + this.resourceComposite = resourceComposite; + } + + @Override + protected boolean hasControlPermission() { + return this.resourceComposite.getResourcePermission().isControl(); + } + + @Override + public Canvas getDetailsView(int id) { + return new Canvas(); // TODO + } + +} 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 de8e667..a7bd459 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 @@ -85,7 +85,7 @@ public abstract class RPCDataSource<T> extends DataSource { }
/** - * A pattern that can be used for Datasource subclassing. Each subclass can add it's own fields prior to + * A pattern that can be used for Datasource subclassing. Each subclass can add its own fields prior to * all of the fields being added to the datasource. */ protected List<DataSourceField> addDataSourceFields() { 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 7cef256..a51ed3f 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 @@ -27,6 +27,7 @@ import org.rhq.core.domain.criteria.GroupOperationHistoryCriteria; import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria; import org.rhq.core.domain.operation.GroupOperationHistory; import org.rhq.core.domain.operation.ResourceOperationHistory; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; import org.rhq.core.domain.operation.composite.ResourceOperationScheduleComposite; @@ -75,7 +76,7 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O ResourceOperationSchedule opSchedule = operationManager.scheduleResourceOperation(getSessionSubject(), resourceId, operationName, 0, 0, 0, 0, parameters, description); } catch (Exception e) { - throw new RuntimeException("Unabled to invoke operation: " + e.getMessage()); + throw new RuntimeException("Unable to invoke operation: " + e.getMessage()); } }
@@ -87,7 +88,7 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O resourceId, operationName, parameters, ct, description);
} catch (Exception e) { - throw new RuntimeException("Unabled to schedule operation execution: " + e.getMessage()); + throw new RuntimeException("Unable to schedule operation execution: " + e.getMessage()); } }
@@ -132,6 +133,28 @@ public class OperationGWTServiceImpl extends AbstractGWTServiceImpl implements O } }
+ public List<ResourceOperationSchedule> findScheduledResourceOperations(int resourceId) throws RuntimeException { + try { + List<ResourceOperationSchedule> resourceOperationSchedules = + operationManager.findScheduledResourceOperations(getSessionSubject(), resourceId); + return SerialUtility.prepare(resourceOperationSchedules, "findScheduledResourceOperations"); + } + catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + public List<GroupOperationSchedule> findScheduledGroupOperations(int groupId) throws RuntimeException { + try { + List<GroupOperationSchedule> groupOperationSchedules = + operationManager.findScheduledGroupOperations(getSessionSubject(), groupId); + return SerialUtility.prepare(groupOperationSchedules, "findScheduledGroupOperations"); + } + catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + private static final IntExtractor<ResourceOperationLastCompletedComposite> RESOURCE_OPERATION_RESOURCE_ID_EXTRACTOR = new IntExtractor<ResourceOperationLastCompletedComposite>() { public int extract(ResourceOperationLastCompletedComposite object) { return object.getResourceId(); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java index cdda16d..a1fc704 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.server.operation;
import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Set; @@ -34,6 +35,7 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetbrains.annotations.Nullable; +import org.quartz.CronTrigger; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.SchedulerException; @@ -44,6 +46,7 @@ import org.rhq.core.clientapi.agent.operation.CancelResults; import org.rhq.core.clientapi.agent.operation.CancelResults.InterruptedState; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; +import org.rhq.core.domain.common.JobTrigger; import org.rhq.core.domain.common.composite.IntegerOptionItem; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; @@ -418,7 +421,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan return operationSchedules; }
- public ResourceOperationSchedule getResourceOperationSchedule(Subject subject, JobDetail jobDetail) { + public ResourceOperationSchedule getResourceOperationSchedule(Subject whoami, JobDetail jobDetail) { JobDataMap jobDataMap = jobDetail.getJobDataMap();
String description = jobDetail.getDescription(); @@ -433,7 +436,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan }
int resourceId = jobDataMap.getIntFromString(ResourceOperationJob.DATAMAP_INT_RESOURCE_ID); - Resource resource = getResourceIfAuthorized(subject, resourceId); + Resource resource = getResourceIfAuthorized(whoami, resourceId);
// note that we throw an exception if the subject does not exist! // this is by design to avoid a malicious user creating a dummy subject in the database, @@ -447,9 +450,13 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan sched.setResource(resource); sched.setOperationName(operationName); sched.setOperationDisplayName(displayName); - sched.setSubject(subjectManager.getSubjectById(subjectId)); + Subject subject = subjectManager.getSubjectById(subjectId); + sched.setSubject(subject); sched.setParameters(parameters); sched.setDescription(description); + Trigger trigger = getTriggerOfJob(jobDetail); + JobTrigger jobTrigger = convertToJobTrigger(trigger); + sched.setJobTrigger(jobTrigger);
return sched; } @@ -515,6 +522,9 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan sched.setExecutionOrder(executionOrder); sched.setDescription(description); sched.setHaltOnFailure(jobDataMap.getBooleanValueFromString(GroupOperationJob.DATAMAP_BOOL_HALT_ON_FAILURE)); + Trigger trigger = getTriggerOfJob(jobDetail); + JobTrigger jobTrigger = convertToJobTrigger(trigger); + sched.setJobTrigger(jobTrigger);
return sched; } @@ -1828,4 +1838,78 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan entityManager); return queryRunner.execute(); } + + private Trigger getTriggerOfJob(JobDetail jobDetail) { + Trigger[] triggers; + try { + triggers = scheduler.getTriggersOfJob(jobDetail.getName(), jobDetail.getGroup()); + } + catch (SchedulerException e) { + throw new RuntimeException("Failed to lookup trigger for job [" + jobDetail.getFullName() + "].", e); + } + if (triggers.length == 0) { + throw new IllegalStateException("Job [" + jobDetail.getFullName() + "] has no triggers."); + } + if (triggers.length > 1) { + throw new IllegalStateException("Job [" + jobDetail.getFullName() + "] has more than one trigger: " + + Arrays.asList(triggers)); + } + return triggers[0]; + } + + private static JobTrigger convertToJobTrigger(Trigger trigger) { + JobTrigger schedule; + if (trigger instanceof SimpleTrigger) { + SimpleTrigger simpleTrigger = (SimpleTrigger)trigger; + Date startTime = simpleTrigger.getStartTime(); + if (startTime != null) { + // later + int repeatCount = simpleTrigger.getRepeatCount(); + if (repeatCount == 0) { + // non-recurring + schedule = JobTrigger.createLaterTrigger(startTime); + } else { + // recurring + long repeatInterval = simpleTrigger.getRepeatInterval(); + if (repeatCount == SimpleTrigger.REPEAT_INDEFINITELY) { + Date endTime = simpleTrigger.getEndTime(); + if (endTime != null) { + schedule = JobTrigger.createLaterAndRepeatTrigger(startTime, repeatInterval, endTime); + } else { + schedule = JobTrigger.createLaterAndRepeatTrigger(startTime, repeatInterval); + } + } else { + schedule = JobTrigger.createLaterAndRepeatTrigger(startTime, repeatInterval, repeatCount); + } + } + } else { + // now + int repeatCount = simpleTrigger.getRepeatCount(); + if (repeatCount == 0) { + // non-recurring + schedule = JobTrigger.createNowTrigger(); + } else { + // recurring + long repeatInterval = simpleTrigger.getRepeatInterval(); + if (repeatCount == SimpleTrigger.REPEAT_INDEFINITELY) { + Date endTime = simpleTrigger.getEndTime(); + if (endTime != null) { + schedule = JobTrigger.createNowAndRepeatTrigger(repeatInterval, endTime); + } else { + schedule = JobTrigger.createNowAndRepeatTrigger(repeatInterval); + } + } else { + schedule = JobTrigger.createNowAndRepeatTrigger(repeatInterval, repeatCount); + } + } + } + } else if (trigger instanceof CronTrigger) { + CronTrigger cronTrigger = (CronTrigger)trigger; + schedule = JobTrigger.createCronTrigger(cronTrigger.getCronExpression()); + } else { + throw new IllegalStateException("Unsupported Quartz trigger type: " + trigger.getClass().getName()); + } + return schedule; + } + } \ No newline at end of file
commit f68131f17112cc6bbe4b619812e0b578bd2f3ede Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 21:03:07 2010 -0500
filter on bundle type now works in deploy wizard
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleSelector.java index 4a3e457..5b0c30c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/BundleSelector.java @@ -19,12 +19,10 @@ package org.rhq.enterprise.gui.coregui.client.bundle;
import java.util.ArrayList; +import java.util.LinkedHashMap;
import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.data.AdvancedCriteria; import com.smartgwt.client.data.Criteria; -import com.smartgwt.client.data.Criterion; -import com.smartgwt.client.types.OperatorId; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.TextItem; @@ -61,9 +59,9 @@ public class BundleSelector extends AbstractSelector<Bundle> { }
public void onSuccess(ArrayList<BundleType> result) { - String[] values = new String[result.size()]; - for (int i = 0, size = result.size(); (i < size); ++i) { - values[i] = result.get(i).getName(); + LinkedHashMap<String, String> values = new LinkedHashMap<String, String>(result.size()); + for (BundleType type : result) { + values.put(String.valueOf(type.getId()), type.getName()); } bundleTypeSelect.setValueMap(values); } @@ -80,16 +78,11 @@ public class BundleSelector extends AbstractSelector<Bundle> {
protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { String search = (String) availableFilterForm.getValue("search"); - String bundleType = (String) availableFilterForm.getValue("bundleType"); - ArrayList<Criterion> criteria = new ArrayList<Criterion>(2); - if (null != search) { - criteria.add(new Criterion("name", OperatorId.CONTAINS, search)); - } - if (null != bundleType) { - criteria.add(new Criterion("bundleType", OperatorId.EQUALS, bundleType)); - } - AdvancedCriteria latestCriteria = new AdvancedCriteria(OperatorId.AND, criteria.toArray(new Criterion[criteria - .size()])); + String bundleType = (String) availableFilterForm.getValueAsString("bundleType"); + + Criteria latestCriteria = new Criteria(); + latestCriteria.addCriteria("search", search); + latestCriteria.addCriteria("bundleType", bundleType);
return latestCriteria; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesDataSource.java index dfb6ae1..4fe31e0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesDataSource.java @@ -88,6 +88,16 @@ public class BundlesDataSource extends RPCDataSource<Bundle> { criteria.addFilterTagName((String) request.getCriteria().getValues().get("tagName")); }
+ if (request.getCriteria().getValues().get("bundleType") != null) { + criteria.addFilterBundleTypeId(Integer.valueOf(request.getCriteria().getValues().get("bundleType") + .toString())); + } + + // TODO: this doesn't work like I think it should, figure out how to search on the name column + // if (request.getCriteria().getValues().get("search") != null) { + // criteria.setSearchExpression(request.getCriteria().getValues().get("search").toString()); + // } + bundleService.findBundlesByCriteria(criteria, new AsyncCallback<PageList<Bundle>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.dataSource_bundle_loadFailed(), caught); @@ -106,7 +116,7 @@ public class BundlesDataSource extends RPCDataSource<Bundle> {
@Override public Bundle copyValues(Record from) { - return null; // TODO: Implement this method. + return (Bundle) from.getAttributeAsObject("object"); }
@Override
commit d84d301e273daba6b31c5e4a7baa8e5f8f24530a Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 20:14:54 2010 -0500
Removes all remnants of the now-obsolete breadcrumbs. The default browser window title is also now more descriptive, based on the URL. if a particular page wants a different title than the default, they can just call Window.setTitle() in, say, the onDraw or renderView method
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Breadcrumb.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Breadcrumb.java deleted file mode 100644 index 2bddbf2..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Breadcrumb.java +++ /dev/null @@ -1,138 +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 as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public 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; - -import com.smartgwt.client.widgets.Canvas; - -/** - * Information about a breadcrumb (i.e. history token component) that is used to render that breadcrumb in the - * breadcrumb trail at the top of the page. - * - * @author Ian Springer - */ -public class Breadcrumb { - private String name; - private String displayName; - private String icon; - private boolean hyperlink; - - public Breadcrumb(String name) { - this(name, null); - } - - public Breadcrumb(String name, String displayName) { - this(name, displayName, null, true); - } - - public Breadcrumb(String name, boolean hyperlink) { - this(name, name, null, hyperlink); - } - - public Breadcrumb(String name, String displayName, String icon, boolean hyperlink) { - if (name == null) { - throw new IllegalArgumentException("Name is null."); - } - this.name = name; - this.icon = icon; - setDisplayName(displayName); - this.hyperlink = hyperlink; - } - - /** - * Returns this breadcrumb's name (e.g. "10001"). - * - * @return this breadcrumb's name (e.g. "10001") - */ - public String getName() { - return this.name; - } - - /** - * Returns the display name to use for this breadcrumb in the breadcrumb trail, or null if the display name should - * be derived from the name. - * - * @return the display name to use for this breadcrumb in the breadcrumb trail, or null if the display name should - * be derived from the name - */ - public String getDisplayName() { - return this.displayName; - } - - /** - * Sets the display name to use for this breadcrumb in the breadcrumb trail, or null if the display name should - * be derived from the name. - */ - public void setDisplayName(String displayName) { - this.displayName = (displayName != null) ? displayName : getDefaultDisplayName(); - } - - /** - * Return true if this breadcrumb should be a hyperlink in the breadcrumb trail, or false otherwise. NOTE: - * Regardless of what this method returns, if this breadcrumb is the last item in the breadcrumb trail, it - * will not be made a hyperlink, since it already corresponds to the current view. - * - * @return true if this breadcrumb should be a hyperlink in the breadcrumb trail, or false otherwise - */ - public boolean isHyperlink() { - return this.hyperlink; - } - - public String getIcon() { - return icon; - } - - public void setIcon(String icon) { - this.icon = icon; - } - - public String getDisplayHTML() { - String display = ""; - if (icon != null) { - display += Canvas.imgHTML(icon, 16, 16); - } - display += this.displayName; - - return display; - } - - - @Override - public String toString() { - return this.name; - } - - private String getDefaultDisplayName() { - StringBuilder displayName = new StringBuilder(); - boolean first = true; - for (int i = 0; i < this.name.length(); i++) { - char currentChar = this.name.charAt(i); - if (!first) { - if (Character.isUpperCase(currentChar)) { - if ((i + 1) == this.name.length() || Character.isLowerCase(this.name.charAt(i + 1))) { - displayName.append(" "); - } - } - } else { - first = false; - } - displayName.append(currentChar); - } - return displayName.toString(); - } -} \ No newline at end of file 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 deleted file mode 100644 index a153ee0..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/BreadcrumbTrailPane.java +++ /dev/null @@ -1,128 +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; - -import com.google.gwt.user.client.Window; -import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.types.VerticalAlignment; -import com.smartgwt.client.widgets.Img; -import com.smartgwt.client.widgets.Label; -import com.smartgwt.client.widgets.layout.LayoutSpacer; -import com.smartgwt.client.widgets.toolbar.ToolStrip; - -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableLabel; -import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; - -/** - * GWT widget for the breadcrumb trail, which is displayed at the top of each page. - * - * @author Greg Hinkle - * @author Ian Springer - */ -public class BreadcrumbTrailPane extends ToolStrip { - - public BreadcrumbTrailPane() { - super(); - setHeight(28); - setAlign(VerticalAlignment.CENTER); - setWidth100(); - setMembersMargin(15); - - setOverflow(Overflow.HIDDEN); - - } - - public void refresh(ViewPath viewPath) { - try { - // before rebuilding the trail, remove the current members, and destroy them to avoid ID conflicts - SeleniumUtility.destroyMembers(this); - - LayoutSpacer ls = new LayoutSpacer(); - ls.setWidth(5); - addMember(ls); - - boolean first = true; - StringBuilder path = new StringBuilder(); - - for (ViewId viewId : viewPath.getViewPath()) { - - if (!first && !viewId.getBreadcrumbs().isEmpty()) { - addMember(getSpacer()); - } - - if (!first) { - path.append("/"); - } else { - first = false; - } - - boolean firstBC = true; - for (Breadcrumb breadcrumb : viewId.getBreadcrumbs()) { - - if (!firstBC) { - addMember(getSpacer()); - } else { - firstBC = false; - } - - addMember(getCrumb(breadcrumb, path.toString())); - } - path.append(viewId.getPath()); - } - - addMember(new LayoutSpacer()); - - } catch (Throwable t) { - System.err.println("Failed to refresh bread crumb HTML - cause: " + t); - } - - String title = "RHQ"; - if (!viewPath.getViewPath().isEmpty()) { - title += ": " - + viewPath.getViewPath().get(viewPath.getViewPath().size() - 1).getBreadcrumbs().get(0) - .getDisplayName(); - - } - Window.setTitle(title); - - redraw(); - } - - private Label getCrumb(Breadcrumb crumb, String path) { - Label l = null; - 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); - } - l.setValign(VerticalAlignment.CENTER); - l.setWrap(false); - l.setAutoWidth(); - return l; - } - - private Img getSpacer() { - return new Img("header/breadcrumb_space.png", 28, 28); - } -} 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 2b1597f..dca51dc 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 @@ -28,6 +28,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; import com.google.gwt.user.client.Window.Location; import com.smartgwt.client.core.KeyIdentifier; import com.smartgwt.client.types.Overflow; @@ -84,8 +85,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
private static MessageBar messageBar;
- private static BreadcrumbTrailPane breadCrumbTrailPane; - private static MessageCenter messageCenter;
private static String currentPath; @@ -153,8 +152,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> {
messageBar = new MessageBar();
- breadCrumbTrailPane = new BreadcrumbTrailPane(); - Canvas canvas = new Canvas(CONTENT_CANVAS_ID); canvas.setWidth100(); canvas.setHeight100(); @@ -303,14 +300,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { } }
- /** - * @deprecated - */ - @Deprecated - public static void refreshBreadCrumbTrail() { - //breadCrumbTrailPane.refresh(currentViewPath); - } - public static Messages getMessages() { return MSG; } @@ -324,7 +313,27 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { setHeight100(); }
+ private String getViewPathTitle(ViewPath viewPath) { + // default title is the path minus any IDs we find. That should give a least some nice default title. + StringBuilder path = new StringBuilder(); + for (ViewId view : viewPath.getViewPath()) { + // none of our path elements start with a digit that is NOT an ID; if we see an ID, skip it + if (!Character.isDigit(view.getPath().charAt(0))) { + if (path.length() > 0) { + path.append(" | "); + } + path.append(view.getPath()); + } + } + if (path.length() == 0) { + path.append("Core Application"); + } + return "RHQ: " + path.toString(); + } + public void renderView(final ViewPath viewPath) { + Window.setTitle(getViewPathTitle(viewPath)); + if (viewPath.isEnd()) { // default view History.newItem(DEFAULT_VIEW_PATH); @@ -363,8 +372,6 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { ((BookmarkableView) currentCanvas).renderView(viewPath.next()); } } - - refreshBreadCrumbTrail(); } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/View.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/View.java index 18a0fd9..2321d65 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/View.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/View.java @@ -30,34 +30,17 @@ package org.rhq.enterprise.gui.coregui.client; public class View { private ViewId id; private BookmarkableView descendantViewRenderer; - private Breadcrumb breadcrumb; private View parent;
public View(ViewId id) { - this(id, null, null); + this(id, null); }
public View(ViewId id, BookmarkableView descendantViewRenderer) { - this(id, descendantViewRenderer, null); - } - - public View(ViewId id, Breadcrumb breadcrumb) { - this(id, null, breadcrumb); - } - - public View(ViewId id, BookmarkableView descendantViewRenderer, Breadcrumb breadcrumb) { if (id == null) { throw new IllegalArgumentException("Id is null."); } this.id = id; - if (breadcrumb != null) { - if (!breadcrumb.getName().equals(id.getPath())) { - throw new IllegalArgumentException("Breadcrumb name is not equal to id name."); - } - this.breadcrumb = breadcrumb; - } else { - this.breadcrumb = new Breadcrumb(id.getPath()); - } this.descendantViewRenderer = descendantViewRenderer; }
@@ -89,17 +72,6 @@ public class View { } }
- /** - * Returns info that should be used when rendering a breadcrumb for this view in the - * breadcrumb trail, or null if a default breadcrumb should be used. - * - * @return info that should be used when rendering a breadcrumb for this view in the - * breadcrumb trail, or null if a default breadcrumb should be used - */ - public Breadcrumb getBreadcrumb() { - return this.breadcrumb; - } - public View getParent() { return this.parent; } @@ -110,11 +82,7 @@ public class View {
@Override public String toString() { - return "View[" + - "id=" + id + - ", descendantViewRenderer=" + - ((this.descendantViewRenderer != null) ? this.descendantViewRenderer.getClass().getName() : null) + - ", breadcrumb=" + this.breadcrumb + - ']'; + return "View[" + "id=" + id + ", descendantViewRenderer=" + + ((this.descendantViewRenderer != null) ? this.descendantViewRenderer.getClass().getName() : null) + ']'; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewId.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewId.java index cba747e..1f0743e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewId.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewId.java @@ -18,38 +18,13 @@ */ package org.rhq.enterprise.gui.coregui.client;
-import java.util.ArrayList; -import java.util.Arrays; -import java.util.List;
-/** - * - * @author Greg Hinkle - */ public class ViewId {
private String path;
- private List<Breadcrumb> breadcrumbs; - - public ViewId(String path, Breadcrumb... breadcrumbs) { - this.path = path; - if ( breadcrumbs != null) { - this.breadcrumbs = Arrays.asList(breadcrumbs); - } else { - this.breadcrumbs = new ArrayList<Breadcrumb>(); - } - } - public ViewId(String path) { this.path = path; - breadcrumbs = new ArrayList<Breadcrumb>(); - - breadcrumbs.add(new Breadcrumb(path)); - } - - public List<Breadcrumb> getBreadcrumbs() { - return breadcrumbs; }
public String getPath() { @@ -63,12 +38,15 @@ public class ViewId {
@Override 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;
ViewId viewId = (ViewId) o;
- if (!path.equals(viewId.path)) return false; + if (!path.equals(viewId.path)) + return false;
return true; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDetailsView.java index abb0657..594cbb4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertDetailsView.java @@ -44,7 +44,6 @@ import org.rhq.core.domain.criteria.AlertCriteria; 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.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.components.table.TimestampCellFormatter; @@ -58,7 +57,6 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; public class AlertDetailsView extends LocatableVLayout implements BookmarkableView {
private int alertId; - private ViewId viewId;
private static AlertDetailsView INSTANCE = new AlertDetailsView("alertDetailsView");
@@ -93,11 +91,6 @@ public class AlertDetailsView extends LocatableVLayout implements BookmarkableVi removeChild(child); }
- if (this.viewId != null) { - viewId.getBreadcrumbs().get(0).setDisplayName(MSG.view_alert_details_breadcrumb()); - CoreGUI.refreshBreadCrumbTrail(); - } - Log.info("AlertDetailsView-Alert: " + alert); ListGridRecord record = AlertDataSource.convert(alert); Log.info("AlertDetailsView-ListGridRecord: " + record); @@ -251,7 +244,6 @@ public class AlertDetailsView extends LocatableVLayout implements BookmarkableVi @Override public void renderView(ViewPath viewPath) { alertId = viewPath.getCurrentAsInt(); - viewId = viewPath.getCurrent();
show(alertId); } 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 e41d351..c8f9261 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 @@ -118,7 +118,6 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView setContent(bundlesListView); } } else { - viewPath.getCurrent().getBreadcrumbs().clear(); if (!viewPath.getNext().equals(currentNextPath)) { currentNextPath = viewPath.getNext(); bundleView = new BundleView(extendLocatorId("Bundle")); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java index 9b91e25..0bb149c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deployment/BundleDeploymentView.java @@ -53,7 +53,6 @@ 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.BookmarkableView; -import org.rhq.enterprise.gui.coregui.client.Breadcrumb; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ImageManager; import org.rhq.enterprise.gui.coregui.client.LinkManager; @@ -311,17 +310,8 @@ public class BundleDeploymentView extends LocatableVLayout implements Bookmarkab }
public void onSuccess(PageList<BundleResourceDeployment> result) { - deployment.setResourceDeployments(result); - - viewPath.getViewForIndex(2).getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(bundle.getId()), bundle.getName())); - viewId.getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(deployment.getId()), deployment.getName())); - CoreGUI.refreshBreadCrumbTrail(); - viewBundleDeployment(deployment, viewPath.getCurrent()); - } });
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java index 1c91fee..dd65070 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/destination/BundleDestinationView.java @@ -41,7 +41,6 @@ import org.rhq.core.domain.criteria.BundleDestinationCriteria; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; -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; @@ -250,15 +249,7 @@ public class BundleDestinationView extends LocatableVLayout implements Bookmarka }
public void onSuccess(PageList<BundleDestination> result) { - final BundleDestination destination = result.get(0); - - viewPath.getViewForIndex(2).getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(destination.getBundle().getId()), destination.getBundle().getName())); - viewId.getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(destination.getId()), destination.getName())); - CoreGUI.refreshBreadCrumbTrail(); - viewBundleDestination(destination, viewPath.getCurrent()); } }); 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 fc3ce87..1d64b7a 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 @@ -41,7 +41,6 @@ import org.rhq.core.domain.criteria.BundleCriteria; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; -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; @@ -294,10 +293,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView {
public void onSuccess(PageList<Bundle> result) { Bundle bundle = result.get(0); - viewId.getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(bundle.getId()), bundle.getName())); viewBundle(bundle, viewPath.getCurrent()); - CoreGUI.refreshBreadCrumbTrail(); } }); } else if (!viewPath.isEnd()) { @@ -307,10 +303,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView { } else if ("destinations".equals(current)) { tabs.selectTab(destinationsTab); } - // The tab change forces an update so fix up the breadcrumb to use displayName and not just the path - viewId.getBreadcrumbs().set(0, new Breadcrumb(String.valueOf(bundle.getId()), bundle.getName())); viewBundle(bundle, viewPath.getCurrent()); - CoreGUI.refreshBreadCrumbTrail(); } } else { // Although still relevant the bundle is no longer being viewed. Set to 0 for re-fetch if needed diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java index 807ec93..e3e8567 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/version/BundleVersionView.java @@ -39,7 +39,6 @@ import org.rhq.core.domain.criteria.BundleVersionCriteria; import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; -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; @@ -207,11 +206,6 @@ public class BundleVersionView extends LocatableVLayout implements BookmarkableV public void onSuccess(PageList<BundleVersion> result) { BundleVersion version = result.get(0); viewBundleVersion(version, viewPath.getCurrent()); - viewPath.getViewForIndex(2).getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(version.getBundle().getId()), version.getBundle().getName())); - viewId.getBreadcrumbs().set(0, - new Breadcrumb(String.valueOf(version.getId()), version.getVersion())); - CoreGUI.refreshBreadCrumbTrail(); } });
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 ddcaf9b..f90af80 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 @@ -34,7 +34,6 @@ import org.rhq.core.domain.event.composite.EventComposite; 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.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.LocatableVLayout; @@ -45,7 +44,6 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; public class EventCompositeDetailsView extends LocatableVLayout implements BookmarkableView {
private int eventId; - private ViewId viewId;
private static EventCompositeDetailsView INSTANCE = new EventCompositeDetailsView("eventCompositeDetailsView");
@@ -81,11 +79,6 @@ public class EventCompositeDetailsView extends LocatableVLayout implements Bookm removeChild(child); }
- if (this.viewId != null) { - viewId.getBreadcrumbs().get(0).setDisplayName(MSG.view_inventory_eventHistory_details()); - CoreGUI.refreshBreadCrumbTrail(); - } - DynamicForm form = new DynamicForm(); form.setWidth100(); form.setHeight100(); @@ -117,8 +110,6 @@ public class EventCompositeDetailsView extends LocatableVLayout implements Bookm @Override public void renderView(ViewPath viewPath) { eventId = viewPath.getCurrentAsInt(); - viewId = viewPath.getCurrent(); - show(eventId); }
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 e6bc5b9..9ab4029 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 @@ -49,7 +49,6 @@ import org.rhq.enterprise.gui.coregui.client.BookmarkableView; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; -import org.rhq.enterprise.gui.coregui.client.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; @@ -68,7 +67,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm private int groupDefinitionId; private GroupDefinition groupDefinition; private String basePath; - private ViewId viewId;
// editable form private TextItem id; @@ -209,14 +207,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm recursive.show(); expression.show(); recalculationInterval.show(); - - if (groupDefinitionId == 0) { - viewId.getBreadcrumbs().get(0).setDisplayName(MSG.view_dynagroup_newGroupDefinition()); - } else { - viewId.getBreadcrumbs().get(0).setDisplayName(MSG.view_dynagroup_editing(name.getValue().toString())); - } - CoreGUI.refreshBreadCrumbTrail(); - markForRedraw(); }
@@ -341,7 +331,6 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm public void onPermissionsLoaded(Set<Permission> permissions) { if (permissions != null && permissions.contains(Permission.MANAGE_INVENTORY)) { groupDefinitionId = viewPath.getCurrentAsInt(); - viewId = viewPath.getCurrent(); basePath = viewPath.getPathToCurrent(); lookupDetails(groupDefinitionId); } else { 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 deleted file mode 100644 index c54c0ff..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java +++ /dev/null @@ -1,360 +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.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.allen_sauer.gwt.log.client.Log; -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.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.ImageManager; -import org.rhq.enterprise.gui.coregui.client.Messages; -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; - -/** - * @author Greg Hinkle - * - * @deprecated {@link ResourceTreeDatasource} is used instead - */ -@Deprecated -public class NewResourceTreeDataSource extends DataSource { - - Messages MSG = CoreGUI.getMessages(); - - int rootId; - - private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); - - public NewResourceTreeDataSource() { - setClientOnly(false); - setDataProtocol(DSProtocol.CLIENTCUSTOM); - setDataFormat(DSDataFormat.CUSTOM); - - this.rootId = rootId; - - DataSourceField idDataField = new DataSourceTextField("id", MSG.common_title_id()); - idDataField.setPrimaryKey(true); - - DataSourceTextField nameDataField = new DataSourceTextField("name", MSG.common_title_name()); - nameDataField.setCanEdit(false); - - DataSourceTextField descriptionDataField = new DataSourceTextField("description", MSG - .common_title_description()); - descriptionDataField.setCanEdit(false); - - DataSourceImageField availabilityDataField = new DataSourceImageField("currentAvailability", MSG - .common_title_availability()); - descriptionDataField.setCanEdit(false); - - DataSourceTextField parentIdField = new DataSourceTextField("parentId", MSG.common_title_id_parent()); - 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"); - - ResourceCriteria criteria = new ResourceCriteria(); - - if (p == null) { - Log.info("DataSourceTree: Loading initial data"); - - criteria.addFilterId(rootId); - - } else { - Log.info("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(MSG.view_tree_common_loadFailed_generic(), 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(buildNodes(result)); - processResponse(requestId, response); - - } - }); - } - - /** - * Construct a set of TreeNodes from a list of resources - * - * @param resources - * @return - */ - public static TreeNode build(int rootId, Map<Integer, Resource> resources) { - Resource root = resources.get(rootId); - - TreeNode rootNode = new ResourceTreeNode(root); - - buildTree(rootNode, root, 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 rootNode; - // return introduceTypeFolders(records); - } - - private static void buildTree(TreeNode parent, Resource parentResource, Map<Integer, Resource> resources) { - - HashMap<ResourceType, TypeTreeNode> types = new HashMap<ResourceType, TypeTreeNode>(); - - ArrayList<ResourceTreeNode> childNodes = new ArrayList<ResourceTreeNode>(); - - for (Resource res : resources.values()) { - if (res.getParentResource() != null && res.getParentResource().getId() == parentResource.getId()) { - - // parent.setChildren(); - - ResourceTreeNode child = new ResourceTreeNode(res); - - childNodes.add(child); - - buildTree(child, res, resources); - - } - } - - parent.setChildren(childNodes.toArray(new TreeNode[childNodes.size()])); - - } - - 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()); - } - } - - 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); - } - - } - - 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()); - - // com.allen_sauer.gwt.log.client.Log.info(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", ImageManager.getAvailabilityIconFromAvailType(resource - .getCurrentAvailability().getAvailabilityType())); - - 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"); - } - } -} 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 deleted file mode 100644 index e957d7d..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java +++ /dev/null @@ -1,508 +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.resource.detail; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; - -import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.types.SelectionStyle; -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.events.SelectionChangedHandler; -import com.smartgwt.client.widgets.grid.events.SelectionEvent; -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.Tree; -import com.smartgwt.client.widgets.tree.TreeGrid; -import com.smartgwt.client.widgets.tree.TreeNode; -import com.smartgwt.client.widgets.tree.events.NodeContextClickEvent; -import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler; - -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.criteria.ResourceCriteria; -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.Resource; -import org.rhq.core.domain.resource.ResourceCategory; -import org.rhq.core.domain.resource.ResourceType; -import org.rhq.core.domain.util.PageControl; -import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.gui.coregui.client.Breadcrumb; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.ImageManager; -import org.rhq.enterprise.gui.coregui.client.ViewId; -import org.rhq.enterprise.gui.coregui.client.ViewPath; -import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; -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.ResourceTypeGWTServiceAsync; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener; -import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.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.message.Message; -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; - - private TreeGrid treeGrid; - private Menu contextMenu; - - private ViewId currentViewId; - - private ArrayList<ResourceSelectListener> selectListeners = new ArrayList<ResourceSelectListener>(); - - private boolean initialSelect = false; - - public NewResourceTreeView(String locatorId) { - super(locatorId); - - setWidth("250"); - setHeight100(); - - setShowResizeBar(true); - } - - public void onInit() { - - } - - private void buildTree() { - - treeGrid = new CustomResourceTreeGrid(getLocatorId()); - - treeGrid.setOpenerImage("resources/dir.png"); - treeGrid.setOpenerIconSize(16); - - // treeGrid.setAutoFetchData(true); - treeGrid.setAnimateFolders(false); - treeGrid.setSelectionType(SelectionStyle.SINGLE); - treeGrid.setShowRollOver(false); - treeGrid.setSortField("name"); - treeGrid.setShowHeader(false); - - treeGrid.setLeaveScrollbarGap(false); - - contextMenu = new Menu(); - MenuItem item = new MenuItem("Expand node"); - - treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { - public void onSelectionChanged(SelectionEvent selectionEvent) { - if (!selectionEvent.isRightButtonDown() && selectionEvent.getState()) { - if (treeGrid.getSelectedRecord() instanceof ResourceTreeDatasource.ResourceTreeNode) { - ResourceTreeDatasource.ResourceTreeNode node = (ResourceTreeDatasource.ResourceTreeNode) treeGrid - .getSelectedRecord(); - Log.info("Resource selected in tree: " + node.getResource()); - - String newToken = "Resource/" + node.getResource().getId(); - String currentToken = History.getToken(); - if (!currentToken.startsWith(newToken)) { - - String ending = currentToken.replaceFirst("^[^\/]*\/[^\/]*", ""); - - History.newItem("Resource/" + node.getResource().getId() + ending); - - } - } - - } - } - }); - - // This constructs the context menu for the resource at the time of the click. - setContextMenu(contextMenu); - - treeGrid.addNodeContextClickHandler(new NodeContextClickHandler() { - public void onNodeContextClick(final NodeContextClickEvent event) { - 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()); - } - } - }); - } - - 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, - ResourceTypeRepository.MetadataType.subCategory, - ResourceTypeRepository.MetadataType.pluginConfigurationDefinition, - ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), - new ResourceTypeRepository.TypeLoadedCallback() { - public void onTypesLoaded(ResourceType type) { - buildResourceContextMenu(node.getResource(), type); - contextMenu.showContextMenu(); - } - }); - } - - private void buildResourceContextMenu(final Resource resource, final ResourceType resourceType) { - contextMenu.setItems(new MenuItem(resource.getName())); - - contextMenu.addItem(new MenuItem(MSG.view_tree_common_contextMenu_type_name_label(resourceType.getName()))); - - MenuItem editPluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); - editPluginConfiguration.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - int resourceId = resource.getId(); - int resourceTypeId = resourceType.getId(); - - Window configEditor = new Window(); - configEditor.setTitle(MSG.view_tree_common_contextMenu_editPluginConfiguration(resource.getName())); - configEditor.setWidth(800); - configEditor.setHeight(800); - configEditor.setIsModal(true); - configEditor.setShowModalMask(true); - configEditor.setCanDragResize(true); - configEditor.centerInPage(); - configEditor.addItem(new ConfigurationEditor("PluginConfig-" + resource.getName(), resourceId, - resourceTypeId, ConfigurationEditor.ConfigType.plugin)); - configEditor.show(); - - } - }); - editPluginConfiguration.setEnabled(resourceType.getPluginConfigurationDefinition() != null); - contextMenu.addItem(editPluginConfiguration); - - MenuItem editResourceConfiguration = new MenuItem(MSG.view_tree_common_contextMenu_resourceConfiguration()); - editResourceConfiguration.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - int resourceId = resource.getId(); - int resourceTypeId = resourceType.getId(); - - final Window configEditor = new Window(); - configEditor.setTitle(MSG.view_tree_common_contextMenu_editResourceConfiguration(resource.getName())); - 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(); - } - }); - configEditor.addItem(new ConfigurationEditor("ResourceConfig-" + resource.getName(), resourceId, - resourceTypeId, ConfigurationEditor.ConfigType.resource)); - configEditor.show(); - - } - }); - editResourceConfiguration.setEnabled(resourceType.getResourceConfigurationDefinition() != null); - contextMenu.addItem(editResourceConfiguration); - - contextMenu.addItem(new MenuItemSeparator()); - - // Operations Menu - MenuItem operations = new MenuItem(MSG.view_tree_common_contextMenu_operations()); - Menu opSubMenu = new Menu(); - for (final OperationDefinition operationDefinition : resourceType.getOperationDefinitions()) { - MenuItem operationItem = new MenuItem(operationDefinition.getDisplayName()); - operationItem.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - new OperationCreateWizard(selectedResource, operationDefinition).startOperationWizard(); - } - }); - opSubMenu.addItem(operationItem); - // todo action - } - operations.setEnabled(!resourceType.getOperationDefinitions().isEmpty()); - operations.setSubmenu(opSubMenu); - contextMenu.addItem(operations); - - contextMenu.addItem(buildMetricsMenu(resourceType)); - - // Create Menu - MenuItem createChildMenu = new MenuItem(MSG.common_button_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); - - // Manually Add Menu - MenuItem importChildMenu = new MenuItem(MSG.common_button_import()); - Menu importChildSubMenu = new Menu(); - for (ResourceType childType : resourceType.getChildResourceTypes()) { - if (childType.isSupportsManualAdd()) { - importChildSubMenu.addItem(new MenuItem(childType.getName())); - //todo action - } - } - if (resourceType.getCategory() == ResourceCategory.PLATFORM) { - loadManuallyAddServersToPlatforms(importChildSubMenu); - } - importChildMenu.setSubmenu(importChildSubMenu); - importChildMenu.setEnabled(importChildSubMenu.getItems().length > 0); - contextMenu.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(MSG.view_tree_common_contextMenu_loadFailed_manualAddChildren(), - 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(MSG.view_tree_common_contextMenu_loadFailed_dashboard(), caught); - } - - public void onSuccess(List<Dashboard> result) { - - 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(MSG.view_tree_common_contextMenu_addChartToDashboard(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_ID, selectedResource.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( - MSG.view_tree_common_contextMenu_saveChartToDashboardFailure(), caught); - } - - public void onSuccess(Dashboard result) { - CoreGUI.getMessageCenter().notify( - new Message(MSG - .view_tree_common_contextMenu_saveChartToDashboardSuccessful(result - .getName()), Message.Severity.Info)); - } - }); - - } - }); - - } - - } - - } - }); - measurements.setSubmenu(measurementsSubMenu); - return measurements; - } - - Resource getResource(int resourceId) { - if (this.treeGrid != null && this.treeGrid.getTree() != null) { - ResourceTreeDatasource.ResourceTreeNode treeNode = (ResourceTreeDatasource.ResourceTreeNode) this.treeGrid - .getTree().findById(String.valueOf(resourceId)); - if (treeNode != null) { - return treeNode.getResource(); - } - } - return null; - } - - private void setRootResource(Resource rootResource) { - this.rootResource = rootResource; - } - - public void setSelectedResource(final Resource selectedResource, final ViewId viewId) { - this.selectedResource = selectedResource; - - TreeNode node = null; - if (treeGrid != null && treeGrid.getTree() != null - && (node = treeGrid.getTree().findById(String.valueOf(selectedResource.getId()))) != 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); - - treeGrid.deselectAllRecords(); - treeGrid.selectRecord(node); - - // Update breadcrumbs - viewId.getBreadcrumbs().clear(); - for (int i = parents.length - 1; i >= 0; i--) { - TreeNode n = parents[i]; - adjustBreadcrumb(n, viewId); - } - adjustBreadcrumb(node, viewId); - - CoreGUI.refreshBreadCrumbTrail(); - - } else { - - // Data not yet loaded or a node in a different tree - - final ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); - - resourceService.getPlatformForResource(selectedResource.getId(), new AsyncCallback<Resource>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_tree_common_loadFailed_root(), caught); - } - - public void onSuccess(Resource result) { - rootResource = result; - - ResourceCriteria criteria = new ResourceCriteria(); - criteria.addFilterRootResourceId(rootResource.getId()); - criteria.setPageControl(PageControl.getUnlimitedInstance()); - - resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler() - .handleError(MSG.view_tree_common_loadFailed_descendants(), caught); - } - - public void onSuccess(PageList<Resource> result) { - - loadTree(rootResource.getId(), result); - } - }); - } - }); - - } - } - - private void loadTree(int rootId, PageList<Resource> result) { - if (this.treeGrid != null) { - this.treeGrid.destroy(); - } - this.buildTree(); - - HashMap<Integer, Resource> data = new HashMap<Integer, Resource>(); - for (Resource res : result) { - data.put(res.getId(), res); - } - - Tree tree = new Tree(); - - tree.setRoot(NewResourceTreeDataSource.build(rootId, data)); - treeGrid.setData(tree); - addMember(this.treeGrid); - } - - private void adjustBreadcrumb(TreeNode node, ViewId viewId) { - if (node instanceof ResourceTreeDatasource.ResourceTreeNode) { - - Resource nr = ((ResourceTreeDatasource.ResourceTreeNode) node).getResource(); - String display = node.getName() + " <span class="subtitle">" + nr.getResourceType().getName() + "</span>"; - String icon = ImageManager.getResourceIcon(nr.getResourceType().getCategory()); - - 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)); - // } - } - } - - public void addResourceSelectListener(ResourceSelectListener listener) { - this.selectListeners.add(listener); - } - - public void renderView(ViewPath viewPath) { - currentViewId = viewPath.getCurrent(); - } -} \ 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 dcbfaea..a0d233d 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 @@ -66,9 +66,7 @@ import org.rhq.core.domain.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.resource.composite.ResourcePermission; 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; -import org.rhq.enterprise.gui.coregui.client.ImageManager; import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; @@ -78,11 +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.InventoryView; +import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule.OperationCreateWizard; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupContextMenu; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupDetailView; 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.common.detail.operation.schedule.OperationCreateWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.factory.ResourceFactoryCreateWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.factory.ResourceFactoryImportWizard; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; @@ -311,36 +309,6 @@ public class ResourceTreeView extends LocatableVLayout { }
treeGrid.markForRedraw(); - - // Update breadcrumbs - if (currentViewId != null) { - currentViewId.getBreadcrumbs().clear(); - if (null != parents) { - for (int i = parents.length - 1; i >= 0; i--) { - TreeNode n = parents[i]; - adjustBreadcrumb(n, currentViewId); - } - } - adjustBreadcrumb(selectedNode, currentViewId); - CoreGUI.refreshBreadCrumbTrail(); - } - } - } - - 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 = ImageManager.getResourceIcon(nr.getResourceType().getCategory()); - - 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 = ImageManager.getResourceIcon(((AutoGroupTreeNode) node).getResourceType().getCategory()); - - viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); } }
@@ -832,5 +800,5 @@ public class ResourceTreeView extends LocatableVLayout { setSelectedResource(resourceId); } } - + } diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index d7c9176..69803a3 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -658,7 +658,6 @@ view_alerts_ack_success = Successfully acknowledged {0} alerts view_alerts_ack_failure = Failed to acknowledge alerts with id''s: {0} view_alerts_ack_failure_all = Failed to acknowledge all alerts from this source view_alert_details_loadFailed = Failed to fetch alert details -view_alert_details_breadcrumb = Details view_alert_details_field_ack_by = Acknowledged by view_alert_details_field_ack_at = Acknowledged at view_alert_details_field_recovery_info = Recovery Info diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/header/breadcrumb_space.png b/modules/enterprise/gui/coregui/src/main/webapp/images/header/breadcrumb_space.png deleted file mode 100644 index e6fdc85..0000000 Binary files a/modules/enterprise/gui/coregui/src/main/webapp/images/header/breadcrumb_space.png and /dev/null differ
commit 8c80f13e1b4b15826e260ebe74d5f3820e6dfea9 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 19:04:23 2010 -0500
partial BZ 663727 - bundle main view no longer shows repositories unless user has manage_inventory perm also adds double click to the bundle list so it drills down just as if you clicked the link
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 6528e76..49395c0 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 @@ -319,4 +319,8 @@ public class LinkManager { public static String getTagLink(String tag) { return "#Reports/Subsystems/Tags/" + tag; } + + public static String getBundleLink(int bundleId) { + return "#Bundles/Bundle/" + bundleId; + } } 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 0dc46b5..e41d351 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 @@ -18,7 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.client.bundle;
-import com.allen_sauer.gwt.log.client.Log; +import java.util.Set; + import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.Canvas; @@ -26,7 +27,10 @@ import com.smartgwt.client.widgets.layout.SectionStack; import com.smartgwt.client.widgets.layout.SectionStackSection; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.authz.Permission; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.bundle.list.BundleView; @@ -38,19 +42,21 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack;
/** + * This is the main bundle view with left hand side trees and right hand side list/details view. + * * @author Greg Hinkle + * @author John Mazzitelli */ public class BundleTopView extends LocatableHLayout implements BookmarkableView {
public static final ViewName VIEW_ID = new ViewName("Bundles", MSG.view_bundle_bundles());
- private BundleTreeView bundleTreeView; - - private VLayout contentCanvas; - private ViewId currentNextPath; - private BundleView bundleView; - private BundlesListView bundlesListView; + + private BundleTreeView bundleTreeView; // the tree of bundle destinations and versions + private VLayout contentCanvas; // the right-side canvas container + private BundleView bundleView; // if the user is viewing an individual bundle, this is that right-side view + private BundlesListView bundlesListView; // if the user is not viewing an indiv. bundle, this is the right-side list
public BundleTopView(String locatorId) { super(locatorId); @@ -59,38 +65,74 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView setHeight100(); }
- @Override - protected void onDraw() { - super.onDraw(); - - SectionStack sectionStack = new LocatableSectionStack(getLocatorId()); - sectionStack.setShowResizeBar(true); - sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); - sectionStack.setWidth(250); - sectionStack.setHeight100(); - - SectionStackSection bundlesSection = new SectionStackSection(MSG.view_bundle_bundles()); - bundleTreeView = new BundleTreeView(extendLocatorId("BundleTree")); - bundlesSection.addItem(bundleTreeView); - sectionStack.addSection(bundlesSection); - - SectionStackSection repositoriesSection = new SectionStackSection(MSG.common_title_repositories()); - ContentRepositoryTreeView repoTree = new ContentRepositoryTreeView(extendLocatorId("RepoTree")); - repositoriesSection.addItem(repoTree); - sectionStack.addSection(repositoriesSection); - - SectionStackSection providersSection = new SectionStackSection(MSG.common_title_providers()); - sectionStack.addSection(providersSection); - - addMember(sectionStack); - - contentCanvas = new VLayout(); - contentCanvas.setWidth100(); - contentCanvas.setHeight100(); - addMember(contentCanvas); + public void renderView(final ViewPath viewPath) { + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { + @Override + public void onPermissionsLoaded(Set<Permission> permissions) { + // if we haven't done it yet, build the view components + if (bundleTreeView == null) { + SectionStack sectionStack = new LocatableSectionStack(getLocatorId()); + sectionStack.setShowResizeBar(true); + sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); + sectionStack.setWidth(250); + sectionStack.setHeight100(); + + SectionStackSection bundlesSection = new SectionStackSection(MSG.view_bundle_bundles()); + bundleTreeView = new BundleTreeView(extendLocatorId("BundleTree")); + bundlesSection.addItem(bundleTreeView); + sectionStack.addSection(bundlesSection); + + // we only show repositories if the user has the global manage_inventory perms since that is required + if (permissions != null && permissions.contains(Permission.MANAGE_INVENTORY)) { + SectionStackSection repositoriesSection = new SectionStackSection(MSG + .common_title_repositories()); + ContentRepositoryTreeView repoTree = new ContentRepositoryTreeView(extendLocatorId("RepoTree")); + repositoriesSection.addItem(repoTree); + sectionStack.addSection(repositoriesSection); + } + + // TODO: we aren't doing anything with providers yet + // SectionStackSection providersSection = new SectionStackSection(MSG.common_title_providers()); + // sectionStack.addSection(providersSection); + + addMember(sectionStack); + + contentCanvas = new VLayout(); + contentCanvas.setWidth100(); + contentCanvas.setHeight100(); + addMember(contentCanvas); + } + + if (viewPath.isRefresh()) { + bundleTreeView.refresh(); + } + + bundleTreeView.selectPath(viewPath); + + if (viewPath.isEnd()) { + if (currentNextPath == null && bundlesListView != null) { + bundlesListView.refresh(); + } else { + currentNextPath = null; + bundlesListView = new BundlesListView(extendLocatorId("BundleList"), permissions); + setContent(bundlesListView); + } + } else { + viewPath.getCurrent().getBreadcrumbs().clear(); + if (!viewPath.getNext().equals(currentNextPath)) { + currentNextPath = viewPath.getNext(); + bundleView = new BundleView(extendLocatorId("Bundle")); + setContent(bundleView); + bundleView.renderView(viewPath.next()); + } else { + bundleView.renderView(viewPath.next()); + } + } + } + }); }
- public void setContent(Canvas newContent) { + private void setContent(Canvas newContent) { for (Canvas c : contentCanvas.getMembers()) { c.destroy(); } @@ -98,36 +140,4 @@ public class BundleTopView extends LocatableHLayout implements BookmarkableView contentCanvas.markForRedraw(); }
- public void renderView(ViewPath viewPath) { - - if (viewPath.isRefresh()) { - bundleTreeView.refresh(); - } - - bundleTreeView.selectPath(viewPath); - - if (viewPath.isEnd()) { - if (currentNextPath == null && bundlesListView != null) { - // refresh - Log.info("Refreshing BundleTopView"); - - bundlesListView.refresh(); - } else { - currentNextPath = null; - this.bundlesListView = new BundlesListView(extendLocatorId("BundleList")); - setContent(this.bundlesListView); - } - } else { - viewPath.getCurrent().getBreadcrumbs().clear(); - if (!viewPath.getNext().equals(currentNextPath)) { - currentNextPath = viewPath.getNext(); - bundleView = new BundleView(extendLocatorId("Bundle")); - setContent(bundleView); - bundleView.renderView(viewPath.next()); - } else { - bundleView.renderView(viewPath.next()); - } - } - } - } 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 bbe68f2..e06b795 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 @@ -18,16 +18,25 @@ */ package org.rhq.enterprise.gui.coregui.client.bundle.list;
+import java.util.Set; + 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.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;
+import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.bundle.Bundle; import org.rhq.core.domain.bundle.composite.BundleWithLatestVersionComposite; import org.rhq.core.domain.criteria.BundleCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.bundle.create.BundleCreateWizard; import org.rhq.enterprise.gui.coregui.client.bundle.deploy.BundleDeployWizard; import org.rhq.enterprise.gui.coregui.client.components.table.AbstractTableAction; @@ -35,109 +44,152 @@ import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableActionEnablement; import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; 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.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** + * Shows a list of bundles in the system. The list gives you some actions like new, delete and deploy but + * only if you provide the proper permissions. If you give null permissions, no action buttons are shown. + * * @author Greg Hinkle + * @author John Mazzitelli */ -public class BundlesListView extends Table { - - public BundlesListView(String locatorId) { - this(locatorId, null); +public class BundlesListView extends Table<RPCDataSource<BundleWithLatestVersionComposite>> { + + private final Set<Permission> permissions; + + /** + * Creates a new list view. + * + * @param locatorId + * @param perms if perms is null, no button actions will be shown in the table + */ + public BundlesListView(String locatorId, Set<Permission> perms) { + this(locatorId, null, perms); }
- public BundlesListView(String locatorId, Criteria criteria) { + public BundlesListView(String locatorId, Criteria criteria, Set<Permission> perms) { super(locatorId, MSG.view_bundle_bundles(), criteria); + this.permissions = perms; setHeaderIcon("subsystems/bundle/Bundle_24.png"); setDataSource(new BundlesWithLatestVersionDataSource()); }
@Override protected void configureTable() { - getListGrid().getField("id").setWidth("60"); - getListGrid().getField("link").setWidth("25%"); - getListGrid().getField("link").setType(ListGridFieldType.LINK); - getListGrid().getField("link").setTarget("_self"); - - // getListGrid().getField("name").setCellFormatter(new CellFormatter() { - // public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { - // return "";//<a href="#Bundles/Bundle/" + listGridRecord.getAttribute("id") + "">" + o + "</a>"; - // } - // }); - - getListGrid().getField("description").setWidth("25%"); - getListGrid().getField("latestVersion").setWidth("25%"); - getListGrid().getField("versionsCount").setWidth("*"); - - addTableAction(extendLocatorId("New"), MSG.common_button_new(), null, new AbstractTableAction() { - public void executeAction(ListGridRecord[] selection, Object actionValue) { - new BundleCreateWizard().startWizard(); + + ListGridField idField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_ID, MSG.common_title_id()); + idField.setType(ListGridFieldType.INTEGER); + idField.setWidth("50"); + + ListGridField nameField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_NAMELINK, MSG + .common_title_name()); + nameField.setType(ListGridFieldType.LINK); + nameField.setTarget("_self"); + nameField.setWidth("33%"); + + ListGridField descField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_DESCRIPTION, MSG + .common_title_description()); + descField.setWidth("33%"); + + ListGridField latestVersionField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_LATEST_VERSION, + MSG.view_bundle_latestVersion()); + latestVersionField.setWidth("20%"); + latestVersionField.setAlign(Alignment.CENTER); + + ListGridField versionsCountField = new ListGridField(BundlesWithLatestVersionDataSource.FIELD_VERSIONS_COUNT, + MSG.view_bundle_list_versionsCount()); + versionsCountField.setType(ListGridFieldType.INTEGER); + versionsCountField.setWidth("*"); + versionsCountField.setAlign(Alignment.CENTER); + + setListGridFields(idField, nameField, descField, latestVersionField, versionsCountField); + + setListGridDoubleClickHandler(new DoubleClickHandler() { + @Override + public void onDoubleClick(DoubleClickEvent event) { + ListGrid listGrid = (ListGrid) event.getSource(); + ListGridRecord[] selectedRows = listGrid.getSelection(); + if (selectedRows != null && selectedRows.length == 1) { + String selectedId = selectedRows[0].getAttribute(BundlesWithLatestVersionDataSource.FIELD_ID); + CoreGUI.goToView(LinkManager.getBundleLink(Integer.valueOf(selectedId))); + } } });
- addTableAction(extendLocatorId("Delete"), MSG.common_button_delete(), MSG.common_msg_areYouSure(), - new AbstractTableAction(TableActionEnablement.ANY) { - public void executeAction(ListGridRecord[] selections, Object actionValue) { - BundlesWithLatestVersionDataSource ds = (BundlesWithLatestVersionDataSource) getDataSource(); - for (ListGridRecord selection : selections) { - BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); - final BundleWithLatestVersionComposite object = ds.copyValues(selection); - bundleManager.deleteBundle(object.getBundleId(), new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - MSG.view_bundle_list_deleteFailure(object.getBundleName()), caught); - } + // only show the buttons if we were given a set of permissions - passing in null is a way to say you only want the list, no actions + if (this.permissions != null) {
- public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_list_deleteSuccessful(object.getBundleName()), - Severity.Info)); + boolean hasAuth = permissions.contains(Permission.MANAGE_BUNDLE);
- CoreGUI.refresh(); - } - }); - } + addTableAction(extendLocatorId("New"), MSG.common_button_new(), null, new AbstractTableAction( + (hasAuth) ? TableActionEnablement.ALWAYS : TableActionEnablement.NEVER) { + public void executeAction(ListGridRecord[] selection, Object actionValue) { + new BundleCreateWizard().startWizard(); } });
- // can change this back to SINGLE selection when we feel like it. currently allowing the wizard to - // select the bundle. - addTableAction(extendLocatorId("Deploy"), MSG.view_bundle_deploy(), null, new AbstractTableAction() { - public void executeAction(ListGridRecord[] selection, Object actionValue) { - if (selection.length == 0) { - new BundleDeployWizard().startWizard(); - return; - } + addTableAction(extendLocatorId("Delete"), MSG.common_button_delete(), MSG.common_msg_areYouSure(), + new AbstractTableAction((hasAuth) ? TableActionEnablement.ANY : TableActionEnablement.NEVER) { + public void executeAction(ListGridRecord[] selections, Object actionValue) { + BundlesWithLatestVersionDataSource ds = (BundlesWithLatestVersionDataSource) getDataSource(); + for (ListGridRecord selection : selections) { + BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); + final BundleWithLatestVersionComposite object = ds.copyValues(selection); + bundleManager.deleteBundle(object.getBundleId(), new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_list_deleteFailure(object.getBundleName()), caught); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_list_deleteSuccessful(object.getBundleName()), + Severity.Info)); + + CoreGUI.refresh(); + } + }); + } + } + });
- BundlesWithLatestVersionDataSource ds = (BundlesWithLatestVersionDataSource) getDataSource(); - final BundleWithLatestVersionComposite object = ds.copyValues(selection[0]); - BundleCriteria bc = new BundleCriteria(); - bc.addFilterId(object.getBundleId()); - BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); - bundleManager.findBundlesByCriteria(bc, new AsyncCallback<PageList<Bundle>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_bundle_list_loadFailure(object.getBundleName()), - caught); + // can change this back to SINGLE selection when we feel like it. currently allowing the wizard to + // select the bundle. + addTableAction(extendLocatorId("Deploy"), MSG.view_bundle_deploy(), null, new AbstractTableAction( + (hasAuth) ? TableActionEnablement.ALWAYS : TableActionEnablement.NEVER) { + public void executeAction(ListGridRecord[] selection, Object actionValue) { + if (selection.length == 0) { + new BundleDeployWizard().startWizard(); + return; }
- public void onSuccess(PageList<Bundle> result) { - if (result == null || result.size() != 1) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_bundle_list_singleLoadFailure(object.getBundleName()), - Severity.Error)); - return; + BundlesWithLatestVersionDataSource ds = (BundlesWithLatestVersionDataSource) getDataSource(); + final BundleWithLatestVersionComposite object = ds.copyValues(selection[0]); + BundleCriteria bc = new BundleCriteria(); + bc.addFilterId(object.getBundleId()); + BundleGWTServiceAsync bundleManager = GWTServiceLookup.getBundleService(); + bundleManager.findBundlesByCriteria(bc, new AsyncCallback<PageList<Bundle>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_bundle_list_loadFailure(object.getBundleName()), caught); } - new BundleDeployWizard(result.get(0).getId()).startWizard(); - } - }); - } - });
+ public void onSuccess(PageList<Bundle> result) { + if (result == null || result.size() != 1) { + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_bundle_list_singleLoadFailure(object.getBundleName()), + Severity.Error)); + return; + } + new BundleDeployWizard(result.get(0).getId()).startWizard(); + } + }); + } + }); + }
}
- public int getMatches() { - return this.getListGrid().getTotalRows(); - } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java index c513513..0932620 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesWithLatestVersionDataSource.java @@ -25,15 +25,13 @@ 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.DataSourceLinkField; -import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.bundle.composite.BundleWithLatestVersionComposite; import org.rhq.core.domain.criteria.BundleCriteria; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; @@ -43,6 +41,13 @@ import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; */ public class BundlesWithLatestVersionDataSource extends RPCDataSource<BundleWithLatestVersionComposite> {
+ public static final String FIELD_ID = "id"; + public static final String FIELD_NAME = "name"; + public static final String FIELD_NAMELINK = "namelink"; + public static final String FIELD_DESCRIPTION = "description"; + public static final String FIELD_LATEST_VERSION = "latestVersion"; + public static final String FIELD_VERSIONS_COUNT = "versionsCount"; + private BundleGWTServiceAsync bundleService = GWTServiceLookup.getBundleService();
public BundlesWithLatestVersionDataSource() { @@ -52,31 +57,6 @@ public class BundlesWithLatestVersionDataSource extends RPCDataSource<BundleWith }
@Override - protected List<DataSourceField> addDataSourceFields() { - List<DataSourceField> fields = super.addDataSourceFields(); - - DataSourceIntegerField idField = new DataSourceIntegerField("id", MSG.common_title_id()); - idField.setPrimaryKey(true); - fields.add(idField); - - DataSourceLinkField linkField = new DataSourceLinkField("link", MSG.common_title_name()); - fields.add(linkField); - - DataSourceTextField descriptionField = new DataSourceTextField("description", MSG.common_title_description()); - fields.add(descriptionField); - - DataSourceTextField latestVersionField = new DataSourceTextField("latestVersion", MSG - .view_bundle_latestVersion()); - fields.add(latestVersionField); - - DataSourceIntegerField deploymentCountField = new DataSourceIntegerField("versionsCount", MSG - .view_bundle_list_versionsCount()); - fields.add(deploymentCountField); - - return fields; - } - - @Override protected void executeFetch(final DSRequest request, final DSResponse response) {
BundleCriteria criteria = new BundleCriteria(); @@ -112,29 +92,22 @@ public class BundlesWithLatestVersionDataSource extends RPCDataSource<BundleWith
@Override public BundleWithLatestVersionComposite copyValues(Record from) { - Integer idAttrib = from.getAttributeAsInt("id"); - String nameAttrib = from.getAttribute("name"); - String descriptionAttrib = from.getAttribute("description"); - String latestVersionAttrib = from.getAttribute("latestVersion"); - Integer versionsCountAttrib = from.getAttributeAsInt("versionsCount"); - - return new BundleWithLatestVersionComposite(idAttrib, nameAttrib, descriptionAttrib, latestVersionAttrib, - versionsCountAttrib.longValue()); + return (BundleWithLatestVersionComposite) from.getAttributeAsObject("object"); }
@Override public ListGridRecord copyValues(BundleWithLatestVersionComposite from) { ListGridRecord record = new ListGridRecord();
- record.setAttribute("id", from.getBundleId()); - record.setAttribute("name", from.getBundleName()); + record.setAttribute(FIELD_ID, from.getBundleId()); + record.setAttribute(FIELD_NAME, from.getBundleName());
- record.setAttribute("link", "#Bundles/Bundle/" + from.getBundleId()); + record.setAttribute(FIELD_NAMELINK, LinkManager.getBundleLink(from.getBundleId())); record.setLinkText(from.getBundleName());
- record.setAttribute("description", from.getBundleDescription()); - record.setAttribute("latestVersion", from.getLatestVersion()); - record.setAttribute("versionsCount", Integer.valueOf(from.getVersionsCount().intValue())); // want int, not long + record.setAttribute(FIELD_DESCRIPTION, from.getBundleDescription()); + record.setAttribute(FIELD_LATEST_VERSION, from.getLatestVersion()); + record.setAttribute(FIELD_VERSIONS_COUNT, Integer.valueOf(from.getVersionsCount().intValue())); // want int, not long
record.setAttribute("object", from);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java index 236f728..12b8e23 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeView.java @@ -44,7 +44,6 @@ public class BundleTreeView extends LocatableTreeGrid { setWidth100(); setHeight100(); setLeaveScrollbarGap(false); - // setShowRoot(true); setAutoFetchData(true); setAnimateFolders(false); setSelectionType(SelectionStyle.SINGLE); 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 feb325e..7192f94 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 @@ -98,7 +98,7 @@ public class TaggedView extends LocatableVLayout implements BookmarkableView {
Tab tab;
- BundlesListView bundlesView = new BundlesListView(getLocatorId(), criteria); + BundlesListView bundlesView = new BundlesListView(getLocatorId(), criteria, null); viewsWithTags.add(bundlesView); tab = new LocatableTab(extendLocatorId("bundleList"), MSG.view_bundle_bundles()); tab.setPane(bundlesView);
commit 647d8e92fe2cf690c42ce6b36889ec8c59109eb1 Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 15:47:43 2010 -0500
introduce a new PermissionsLoader. this does NOT cache - but it makes getting permissions a bit easier and less boiler plate code is needed. I've noticed all the uses of AuthorizationService all had the same basic onFailure implementation - this helps eliminate the need for that duplicate code and also makes the error message common across (which is what it should have been but some places duplicated messages in Message.properties - those dups have been removed).
this now provides a single place where perms can be obtained and, in the future, if we do want to do some type of caching or at least limit the loading of the same perms repeatedly in the same request, this one place is all that is needed to change.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoadedListener.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoadedListener.java index 0c20eca..2ae6faa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoadedListener.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoadedListener.java @@ -24,10 +24,22 @@ import java.util.Set; import org.rhq.core.domain.authz.Permission;
/** + * This is called by the {@link PermissionsLoader} when a set of permissions have been loaded + * or a failure occurred and the permissions failed to load. + * * @author Ian Springer + * @author John Mazzitelli */ public interface PermissionsLoadedListener {
- void onPermissionsLoaded(Set<Permission> permissions); - + /** + * The callback method that is called when the {@link PermissionsLoader} finished + * its remote call. If the call was successful, the given permissions argument will + * be non-null (but may be empty). If an error occurred that failed to load the permissions, + * <code>null</code> will be passed in as the value. + * + * @param permissions the permissions if successfully loaded; <code>null</code> if an error + * occurred and the permissions are unknown + */ + void onPermissionsLoaded(Set<Permission> permissions); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoader.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoader.java new file mode 100644 index 0000000..42cb182 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/PermissionsLoader.java @@ -0,0 +1,117 @@ +/* + * 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 java.util.EnumSet; +import java.util.Set; + +import com.google.gwt.user.client.rpc.AsyncCallback; + +import org.rhq.core.domain.authz.Permission; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.Message.Option; +import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; + +/** + * Provides convienence methods that loads permissions and notifies you via a callback when done. + * If an error occurs, the error will be logged in the message center. + * This stores the last error received, in case a caller wants more information on failures. + * + * Usage of this ensures consistency of error messages that occur when permission loading fails and + * allows callers to implement a smaller callback object ({@link PermissionsLoadedListener}). + * + * @author John Mazzitelli + */ +public class PermissionsLoader { + + private static Messages MSG = CoreGUI.getMessages(); + private Throwable lastError; + + /** + * Returns the last error that occurred while trying to load permissions. + * + * @return last error that occurred during permissions loading + */ + public Throwable getLastError() { + return lastError; + } + + public void loadExplicitGlobalPermissions(final PermissionsLoadedListener callback) { + GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + + @Override + public void onSuccess(Set<Permission> result) { + callback.onPermissionsLoaded(result); + } + + @Override + public void onFailure(Throwable caught) { + processFailure(MSG.util_userPerm_loadFailGlobal(), caught); + callback.onPermissionsLoaded(null); // indicate an error by passing in null + } + }); + } + + public void loadExplicitGroupPermissions(final int groupId, final PermissionsLoadedListener callback) { + GWTServiceLookup.getAuthorizationService().getExplicitGroupPermissions(groupId, + new AsyncCallback<Set<Permission>>() { + + @Override + public void onSuccess(Set<Permission> result) { + callback.onPermissionsLoaded(result); + } + + @Override + public void onFailure(Throwable caught) { + processFailure(MSG.util_userPerm_loadFailGroup(String.valueOf(groupId)), caught); + callback.onPermissionsLoaded(null); // indicate an error by passing in null + } + }); + } + + public void loadExplicitResourcePermissions(final int resourceId, final PermissionsLoadedListener callback) { + GWTServiceLookup.getAuthorizationService().getExplicitResourcePermissions(resourceId, + new AsyncCallback<Set<Permission>>() { + + @Override + public void onSuccess(Set<Permission> result) { + callback.onPermissionsLoaded(result); + } + + @Override + public void onFailure(Throwable caught) { + processFailure(MSG.util_userPerm_loadFailResource(String.valueOf(resourceId)), caught); + callback.onPermissionsLoaded(null); // indicate an error by passing in null + } + }); + } + + protected void processFailure(String msg, Throwable caught) { + this.lastError = caught; + EnumSet<Option> options = EnumSet.of(Message.Option.BackgroundJobResult); + Severity severity = Message.Severity.Error; + CoreGUI.getMessageCenter().notify(new Message(msg, caught, severity, options)); + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RoleEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RoleEditView.java index 0757313..3d63160 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RoleEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/RoleEditView.java @@ -19,7 +19,6 @@ package org.rhq.enterprise.gui.coregui.client.admin.roles;
import java.util.ArrayList; -import java.util.EnumSet; import java.util.List; import java.util.Set;
@@ -40,6 +39,8 @@ import org.rhq.core.domain.resource.group.GroupCategory; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ImageManager; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.admin.users.UsersDataSource; @@ -49,7 +50,6 @@ import org.rhq.enterprise.gui.coregui.client.components.selector.AssignedItemsCh import org.rhq.enterprise.gui.coregui.client.components.selector.AssignedItemsChangedHandler; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourceGroupSelector; -import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTab; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTabSet; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; @@ -89,18 +89,13 @@ public class RoleEditView extends AbstractRecordEditor<RolesDataSource> implemen
this.isSystemRole = RolesDataSource.isSystemRoleId(getRecordId());
- GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { @Override - public void onSuccess(Set<Permission> result) { - RoleEditView.this.hasManageSecurityPermission = result.contains(Permission.MANAGE_SECURITY); - checkIfLdapConfigured(); - } - - @Override - public void onFailure(Throwable caught) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.util_userPerm_loadFailGlobal(), caught, Message.Severity.Error, EnumSet - .of(Message.Option.BackgroundJobResult))); + public void onPermissionsLoaded(Set<Permission> perms) { + if (perms != null) { + RoleEditView.this.hasManageSecurityPermission = perms.contains(Permission.MANAGE_SECURITY); + checkIfLdapConfigured(); + } } }); } 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 3c1c5f1..190045a 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 @@ -18,23 +18,20 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.roles;
-import java.util.EnumSet; import java.util.Set;
-import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; 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.BookmarkableView; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.admin.AdministrationView; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * A table that lists all roles and provides the ability to view details of or delete those roles and to create new @@ -48,7 +45,7 @@ public class RolesView extends TableSection<RolesDataSource> implements Bookmark public static final ViewName VIEW_ID = new ViewName("Roles", MSG.view_adminSecurity_roles()); public static final String VIEW_PATH = AdministrationView.VIEW_ID + "/" + AdministrationView.SECTION_SECURITY_VIEW_ID + "/" + VIEW_ID; - + private static final String HEADER_ICON = "global/Role_24.png";
private boolean hasManageSecurity; @@ -60,7 +57,7 @@ public class RolesView extends TableSection<RolesDataSource> implements Bookmark setDataSource(datasource); setHeaderIcon(HEADER_ICON); } - + @Override protected void configureTable() { super.configureTable(); @@ -108,23 +105,17 @@ public class RolesView extends TableSection<RolesDataSource> implements Bookmark }
private void fetchManageSecurityPermissionAsync() { - GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions( - new AsyncCallback<Set<Permission>>() { - - @Override - public void onSuccess(Set<Permission> result) { - hasManageSecurity = result.contains(Permission.MANAGE_SECURITY); + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { + @Override + public void onPermissionsLoaded(Set<Permission> permissions) { + if (permissions != null) { + hasManageSecurity = permissions.contains(Permission.MANAGE_SECURITY); refresh(); - } - - @Override - public void onFailure(Throwable caught) { + } else { hasManageSecurity = false; - CoreGUI.getMessageCenter().notify( - new Message(MSG.util_userPerm_loadFailGlobal(), caught, Message.Severity.Error, EnumSet - .of(Message.Option.BackgroundJobResult))); } - }); + } + }); }
@Override 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 d7a7481..04bc1b3 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 @@ -19,11 +19,9 @@ package org.rhq.enterprise.gui.coregui.client.admin.users;
import java.util.ArrayList; -import java.util.EnumSet; import java.util.List; import java.util.Set;
-import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Record; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.PasswordItem; @@ -37,15 +35,14 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.auth.Principal; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.form.AbstractRecordEditor; import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; import org.rhq.enterprise.gui.coregui.client.components.selector.AssignedItemsChangedEvent; import org.rhq.enterprise.gui.coregui.client.components.selector.AssignedItemsChangedHandler; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * A form for viewing and/or editing an RHQ user (i.e. a {@link Subject}, and optionally an associated @@ -70,21 +67,16 @@ public class UserEditView extends AbstractRecordEditor<UsersDataSource> { public void renderView(ViewPath viewPath) { super.renderView(viewPath);
- GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { @Override - public void onSuccess(Set<Permission> result) { - UserEditView.this.hasManageSecurityPermission = result.contains(Permission.MANAGE_SECURITY); - Subject sessionSubject = UserSessionManager.getSessionSubject(); - boolean isEditingSelf = (sessionSubject.getId() == getRecordId()); - boolean isReadOnly = (!UserEditView.this.hasManageSecurityPermission && !isEditingSelf); - init(isReadOnly); - } - - @Override - public void onFailure(Throwable caught) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.util_userPerm_loadFailGlobal(), caught, Message.Severity.Error, EnumSet - .of(Message.Option.BackgroundJobResult))); + public void onPermissionsLoaded(Set<Permission> permissions) { + if (permissions != null) { + UserEditView.this.hasManageSecurityPermission = permissions.contains(Permission.MANAGE_SECURITY); + Subject sessionSubject = UserSessionManager.getSessionSubject(); + boolean isEditingSelf = (sessionSubject.getId() == getRecordId()); + boolean isReadOnly = (!UserEditView.this.hasManageSecurityPermission && !isEditingSelf); + init(isReadOnly); + } } }); } 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 26ef84d..4249101 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 @@ -19,23 +19,20 @@ package org.rhq.enterprise.gui.coregui.client.admin.users;
import java.util.ArrayList; -import java.util.EnumSet; 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.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.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.admin.AdministrationView; import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * A table that lists all users and provides the ability to view or edit details of users, delete users, or create new @@ -78,20 +75,17 @@ public class UsersView extends TableSection<UsersDataSource> { }
private void fetchManageSecurityPermissionAsync() { - GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions( - new AsyncCallback<Set<Permission>>() { - public void onSuccess(Set<Permission> result) { - hasManageSecurity = result.contains(Permission.MANAGE_SECURITY); + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { + @Override + public void onPermissionsLoaded(Set<Permission> permissions) { + if (permissions != null) { + hasManageSecurity = permissions.contains(Permission.MANAGE_SECURITY); refresh(); - } - - public void onFailure(Throwable caught) { + } else { hasManageSecurity = false; - CoreGUI.getMessageCenter().notify( - new Message(MSG.util_userPerm_loadFailGlobal(), caught, Message.Severity.Error, EnumSet - .of(Message.Option.BackgroundJobResult))); } - }); + } + }); }
private List<ListGridField> createFields() { 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 5ec9af2..981fadc 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 @@ -24,6 +24,7 @@ import com.google.gwt.user.client.rpc.RpcRequestBuilder; import com.google.gwt.user.client.rpc.ServiceDefTarget;
import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.UserSessionManager;
/** @@ -101,6 +102,10 @@ public class GWTServiceLookup { return secure(ResourceBossGWTServiceAsync.Util.getInstance()); }
+ /** + * Consider using {@link PermissionsLoader} instead of using + * this authorization service directly. + */ public static AuthorizationGWTServiceAsync getAuthorizationService() { return secure(AuthorizationGWTServiceAsync.Util.getInstance()); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java index c7172a9..2e3d919 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java @@ -23,7 +23,6 @@ import java.util.EnumSet; import java.util.List; import java.util.Set;
-import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.Label; @@ -33,15 +32,15 @@ import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.group.GroupCategory; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ImageManager; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.components.TitleBar; import org.rhq.enterprise.gui.coregui.client.components.view.AbstractSectionedLeftNavigationView; import org.rhq.enterprise.gui.coregui.client.components.view.NavigationItem; import org.rhq.enterprise.gui.coregui.client.components.view.NavigationSection; import org.rhq.enterprise.gui.coregui.client.components.view.ViewFactory; import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField; import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupListView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.definitions.GroupDefinitionListView; @@ -92,17 +91,10 @@ public class InventoryView extends AbstractSectionedLeftNavigationView {
@Override protected void onInit() { - GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_inventory_cannotGetGlobalPerms(), caught); - globalPermissions = EnumSet.noneOf(Permission.class); - InventoryView.super.onInit(); - } - - @Override - public void onSuccess(Set<Permission> result) { - globalPermissions = result; + public void onPermissionsLoaded(Set<Permission> permissions) { + globalPermissions = (permissions != null) ? permissions : EnumSet.noneOf(Permission.class); InventoryView.super.onInit(); } }); 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 d36e17c..0ad75df 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,14 +18,12 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail;
-import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set;
import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.user.client.History; -import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Side; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.layout.Layout; @@ -33,6 +31,8 @@ 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.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; 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; @@ -40,8 +40,6 @@ 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.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -160,19 +158,10 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo }
public void renderView(final ViewPath viewPath) { - GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { @Override - public void onSuccess(Set<Permission> result) { - globalPermissions = result; - renderTabs(viewPath); - } - - @Override - public void onFailure(Throwable caught) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.util_userPerm_loadFailGlobal(), caught, Message.Severity.Error, EnumSet - .of(Message.Option.BackgroundJobResult))); - globalPermissions = new HashSet<Permission>(); + public void onPermissionsLoaded(Set<Permission> permissions) { + globalPermissions = (permissions != null) ? permissions : new HashSet<Permission>(); renderTabs(viewPath); } }); 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 0fb0e77..0f5fe93 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 @@ -29,6 +29,8 @@ 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.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.table.AbstractTableAction; import org.rhq.enterprise.gui.coregui.client.components.table.TableActionEnablement; @@ -153,26 +155,21 @@ public class GroupDefinitionListView extends TableSection {
@Override public void renderView(final ViewPath viewPath) { - GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_dynagroup_permUnknown(), caught); - handleAuthorizationFailure(); + public void onPermissionsLoaded(Set<Permission> permissions) { + if (permissions != null && permissions.contains(Permission.MANAGE_INVENTORY)) { + GroupDefinitionListView.super.renderView(viewPath); + } else { + handleAuthorizationFailure(); + } }
private void handleAuthorizationFailure() { CoreGUI.getErrorHandler().handleError(MSG.view_dynagroup_permDenied()); 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 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 3a9fdcf..e6bc5b9 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 @@ -47,6 +47,8 @@ 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.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; 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; @@ -334,31 +336,24 @@ public class SingleGroupDefinitionView extends LocatableVLayout implements Bookm
@Override public void renderView(final ViewPath viewPath) { - GWTServiceLookup.getAuthorizationService().getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { + new PermissionsLoader().loadExplicitGlobalPermissions(new PermissionsLoadedListener() { @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_dynagroup_permUnknown(), caught); - handleAuthorizationFailure(); - } - - private void handleAuthorizationFailure() { - CoreGUI.getErrorHandler().handleError(MSG.view_dynagroup_permDenied()); - History.back(); - } - - @Override - public void onSuccess(Set<Permission> result) { - if (result.contains(Permission.MANAGE_INVENTORY) == false) { - handleAuthorizationFailure(); - } else { + public void onPermissionsLoaded(Set<Permission> permissions) { + if (permissions != null && permissions.contains(Permission.MANAGE_INVENTORY)) { groupDefinitionId = viewPath.getCurrentAsInt(); viewId = viewPath.getCurrent(); basePath = viewPath.getPathToCurrent(); lookupDetails(groupDefinitionId); + } else { + handleAuthorizationFailure(); } } - });
+ private void handleAuthorizationFailure() { + CoreGUI.getErrorHandler().handleError(MSG.view_dynagroup_permDenied()); + History.back(); + } + }); }
} 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 7629074..fa7a0f8 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 @@ -44,7 +44,8 @@ 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.Messages; -import org.rhq.enterprise.gui.coregui.client.gwt.AuthorizationGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; +import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTServiceAsync;
@@ -65,7 +66,7 @@ public class AutodiscoveryQueueDataSource extends DataSource { private int unlimited = -1; private int maximumPlatformsToDisplay = -1; private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); - private AuthorizationGWTServiceAsync authorizationService = GWTServiceLookup.getAuthorizationService(); + private PermissionsLoader permissionsLoader = new PermissionsLoader(); private TreeGrid dataContainerReference = null; private static final Permission MANAGE_INVENTORY = Permission.MANAGE_INVENTORY;
@@ -141,40 +142,40 @@ public class AutodiscoveryQueueDataSource extends DataSource { }
//determine if has manage inventory perms, if so then chain and proceed with getting discovered resources - authorizationService.getExplicitGlobalPermissions(new AsyncCallback<Set<Permission>>() { - public void onSuccess(Set<Permission> globalPermissions) { - Boolean accessGranted = globalPermissions.contains(MANAGE_INVENTORY); - if (accessGranted) { - if (dataContainerReference != null) { - dataContainerReference.setEmptyMessage(EMPTY_MESSAGE); + permissionsLoader.loadExplicitGlobalPermissions(new PermissionsLoadedListener() { + @Override + public void onPermissionsLoaded(Set<Permission> permissions) { + if (permissions != null) { + Boolean accessGranted = permissions.contains(MANAGE_INVENTORY); + if (accessGranted) { + if (dataContainerReference != null) { + dataContainerReference.setEmptyMessage(EMPTY_MESSAGE); + } + resourceService.getQueuedPlatformsAndServers(statuses, pc, + new AsyncCallback<Map<Resource, List<Resource>>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler() + .handleError(MSG.view_autoDiscoveryQ_loadFailure(), caught); + } + + public void onSuccess(Map<Resource, List<Resource>> result) { + response.setData(buildNodes(result)); + processResponse(request.getRequestId(), response); + } + }); + } else { + Log.debug("(User does not have required managed inventory permissions. " + EMPTY_MESSAGE); + response.setTotalRows(0); + if (dataContainerReference != null) { + Log.trace("Setting better empty container message." + + NO_MANAGE_INVENTORY_PERMS_EMPTY_MESSAGE); + dataContainerReference.setEmptyMessage(NO_MANAGE_INVENTORY_PERMS_EMPTY_MESSAGE); + } + processResponse(request.getRequestId(), response); } - resourceService.getQueuedPlatformsAndServers(statuses, pc, - new AsyncCallback<Map<Resource, List<Resource>>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_autoDiscoveryQ_loadFailure(), caught); - } - - public void onSuccess(Map<Resource, List<Resource>> result) { - response.setData(buildNodes(result)); - processResponse(request.getRequestId(), response); - } - }); - } else { - Log.debug("(User does not have required managed inventory permissions. " + EMPTY_MESSAGE); - response.setTotalRows(0); - if (dataContainerReference != null) { - Log.trace("Setting better empty container message." + NO_MANAGE_INVENTORY_PERMS_EMPTY_MESSAGE); - dataContainerReference.setEmptyMessage(NO_MANAGE_INVENTORY_PERMS_EMPTY_MESSAGE); - } - processResponse(request.getRequestId(), response); } } - - public void onFailure(Throwable caught) { - Log.error("Unable to determine whether if user has manage inventory permissions - check server logs."); - } }); - }
private TreeNode[] buildNodes(Map<Resource, List<Resource>> result) { diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 2b65a7f..d7c9176 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -869,7 +869,7 @@ view_autoDiscoveryQ_ignoreFailure = Failed to ignore resources view_autoDiscoveryQ_ignoreSuccessful = You have successfully ignored the selected resources. view_autoDiscoveryQ_unignoreFailure = Failed to unignore resources view_autoDiscoveryQ_unignoreSuccessful = You have successfully unignored the selected resources. -view_autoDiscoveryQ_noperm = (Required manage inventory permissions missing. See Administrator to change) +view_autoDiscoveryQ_noperm = (You are not authorized to view the auto-discovery queue) view_autoDiscoveryQ_noItems = No items to show view_autoDiscoveryQ_field_parentId = Parent ID view_autoDiscoveryQ_field_name = Resource Name @@ -1219,7 +1219,6 @@ view_portlet_tagCloud_title = TagCloud # =================== Inventory ===================== view_inventory_adq = Discovery Queue view_inventory_sectionHelp = From this section, newly discovered Resources, inventoried Resources, and Groups can be viewed and managed. -view_inventory_cannotGetGlobalPerms = Could not determine global permissions - assuming none. view_inventory_problemGroups = Problem Groups view_inventory_collectionInterval = Collection Interval view_inventory_mixed = mixed @@ -1387,7 +1386,6 @@ view_dynagroup_expression = Expression view_dynagroup_recursive = Recursive view_dynagroup_loadDefinitionFailure = Failed to load group definition [{0}] view_dynagroup_loadDefinitionMissing = There is no group definition with the ID of [{0}] -view_dynagroup_permUnknown = Could not determine if you have the proper permissions - access is denied view_dynagroup_permDenied = You do not have permission to view group definitions view_dynagroup_definitions = DynaGroup Definitions view_group_detail_failLoad = Failed to load group for group with ID [{0}]
commit 2a36e647404caa3c850b564512a892da74e1b309 Merge: 58f7d81... bfa4afd... Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 14:03:13 2010 -0500
Merge commit 'origin/master'
commit 58f7d81f12eb70697b8beb5cf96507b07cbda16c Author: John Mazzitelli mazz@redhat.com Date: Thu Dec 16 13:29:35 2010 -0500
propogate exceptions to gwt client
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java index 50253c9..b8a0a6e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/RepoGWTService.java @@ -33,7 +33,6 @@ import org.rhq.core.domain.util.PageList; */ public interface RepoGWTService extends RemoteService {
- - PageList<Repo> findReposByCriteria(RepoCriteria criteria); + PageList<Repo> findReposByCriteria(RepoCriteria criteria) throws Exception;
} 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 073a6f7..98c26cc 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 @@ -40,10 +40,10 @@ public class RepoGWTServiceImpl extends AbstractGWTServiceImpl implements RepoGW
private RepoManagerLocal repoManager = LookupUtil.getRepoManagerLocal();
- public PageList<Repo> findReposByCriteria(RepoCriteria criteria) { + public PageList<Repo> findReposByCriteria(RepoCriteria criteria) throws Exception { try { return SerialUtility.prepare(repoManager.findReposByCriteria(getSessionSubject(), criteria), - "ContentService.findReposByCriteria"); + "RepoService.findReposByCriteria"); } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); }
commit bfa4afdfdf10b80f08113fcb31b301d5e2e958e1 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Dec 16 19:25:54 2010 +0100
BZ 653695 - refactor the apache discovery to continue processing the rest of process scan results after an error during processing one of them.
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 a5e19e5..c82d3ae 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 @@ -26,6 +26,7 @@ import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; +import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -77,6 +78,14 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
private static final Log log = LogFactory.getLog(ApacheServerDiscoveryComponent.class);
+ private static class DiscoveryFailureException extends Exception { + private static final long serialVersionUID = 1L; + + public DiscoveryFailureException(String message) { + super(message); + } + } + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws Exception { Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>(); @@ -84,107 +93,125 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen // Process any PC-discovered OS processes... List<ProcessScanResult> processes = discoveryContext.getAutoDiscoveredProcesses(); for (ProcessScanResult process : processes) { - //String executablePath = process.getProcessInfo().getName(); - String executableName = getExecutableName(process); - File executablePath = OsProcessUtility.getProcExe(process.getProcessInfo().getPid(), executableName); - if (executablePath == null) { - log.error("Executable path could not be determined for Apache [" + process.getProcessInfo() + "]."); - 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."); - continue; - } - log.debug("Apache executable path: " + executablePath); - ApacheBinaryInfo binaryInfo; try { - binaryInfo = ApacheBinaryInfo - .getInfo(executablePath.getPath(), discoveryContext.getSystemInformation()); + DiscoveredResourceDetails apache = discoverSingleProcess(discoveryContext, process); + discoveredResources.add(apache); + } catch (DiscoveryFailureException e) { + log.warn("Discovery of Apache process [" + process.getProcessInfo() + "] failed: " + e.getMessage()); } catch (Exception e) { - log.error("'" + executablePath + "' is not a valid Apache executable (" + e + ")."); - continue; + log.error("Discovery of Apache process [" + process.getProcessInfo() + "] failed with an exception.", e); } + }
- if (isSupportedVersion(binaryInfo.getVersion())) { - String serverRoot = getServerRoot(binaryInfo, process.getProcessInfo()); - if (serverRoot == null) { - log.error("Unable to determine server root for Apache process: " + process.getProcessInfo()); - continue; - } + return discoveredResources; + }
- File serverConfigFile = getServerConfigFile(binaryInfo, process.getProcessInfo(), serverRoot); - if (serverConfigFile == null) { - log.error("Unable to determine server config file for Apache process: " + process.getProcessInfo()); - continue; - } + /** + * Performs discovery on the single process scan result. + * + * @param discoveryContext the discovery context + * @param process the process discovered by the scan + * @return resource details + * @throws DiscoveryFailureException if the discovery failed due to inability to detect necessary data from + * the process info. + * @throws Exception other unhandled exception + */ + private DiscoveredResourceDetails discoverSingleProcess(ResourceDiscoveryContext<PlatformComponent> discoveryContext, + ProcessScanResult process) throws DiscoveryFailureException, Exception { + //String executablePath = process.getProcessInfo().getName(); + String executableName = getExecutableName(process); + File executablePath = OsProcessUtility.getProcExe(process.getProcessInfo().getPid(), executableName); + if (executablePath == null) { + throw new DiscoveryFailureException("Executable path could not be determined."); + } + if (!executablePath.isAbsolute()) { + throw new DiscoveryFailureException("Executable path (" + executablePath + ") is not absolute." + + "Please restart Apache specifying an absolute path for the executable."); + } + log.debug("Apache executable path: " + executablePath); + ApacheBinaryInfo binaryInfo; + try { + binaryInfo = ApacheBinaryInfo + .getInfo(executablePath.getPath(), discoveryContext.getSystemInformation()); + } catch (Exception e) { + throw new DiscoveryFailureException("'" + executablePath + "' is not a valid Apache executable (" + e + ")."); + }
- Configuration pluginConfig = discoveryContext.getDefaultPluginConfiguration(); + if (!isSupportedVersion(binaryInfo.getVersion())) { + throw new DiscoveryFailureException("Apache " + binaryInfo.getVersion() + " is not suppported."); + } + + String serverRoot = getServerRoot(binaryInfo, process.getProcessInfo()); + if (serverRoot == null) { + throw new DiscoveryFailureException("Unable to determine server root."); + }
- PropertySimple executablePathProp = new PropertySimple( - ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, executablePath); - pluginConfig.put(executablePathProp); + File serverConfigFile = getServerConfigFile(binaryInfo, process.getProcessInfo(), serverRoot); + if (serverConfigFile == null) { + throw new DiscoveryFailureException("Unable to determine server config file."); + }
- PropertySimple serverRootProp = new PropertySimple( - ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT, serverRoot); - pluginConfig.put(serverRootProp); + Configuration pluginConfig = discoveryContext.getDefaultPluginConfiguration();
- PropertySimple configFile = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF, - serverConfigFile); - pluginConfig.put(configFile); + PropertySimple executablePathProp = new PropertySimple( + ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, executablePath); + pluginConfig.put(executablePathProp);
- PropertySimple inclusionGlobs = new PropertySimple( - PluginDescriptorBasedAugeasConfiguration.INCLUDE_GLOBS_PROP, serverConfigFile); - pluginConfig.put(inclusionGlobs); + PropertySimple serverRootProp = new PropertySimple( + ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT, serverRoot); + pluginConfig.put(serverRootProp);
- ApacheDirectiveTree serverConfig = loadParser(serverConfigFile.getAbsolutePath(), serverRoot); + PropertySimple configFile = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF, + serverConfigFile); + pluginConfig.put(configFile);
- String serverUrl = null; - String vhostsGlobInclude = null; + PropertySimple inclusionGlobs = new PropertySimple( + PluginDescriptorBasedAugeasConfiguration.INCLUDE_GLOBS_PROP, serverConfigFile); + pluginConfig.put(inclusionGlobs);
- //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); - //reparse the configuration with the new ServerRoot - serverConfig = loadParser(serverConfigFile.getAbsolutePath(), serverRoot); - } + ApacheDirectiveTree serverConfig = loadParser(serverConfigFile.getAbsolutePath(), serverRoot);
- serverUrl = getUrl(serverConfig, binaryInfo.getVersion()); - vhostsGlobInclude = scanForGlobInclude(serverConfig); + String serverUrl = null; + String vhostsGlobInclude = null;
- if (serverUrl != null) { - Property urlProp = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_URL, serverUrl); - pluginConfig.put(urlProp); - } + //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); + //reparse the configuration with the new ServerRoot + serverConfig = loadParser(serverConfigFile.getAbsolutePath(), serverRoot); + }
- if (vhostsGlobInclude != null) { - 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 + "*")); - } + serverUrl = getUrl(serverConfig, binaryInfo.getVersion()); + vhostsGlobInclude = scanForGlobInclude(serverConfig);
- List<InetSocketAddress> snmpAddresses = findSNMPAddresses(serverConfig, new File(serverRoot)); - if (snmpAddresses != null && snmpAddresses.size() > 0) { - InetSocketAddress addr = snmpAddresses.get(0); - int port = addr.getPort(); - InetAddress host = addr.getAddress() == null ? InetAddress.getLocalHost() : addr.getAddress(); - - pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_HOST, host.getHostAddress())); - pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_PORT, port)); - } - - discoveredResources.add(createResourceDetails(discoveryContext, pluginConfig, process.getProcessInfo(), - binaryInfo)); - } + if (serverUrl != null) { + Property urlProp = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_URL, serverUrl); + pluginConfig.put(urlProp); }
- return discoveredResources; + if (vhostsGlobInclude != null) { + 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 + "*")); + } + + List<InetSocketAddress> snmpAddresses = findSNMPAddresses(serverConfig, new File(serverRoot)); + if (snmpAddresses != null && snmpAddresses.size() > 0) { + InetSocketAddress addr = snmpAddresses.get(0); + int port = addr.getPort(); + InetAddress host = addr.getAddress() == null ? InetAddress.getLocalHost() : addr.getAddress(); + + pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_HOST, host.getHostAddress())); + pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_PORT, port)); + } + + return createResourceDetails(discoveryContext, pluginConfig, process.getProcessInfo(), + binaryInfo); }
public ResourceUpgradeReport upgrade(ResourceUpgradeContext<PlatformComponent> context) {
commit 9d2a7b2c94f485660161085982e4084ee2d3677d Author: Ian Springer ian.springer@redhat.com Date: Thu Dec 16 12:49:02 2010 -0500
move OperationSchedule, ResourceOperationSchedule and GroupOperationSchedule POJOs from server-jar to core-domain, so they can be used by coregui
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java b/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java index 6f6756c..da58047 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/common/Trigger.java @@ -19,6 +19,7 @@ */ package org.rhq.core.domain.common;
+import java.io.Serializable; import java.util.Date;
/** @@ -28,7 +29,9 @@ import java.util.Date; * * @author Ian Springer */ -public class Trigger { +public class Trigger implements Serializable { + + private static final long serialVersionUID = 1L;
// Together, the startType, recurrenceType, and endType define what type of trigger this is. // For the remaining fields in this class, only those that apply to the trigger's type will have non-null values. @@ -125,6 +128,22 @@ public class Trigger { return repeatCount; }
+ @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append("Trigger"); + sb.append("[cronExpression='").append(cronExpression).append('''); + sb.append(", startType=").append(startType); + sb.append(", recurrenceType=").append(recurrenceType); + sb.append(", endType=").append(endType); + sb.append(", startDate=").append(startDate); + sb.append(", repeatInterval=").append(repeatInterval); + sb.append(", endDate=").append(endDate); + sb.append(", repeatCount=").append(repeatCount); + sb.append(']'); + return sb.toString(); + } + /** * Create a trigger that will run now, once. * diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/GroupOperationSchedule.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/GroupOperationSchedule.java new file mode 100644 index 0000000..64c74de --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/GroupOperationSchedule.java @@ -0,0 +1,98 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.core.domain.operation.bean; + +import java.util.List; + +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.group.ResourceGroup; + +/** + * A simple non-entity POJO that describes a particular scheduled Resource group operation. + */ +public class GroupOperationSchedule extends OperationSchedule { + private static final long serialVersionUID = 1L; + + private ResourceGroup group; + private List<Resource> executionOrder; + private boolean haltOnFailure = false; // default to not stop on error + + public GroupOperationSchedule() { + } + + public ResourceGroup getGroup() { + return group; + } + + public void setGroup(ResourceGroup group) { + this.group = group; + } + + /** + * The order to execute the operations - the first resource in the list is the first one to get its operation + * invoked. If this is <code>null</code>, all operations can be invoked in any order and may even be done + * concurrently. + * + * @return list of resources in the order in which their operations are invoked, or <code>null</code> + */ + public List<Resource> getExecutionOrder() { + return executionOrder; + } + + public void setExecutionOrder(List<Resource> executionOrder) { + this.executionOrder = executionOrder; + } + + /** + * If <code>true</code>, the group operation will halt whenever one individual resource fails to execute. When + * executing in order, this means once a failure occurs, the resources next in line to execute will abort and not + * attempt to execute. If not executing in any particular order, you are not guaranteed which will stop and which + * will continue since all are executed as fast as possible, but the group operation will attempt to stop as best it + * can. + * + * @return halt flag + */ + public boolean isHaltOnFailure() { + return haltOnFailure; + } + + /** + * need a getXXX method instead of isXXX method for proper referencing from facelets pages + */ + public boolean getHaltOnFailure() { + return haltOnFailure; + } + + public void setHaltOnFailure(boolean haltOnFailure) { + this.haltOnFailure = haltOnFailure; + } + + @Override + public String toString() { + StringBuilder str = new StringBuilder("GroupOperationSchedule: "); + + str.append("group=[" + this.group); + str.append("], execution-order=[" + this.executionOrder); + str.append("], halt-on-failure=[" + this.haltOnFailure); + str.append("],"); + str.append(super.toString()); + + return str.toString(); + } +} \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java new file mode 100644 index 0000000..f92f3d0 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/OperationSchedule.java @@ -0,0 +1,154 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.core.domain.operation.bean; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.operation.HistoryJobId; +import org.rhq.core.domain.operation.JobId; + +/** + * A simple non-entity POJO that describes a particular scheduled operation. + * + * @author John Mazzitelli + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +public abstract class OperationSchedule implements Serializable { + private static final long serialVersionUID = 1L; + + private String jobName; + private String jobGroup; + private String operationName; + private String operationDisplayName; + private Configuration parameters; + private Subject subject; + private String description; + + public OperationSchedule() { + } + + public String getJobGroup() { + return jobGroup; + } + + public void setJobGroup(String jobGroup) { + this.jobGroup = jobGroup; + } + + public String getJobName() { + return jobName; + } + + public void setJobName(String jobName) { + this.jobName = jobName; + } + + public String getOperationName() { + return operationName; + } + + public void setOperationName(String operationName) { + this.operationName = operationName; + } + + public String getOperationDisplayName() { + /* + * this conditional is for "legacy" purposes, so that pre-existing operation schedules don't return blank + * displayNames, they will default to returning the operationDefinition.name instead + */ + if ((operationDisplayName == null) || operationDisplayName.equals("")) { + return getOperationName(); + } + + return operationDisplayName; + } + + public void setOperationDisplayName(String operationDisplayName) { + this.operationDisplayName = operationDisplayName; + } + + /** + * Returns the option parameters that are passed to the operation invocation. + * + * @return the parameters, or <code>null</code> if no parameters are to be passed + */ + public Configuration getParameters() { + return parameters; + } + + public void setParameters(Configuration parameters) { + this.parameters = parameters; + } + + public Subject getSubject() { + return subject; + } + + public void setSubject(Subject subject) { + if (subject == null) { + throw new NullPointerException("Cannot schedule an operation without a user associated with it"); + } + + this.subject = subject; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + /** + * The single job ID which identifies the operation. It can later be parsed via {@link JobId#JobId(String)}. Note + * that this job ID only identifies the scheduled operation; it does not identify any specific invocation of that + * operation (see {@link HistoryJobId} for that). + * + * @return job ID + */ + @XmlElement + public JobId getJobId() { + 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(); + str.append("job-name=[" + this.jobName); + str.append("], job-group=[" + this.jobGroup); + str.append("], operation-name=[" + this.operationName); + str.append("], subject=[" + this.subject); + str.append("], description=[" + this.description); + str.append("]"); + return str.toString(); + } +} \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/ResourceOperationSchedule.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/ResourceOperationSchedule.java new file mode 100644 index 0000000..b00e867 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/bean/ResourceOperationSchedule.java @@ -0,0 +1,56 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.core.domain.operation.bean; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import org.rhq.core.domain.resource.Resource; + +/** + * A simple non-entity POJO that describes a particular scheduled Resource operation. + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +public class ResourceOperationSchedule extends OperationSchedule { + private Resource resource; + + public ResourceOperationSchedule() { + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } + + @Override + public String toString() { + StringBuilder str = new StringBuilder("ResourceOperationSchedule: "); + + str.append("resource=[" + this.resource); + str.append("],"); + str.append(super.toString()); + + return str.toString(); + } +} \ No newline at end of file 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 a44e5f0..7cef256 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 @@ -27,6 +27,7 @@ import org.rhq.core.domain.criteria.GroupOperationHistoryCriteria; import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria; import org.rhq.core.domain.operation.GroupOperationHistory; import org.rhq.core.domain.operation.ResourceOperationHistory; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; import org.rhq.core.domain.operation.composite.ResourceOperationScheduleComposite; import org.rhq.core.domain.resource.composite.DisambiguationReport; @@ -37,7 +38,6 @@ import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.OperationGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.disambiguation.DefaultDisambiguationUpdateStrategies; import org.rhq.enterprise.server.util.LookupUtil; diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/model/OperationParameters.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/model/OperationParameters.java index e7317da..4b0617c 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/model/OperationParameters.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/model/OperationParameters.java @@ -25,15 +25,15 @@ import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.OperationHistory; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; 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.enterprise.server.core.plugin.PluginReloadedException; -import org.rhq.enterprise.server.operation.GroupOperationSchedule; import org.rhq.enterprise.server.operation.OperationDefinitionNotFoundException; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.enterprise.server.operation.OperationSchedule; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.OperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.util.LookupUtil;
public class OperationParameters { diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleDetailsUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleDetailsUIBean.java index d04f199..55da3bc 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleDetailsUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleDetailsUIBean.java @@ -22,12 +22,12 @@ import org.quartz.SchedulerException; import org.quartz.SimpleTrigger;
import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.operation.bean.OperationSchedule; import org.rhq.core.gui.util.FacesContextUtility; import org.rhq.enterprise.gui.common.scheduling.OperationDetailsScheduleComponent; import org.rhq.enterprise.gui.operation.model.OperationParameters; import org.rhq.enterprise.gui.util.EnterpriseFacesContextUtility; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.enterprise.server.operation.OperationSchedule; import org.rhq.enterprise.server.scheduler.SchedulerLocal; import org.rhq.enterprise.server.util.LookupUtil;
diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleUIBean.java index d8b7692..adadafb 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/OperationScheduleUIBean.java @@ -34,6 +34,7 @@ import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.operation.OperationDefinition; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.gui.util.FacesContextUtility; @@ -51,8 +52,7 @@ import org.rhq.enterprise.gui.operation.schedule.group.ResourceGroupOperationSch import org.rhq.enterprise.gui.operation.schedule.resource.ResourceOperationScheduleUIBean; import org.rhq.enterprise.gui.util.EnterpriseFacesContextUtility; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.enterprise.server.operation.OperationSchedule; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.OperationSchedule; import org.rhq.enterprise.server.util.LookupUtil;
public abstract class OperationScheduleUIBean extends PagedDataTableUIBean { diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleDetailsUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleDetailsUIBean.java index e6111ca..8e32bcd 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleDetailsUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleDetailsUIBean.java @@ -23,11 +23,11 @@ import java.util.List;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.composite.IntegerOptionItem; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; import org.rhq.core.domain.resource.Resource; import org.rhq.enterprise.gui.operation.definition.group.ResourceGroupExecutionTypeUIBean; import org.rhq.enterprise.gui.operation.schedule.OperationScheduleDetailsUIBean; -import org.rhq.enterprise.server.operation.GroupOperationSchedule; -import org.rhq.enterprise.server.operation.OperationSchedule; +import org.rhq.core.domain.operation.bean.OperationSchedule;
public class ResourceGroupOperationScheduleDetailsUIBean extends OperationScheduleDetailsUIBean {
diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleUIBean.java index e70ea9b..ee07ab0 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/group/ResourceGroupOperationScheduleUIBean.java @@ -35,7 +35,7 @@ import org.rhq.core.gui.util.FacesContextUtility; import org.rhq.enterprise.gui.operation.definition.group.ResourceGroupOperationDefinitionUIBean; import org.rhq.enterprise.gui.operation.schedule.OperationScheduleUIBean; import org.rhq.enterprise.gui.util.EnterpriseFacesContextUtility; -import org.rhq.enterprise.server.operation.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; import org.rhq.enterprise.server.scheduler.SchedulerLocal; import org.rhq.enterprise.server.util.LookupUtil; import org.rhq.enterprise.server.util.QuartzUtil; diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleDetailsUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleDetailsUIBean.java index 0f6983f..a56b845 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleDetailsUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleDetailsUIBean.java @@ -21,7 +21,7 @@ package org.rhq.enterprise.gui.operation.schedule.resource; import org.quartz.SchedulerException; import org.rhq.core.domain.auth.Subject; import org.rhq.enterprise.gui.operation.schedule.OperationScheduleDetailsUIBean; -import org.rhq.enterprise.server.operation.OperationSchedule; +import org.rhq.core.domain.operation.bean.OperationSchedule;
public class ResourceOperationScheduleDetailsUIBean extends OperationScheduleDetailsUIBean { @Override diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleUIBean.java index 9f8857c..4d9cecf 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/operation/schedule/resource/ResourceOperationScheduleUIBean.java @@ -32,7 +32,7 @@ import org.rhq.core.domain.resource.Resource; import org.rhq.core.gui.util.FacesContextUtility; import org.rhq.enterprise.gui.operation.schedule.OperationScheduleUIBean; import org.rhq.enterprise.gui.util.EnterpriseFacesContextUtility; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.scheduler.SchedulerLocal; import org.rhq.enterprise.server.util.LookupUtil; import org.rhq.enterprise.server.util.QuartzUtil; 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 a76a0ad..6d56a76 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 @@ -64,7 +64,7 @@ import org.rhq.enterprise.client.utility.ShortOutput; import org.rhq.enterprise.client.utility.ConfigurationClassBuilder; import org.rhq.enterprise.client.utility.ScriptUtil; import org.rhq.enterprise.server.content.ContentManagerRemote; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.resource.ResourceTypeNotFoundException;
/** diff --git a/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/utility/ScriptUtil.java b/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/utility/ScriptUtil.java index f75ecec..5333522 100644 --- a/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/utility/ScriptUtil.java +++ b/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/utility/ScriptUtil.java @@ -31,7 +31,7 @@ import org.rhq.core.domain.util.PageList; import org.rhq.core.domain.util.PageOrdering; import org.rhq.enterprise.client.ClientMain; import org.rhq.enterprise.client.commands.ScriptCommand; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.resource.ResourceManagerRemote;
import javax.script.Bindings; diff --git a/modules/enterprise/remoting/cli/src/test/java/org/rhq/enterprise/client/ClientMainTest.java b/modules/enterprise/remoting/cli/src/test/java/org/rhq/enterprise/client/ClientMainTest.java index 2dc4193..98549fd 100644 --- a/modules/enterprise/remoting/cli/src/test/java/org/rhq/enterprise/client/ClientMainTest.java +++ b/modules/enterprise/remoting/cli/src/test/java/org/rhq/enterprise/client/ClientMainTest.java @@ -1,42 +1,8 @@ package org.rhq.enterprise.client;
-import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.testng.AssertJUnit; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
-import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.authz.Role; -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.content.Architecture; -import org.rhq.core.domain.content.Repo; -import org.rhq.core.domain.content.PackageType; -import org.rhq.core.domain.content.PackageVersion; -import org.rhq.core.domain.measurement.AvailabilityType; -import org.rhq.core.domain.operation.ResourceOperationHistory; -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.resource.composite.ResourceComposite; -import org.rhq.core.domain.util.PageControl; -import org.rhq.enterprise.server.auth.SubjectManagerRemote; -import org.rhq.enterprise.server.authz.RoleManagerRemote; -import org.rhq.enterprise.server.configuration.ConfigurationManagerRemote; -import org.rhq.enterprise.server.content.RepoManagerRemote; -import org.rhq.enterprise.server.content.ContentManagerRemote; -import org.rhq.enterprise.server.operation.OperationManagerRemote; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; -import org.rhq.enterprise.server.resource.ResourceManagerRemote; - /** * These tests can not be executed in our standard unit test fashion as they require a running RHQ * Server with our web services deployed. diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationJob.java index 7192a9c..42e0312 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationJob.java @@ -33,6 +33,8 @@ import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.OperationHistory; import org.rhq.core.domain.operation.OperationRequestStatus; import org.rhq.core.domain.operation.ResourceOperationHistory; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageControl; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationSchedule.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationSchedule.java deleted file mode 100644 index 8ebf8d9..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/GroupOperationSchedule.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.enterprise.server.operation; - -import java.util.List; - -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.group.ResourceGroup; - -public class GroupOperationSchedule extends OperationSchedule { - private static final long serialVersionUID = 1L; - - private ResourceGroup group; - private List<Resource> executionOrder; - private boolean haltOnFailure = false; // default to not stop on error - - public GroupOperationSchedule() { - } - - public ResourceGroup getGroup() { - return group; - } - - public void setGroup(ResourceGroup group) { - this.group = group; - } - - /** - * The order to execute the operations - the first resource in the list is the first one to get its operation - * invoked. If this is <code>null</code>, all operations can be invoked in any order and may even be done - * concurrently. - * - * @return list of resources in the order in which their operations are invoked, or <code>null</code> - */ - public List<Resource> getExecutionOrder() { - return executionOrder; - } - - public void setExecutionOrder(List<Resource> executionOrder) { - this.executionOrder = executionOrder; - } - - /** - * If <code>true</code>, the group operation will halt whenever one individual resource fails to execute. When - * executing in order, this means once a failure occurs, the resources next in line to execute will abort and not - * attempt to execute. If not executing in any particular order, you are not guaranteed which will stop and which - * will continue since all are executed as fast as possible, but the group operation will attempt to stop as best it - * can. - * - * @return halt flag - */ - public boolean isHaltOnFailure() { - return haltOnFailure; - } - - /** - * need a getXXX method instead of isXXX method for proper referencing from facelets pages - */ - public boolean getHaltOnFailure() { - return haltOnFailure; - } - - public void setHaltOnFailure(boolean haltOnFailure) { - this.haltOnFailure = haltOnFailure; - } - - @Override - public String toString() { - StringBuilder str = new StringBuilder("GroupOperationSchedule: "); - - str.append("group=[" + this.group); - str.append("], execution-order=[" + this.executionOrder); - str.append("], halt-on-failure=[" + this.haltOnFailure); - str.append("],"); - str.append(super.toString()); - - return str.toString(); - } -} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java index 558c50d..f5988e3 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationJob.java @@ -30,6 +30,7 @@ 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.operation.ScheduleJobId; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java index 992e401..cdda16d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java @@ -61,6 +61,8 @@ import org.rhq.core.domain.operation.OperationScheduleEntity; import org.rhq.core.domain.operation.ResourceOperationHistory; import org.rhq.core.domain.operation.ResourceOperationScheduleEntity; import org.rhq.core.domain.operation.ScheduleJobId; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.operation.composite.GroupOperationLastCompletedComposite; import org.rhq.core.domain.operation.composite.GroupOperationScheduleComposite; import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java index b8ff855..d74a88c 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java @@ -38,6 +38,8 @@ import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.OperationHistory; import org.rhq.core.domain.operation.ResourceOperationHistory; import org.rhq.core.domain.operation.ScheduleJobId; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.operation.composite.GroupOperationLastCompletedComposite; import org.rhq.core.domain.operation.composite.GroupOperationScheduleComposite; import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerRemote.java index cc6f557..26e5f4f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerRemote.java @@ -35,6 +35,8 @@ import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria; 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.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.exception.ScheduleException; import org.rhq.enterprise.server.exception.UnscheduleException; 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 deleted file mode 100644 index bb5a636..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.enterprise.server.operation; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.operation.HistoryJobId; -import org.rhq.core.domain.operation.JobId; - -/** - * A simple non-entity POJO that describes a particular scheduled operation. - * - * @author John Mazzitelli - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -public abstract class OperationSchedule implements Serializable { - private static final long serialVersionUID = 1L; - - private String jobName; - private String jobGroup; - private String operationName; - private String operationDisplayName; - private Configuration parameters; - private Subject subject; - private String description; - - public OperationSchedule() { - } - - public String getJobGroup() { - return jobGroup; - } - - public void setJobGroup(String jobGroup) { - this.jobGroup = jobGroup; - } - - public String getJobName() { - return jobName; - } - - public void setJobName(String jobName) { - this.jobName = jobName; - } - - public String getOperationName() { - return operationName; - } - - public void setOperationName(String operationName) { - this.operationName = operationName; - } - - public String getOperationDisplayName() { - /* - * this conditional is for "legacy" purposes, so that pre-existing operation schedules don't return blank - * displayNames, they will default to returning the operationDefinition.name instead - */ - if ((operationDisplayName == null) || operationDisplayName.equals("")) { - return getOperationName(); - } - - return operationDisplayName; - } - - public void setOperationDisplayName(String operationDisplayName) { - this.operationDisplayName = operationDisplayName; - } - - /** - * Returns the option parameters that are passed to the operation invocation. - * - * @return the parameters, or <code>null</code> if no parameters are to be passed - */ - public Configuration getParameters() { - return parameters; - } - - public void setParameters(Configuration parameters) { - this.parameters = parameters; - } - - public Subject getSubject() { - return subject; - } - - public void setSubject(Subject subject) { - if (subject == null) { - throw new NullPointerException("Cannot schedule an operation without a user associated with it"); - } - - this.subject = subject; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - /** - * The single job ID which identifies the operation. It can later be parsed via {@link JobId#JobId(String)}. Note - * that this job ID only identifies the scheduled operation; it does not identify any specific invocation of that - * operation (see {@link HistoryJobId} for that). - * - * @return job ID - */ - @XmlElement - public JobId getJobId() { - 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(); - str.append("job-name=[" + this.jobName); - str.append("], job-group=[" + this.jobGroup); - str.append("], operation-name=[" + this.operationName); - str.append("], subject=[" + this.subject); - str.append("], description=[" + this.description); - str.append("]"); - return str.toString(); - } -} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationJob.java index 2139ac7..e0ac109 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationJob.java @@ -29,6 +29,7 @@ import org.quartz.JobExecutionException;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.operation.ResourceOperationHistory; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.util.exception.ThrowableUtil; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationSchedule.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationSchedule.java deleted file mode 100644 index d36fed8..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/ResourceOperationSchedule.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.enterprise.server.operation; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -import org.rhq.core.domain.resource.Resource; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -public class ResourceOperationSchedule extends OperationSchedule { - private Resource resource; - - public ResourceOperationSchedule() { - } - - public Resource getResource() { - return resource; - } - - public void setResource(Resource resource) { - this.resource = resource; - } - - @Override - public String toString() { - StringBuilder str = new StringBuilder("ResourceOperationSchedule: "); - - str.append("resource=[" + this.resource); - str.append("],"); - str.append(super.toString()); - - return str.toString(); - } -} \ No newline at end of file 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 0a9419a..3208c7e 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 @@ -65,6 +65,7 @@ import org.rhq.core.domain.criteria.Criteria; import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.measurement.DataType; import org.rhq.core.domain.measurement.DisplayType; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; @@ -88,7 +89,6 @@ import org.rhq.enterprise.server.authz.PermissionException; import org.rhq.enterprise.server.authz.RequiredPermission; import org.rhq.enterprise.server.exception.UnscheduleException; import org.rhq.enterprise.server.jaxb.adapter.ResourceGroupAdapter; -import org.rhq.enterprise.server.operation.GroupOperationSchedule; import org.rhq.enterprise.server.operation.OperationManagerLocal; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/AsyncResourceDeleteJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/AsyncResourceDeleteJob.java index b0d183d..75051c2 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/AsyncResourceDeleteJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/AsyncResourceDeleteJob.java @@ -29,7 +29,7 @@ import org.rhq.core.domain.auth.Subject; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.server.exception.UnscheduleException; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
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 9b36df1..6e4f1a6 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 @@ -140,9 +140,9 @@ import org.rhq.enterprise.server.measurement.MeasurementDataManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementDefinitionManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementProblemManagerLocal; import org.rhq.enterprise.server.measurement.MeasurementScheduleManagerLocal; -import org.rhq.enterprise.server.operation.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; import org.rhq.enterprise.server.operation.OperationManagerLocal; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.resource.ResourceFactoryManagerLocal; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.ResourceNotFoundException; diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/operation/OperationManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/operation/OperationManagerBeanTest.java index eaf6182..0ae4e9e 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/operation/OperationManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/operation/OperationManagerBeanTest.java @@ -27,6 +27,8 @@ import javax.persistence.EntityManager;
import org.quartz.SimpleTrigger; import org.quartz.Trigger; +import org.rhq.core.domain.operation.bean.GroupOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; diff --git a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsSender.java b/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsSender.java index 1fcb295..c183b2a 100644 --- a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsSender.java +++ b/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsSender.java @@ -27,7 +27,7 @@ import org.rhq.core.domain.operation.JobId; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.operation.OperationRequestStatus; import org.rhq.core.domain.resource.Resource; -import org.rhq.enterprise.server.operation.ResourceOperationSchedule; +import org.rhq.core.domain.operation.bean.ResourceOperationSchedule; import org.rhq.enterprise.server.plugin.pc.alert.AlertSender; import org.rhq.enterprise.server.util.LookupUtil;
commit 79743e71e32db1c606b029effbc4a43ece826d2f Author: Ian Springer ian.springer@redhat.com Date: Thu Dec 16 12:47:50 2010 -0500
fix bug where subjects and resource group associations did not get persisted when creating a new Role
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Role.java b/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Role.java index b9cb102..842a1b4 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Role.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Role.java @@ -108,16 +108,16 @@ public class Role implements Serializable { private Boolean fsystem;
@ManyToMany(mappedBy = "roles") - private java.util.Set<Subject> subjects = new HashSet<Subject>(); + private Set<Subject> subjects = new HashSet<Subject>();
@ManyToMany(mappedBy = "ldapRoles") - private java.util.Set<Subject> ldapSubjects = new HashSet<Subject>(); + private Set<Subject> ldapSubjects = new HashSet<Subject>();
@OneToMany(mappedBy = "role", cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }) private Set<LdapGroup> ldapGroups = new HashSet<LdapGroup>();
@ManyToMany(mappedBy = "roles") - private java.util.Set<org.rhq.core.domain.resource.group.ResourceGroup> resourceGroups = new HashSet<org.rhq.core.domain.resource.group.ResourceGroup>(); + private Set<ResourceGroup> resourceGroups = new HashSet<org.rhq.core.domain.resource.group.ResourceGroup>();
@Cascade( { org.hibernate.annotations.CascadeType.ALL }) @CollectionOfElements(fetch = FetchType.EAGER) @@ -241,7 +241,7 @@ public class Role implements Serializable { this.subjects.remove(subject); }
- public java.util.Set<Subject> getLdapSubjects() { + public Set<Subject> getLdapSubjects() { return ldapSubjects; }
@@ -267,11 +267,11 @@ public class Role implements Serializable { this.ldapSubjects.remove(subject); }
- public Set<org.rhq.core.domain.resource.group.ResourceGroup> getResourceGroups() { + public Set<ResourceGroup> getResourceGroups() { return resourceGroups; }
- public void setResourceGroups(Set<org.rhq.core.domain.resource.group.ResourceGroup> resourceGroups) { + public void setResourceGroups(Set<ResourceGroup> resourceGroups) { if (resourceGroups == null) { this.resourceGroups = new HashSet<ResourceGroup>(); } else { @@ -283,18 +283,18 @@ public class Role implements Serializable { } }
- public void addResourceGroup(org.rhq.core.domain.resource.group.ResourceGroup resourceGroup) { + public void addResourceGroup(ResourceGroup resourceGroup) { if (this.resourceGroups == null) { - this.resourceGroups = new HashSet<org.rhq.core.domain.resource.group.ResourceGroup>(); + this.resourceGroups = new HashSet<ResourceGroup>(); }
resourceGroup.addRole(this); this.resourceGroups.add(resourceGroup); }
- public void removeResourceGroup(org.rhq.core.domain.resource.group.ResourceGroup resourceGroup) { + public void removeResourceGroup(ResourceGroup resourceGroup) { if (this.resourceGroups == null) { - this.resourceGroups = new HashSet<org.rhq.core.domain.resource.group.ResourceGroup>(); + this.resourceGroups = new HashSet<ResourceGroup>(); }
resourceGroup.removeRole(this); 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 e96825b..04330ae 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,10 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.roles;
-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; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/RoleManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/RoleManagerBean.java index afefb7f..93b1ca8 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/RoleManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/RoleManagerBean.java @@ -137,7 +137,7 @@ public class RoleManagerBean implements RoleManagerLocal, RoleManagerRemote { * @see org.rhq.enterprise.server.authz.RoleManagerLocal#createRole(Subject, Role) */ @RequiredPermission(Permission.MANAGE_SECURITY) - public Role createRole(Subject subject, Role newRole) { + public Role createRole(Subject whoami, Role newRole) { // TODO (ips): Do we want to enforce uniqueness of the Role name?
if (newRole.getFsystem()) { @@ -153,6 +153,16 @@ public class RoleManagerBean implements RoleManagerLocal, RoleManagerRemote {
entityManager.persist(newRole);
+ // Now we must merge subjects and resource groups, since those fields in Role do not have persist cascade + // enabled. + for (Subject subject : newRole.getSubjects()) { + entityManager.merge(subject); + } + + for (ResourceGroup resourceGroup : newRole.getResourceGroups()) { + entityManager.merge(resourceGroup); + } + return newRole; }
rhq-commits@lists.fedorahosted.org