From e38b27b97cdf89e2a02b979d6dbc9a251bc3b46c Mon Sep 17 00:00:00 2001 From: Massimiliano Assante Date: Fri, 24 Mar 2017 11:22:29 +0000 Subject: [PATCH] git-svn-id: https://svn.d4science-ii.research-infrastructures.eu/gcube/private/alessandro.pieve/rmp-common-library@146319 82a268e6-3cf1-43bd-a215-b396298e98cf --- .checkstyle | 8 + .classpath | 27 + .project | 53 + .settings/com.google.gwt.eclipse.core.prefs | 4 + .settings/org.eclipse.core.resources.prefs | 4 + .settings/org.eclipse.jdt.core.prefs | 12 + .settings/org.eclipse.m2e.core.prefs | 5 + .settings/org.eclipse.wst.common.component | 5 + ....eclipse.wst.common.project.facet.core.xml | 5 + .settings/org.eclipse.wst.validation.prefs | 2 + distro/LICENSE | 1 + distro/README | 67 ++ distro/changelog.xml | 63 ++ distro/descriptor.xml | 42 + distro/profile.xml | 25 + pom.xml | 208 ++++ .../support/Resource_support.gwt.xml | 13 + .../support/client/Resource_support.java | 33 + .../support/client/events/SetScopeEvent.java | 28 + .../client/events/SetScopeEventHandler.java | 7 + .../support/client/utils/CurrentStatus.java | 128 +++ .../support/client/utils/LocalStatus.java | 42 + .../support/client/utils/StatusHandler.java | 37 + .../client/views/ResourceTypeDecorator.java | 89 ++ .../views/validators/SelectValidator.java | 39 + .../views/validators/StringValidator.java | 46 + .../client/views/validators/XMLValidator.java | 45 + .../exceptions/AbstractResourceException.java | 48 + .../exceptions/ResourceAccessException.java | 43 + .../ResourceOperationException.java | 55 ++ .../ResourceParameterException.java | 42 + .../support/server/gcube/CacheManager.java | 18 + .../server/gcube/ISClientRequester.java | 932 ++++++++++++++++++ .../support/server/gcube/ISQueryCache.java | 91 ++ .../server/gcube/queries/QueryLoader.java | 73 ++ .../server/gcube/queries/QueryLocation.java | 97 ++ .../xquery/RETURN_getResourcesDetails.xq | 8 + .../RETURN_getResourcesDetailsSubtype.xq | 8 + .../RETURN_getWSResourcesDetailsSubType.xq | 13 + .../server/gcube/queries/xquery/getPlugins.xq | 32 + .../gcube/queries/xquery/getResourceByID.xq | 4 + .../queries/xquery/getResourcesDetails.xq | 29 + .../xquery/getResourcesDetailsSubtype.xq | 30 + .../gcube/queries/xquery/getSubTypes.xq | 27 + .../queries/xquery/getTreeManagerPlugins.xq | 29 + .../server/gcube/queries/xquery/getTypes.xq | 4 + .../gcube/queries/xquery/getWSResourceByID.xq | 4 + .../queries/xquery/getWSResourcesDetails.xq | 16 + .../xquery/getWSResourcesDetailsSubType.xq | 5 + .../queries/xquery/getWSResourcesTypes.xq | 5 + .../gcube/queries/xquery/related/GHN.xq | 18 + .../queries/xquery/related/RETURN_GHN.xq | 8 + .../xquery/related/RETURN_RunningInstance.xq | 45 + .../queries/xquery/related/RETURN_Service.xq | 21 + .../queries/xquery/related/RunningInstance.xq | 11 + .../gcube/queries/xquery/related/Service.xq | 16 + .../queries/xquery/resources/Collection.xq | 8 + .../gcube/queries/xquery/resources/GHN.xq | 8 + .../xquery/resources/GenericResource.xq | 7 + .../xquery/resources/RETURN_Collection.xq | 11 + .../queries/xquery/resources/RETURN_GHN.xq | 18 + .../resources/RETURN_GenericResource.xq | 8 + .../resources/RETURN_RunningInstance.xq | 11 + .../resources/RETURN_RuntimeResource.xq | 8 + .../xquery/resources/RETURN_Service.xq | 10 + .../xquery/resources/RunningInstance.xq | 11 + .../xquery/resources/RuntimeResource.xq | 7 + .../gcube/queries/xquery/resources/Service.xq | 6 + .../gcube/queries/xquery/resources/VIEW.xq | 21 + .../queries/xquery/sweeper/RETURN_deadGhns.xq | 14 + .../xquery/sweeper/RETURN_expiredGhns.xq | 13 + .../queries/xquery/sweeper/RETURN_orphanRI.xq | 9 + .../gcube/queries/xquery/sweeper/deadGhns.xq | 13 + .../queries/xquery/sweeper/expiredGhns.xq | 12 + .../gcube/queries/xquery/sweeper/orphanRI.xq | 7 + .../server/managers/report/ReportBuilder.java | 56 ++ .../server/managers/report/ReportEntry.java | 100 ++ .../managers/report/ReportOperation.java | 33 + .../resources/AbstractResourceManager.java | 578 +++++++++++ .../managers/resources/CollectionManager.java | 75 ++ .../server/managers/resources/GHNManager.java | 201 ++++ .../resources/GenericResourceManager.java | 247 +++++ .../managers/resources/ManagementUtils.java | 335 +++++++ .../managers/resources/ResourceFactory.java | 71 ++ .../resources/RunningInstanceManager.java | 251 +++++ .../resources/RuntimeResourceManager.java | 112 +++ .../managers/resources/ServiceManager.java | 88 ++ .../server/managers/scope/ScopeManager.java | 232 +++++ .../server/sweeper/QueryParameter.java | 17 + .../support/server/sweeper/Sweeper.java | 174 ++++ .../support/server/tests/GenericTest.java | 204 ++++ .../support/server/tests/ScopeTest.java | 45 + .../server/types/AllowedResourceTypes.java | 31 + .../support/server/utils/Assertion.java | 65 ++ .../support/server/utils/ServerConsole.java | 65 ++ .../utils/persistence/PersistenceHandler.java | 62 ++ .../utils/persistence/PersistentItem.java | 154 +++ .../utils/persistence/TestPersistence.java | 46 + .../exceptions/InvalidParameterException.java | 44 + .../InvalidPermissionsException.java | 44 + .../operations/SupportedOperations.java | 88 ++ .../shared/plugins/GenericResourcePlugin.java | 172 ++++ .../shared/plugins/TMPluginFormField.java | 64 ++ .../support/shared/types/RunningMode.java | 39 + .../support/shared/types/Tuple.java | 166 ++++ .../support/shared/types/UserGroup.java | 31 + .../types/datamodel/AtomicTreeNode.java | 100 ++ .../datamodel/CompleteResourceProfile.java | 81 ++ .../types/datamodel/ResourceDescriptor.java | 120 +++ .../types/datamodel/ResourceDetailModel.java | 835 ++++++++++++++++ .../support/shared/util/Assertion.java | 66 ++ .../support/shared/util/Configuration.java | 39 + .../support/shared/util/DelayedOperation.java | 57 ++ .../shared/util/PerformanceMonitor.java | 96 ++ .../support/shared/util/SweeperActions.java | 72 ++ .../support/shared/util/TokenFilter.java | 35 + test-suite/scopes/scopedata.xml | 57 ++ test-suite/scopes/scopedata_admin.xml | 56 ++ 118 files changed, 8476 insertions(+) create mode 100644 .checkstyle create mode 100644 .classpath create mode 100644 .project create mode 100644 .settings/com.google.gwt.eclipse.core.prefs create mode 100644 .settings/org.eclipse.core.resources.prefs create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.m2e.core.prefs create mode 100644 .settings/org.eclipse.wst.common.component create mode 100644 .settings/org.eclipse.wst.common.project.facet.core.xml create mode 100644 .settings/org.eclipse.wst.validation.prefs create mode 100644 distro/LICENSE create mode 100644 distro/README create mode 100644 distro/changelog.xml create mode 100644 distro/descriptor.xml create mode 100644 distro/profile.xml create mode 100644 pom.xml create mode 100644 src/main/java/org/gcube/resourcemanagement/support/Resource_support.gwt.xml create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/Resource_support.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEvent.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEventHandler.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/utils/CurrentStatus.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/utils/LocalStatus.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/utils/StatusHandler.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/views/ResourceTypeDecorator.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/views/validators/SelectValidator.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/views/validators/StringValidator.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/client/views/validators/XMLValidator.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/exceptions/AbstractResourceException.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceAccessException.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceOperationException.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceParameterException.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/CacheManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISClientRequester.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISQueryCache.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLoader.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLocation.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetails.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetailsSubtype.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getWSResourcesDetailsSubType.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getPlugins.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourceByID.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetails.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetailsSubtype.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getSubTypes.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTreeManagerPlugins.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTypes.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourceByID.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetails.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetailsSubType.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesTypes.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/GHN.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_GHN.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_RunningInstance.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_Service.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RunningInstance.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/Service.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Collection.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GHN.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GenericResource.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Collection.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GHN.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GenericResource.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RunningInstance.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RuntimeResource.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Service.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RunningInstance.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RuntimeResource.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Service.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/VIEW.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_deadGhns.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_expiredGhns.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_orphanRI.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/deadGhns.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/expiredGhns.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/orphanRI.xq create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportBuilder.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportEntry.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportOperation.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/AbstractResourceManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/CollectionManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GHNManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GenericResourceManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ManagementUtils.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ResourceFactory.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RunningInstanceManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RuntimeResourceManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ServiceManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/managers/scope/ScopeManager.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/sweeper/QueryParameter.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/sweeper/Sweeper.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/tests/GenericTest.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/tests/ScopeTest.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/types/AllowedResourceTypes.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/utils/Assertion.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/utils/ServerConsole.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistenceHandler.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistentItem.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/TestPersistence.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidParameterException.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidPermissionsException.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/operations/SupportedOperations.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/plugins/GenericResourcePlugin.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/plugins/TMPluginFormField.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/RunningMode.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/Tuple.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/UserGroup.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/AtomicTreeNode.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/CompleteResourceProfile.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDescriptor.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDetailModel.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/util/Assertion.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/util/Configuration.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/util/DelayedOperation.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/util/PerformanceMonitor.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/util/SweeperActions.java create mode 100644 src/main/java/org/gcube/resourcemanagement/support/shared/util/TokenFilter.java create mode 100644 test-suite/scopes/scopedata.xml create mode 100644 test-suite/scopes/scopedata_admin.xml diff --git a/.checkstyle b/.checkstyle new file mode 100644 index 0000000..7f7eb5f --- /dev/null +++ b/.checkstyle @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..5cca4e3 --- /dev/null +++ b/.classpath @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..017948d --- /dev/null +++ b/.project @@ -0,0 +1,53 @@ + + + rmp-common-library + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.jdt.core.javabuilder + + + + + net.sf.eclipsecs.core.CheckstyleBuilder + + + + + com.google.gdt.eclipse.core.webAppProjectValidator + + + + + com.google.gwt.eclipse.core.gwtProjectValidator + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + net.sf.eclipsecs.core.CheckstyleNature + com.google.gwt.eclipse.core.gwtNature + org.eclipse.wst.common.project.facet.core.nature + + diff --git a/.settings/com.google.gwt.eclipse.core.prefs b/.settings/com.google.gwt.eclipse.core.prefs new file mode 100644 index 0000000..9898e9b --- /dev/null +++ b/.settings/com.google.gwt.eclipse.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +entryPointModules= +filesCopiedToWebInfLib=gwt-servlet.jar +gwtCompileSettings=PGd3dC1jb21waWxlLXNldHRpbmdzPjxsb2ctbGV2ZWw+SU5GTzwvbG9nLWxldmVsPjxvdXRwdXQtc3R5bGU+T0JGVVNDQVRFRDwvb3V0cHV0LXN0eWxlPjxleHRyYS1hcmdzPjwhW0NEQVRBW11dPjwvZXh0cmEtYXJncz48dm0tYXJncz48IVtDREFUQVstWG14NTEybV1dPjwvdm0tYXJncz48ZW50cnktcG9pbnQtbW9kdWxlPm9yZy5nY3ViZS5yZXNvdXJjZW1hbmFnZW1lbnQuc3VwcG9ydC5SZXNvdXJjZV9zdXBwb3J0PC9lbnRyeS1wb2ludC1tb2R1bGU+PC9nd3QtY29tcGlsZS1zZXR0aW5ncz4\= diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..f9fe345 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..6249222 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..a2b441e --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,5 @@ +#Wed Dec 19 12:41:58 CET 2012 +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..50ed371 --- /dev/null +++ b/.settings/org.eclipse.wst.common.component @@ -0,0 +1,5 @@ + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..4f92af5 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/.settings/org.eclipse.wst.validation.prefs b/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/distro/LICENSE b/distro/LICENSE new file mode 100644 index 0000000..2d9616a --- /dev/null +++ b/distro/LICENSE @@ -0,0 +1 @@ +${gcube.license} \ No newline at end of file diff --git a/distro/README b/distro/README new file mode 100644 index 0000000..35c99c0 --- /dev/null +++ b/distro/README @@ -0,0 +1,67 @@ +The gCube System - ${name} +-------------------------------------------------- + +${description} + + +${gcube.description} + +${gcube.funding} + + +Version +-------------------------------------------------- + +${version} (${buildDate}) + +Please see the file named "changelog.xml" in this directory for the release notes. + + +Authors +-------------------------------------------------- + +* Massimiliano Assante (massimiliano.assante-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy). + + + +Maintainers +----------- + +* Massimiliano Assante (massimiliano.assante-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy). + + +Download information +-------------------------------------------------- + +Source code is available from SVN: + ${scm.url} + +Binaries can be downloaded from the gCube website: + ${gcube.website} + + +Installation +-------------------------------------------------- + +Installation documentation is available on-line in the gCube Wiki: + ${gcube.wikiRoot}/ + + +Documentation +-------------------------------------------------- + +Documentation is available on-line in the gCube Wiki: + ${gcube.wikiRoot}/ + ${gcube.wikiRoot}/ + +Support +-------------------------------------------------- + +Bugs and support requests can be reported in the gCube issue tracking tool: + ${gcube.issueTracking} + + +Licensing +-------------------------------------------------- + +This software is licensed under the terms you may find in the file named "LICENSE" in this directory. diff --git a/distro/changelog.xml b/distro/changelog.xml new file mode 100644 index 0000000..4658d47 --- /dev/null +++ b/distro/changelog.xml @@ -0,0 +1,63 @@ + + + Changed codes for AuthZ framework + + + Added support for new AuthZ framework, Feature #1496 + + + Refactored code to promote reuse of sweeper features + + + Implemented Feature #187, remove scope operation with Report + Implemented Feature #446 Show SmartGearsDistribution version instead of SmartGearsDistributionBundle version for Distro Version + + + Fix for Incident #187, remove scope operation not passing + through Resource Manager + + + Fix for Incident #148, Resource Sweeper does not sweep GHN + Resources + + + + Modified xqueries for showing SmartGears and SmarGearsBundle + version + + Updated label names for the gHN grid columns + Modified xquery to fix bug about wrong scoped generic resource + + + + Modified xquery to get also the hostname info about service + endpoints in a given scope + + Modified the Resource detail model class to in shared package + to support the change explained above + + + + Ported to Feather Weight Stack + Removed GCF Dependency + Logging with sl4j Enabled + + + Create valid request for TM-plugins + + + First release + + \ No newline at end of file diff --git a/distro/descriptor.xml b/distro/descriptor.xml new file mode 100644 index 0000000..9144461 --- /dev/null +++ b/distro/descriptor.xml @@ -0,0 +1,42 @@ + + servicearchive + + tar.gz + + / + + + ${distroDirectory} + / + true + + README + LICENSE + changelog.xml + profile.xml + + 755 + true + + + target/apidocs + /${artifactId}/doc/api + true + 755 + + + + + ${distroDirectory}/profile.xml + ./ + true + + + target/${build.finalName}.jar + /${artifactId} + + + \ No newline at end of file diff --git a/distro/profile.xml b/distro/profile.xml new file mode 100644 index 0000000..1f95c6b --- /dev/null +++ b/distro/profile.xml @@ -0,0 +1,25 @@ + + + + Library + + ${description} + PortletsAdmin + ${artifactId} + 1.0.0 + + + ${artifactId} + ${version} + + ${groupId} + ${artifactId} + ${version} + + + ${build.finalName}.jar + + + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..1b28e88 --- /dev/null +++ b/pom.xml @@ -0,0 +1,208 @@ + + + 4.0.0 + + maven-parent + org.gcube.tools + 1.0.0 + + + + org.gcube.portlets.admin + rmp-common-library + 2.7.1-SNAPSHOT + Resource Management Library + + gCube Resource Management Library is a common library containing shared code for Information System Operations + used by all the Portlets and Widgets partaking into the Monitoring and Management of the Infrasturcture. + + + scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId} + scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId} + http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId} + + + + 2.7.0 + distro + + 1.7 + 1.7 + + UTF-8 + UTF-8 + + + + + org.gcube.distribution + maven-portal-bom + LATEST + pom + import + + + + + + + com.google.gwt + gwt-user + ${gwtVersion} + provided + + + com.sencha.gxt + gxt2.2.5-gwt2.X + 2.7.0 + compile + + + + org.gcube.common + authorization-client + provided + + + org.gcube.common + common-authorization + provided + + + + org.gcube.resources.discovery + ic-client + + + org.gcube.core + common-scope-maps + provided + + + org.gcube.resourcemanagement + resourcemanager-client + [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) + provided + + + org.gcube.resources + registry-publisher + provided + + + org.gcube.resourcemanagement + ghn-manager-client + [1.1.0-SNAPSHOT, 2.0.0-SNAPSHOT) + provided + + + + log4j + log4j + + + com.thoughtworks.xstream + xstream + provided + + + junit + junit + 3.8.1 + test + + + + + + src/main/java + + **/*.* + + + + + + maven-compiler-plugin + + 1.7 + 1.7 + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + test-jar + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + true + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + + copy-profile + install + + copy-resources + + + target + + + ${distroDirectory} + true + + profile.xml + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.2 + + + ${distroDirectory}/descriptor.xml + + + + fully.qualified.MainClass + + + + + + servicearchive + install + + single + + + + + + + diff --git a/src/main/java/org/gcube/resourcemanagement/support/Resource_support.gwt.xml b/src/main/java/org/gcube/resourcemanagement/support/Resource_support.gwt.xml new file mode 100644 index 0000000..d85d1ad --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/Resource_support.gwt.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/Resource_support.java b/src/main/java/org/gcube/resourcemanagement/support/client/Resource_support.java new file mode 100644 index 0000000..668731a --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/Resource_support.java @@ -0,0 +1,33 @@ +package org.gcube.resourcemanagement.support.client; + +import com.google.gwt.core.client.EntryPoint; +import com.google.gwt.event.shared.HandlerManager; + +public class Resource_support implements EntryPoint { + private HandlerManager eventBus; + + public Resource_support() { + super(); + } + + public Resource_support(HandlerManager eventBus){ + singleton = this; + this.eventBus = eventBus; + } + + private static Resource_support singleton; + + public static Resource_support get() { + return singleton; + } + + public HandlerManager getEventBus() { + return this.eventBus; + } + + /** + * This is the entry point method. + */ + public void onModuleLoad() { + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEvent.java b/src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEvent.java new file mode 100644 index 0000000..174768c --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEvent.java @@ -0,0 +1,28 @@ +package org.gcube.resourcemanagement.support.client.events; + +import com.google.gwt.event.shared.GwtEvent; + + + +public class SetScopeEvent extends GwtEvent { + public static Type TYPE = new Type(); + + private String scope2Set; + + public String getScope() { + return scope2Set; + } + public SetScopeEvent(String scope2Set) { + this.scope2Set = scope2Set; + } + + @Override + public Type getAssociatedType() { + return TYPE; + } + + @Override + protected void dispatch(SetScopeEventHandler handler) { + handler.onSetScope(this); + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEventHandler.java b/src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEventHandler.java new file mode 100644 index 0000000..6e6bfbc --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/events/SetScopeEventHandler.java @@ -0,0 +1,7 @@ +package org.gcube.resourcemanagement.support.client.events; + +import com.google.gwt.event.shared.EventHandler; + +public interface SetScopeEventHandler extends EventHandler { + void onSetScope(SetScopeEvent event); +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/utils/CurrentStatus.java b/src/main/java/org/gcube/resourcemanagement/support/client/utils/CurrentStatus.java new file mode 100644 index 0000000..658ac22 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/utils/CurrentStatus.java @@ -0,0 +1,128 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: CurrentStatus.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.utils; + +import java.io.Serializable; + +import org.gcube.resourcemanagement.support.client.Resource_support; +import org.gcube.resourcemanagement.support.client.events.SetScopeEvent; +import org.gcube.resourcemanagement.support.shared.types.RunningMode; +import org.gcube.resourcemanagement.support.shared.types.UserGroup; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.user.client.Window; + +/** + * @author Daniele Strollo (ISTI-CNR) + */ +public final class CurrentStatus implements Serializable { + private static final long serialVersionUID = 6487678609485417222L; + private String currentScope = "/gcube/devsec"; + private String currentResourceType = null; + private String currentResourceSubType = ""; + private String currentUser = "anonymous"; + private UserGroup credentials = UserGroup.DEBUG; + private RunningMode runningMode = RunningMode.STANDALONE; + private boolean useCache = false; + private boolean loadGHNatStartup = true; + + public CurrentStatus() { + } + + public boolean useCache() { + return this.useCache; + } + + public void setUseCache(final boolean useCache) { + this.useCache = useCache; + } + + public void setCurrentScope(final String scope) { + if (scope != null) { + currentScope = scope.trim(); + } + if (Resource_support.get() != null) { + Resource_support.get().getEventBus().fireEvent(new SetScopeEvent(scope)); + } + //Commands.setStatusScope(scope); + } + + public String getCurrentScope() { + return currentScope; + } + + public void setCurrentResourceType(String resType) { + if (resType != null) { + currentResourceType = resType.trim(); + } else { + currentResourceType = null; + } + } + + public String getCurrentResourceType() { + return currentResourceType; + } + + public String getCurrentResourceSubType() { + return currentResourceSubType; + } + + public void setCurrentResourceSubType(final String currentResourceSubType) { + if (currentResourceSubType != null) { + this.currentResourceSubType = currentResourceSubType.trim(); + } else { + this.currentResourceSubType = null; + } + } + + public UserGroup getCredentials() { + return credentials; + } + + public void setCredentials(final UserGroup credentials) { + this.credentials = credentials; + } + + public void setRunningMode(final RunningMode runningMode) { + this.runningMode = runningMode; + } + + public RunningMode getRunningMode() { + return runningMode; + } + + public void setCurrentUser(final String currentUser) { + if (currentUser != null) { + this.currentUser = currentUser.trim(); + } else { + this.currentUser = null; + } + } + + public String getCurrentUser() { + return currentUser; + } + + public boolean isLoadGHNatStartup() { + return loadGHNatStartup; + } + + public void setLoadGHNatStartup(boolean loadGHNatStartup) { + this.loadGHNatStartup = loadGHNatStartup; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/utils/LocalStatus.java b/src/main/java/org/gcube/resourcemanagement/support/client/utils/LocalStatus.java new file mode 100644 index 0000000..c3948d2 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/utils/LocalStatus.java @@ -0,0 +1,42 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: LocalStatus.java + **************************************************************************** + * @author Massimiliano Assante + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.utils; + +import java.util.ArrayList; +import java.util.List; + +/** + * Here represented the local status of the client side application. + * @author Massimilianio Assante (ISTI-CNR) + */ +public class LocalStatus { + private final ArrayList availableScopes = new ArrayList(); + private final ArrayList deployReports = new ArrayList(); + private static final LocalStatus INSTANCE = new LocalStatus(); + + public static synchronized LocalStatus getInstance() { + return INSTANCE; + } + + public final ArrayList getAvailableScopes() { + return this.availableScopes; + } + + public final List getDeployReports() { + return this.deployReports; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/utils/StatusHandler.java b/src/main/java/org/gcube/resourcemanagement/support/client/utils/StatusHandler.java new file mode 100644 index 0000000..86592bc --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/utils/StatusHandler.java @@ -0,0 +1,37 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: StatusHandler.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.utils; + + + + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class StatusHandler { + + private static CurrentStatus status = new CurrentStatus(); + + public static final synchronized void setStatus(final CurrentStatus status) { + StatusHandler.status = status; + } + + public static final synchronized CurrentStatus getStatus() { + return StatusHandler.status; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/views/ResourceTypeDecorator.java b/src/main/java/org/gcube/resourcemanagement/support/client/views/ResourceTypeDecorator.java new file mode 100644 index 0000000..964c5a0 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/views/ResourceTypeDecorator.java @@ -0,0 +1,89 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceTypeDecorator.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.views; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public enum ResourceTypeDecorator { + /**************************************** + * RESOURCES IN THE TREE + ****************************************/ + GHN("gCube Hosting Node", "ghn-icon","Hosting Node"), + RunningInstance("Running Instances", "runninginstance-icon", "GCore Endpoint"), + Service("Software", "service-icon","Software"), + VIEW("View", "metadatacollection-icon",""), + GenericResource("Generic Resources", "genericresource-icon","Generic Resource"), + Collection("Collection", "collection-icon",""), + WSResource("WSResource", "wsresources-icon",""), + Empty("Empty Tree", "empty-icon",""), + RuntimeResource("Runtime Resources", "runtimeresource-icon", "Service Endpoint"), + + /**************************************** + * Other components + ****************************************/ + // For deploying services - similar to the software but with an + // extension to handle checkbox for install + InstallableSoftware("InstallableSoftware", "empty-icon",""), + // In the taskbar for handlig the refresh of deployment reports + DeployReport("Deploy Report", "report-big-icon",""), + AddScopeReport("Add to Scope Report", "report-big-icon",""), + RemoveScopeReport("Remove from Scope Report", "report-big-icon",""), + + + /**************************************** + * Related resources + ****************************************/ + GHNRelated("Running Instances", "runninginstance-icon",""), + ServiceRelated("Running Instances", "runninginstance-icon",""), + RunningInstanceRelated("Running Instances", "runninginstance-icon",""), + + /**************************************** + * Models for SWEEPER + ***************************************/ + Sweeper_GHN("gCube Hosting Node", "ghn-icon","Hosting Node"), + Sweeper_RI("Running Instance", "runninginstance-icon", "GCore Endpoint"), + Sweeper_RI_Orphan("Orphan Running Instance", "orphan-runninginstance-icon", "Orphan GCore Endpoint"), + Sweeper_GHN_Expired("Expired gHN", "expired-ghn-icon", "Expired Nodes"), + Sweeper_GHN_Dead("Dead gHN", "dead-ghn-icon", "Unreachable Nodes"); + + + private String fwsName = null; + private String label = null; + private String icon = null; + + ResourceTypeDecorator(final String label, final String icon, final String fwsName) { + this.label = label; + this.icon = icon; + this.fwsName = fwsName; + } + + public String getLabel() { + return this.label; + } + + public String getIcon() { + return this.icon; + } + + public String getFWSName() { + if (this.fwsName == null || this.fwsName.equals("")) + return this.label; + return this.fwsName; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/SelectValidator.java b/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/SelectValidator.java new file mode 100644 index 0000000..fc204f4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/SelectValidator.java @@ -0,0 +1,39 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: SelectValidator.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.views.validators; + +import com.extjs.gxt.ui.client.widget.form.Field; +import com.extjs.gxt.ui.client.widget.form.Validator; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class SelectValidator implements Validator { + private boolean emptyAllowed = false; + + public SelectValidator(final boolean emptyAllowed) { + this.emptyAllowed = emptyAllowed; + } + + public final String validate(final Field field, final String value) { + if (!emptyAllowed && (value == null || value.trim().length() == 0)) { + return "The field value is invalid. Empty or null value not allowed."; + } + return null; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/StringValidator.java b/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/StringValidator.java new file mode 100644 index 0000000..2d814c7 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/StringValidator.java @@ -0,0 +1,46 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: XMLValidator.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.views.validators; + +import com.extjs.gxt.ui.client.widget.form.Field; +import com.extjs.gxt.ui.client.widget.form.Validator; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class StringValidator implements Validator { + private int maxLenght = 256; + private boolean emptyAllowed = false; + + public StringValidator(final int maxLenght, final boolean emptyAllowed) { + this.maxLenght = maxLenght; + this.emptyAllowed = emptyAllowed; + } + + public final String validate(final Field field, final String value) { + if (!emptyAllowed && (value == null || value.trim().length() == 0)) { + return "The field value is invalid. Empty or null value not allowed."; + } + if (value != null && value.length() > this.maxLenght) { + return "The value is too long. Limit of " + this.maxLenght + " chars exceeded."; + } + return null; + } +} + + diff --git a/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/XMLValidator.java b/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/XMLValidator.java new file mode 100644 index 0000000..9f6f7e2 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/client/views/validators/XMLValidator.java @@ -0,0 +1,45 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: XMLValidator.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.client.views.validators; + +import com.extjs.gxt.ui.client.widget.form.Field; +import com.extjs.gxt.ui.client.widget.form.Validator; +import com.google.gwt.xml.client.XMLParser; +import com.google.gwt.xml.client.impl.DOMParseException; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class XMLValidator implements Validator { + private String rootNode = "body"; + + public XMLValidator(final String rootNode) { + this.rootNode = rootNode; + } + + public final String validate(final Field field, final String value) { + try { + XMLParser.parse("<" + this.rootNode + ">" + value + ""); + } catch (DOMParseException e) { + return "Not a valid XML document"; + } + return null; + } +} + + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/AbstractResourceException.java b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/AbstractResourceException.java new file mode 100644 index 0000000..5e2911a --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/AbstractResourceException.java @@ -0,0 +1,48 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: AbstractResourceException.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.exceptions; + +/** + * Represents the basic type of exception thrown by functionalities exposed + * in this library. + * + * The reason is to provide an access point for serialization issues + * (e.g. for GWT based portlets that require additional serialization + * annotations). + * + * @author Daniele Strollo (ISTI-CNR) + */ +public class AbstractResourceException extends Exception { + private static final long serialVersionUID = 4851998460190622583L; + + public AbstractResourceException() { + super(); + } + + public AbstractResourceException(final String message, final Throwable cause) { + super(message, cause); + } + + public AbstractResourceException(final String message) { + super(message); + } + + public AbstractResourceException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceAccessException.java b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceAccessException.java new file mode 100644 index 0000000..8092fc2 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceAccessException.java @@ -0,0 +1,43 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceAccessException.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.exceptions; + +/** + * Thrown when is required an operation the user is not allowed to execute. + * + * @author Daniele Strollo (ISTI-CNR) + */ +@SuppressWarnings("serial") +public class ResourceAccessException extends AbstractResourceException { + + public ResourceAccessException() { + super(); + } + + public ResourceAccessException(final String message, final Throwable cause) { + super(message, cause); + } + + public ResourceAccessException(final String message) { + super(message); + } + + public ResourceAccessException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceOperationException.java b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceOperationException.java new file mode 100644 index 0000000..9491238 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceOperationException.java @@ -0,0 +1,55 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceOperationException.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.exceptions; + +/** + * If an operation of the library internally fails. + * @author Daniele Strollo (ISTI-CNR) + */ +public class ResourceOperationException extends AbstractResourceException { + private static final long serialVersionUID = -8748539948441128210L; + + /** + * + */ + public ResourceOperationException() { + super(); + } + + /** + * @param message + */ + public ResourceOperationException(final String message) { + super(message); + } + + /** + * @param cause + */ + public ResourceOperationException(final Throwable cause) { + super(cause); + } + + /** + * @param message + * @param cause + */ + public ResourceOperationException(final String message, final Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceParameterException.java b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceParameterException.java new file mode 100644 index 0000000..98b8607 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/exceptions/ResourceParameterException.java @@ -0,0 +1,42 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceParameterException.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.exceptions; + +/** + * Wrong parameters provided by the user. + * @author Daniele Strollo (ISTI-CNR) + */ +public class ResourceParameterException extends AbstractResourceException { + private static final long serialVersionUID = -1117521050663690780L; + + public ResourceParameterException() { + super(); + } + + public ResourceParameterException(final String message, final Throwable cause) { + super(message, cause); + } + + public ResourceParameterException(final String message) { + super(message); + } + + public ResourceParameterException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/CacheManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/CacheManager.java new file mode 100644 index 0000000..f4311d5 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/CacheManager.java @@ -0,0 +1,18 @@ +package org.gcube.resourcemanagement.support.server.gcube; + +public class CacheManager { + private boolean useCache = false; + + + public CacheManager() { + // for serialization only + } + + public boolean isUsingCache() { + return this.useCache; + } + + public void setUseCache(final boolean useCache) { + this.useCache = useCache; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISClientRequester.java b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISClientRequester.java new file mode 100644 index 0000000..ba2100d --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISClientRequester.java @@ -0,0 +1,932 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ISClientRequester.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.gcube; + +import static org.gcube.resources.discovery.icclient.ICFactory.client; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.Vector; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import org.gcube.common.resources.gcore.utils.XPathHelper; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.client.views.ResourceTypeDecorator; +import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLoader; +import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLocation; +import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resourcemanagement.support.shared.plugins.GenericResourcePlugin; +import org.gcube.resourcemanagement.support.shared.plugins.TMPluginFormField; +import org.gcube.resourcemanagement.support.shared.types.Tuple; +import org.gcube.resourcemanagement.support.shared.types.datamodel.CompleteResourceProfile; +import org.gcube.resourcemanagement.support.shared.types.datamodel.ResourceDescriptor; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.Query; +import org.gcube.resources.discovery.client.queries.impl.QueryBox; +import org.gcube.resources.discovery.client.queries.impl.QueryTemplate; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + + +/** + * All the requests to the IS are implemented here. + * @author Massimiliano Assante (ISTI-CNR) + * @author Daniele Strollo + */ +public class ISClientRequester { + + private static final ISQueryCache CACHE = new ISQueryCache(); + private static final String LOG_PREFIX = "[ISCLIENT-REQS]"; + + public static void emptyCache() { + CACHE.empty(); + } + + private static final ArrayList getResourceTypes(final CacheManager status, final ScopeBean queryScope) throws Exception { + + List resultz = null; + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_TREE_TYPES)); + DiscoveryClient client = client(); + + // Handles the cache + ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), + isQuery.expression(), + "getResourcesTypes"); + + if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { + resultz = CACHE.get(cacheKey); + } else { + try { + + resultz = client.submit(isQuery); + if (status.isUsingCache()) { + CACHE.insert(cacheKey, resultz); + } + } catch (Exception e) { + throw new Exception(e.getMessage()); + } + } + if (resultz == null || resultz.size() == 0) { + return null; + } + + String type = null; + ArrayList types = new ArrayList(); + try { + for (String elem : resultz) { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + type = helper.evaluate("/type/text()").get(0); + if (type != null && type.trim().length() > 0) { + types.add(type.trim()); + } + } + //**** CHANGES TO KNOW IF VIEWS AND GCUBECollection are present + types.remove("MetadataCollection"); + + isQuery = new QueryBox("declare namespace vm = 'http://gcube-system.org/namespaces/contentmanagement/viewmanager';"+ + "declare namespace gc = 'http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider';"+ + "declare namespace is = 'http://gcube-system.org/namespaces/informationsystem/registry';" + + "for $data in collection(\"/db/Properties\")//Document, $view in $data/Data where $view/gc:ServiceName/string() eq \"ViewManager\" " + + " and $view/gc:ServiceClass/string() eq \"ContentManagement\" and count($view//vm:View)>0 return true"); + + if (client.submit(isQuery).size() > 0) + types.add("VIEW"); + + isQuery = new QueryBox("declare namespace gc = 'http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider';"+ + "declare namespace is = 'http://gcube-system.org/namespaces/informationsystem/registry';" + + "for $data in collection(\"/db/Profiles/GenericResource\")//Document/Data/is:Profile/Resource where $data/Profile/SecondaryType eq \"GCUBECollection\" " + + " return true"); + + if (client.submit(isQuery).size() > 0) + types.add("Collection"); + + } catch (IndexOutOfBoundsException e) { + // ignore exception + } + ScopeProvider.instance.set(currScope); + return types; + } + + /** + * + * @param status + * @param queryScope + * @param resourceType + * @return + * @throws Exception + */ + private static final ArrayList getResourceSubTypes(final CacheManager status, final ScopeBean queryScope, final String resourceType) throws Exception { + + ArrayList subtypes = new ArrayList(); + if (resourceType.equals("Collection")) { + subtypes.add("System"); + subtypes.add("User"); + return subtypes; + } + if (resourceType.equals("VIEW")) { + subtypes.add("Not supported"); + return subtypes; + } + + + List resultz = null; + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + QueryTemplate isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_TREE_SUBTYPES)); + DiscoveryClient client = client(); + + isQuery.addParameter("RES_TYPE", resourceType); + isQuery.addParameter("SUBTYPE", "{$subtype}"); + + // Handles the cache + ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), + isQuery.expression(), + "getResourcesSubTypes"); + + if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { + resultz = CACHE.get(cacheKey); + } else { + try { + resultz = client.submit(isQuery); + if (status.isUsingCache()) { + CACHE.insert(cacheKey, resultz); + } + } catch (Exception e) { + throw new Exception(e.getMessage()); + } + } + if (resultz == null || resultz.size() == 0) + return null; + + for (String elem : resultz) { + try { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + String subtype = helper.evaluate("/subtype/text()").get(0); + if (subtype != null && subtype.trim().length() > 0) { + subtypes.add(subtype.trim()); + } + + } catch (IndexOutOfBoundsException e) { + // ignore exception + } + } + ScopeProvider.instance.set(currScope); + return subtypes; + } + + + /** + * For all the resource in the scope retrieves their + * (type, subtype) values. + * The result is a list of couples of that form. + * @return a list of string tuples (type, subtype) + * @throws Exception + */ + public static final HashMap> getResourcesTree(final CacheManager status, final ScopeBean queryScope) throws Exception { + HashMap> retval = new HashMap>(); + + // Loads the Resources + ArrayList types = getResourceTypes(status, queryScope); + ArrayList subtypes = null; + + for (String type : types) { + try { + subtypes = getResourceSubTypes(status, queryScope, type); + if (subtypes != null && subtypes.size() > 0) { + retval.put(type, subtypes); + } + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + + // Loads the WSResources + // This types is statically handled since it is a particular case of resource. + + + List resultz = null; + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_WSRES_TYPES)); + DiscoveryClient client = client(); + + resultz = client.submit(isQuery); + if (resultz == null || resultz.size() == 0) { + return retval; + } + subtypes = new ArrayList(); + for (String elem : resultz) { + subtypes.add(elem.toString()); + } + retval.put("WSResource", subtypes); + ScopeProvider.instance.set(currScope); + return retval; + } + + public static final List getRelatedResources(final CacheManager status, final String type, final String id, final ScopeBean queryScope) throws Exception { + QueryLocation queryPath = null; + try { + queryPath = QueryLocation.valueOf("LIST_RELATED_" + type); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, "Getting the resource query.", e); + throw new Exception(e.getMessage()); + } + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + QueryTemplate isQuery = new QueryTemplate(QueryLoader.getQuery(queryPath)); + DiscoveryClient client = client(); + + isQuery.addParameter("RES_ID", id.trim()); + //add the return statement + isQuery.addParameter("RESOURCE", QueryLoader.getQuery(QueryLocation.valueOf("LIST_RELATED_RETURN_" + type))); + + ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), isQuery.expression(), "getResourceRelated"); + + List resultz = null; + // Handle cache + if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { + resultz = CACHE.get(cacheKey); + } else { + resultz = client.submit(isQuery); + if (status.isUsingCache()) { + CACHE.insert(cacheKey, resultz); + } + } + if (resultz == null || resultz.size() == 0) { + ServerConsole.debug(LOG_PREFIX, "[getResourcesRelated] Got No Results"); + return null; + } + // ENDOF Handle cache + + List retval = new ArrayList(); + + for (String elem : resultz) { + // Removes the resources with no ID or empty + try { + String toAdd = elem.toString(); + if (toAdd != null) { + toAdd = toAdd.replace("", ""); + toAdd = toAdd.replace("", ""); + } + retval.add(toAdd); + } catch (Exception e) { + ServerConsole.debug(LOG_PREFIX, "[getResourcesRelated] found and invalid resource"); + } + } + ScopeProvider.instance.set(currScope); + ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type); + return retval; + } + /** + * + * @param status + * @param queryScope + * @param type + * @param subType + * @return + * @throws Exception + */ + public static final List getResourcesByType(final CacheManager status, final ScopeBean queryScope, final String type, final String subType) throws Exception { + + QueryLocation queryPath = null; + QueryLocation returnPath = null; + try { + if (type.equals(ResourceTypeDecorator.WSResource.name())) { + queryPath = QueryLocation.GET_WSRES_DETAILS_BYSUBTYPE; + returnPath = QueryLocation.valueOf("RETURN_" + QueryLocation.GET_WSRES_DETAILS_BYSUBTYPE); + } else { + queryPath = QueryLocation.valueOf("LIST_" + type); + returnPath = QueryLocation.valueOf("RETURN_" + type); + + } + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, "Getting the resource query.", e); + throw new Exception(e.getMessage()); + } + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + QueryTemplate isQuery = new QueryTemplate(QueryLoader.getQuery(queryPath)); + DiscoveryClient client = client(); + + if (type.equals(ResourceTypeDecorator.WSResource.name())) { + if (subType != null && subType.length() > 0) { + isQuery.addParameter("RES_SUBTYPE", subType.trim()); + } + } else { + if (subType != null && subType.length() > 0) { + if (subType.equalsIgnoreCase("User") || subType.equalsIgnoreCase("System")) { + isQuery.addParameter("RES_SUBTYPE", " and $profiles/Profile/Body/CollectionInfo/user/text() = \"" + ((subType.trim().equals("User")) ? "true" : "false") + "\""); + } + else + isQuery.addParameter("RES_SUBTYPE", "where $subtype = \"" + subType.trim() + "\""); + } + } + String retParam = type.equals(ResourceTypeDecorator.WSResource.name()) ? "WSRESOURCE" : "RESOURCE"; + //add the return statement + isQuery.addParameter(retParam, QueryLoader.getQuery(returnPath)); + + ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), isQuery.expression(), "getResourcesTypes"); + + List resultz = null; + + if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { + resultz = CACHE.get(cacheKey); + } else { + resultz = client.submit(isQuery); + if (status.isUsingCache()) { + CACHE.insert(cacheKey, resultz); + } + } + if (resultz == null || resultz.size() == 0) { + return null; + } + List retval = new Vector(); + + for (String elem : resultz) { + // Removes the resources with no ID or empty + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + try { + if (helper.evaluate("//ID").get(0) != null && helper.evaluate("//ID").get(0).trim().length() > 0) { + retval.add(elem.toString()); + //ServerConsole.debug("", elem.toString());// Print the result + } else { + ServerConsole.debug(LOG_PREFIX, "*** Found an invalid element with no ID"); + } + + } catch (Exception e) { + ServerConsole.debug(LOG_PREFIX, "[getResourcesByType] found a resource with empty ID"); + } + } + //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type); + ScopeProvider.instance.set(currScope); + return retval; + } + /** + * @param queryScope + * @param type + * @param subType + * @param additionalMaps + * @return + * @throws Exception + */ + public static final List getResourceModels(final ScopeBean queryScope, final String type, final String subType, final List> additionalMaps) throws Exception { + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + QueryTemplate isQuery = null; + DiscoveryClient client = client(); + + if (subType != null && subType.trim().length() > 0) { + isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RES_DETAILS_BYSUBTYPE)); + isQuery.addParameter("RES_TYPE", type.trim()); + isQuery.addParameter("RES_SUBTYPE", subType.trim()); + //add the return statement + isQuery.addParameter("RESOURCE", QueryLoader.getQuery(QueryLocation.RETURN_GET_RES_DETAILS_BYSUBTYPE)); + } else { + isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RES_DETAILS_BYTYPE)); + isQuery.addParameter("RES_TYPE", type); + isQuery.addParameter("RESOURCE", QueryLoader.getQuery(QueryLocation.RETURN_GET_RES_DETAILS_BYTYPE)); + } + List resultz = client.submit(isQuery); + + List retval = new Vector(); + ResourceDescriptor toAdd = null; + for (String elem : resultz) { + // Removes the resources with no ID or empty + try { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + + if (helper.evaluate("//ID").get(0) != null) { + toAdd = new ResourceDescriptor( + helper.evaluate("//Type/text()").get(0), + helper.evaluate("//SubType/text()").get(0), + helper.evaluate("//ID/text()").get(0), + helper.evaluate("//Name/text()").get(0)); + + // Additional mappings can be defined by the requester. + // e.g. new Tuple("description", "//Profile/Description/text()"); + if (additionalMaps != null && additionalMaps.size() > 0) { + for (Tuple map : additionalMaps) { + try { + toAdd.addProperty(map.get(0), + helper.evaluate(map.get(1)).get(0)); + } catch (final Exception e) { + toAdd.addProperty(map.get(0), + ""); + } + } + } + + retval.add(toAdd); + } + } catch (Exception e) { + ServerConsole.debug(LOG_PREFIX, "[getResourcesByType] found a resource with empty ID"); + } + } + //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type); + ScopeProvider.instance.set(currScope); + return retval; + } + /** + * + * @param queryScope + * @return + * @throws Exception + */ + public static final List getWSResources(final ScopeBean queryScope) throws Exception { + + + List resultz = null; + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_WSRES_DETAILS_BYTYPE)); + DiscoveryClient client = client(); + + List retval = new Vector(); + resultz = client.submit(isQuery); + + for (String elem : resultz) { + retval.add(elem.toString()); + } + //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + ResourceTypeDecorator.WSResource.name()); + ScopeProvider.instance.set(currScope); + return retval; + } + /** + * + * @param xmlFilePath + * @param queryScope + * @param resType + * @param resID + * @return + * @throws Exception + */ + public static final CompleteResourceProfile getResourceByID(String xmlFilePath, ScopeBean queryScope, String resType, String resID) throws Exception { + + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + QueryTemplate isQuery = null; + DiscoveryClient client = client(); + + + if (resType == null) { + isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RESOURCE_BYID)); + isQuery.addParameter("RES_ID", resID); + } else if (resType.equalsIgnoreCase(ResourceTypeDecorator.WSResource.name())) { + isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_WSRESOURCE_BYID)); + isQuery.addParameter("RES_ID", resID); + } else { + isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RESOURCE_BYID)); + isQuery.addParameter("RES_ID", resID); + isQuery.addParameter("RES_TYPE", resType); + } + List results = client.submit(isQuery); + + + //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") Resource for ID: " + resID); + + if (results != null && results.size() > 0) { + String type = null; + if (resType == null) { + try { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(results.get(0)))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + type = helper.evaluate("/Resource/Type/text()").get(0); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } else { + type = resType; + } + String xmlRepresentation = results.get(0).toString(); + String htmlRepresentation = XML2HTML(xmlRepresentation, xmlFilePath); + ScopeProvider.instance.set(currScope); + return new CompleteResourceProfile(resID, ResourceTypeDecorator.valueOf(type), getResourceName(type, resID, results.get(0)), xmlRepresentation, htmlRepresentation); + } + ScopeProvider.instance.set(currScope); + return null; + } + + public static Map getGenericResourcePlugins(final ScopeBean scope) throws Exception { + //set the scope + ScopeProvider.instance.set(scope.toString()); + + Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_GENERIC_RESOURCE_PLUGINS)); + DiscoveryClient client = client(); + List resultz= client.submit(isQuery); + + Map retval = new HashMap(); + gonext: for (String plugin : resultz) { + + try { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(plugin))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + for (String entry : helper.evaluate("/CMPlugins/Plugin/Entry")) { + + Document doc = ScopeManager.getDocumentGivenXML(entry); + String name = doc.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-PLUGIN] found: *** name " + name); + String pluginType = doc.getElementsByTagName("Type").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-PLUGIN] found: *** type " + pluginType); + String description = doc.getElementsByTagName("description").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-PLUGIN] found: *** description " + description); + String namespace = null; + try { + namespace = doc.getElementsByTagName("namespace").item(0).getFirstChild().getNodeValue(); + ServerConsole.debug("[LOAD-PLUGIN] found: *** namespace " + namespace); + } catch (Exception e) { + ServerConsole.warn("[LOAD-PLUGIN] namespace not found"); + } + + GenericResourcePlugin toAdd = new GenericResourcePlugin(name, namespace, description, pluginType); + + NodeList params = doc.getElementsByTagName("param"); + for (int i = 0; i < params.getLength(); i++) { + + NodeList paramTree = params.item(i).getChildNodes(); + String paramName = null; + String paramDefinition = null; + for (int j = 0; j < paramTree.getLength(); j++) { + if (paramTree.item(j).getNodeName().equals("param-name")) { + paramName = paramTree.item(j).getFirstChild().getNodeValue(); + } + + if (paramTree.item(j).getNodeName().equals("param-definition")) { + paramDefinition = paramTree.item(j).getFirstChild().getNodeValue(); + } + } + + ServerConsole.trace("[LOAD-PLUGIN] found: param " + paramName); + + GenericResourcePlugin.Field paramField = new GenericResourcePlugin.Field(paramName, GenericResourcePlugin.FieldType.string); + if (paramDefinition != null) { + StringTokenizer parser = new StringTokenizer(paramDefinition, ";"); + while (parser.hasMoreTokens()) { + try { + String currElem = parser.nextToken(); + String key = currElem.substring(0, currElem.indexOf("=")); + String value = currElem.substring(currElem.indexOf("=") + 1, currElem.length()).trim(); + if (key.equals("type")) { + paramField.setType(GenericResourcePlugin.FieldType.valueOf(value)); + } + if (key.equals("opt")) { + paramField.setIsRequired(!Boolean.parseBoolean(value)); + } + if (key.equals("label")) { + if (value.startsWith("'")) { + value = value.substring(1, value.length()); + } + if (value.endsWith("'")) { + value = value.substring(0, value.length() - 1); + } + paramField.setLabel(value); + } + if (key.equals("default")) { + if (value.startsWith("'")) { + value = value.substring(1, value.length()); + } + if (value.endsWith("'")) { + value = value.substring(0, value.length() - 1); + } + paramField.setDefaultValue(value); + } + } catch (Exception e) { + // parsing error - not well formed string + } + } + } + toAdd.addParam(paramField); + } + + retval.put(name + "::" + pluginType, toAdd); + } + } catch (RuntimeException e) { + continue gonext; + } + + + } + + return retval; + } + /** + * get the plugins for tree manager + * @param scope + * @return a map containing the plugin name as key and a List of formfield + * @throws Exception + */ + public static HashMap> getGenericResourceTreeManagerPlugins(final ScopeBean scope) throws Exception { + + ScopeProvider.instance.set(scope.toString()); + + Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_GENERIC_RESOURCE_TREE_MANAGER_PLUGINS)); + DiscoveryClient client = client(); + List resultz= client.submit(isQuery); + + HashMap> retval = new HashMap>(); + gonext: for (String plugin : resultz) { + try { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(plugin))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + for (String entry : helper.evaluate("/TMPlugins/Plugin/Entry")) { + String requestName = null; + boolean foundRequest = false; + Document doc = ScopeManager.getDocumentGivenXML(entry); + String name = doc.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-TMPLUGIN] found: *** name " + name); + String pluginType = doc.getElementsByTagName("Type").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-TMPLUGIN] found: *** type " + pluginType); + String description = doc.getElementsByTagName("description").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-TMPLUGIN] found: *** description " + description); + String namespace = null; + try { + namespace = doc.getElementsByTagName("namespace").item(0).getFirstChild().getNodeValue(); + ServerConsole.trace("[LOAD-TMPLUGIN] found: *** namespace " + namespace); + } catch (Exception e) { + ServerConsole.warn("[LOAD-TMPLUGIN] namespace not found"); + } + + NodeList params = doc.getElementsByTagName("param"); + ArrayList formFields = new ArrayList(); + + for (int i = 0; i < params.getLength(); i++) { + + NodeList paramTree = params.item(i).getChildNodes(); + String paramName = null; + String xmlToParse = null; + boolean foundSample = false; + for (int j = 0; j < paramTree.getLength(); j++) { + if (paramTree.item(j).getNodeName().equals("param-name")) { + paramName = paramTree.item(j).getFirstChild().getNodeValue(); + + if (paramName.compareTo("requestSample") == 0) { + foundSample = true; + foundRequest = true; + } + } + if (paramTree.item(j).getNodeName().equals("param-definition") && foundSample) { + xmlToParse = paramTree.item(j).getFirstChild().getNodeValue(); + xmlToParse = xmlToParse.replaceAll("<", "<"); + xmlToParse = xmlToParse.replaceAll(">", "<"); + foundSample = false; + + requestName = getRequestName(xmlToParse); + + formFields = getPluginFormFromXml(xmlToParse); + } + } + // if (params.getLength()>1) + retval.put(name + ":" + requestName, formFields); + + } + if (foundRequest == false){ + retval.put(name, formFields); + } + + } + } catch (RuntimeException e) { + continue gonext; + } + } + return retval; + } + + + /** + * get Request Name + * + * + * @param xmlToParse + * @return the list + */ + private static String getRequestName(String xmlToParse) { + Document doc = ScopeManager.getDocumentGivenXML(xmlToParse); + + return doc.getDocumentElement().getNodeName(); + + } + + /** + * parses the following and return the list to generate the form automatically + * + * sample + * + * Parachela collection + * Parachela collection from Itis + * Parachela + * ITIS + * true + * 5 + * MINUTES + * + * + * @param xmlToParse + * @return the list + */ + private static ArrayList getPluginFormFromXml(String xmlToParse) { + ArrayList toReturn = new ArrayList(); + Document doc = ScopeManager.getDocumentGivenXML(xmlToParse); + // Node root = doc.getElementsByTagName("request").item(0); + + Node root = doc.getDocumentElement(); + NodeList children = root.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + String label = children.item(i).getNodeName(); + String defaultValue = children.item(i).getFirstChild().getNodeValue(); + boolean repeatable = false; + boolean required = false; + if (children.item(i).hasAttributes()) { + NamedNodeMap attributes = children.item(i).getAttributes(); + if (children.item(i).getAttributes().getNamedItem("repeatable") != null) + repeatable = attributes.getNamedItem("repeatable").getNodeValue().equalsIgnoreCase("true"); + if (children.item(i).getAttributes().getNamedItem("required") != null) + required = attributes.getNamedItem("required").getNodeValue().equalsIgnoreCase("true"); + } + toReturn.add(new TMPluginFormField(label, defaultValue, required, repeatable)); + } + return toReturn; + } + + /** + * From the ID of a resource retrieves its name. Notice that resource name + * is retrieved according to their type. + * @param type the type of the resource + * @param ID the identifier of the resource + * @param node the XML node from which retrieve the information + * @return + * @throws IOException + * @throws SAXException + */ + private static String getResourceName(String type, String ID, String node) throws Exception { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node xnode = docBuilder.parse(new InputSource(new StringReader(node))).getDocumentElement(); + XPathHelper helper = new XPathHelper(xnode); + + if (type.equalsIgnoreCase(ResourceTypeDecorator.GHN.name())) { + try { + return helper.evaluate("/Resource/Profile/GHNDescription/Name/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.Collection.name())) { + try { + return helper.evaluate("/Resource/Profile/Name/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.Service.name())) { + try { + return helper.evaluate("/Resource/Profile/Name/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.RunningInstance.name())) { + try { + return helper.evaluate("/Resource/Profile/ServiceName/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.VIEW.name())) { + try { + return helper.evaluate("/Resource/Profile/Name/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.RuntimeResource.name())) { + try { + return helper.evaluate("/Resource/Profile/Name/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.GenericResource.name())) { + try { + return helper.evaluate("/Resource/Profile/Name/text()").get(0); + } catch (Exception e) { + return ID; + } + } + if (type.equalsIgnoreCase(ResourceTypeDecorator.WSResource.name())) { + try { + return helper.evaluate("/Document/Data/child::*[local-name()='ServiceName']/text()").get(0); + } catch (Exception e) { + return ID; + } + } + return null; + } + /** + * transform an xml in a readable xml by using HTML + * @param xml + * @param xslt + * @return + * @throws Exception + */ + public static String XML2HTML(final String xml, final String xslt) throws Exception { + TransformerFactory tf = TransformerFactory.newInstance(); + + InputStream stream = new FileInputStream(xslt); + BufferedReader in = new BufferedReader(new InputStreamReader(stream)); + StringBuilder retval = new StringBuilder(); + String currLine = null; + + while ((currLine = in.readLine()) != null) { + // a comment + if (currLine.trim().length() > 0 && currLine.trim().startsWith("#")) { + continue; + } + if (currLine.trim().length() == 0) { continue; } + retval.append(currLine + System.getProperty("line.separator")); + } + in.close(); + + + StreamSource source = new StreamSource(new ByteArrayInputStream(retval.toString().getBytes())); + Templates compiledXSLT = tf.newTemplates(source); + Transformer t = compiledXSLT.newTransformer(); + t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "true"); + StringWriter w = new StringWriter(); + t.transform(new StreamSource(new StringReader(xml)), new StreamResult(w)); + return w.toString(); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISQueryCache.java b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISQueryCache.java new file mode 100644 index 0000000..601dff4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/ISQueryCache.java @@ -0,0 +1,91 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ISQueryCache.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.gcube; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class ISQueryCacheKeyT { + String keyValue = null; + String queryExpression = null; + + public ISQueryCacheKeyT(String scope, String queryExpression, String... params) { + if (scope != null && queryExpression != null && params != null && params.length > 0) { + this.queryExpression = queryExpression.trim(); + this.keyValue = scope + "*" + queryExpression + "*" + "["; + for (String entry : params) { + keyValue += "(" + entry + ")"; + } + this.keyValue += "]"; + } + } + + public String getQueryExpression() { + return this.queryExpression; + } + + @Override + public String toString() { + return this.keyValue; + } + + @Override + public boolean equals(Object obj) { + if (this.keyValue == null) { + return false; + } + if (obj instanceof ISQueryCacheKeyT) { + return this.keyValue.equals(((ISQueryCacheKeyT) obj).keyValue); + } + return super.equals(obj); + } + + public int hashCode() { + return this.keyValue.hashCode(); + } +} + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class ISQueryCache { + Map> results = new HashMap>(); + + public void insert(ISQueryCacheKeyT key, List elem) { + this.results.put(key, elem); + } + + public boolean contains(ISQueryCacheKeyT key) { + if (key == null) { + return false; + } + return this.results.containsKey(key); + } + + public List get(ISQueryCacheKeyT key) { + if (key != null && this.results.containsKey(key)) { + return this.results.get(key); + } + return null; + } + + public void empty() { + this.results.clear(); + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLoader.java b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLoader.java new file mode 100644 index 0000000..2306126 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLoader.java @@ -0,0 +1,73 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: QueryLoader.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.gcube.queries; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.HashMap; + +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; + +/** + * Resource_support utility to load at runtime the customized queries to submit to + * the IS. + * @author Daniele Strollo + * @author Massimiliano Assante (ISTI-CNR) + */ +public class QueryLoader { + private static final HashMap cachedQueries = new HashMap(); + private static final String LOG_PREFIX = "[QUERY-LOADER]"; + + /** + * @param query the location of query file to load + * @return the string consisting of the xquery to submit to the server + * @throws Exception + */ + public static String getQuery(final QueryLocation query) throws Exception { + if (query == null) { + throw new Exception("Invalid query parameter. Null not allowed."); + } + + ServerConsole.trace(LOG_PREFIX, "loading " + query.name()); + + if (query != null && cachedQueries.containsKey(query)) { + return cachedQueries.get(query); + } + + BufferedReader in = new BufferedReader(new InputStreamReader(query.getFileName())); + StringBuilder retval = new StringBuilder(); + String currLine = null; + + while ((currLine = in.readLine()) != null) { + // a comment + if (currLine.trim().length() > 0 && currLine.trim().startsWith("#")) { + continue; + } + if (currLine.trim().length() == 0) { continue; } + retval.append(currLine + System.getProperty("line.separator")); + } + in.close(); + + String tmp = retval.toString(); + if (cachedQueries != null) { + cachedQueries.put(query, tmp); + } + + return tmp; + } +} + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLocation.java b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLocation.java new file mode 100644 index 0000000..0dcd817 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/QueryLocation.java @@ -0,0 +1,97 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: QueryLocator.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.gcube.queries; + +import java.io.InputStream; + +/** + * Keeps the association between an xquery and the path + * on which it can be retrieved. + * @author Daniele Strollo + * @author Massimiliano Assante (ISTI-CNR) + */ +public enum QueryLocation { + // These two queries are needed to build the tree of resource types and subtypes + // for resources different from wsresources. + GET_TREE_TYPES("getTypes.xq"), + GET_TREE_SUBTYPES("getSubTypes.xq"), + + // Customized queries to retrieve the relevant data from resources + // according to their type + LIST_GHN("resources/GHN.xq"), + RETURN_GHN("resources/RETURN_GHN.xq"), + LIST_Collection("resources/Collection.xq"), + RETURN_Collection("resources/RETURN_Collection.xq"), + LIST_VIEW("resources/VIEW.xq"), + LIST_Service("resources/Service.xq"), + RETURN_Service("resources/RETURN_Service.xq"), + LIST_GenericResource("resources/GenericResource.xq"), + RETURN_GenericResource("resources/RETURN_GenericResource.xq"), + LIST_RunningInstance("resources/RunningInstance.xq"), + RETURN_RunningInstance("resources/RETURN_RunningInstance.xq"), + LIST_RuntimeResource("resources/RuntimeResource.xq"), + RETURN_RuntimeResource("resources/RETURN_RuntimeResource.xq"), + + // To retrieve the list of generic resources publishing plugins + // to deploy activation records + GET_GENERIC_RESOURCE_PLUGINS("getPlugins.xq"), + RETURN_GET_GENERIC_RESOURCE_PLUGINS("RETURN_getPlugins.xq"), + + // to deploy activation records for Tree manager + GET_GENERIC_RESOURCE_TREE_MANAGER_PLUGINS("getTreeManagerPlugins.xq"), + + // Related resources + LIST_RELATED_GHN("related/GHN.xq"), + LIST_RELATED_RETURN_GHN("related/RETURN_GHN.xq"), + LIST_RELATED_RunningInstance("related/RunningInstance.xq"), + LIST_RELATED_RETURN_RunningInstance("related/RETURN_RunningInstance.xq"), + LIST_RELATED_Service("related/Service.xq"), + LIST_RELATED_RETURN_Service("related/RETURN_Service.xq"), + + // Queries for sweeper + SWEEPER_EXPIRED_GHN("sweeper/expiredGhns.xq"), + RETURN_SWEEPER_EXPIRED_GHN("sweeper/RETURN_expiredGhns.xq"), + + SWEEPER_DEAD_GHN("sweeper/deadGhns.xq"), + RETURN_SWEEPER_DEAD_GHN("sweeper/RETURN_deadGhns.xq"), + + SWEEPER_ORPHAN_RI("sweeper/orphanRI.xq"), + RETURN_SWEEPER_ORPHAN_RI("sweeper/RETURN_orphanRI.xq"), + + // Used to build the gwt model representation inside dialogs. + // see getResourceModels inside ISClientRequester. + GET_RES_DETAILS_BYTYPE("getResourcesDetails.xq"), + RETURN_GET_RES_DETAILS_BYTYPE("RETURN_getResourcesDetails.xq"), + GET_RES_DETAILS_BYSUBTYPE("getResourcesDetailsSubtype.xq"), + RETURN_GET_RES_DETAILS_BYSUBTYPE("RETURN_getResourcesDetailsSubtype.xq"), + + GET_RESOURCE_BYID("getResourceByID.xq"), + GET_WSRES_TYPES("getWSResourcesTypes.xq"), + GET_WSRES_DETAILS_BYTYPE("getWSResourcesDetails.xq"), + GET_WSRES_DETAILS_BYSUBTYPE("getWSResourcesDetailsSubType.xq"), + RETURN_GET_WSRES_DETAILS_BYSUBTYPE("RETURN_getWSResourcesDetailsSubType.xq"), + GET_WSRESOURCE_BYID("getWSResourceByID.xq"); + + private final String path = "org/gcube/resourcemanagement/support/server/gcube/queries/xquery/"; + private String filename = null; + QueryLocation(final String filename) { + this.filename = filename; + } + public InputStream getFileName() { + return this.getClass().getClassLoader().getResourceAsStream(this.path + this.filename); + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetails.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetails.xq new file mode 100644 index 0000000..56da18a --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetails.xq @@ -0,0 +1,8 @@ + + {$profiles//Resource/child::*} + {$subtype} + {$gcf-version} + {$ghn-version} + {$scopes} + {$ghn-name} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetailsSubtype.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetailsSubtype.xq new file mode 100644 index 0000000..56da18a --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getResourcesDetailsSubtype.xq @@ -0,0 +1,8 @@ + + {$profiles//Resource/child::*} + {$subtype} + {$gcf-version} + {$ghn-version} + {$scopes} + {$ghn-name} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getWSResourcesDetailsSubType.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getWSResourcesDetailsSubType.xq new file mode 100644 index 0000000..17b6dd6 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/RETURN_getWSResourcesDetailsSubType.xq @@ -0,0 +1,13 @@ + + {$outer//Document/ID} + {$outer//Document/Source} + {$outer//Document/SourceKey} + {$outer//Document/Data/child::*[local-name()='ServiceClass']/text()} + {$outer//Document/Data/child::*[local-name()='ServiceName']/text()} + {$outer//Document/Data/child::*[local-name()='ServiceClass']/text()} + {$outer//Document/TerminationTimeHuman} + {$outer//Document/LastUpdateHuman} + {$outer//Document/Data/child::*[local-name()='RI']/text()} + WSResource + {$scopes} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getPlugins.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getPlugins.xq new file mode 100644 index 0000000..504cfc4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getPlugins.xq @@ -0,0 +1,32 @@ +for $_outer in collection("/db/Properties")//Document +where ($_outer//Document/Data/child::*[local-name()='ServiceClass']/text() = 'ContentManagement' +and exists($_outer/Data/child::*[local-name()='Plugin']/name)) +return + + { + for $plugin in $_outer/Data/child::*[local-name()='Plugin'] + return + + { + for $elem in $plugin/parameters/child::* + return + + {$plugin/name} + {$plugin/description} + {namespace-uri($elem)} + {local-name($elem)} + + { + for $p in $elem/child::* + return + + {$p/name()} + {$p/text()} + + } + + + } + + } + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourceByID.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourceByID.xq new file mode 100644 index 0000000..9a394d6 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourceByID.xq @@ -0,0 +1,4 @@ +declare namespace ic = 'http://gcube-system.org/namespaces/informationsystem/registry'; +for $resource in collection('/db/Profiles/')//Document/Data/ic:Profile/Resource +where $resource/ID/string() eq '' +return $resource \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetails.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetails.xq new file mode 100644 index 0000000..b732bc4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetails.xq @@ -0,0 +1,29 @@ +# Given a couple of (type, subtype) retrieves +# the list of all resources contained in such category. +# Parameters: +# RES_TYPE the main type of the resource +# This query is used by forms + +for $profiles in collection('/db/Profiles/')//Resource +let $ghn-name := $profiles//Resource/Profile/GHN/@UniqueID/string() +let $gcf-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'gCF-version']/Value/text() +let $ghn-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'GHN-distribution-version']/Value/text() +let $scopes := string-join( $profiles//Resource/Scopes//Scope/text(), ';') +let $subtype := + if ($profiles//Resource/Type eq "Service") + then $profiles//Resource/Profile/Class/text() + else if ($profiles//Resource/Type eq "RunningInstance") + then $profiles//Resource/Profile/ServiceClass/text() + else if ($profiles//Resource/Type eq "GenericResource") + then $profiles//Resource/Profile/SecondaryType/text() + else if ($profiles//Resource/Type eq "GHN") + then $profiles//Resource/Profile/Site/Domain/text() + else if ($profiles//Resource/Type eq "MetadataCollection") + then $profiles//Resource/Profile/MetadataFormat/Name/text() + else if ($profiles//Resource/Type eq "Collection" and ($profiles//Resource/Profile/IsUserCollection/string(@value) eq 'true')) + then "User" + else if ($profiles//Resource/Type eq "Collection" and ($profiles//Resource/Profile/IsUserCollection/string(@value) eq 'false')) + then "System" + else "" + return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetailsSubtype.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetailsSubtype.xq new file mode 100644 index 0000000..3ce789f --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getResourcesDetailsSubtype.xq @@ -0,0 +1,30 @@ +# Given a couple of (type, subtype) retrieves +# the list of all resources contained in such category. +# Parameters: +# RES_TYPE the main type of the resource +# This query is used by forms + +for $profiles in collection('/db/Profiles/')//Resource +let $ghn-name := $profiles//Resource/Profile/GHN/@UniqueID/string() +let $gcf-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'gCF-version']/Value/text() +let $ghn-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'GHN-distribution-version']/Value/text() +let $scopes := string-join( $profiles//Resource/Scopes//Scope/text(), ';') +let $subtype := + if ($profiles//Resource/Type eq "Service") + then $profiles//Resource/Profile/Class/text() + else if ($profiles//Resource/Type eq "RunningInstance") + then $profiles//Resource/Profile/ServiceClass/text() + else if ($profiles//Resource/Type eq "GenericResource") + then $profiles//Resource/Profile/SecondaryType/text() + else if ($profiles//Resource/Type eq "GHN") + then $profiles//Resource/Profile/Site/Domain/text() + else if ($profiles//Resource/Type eq "MetadataCollection") + then $profiles//Resource/Profile/MetadataFormat/Name/text() + else if ($profiles//Resource/Type eq "Collection" and ($profiles//Resource/Profile/IsUserCollection/string(@value) eq 'true')) + then "User" + else if ($profiles//Resource/Type eq "Collection" and ($profiles//Resource/Profile/IsUserCollection/string(@value) eq 'false')) + then "System" + else "" + where $subtype eq '' + return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getSubTypes.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getSubTypes.xq new file mode 100644 index 0000000..640f883 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getSubTypes.xq @@ -0,0 +1,27 @@ +let $type := '' +let $subtypes := + for $_profiles in collection('/db/Profiles/')//Resource + let $elem := if ($type eq "Service") + then $_profiles//Resource/Profile/Class + else if ($type eq "RunningInstance") + then $_profiles//Resource/Profile/ServiceClass + else if ($type eq "GenericResource") + then $_profiles//Resource/Profile/SecondaryType + else if ($type eq "GHN") + then $_profiles//Resource/Profile/Site/Domain + else if ($type eq "MetadataCollection") + then $_profiles//Resource/Profile/MetadataFormat/Name + else if ($type eq "RuntimeResource") + then $_profiles//Resource/Profile/Category + else if ($type eq "Collection" and ($_profiles//Resource/Profile/IsUserCollection/string(@value) eq 'true')) + then "User" + else if ($type eq "Collection" and ($_profiles//Resource/Profile/IsUserCollection/string(@value) eq 'false')) + then "System" + else "" + return $elem + +for $subtype in distinct-values($subtypes) +return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTreeManagerPlugins.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTreeManagerPlugins.xq new file mode 100644 index 0000000..c12f8b4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTreeManagerPlugins.xq @@ -0,0 +1,29 @@ + +for $_outer in collection("/db/Properties")//Document +where ($_outer//Document/Data/child::*[local-name()='ServiceClass']/text() = 'DataAccess' +and exists($_outer/Data/child::*[local-name()='Plugin']/name)) +return + + { + for $plugin in $_outer/Data/child::*[local-name()='Plugin'] + return + + + {$plugin/name} + {$plugin/description} + {namespace-uri($plugin)} + treeManagerPlugin + + { + for $elem in $plugin/child::*[local-name()='property'] + return + + {$elem/name/text()} + {$elem/value/text()} + + } + + + + } + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTypes.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTypes.xq new file mode 100644 index 0000000..6b5dc34 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getTypes.xq @@ -0,0 +1,4 @@ +declare namespace ic = 'http://gcube-system.org/namespaces/informationsystem/registry'; +let $entry0ValueAuth := collection("/db/Profiles")//Document/Data/ic:Profile/Resource +for $types in distinct-values($entry0ValueAuth/Type/text()) + return {$types} \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourceByID.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourceByID.xq new file mode 100644 index 0000000..fe85999 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourceByID.xq @@ -0,0 +1,4 @@ + +for $resource in collection("/db/Properties")//Document +where $resource/ID/string() eq '' +return $resource \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetails.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetails.xq new file mode 100644 index 0000000..5b4a84b --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetails.xq @@ -0,0 +1,16 @@ +for $_outer in collection("/db/Properties")//Document +let $_scopes := string-join( $_outer//Document/Data/child::*[local-name()='Scope']/text(), ';') +return + + {$_outer//Document/ID} + {$_outer//Document/Source} + {$_outer//Document/SourceKey} + {$_outer//Document/Data/child::*[local-name()='ServiceClass']/text()} + {$_outer//Document/Data/child::*[local-name()='ServiceName']/text()} + {$_outer//Document/Data/child::*[local-name()='ServiceClass']/text()} + {$_outer//Document/TerminationTimeHuman} + {$_outer//Document/LastUpdateHuman} + {$_outer//Document/Data/child::*[local-name()='RI']/text()} + WSResource + {$_scopes} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetailsSubType.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetailsSubType.xq new file mode 100644 index 0000000..0ea3d09 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesDetailsSubType.xq @@ -0,0 +1,5 @@ +for $outer in collection("/db/Properties")//Document +let $scopes := string-join( $outer//Document/Data/child::*[local-name()='Scope']/text(), ';') +where $outer//Document/Data/child::*[local-name()='ServiceClass']/text() eq '' +return + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesTypes.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesTypes.xq new file mode 100644 index 0000000..23c3e35 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/getWSResourcesTypes.xq @@ -0,0 +1,5 @@ + +let $tempcollection := for $outer in collection("/db/Properties")//Document + return $outer//Document/Data/child::*[local-name()='ServiceClass'] +for $elem in distinct-values($tempcollection) +return $elem \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/GHN.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/GHN.xq new file mode 100644 index 0000000..ab2d884 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/GHN.xq @@ -0,0 +1,18 @@ + +for $ris in collection('/db/Profiles/RunningInstance')//Resource +where $ris//Resource/Profile/GHN/@UniqueID/string() eq '' +return + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_GHN.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_GHN.xq new file mode 100644 index 0000000..0b94a44 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_GHN.xq @@ -0,0 +1,8 @@ + + {$ris/ID} + {$ris/Profile/ServiceName} + {$ris/Profile/ServiceClass} + {$ris//Resource/@version/string()} + {$ris/Profile/Version/text()} + {$ris/Profile/DeploymentData/Status/text()} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_RunningInstance.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_RunningInstance.xq new file mode 100644 index 0000000..4334898 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_RunningInstance.xq @@ -0,0 +1,45 @@ + + + ID + {$ri//Resource/ID/string()} + + + ServiceStatus + {$ri/Profile/DeploymentData/Status/string()} + + + ActivationTime + {$ri/Profile/DeploymentData/ActivationTime/@value/string()} + + + GHNName + {$ghn-name} + + + GHNSite + {$relatedghn/Profile/Site/Domain/string()} + + + GHNStatus + {$relatedghn/Profile/GHNDescription/Status/string()} + + + GHNActivationTime + {$relatedghn/Profile/GHNDescription/ActivationTime/string()} + + + GHNLastUpdate + {$relatedghn/Profile/GHNDescription/LastUpdate/string()} + + + GHNLoad15Min + {$relatedghn/Profile/GHNDescription/Load/@Last15Min/string()} + + + GHNLoad5Min + {$relatedghn/Profile/GHNDescription/Load/@Last5Min/string()} + + GHNLoad1Min + {$relatedghn/Profile/GHNDescription/Load/@Last1Min/string()} + + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_Service.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_Service.xq new file mode 100644 index 0000000..52dd6e4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RETURN_Service.xq @@ -0,0 +1,21 @@ + + + {$ri/ID/string()} + {$ri/Profile/DeploymentData/Status/string()} + {$ri/Profile/DeploymentData/ActivationTime/@value/string()} + {$ri/Profile/Version/string()} + + {$ghn-id} + {$ghn/Profile/GHNDescription/Name/string()} + {$ghn/Profile/Site/Domain/string()} + {$ghn/Profile/GHNDescription/Status/string()} + {$ghn/Profile/GHNDescription/Load/@Last15Min/string()} + {$ghn/Profile/GHNDescription/Load/@Last15Min/string()} + {$ghn/Profile/GHNDescription/Load/@Last15Min/string()} + {$ghn/Profile/GHNDescription/ActivationTime/string()} + {$ghn/Profile/GHNDescription/LastUpdate/string()} + +return + + {$relatedris} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RunningInstance.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RunningInstance.xq new file mode 100644 index 0000000..ef22c5e --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/RunningInstance.xq @@ -0,0 +1,11 @@ + +let $profiles := collection('/db/Profiles/')//Resource[ID/string() eq ''] +let $relatedghn := collection('/db/Profiles/GHN')//Resource[ID/string() eq $profiles/Profile/GHN/@UniqueID/string()] +let $ghn-name := if (empty($relatedghn/Profile/GHNDescription/Name/string())) + then $profiles/Profile/GHN/@UniqueID/string() + else $relatedghn/Profile/GHNDescription/Name/string() +for $ri in $profiles +return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/Service.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/Service.xq new file mode 100644 index 0000000..d74a3e5 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/related/Service.xq @@ -0,0 +1,16 @@ + +let $service := collection('/db/Profiles/Service')//Resource//Resource[ID/text() eq ''] +let $ServiceClass := $service/Profile/Class +let $ServiceName := $service/Profile/Name +let $ServiceVersion := $service/Profile/Version +let $riloop := collection('/db/Profiles/RunningInstance')//Resource[Profile/ServiceClass/string() eq $ServiceClass and Profile/ServiceName/string() eq $ServiceName] +let $relatedris := + for $ri in $riloop + let $ghn-id := $ri/Profile/GHN/@UniqueID/string() + let $ghn := collection('/db/Profiles/GHN')//Resource[ID/string() eq $ghn-id] + + return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Collection.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Collection.xq new file mode 100644 index 0000000..2b8c939 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Collection.xq @@ -0,0 +1,8 @@ +for $profiles in collection('/db/Profiles/GenericResource')//Resource, $wsresource in collection('/db/Properties')//Document +let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') +let $subtype := $profiles//Resource/Profile/SecondaryType/text() +where $subtype = "DataSource" and $profiles//Resource/ID eq $wsresource/SourceKey and $wsresource/Data//child::*[local-name()='ServiceName']/string() eq 'tree-manager-service' + + return + + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GHN.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GHN.xq new file mode 100644 index 0000000..8214a21 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GHN.xq @@ -0,0 +1,8 @@ +for $profiles in collection('/db/Profiles/GHN')//Resource +let $gcf-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'gCF-version']/Value/text() | $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'SmartGears']/Value/text() +let $ghn-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'GHN-distribution-version']/Value/text() | $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'SmartGearsDistribution']/Value/text() +let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') +let $subtype := $profiles//Resource/Profile/Site/Domain/text() + + return + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GenericResource.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GenericResource.xq new file mode 100644 index 0000000..15d40c2 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/GenericResource.xq @@ -0,0 +1,7 @@ +declare namespace ic = 'http://gcube-system.org/namespaces/informationsystem/registry'; +for $profiles in collection('/db/Profiles/GenericResource')//Document/Data/ic:Profile/Resource +let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') +let $subtype := $profiles/Profile/SecondaryType/text() + + return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Collection.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Collection.xq new file mode 100644 index 0000000..7342462 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Collection.xq @@ -0,0 +1,11 @@ + + {$profiles//Resource/ID} + {$profiles//Resource/Type/text()} + {$subtype} + {$scopes} + {$profiles//Resource/Profile/Name/text()} + {$profiles//Resource/Profile/Body/SourceProperties/creationTime/text()} + {$profiles//Resource/Profile/Body/SourceProperties/user/text()} + {$wsresource/LastUpdateHuman/text()} + {$wsresource//child::*[local-name()='Cardinality']/text()} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GHN.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GHN.xq new file mode 100644 index 0000000..b86ec60 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GHN.xq @@ -0,0 +1,18 @@ + + {$profiles//Resource/ID} + {$profiles//Resource/Type/text()} + {$subtype} + {$profiles//Resource/Profile/GHNDescription/Status/text()} + {$profiles//Resource/Profile/GHNDescription/Name/text()} + {$profiles//Resource/Profile/GHNDescription/Uptime/text()} + {$profiles//Resource/Profile/GHNDescription/LastUpdate/text()} + {$profiles//Resource/Profile/GHNDescription/LocalAvailableSpace/text()} + {$profiles//Resource/Profile/GHNDescription/MainMemory/string(@VirtualSize)} + {$profiles//Resource/Profile/GHNDescription/MainMemory/string(@VirtualAvailable)} + {$profiles//Resource/Profile/GHNDescription/Load/string(@Last1Min)} + {$profiles//Resource/Profile/GHNDescription/Load/string(@Last5Min)} + {$profiles//Resource/Profile/GHNDescription/Load/string(@Last15Min)} + {$gcf-version} + {$ghn-version} + {$scopes} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GenericResource.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GenericResource.xq new file mode 100644 index 0000000..e7862a4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_GenericResource.xq @@ -0,0 +1,8 @@ + + {$profiles//Resource/ID} + {$profiles//Resource/Type/text()} + {$subtype} + {$scopes} + {$profiles//Resource/Profile/Name/text()} + {$profiles//Resource/Profile/Description/text()} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RunningInstance.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RunningInstance.xq new file mode 100644 index 0000000..705214b --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RunningInstance.xq @@ -0,0 +1,11 @@ + + {$profiles/ID} + {$profiles/Type/text()} + {$subtype} + {$scopes} + {$profiles/Profile/ServiceClass/text()} + {$profiles/Profile/ServiceName/text()} + {$profiles/Profile/Version/text()} + {$profiles/Profile/DeploymentData/Status/text()} + {$ghn-name} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RuntimeResource.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RuntimeResource.xq new file mode 100644 index 0000000..a9296d1 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_RuntimeResource.xq @@ -0,0 +1,8 @@ + + {$profiles//Resource/ID} + {$profiles//Resource/Type/text()} + {$subtype} + {$scopes} + {$profiles//Resource/Profile/Name/text()} + {$profiles//Resource/Profile/RunTime/HostedOn/text()} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Service.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Service.xq new file mode 100644 index 0000000..42f770f --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RETURN_Service.xq @@ -0,0 +1,10 @@ + + {$profiles//Resource/ID} + {$profiles//Resource/Type/text()} + {$subtype} + {$scopes} + {$profiles//Resource/Profile/Class/text()} + {$profiles//Resource/Profile/Name/text()} + {$profiles//Resource/Profile/Packages/Software[1]/Version/text()} + {$profiles//Resource/Profile/Packages/Software/Shareable/string(@level)} + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RunningInstance.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RunningInstance.xq new file mode 100644 index 0000000..0fbceb3 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RunningInstance.xq @@ -0,0 +1,11 @@ +for $profiles in collection('/db/Profiles/RunningInstance')//Resource +let $ghns := collection('/db/Profiles/GHN')//Resource +let $_ghn-name := for $ghn in $ghns + where $ghn/ID/string() eq $profiles/Profile/GHN/@UniqueID/string() + return $ghn/Profile/GHNDescription/Name/string() +let $ghn-name := if (empty($_ghn-name)) then $profiles/Profile/GHN/@UniqueID/string() else $_ghn-name +let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') +let $subtype := $profiles/Profile/ServiceClass/text() + + return + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RuntimeResource.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RuntimeResource.xq new file mode 100644 index 0000000..8dba6fc --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/RuntimeResource.xq @@ -0,0 +1,7 @@ +for $profiles in collection('/db/Profiles/RuntimeResource')//Resource +let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') +let $subtype := $profiles//Resource/Profile/Category/text() + + return + + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Service.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Service.xq new file mode 100644 index 0000000..e08ff29 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/Service.xq @@ -0,0 +1,6 @@ +for $profiles in collection('/db/Profiles/Service')//Resource +let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') +let $subtype := $profiles//Resource/Profile/Class/text() + + return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/VIEW.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/VIEW.xq new file mode 100644 index 0000000..641e7d8 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/resources/VIEW.xq @@ -0,0 +1,21 @@ +declare namespace gc = 'http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider'; +declare namespace wmns= 'http://gcube-system.org/namespaces/contentmanagement/viewmanager'; +for $outer in collection("/db/Properties")//Document, $res in $outer/Data where $res/gc:ServiceClass/string() eq 'ContentManagement' +and count($res//wmns:View)>0 and $res/gc:ServiceName/string() eq 'ViewManager' +return + + {$outer//Document/ID} + {$outer//Document/Source} + {$outer//Document/SourceKey} + {$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='property']/child::*[local-name()='name' and text()='name']/../child::*[local-name()='value']/text()} + {$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='cardinality']/text()} + {$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='type']/text()} + {$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='collectionID']/text()} + {$outer//Document/Data/child::*[local-name()='ServiceClass']/text()} + {$outer//Document/Data/child::*[local-name()='ServiceName']/text()} + {$outer//Document/Data/child::*[local-name()='ServiceClass']/text()} + {$outer//Document/TerminationTimeHuman} {$outer//Document/LastUpdateHuman} + {$outer//Document/Data/child::*[local-name()='RI']/text()} + WSResource + {$outer//Document/Data/child::*[local-name()='Scope']/text()} + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_deadGhns.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_deadGhns.xq new file mode 100644 index 0000000..8388ec3 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_deadGhns.xq @@ -0,0 +1,14 @@ + + {$GHNs/ID} + {$GHNs/Profile/GHNDescription/Name} + {$GHNs/Profile/GHNDescription/Status} + {$GHNs/Profile/GHNDescription/Type} + {$GHNs/Profile/Site/Location} + {$GHNs/Profile/Site/Domain} + {$GHNs/Profile/GHNDescription/NetworkAdapter/@IPAddress/string()} + {$scopes} + {count($RIinstalled)} + {$GHNs/Profile/GHNDescription/LastUpdate} + {$totalminutes} + APPLY_GHN_DELETE + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_expiredGhns.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_expiredGhns.xq new file mode 100644 index 0000000..93edbd0 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_expiredGhns.xq @@ -0,0 +1,13 @@ + + {$GHNs/ID} + {$GHNs/Profile/GHNDescription/Name} + {$GHNs/Profile/GHNDescription/Status} + {$GHNs/Profile/GHNDescription/Type} + {$GHNs/Profile/Site/Location} + {$GHNs/Profile/Site/Domain} + {$GHNs/Profile/GHNDescription/NetworkAdapter/@IPAddress/string()} + {$scopes} + {count($RIinstalled)} + {$GHNs/Profile/GHNDescription/LastUpdate} + APPLY_GHN_MOVE_TO_UNREACHABLE + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_orphanRI.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_orphanRI.xq new file mode 100644 index 0000000..3f1ff75 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/RETURN_orphanRI.xq @@ -0,0 +1,9 @@ + + {$ri//Resource/ID/string()} + {$ri/Profile/DeploymentData/Status/string()} + {$ri/Profile/DeploymentData/ActivationTime/@value/string()} + {$ri/Profile/GHN/@UniqueID/string()} + {$ri/Profile/ServiceClass/string()} + {$ri/Profile/ServiceName/string()} + APPLY_RI_DELETE + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/deadGhns.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/deadGhns.xq new file mode 100644 index 0000000..6cbf401 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/deadGhns.xq @@ -0,0 +1,13 @@ + +let $RIs := collection("/db/Profiles/RunningInstance")//Document/Data/child::*[local-name()='Profile']/Resource +for $GHNs in collection("/db/Profiles/GHN")//Document/Data/child::*[local-name()='Profile']/Resource +let $totalminutes := hours-from-dateTime($GHNs/Profile/GHNDescription/LastUpdate/text()) +let $RIinstalled := $RIs[Profile/GHN/string(@UniqueID)=$GHNs/ID] +let $scopes := string-join( $GHNs/Scopes//Scope/text(), ';') +where ($GHNs/Profile/GHNDescription/Status/string() eq 'down' or $GHNs/Profile/GHNDescription/Status/string() eq 'unreachable') +return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/expiredGhns.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/expiredGhns.xq new file mode 100644 index 0000000..ff9b32c --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/expiredGhns.xq @@ -0,0 +1,12 @@ + +let $RIs := collection("/db/Profiles/RunningInstance")//Document/Data/child::*[local-name()='Profile']/Resource +for $GHNs in collection("/db/Profiles/GHN")//Document/Data/child::*[local-name()='Profile']/Resource +let $RIinstalled := $RIs[Profile/GHN/string(@UniqueID)=$GHNs/ID] +let $scopes := string-join( $GHNs/Scopes//Scope/text(), ';') +where $GHNs/Profile/GHNDescription/Status/string() != 'down' and $GHNs/Profile/GHNDescription/Status/string() != 'unreachable' +return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/orphanRI.xq b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/orphanRI.xq new file mode 100644 index 0000000..83f3f40 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/gcube/queries/xquery/sweeper/orphanRI.xq @@ -0,0 +1,7 @@ +let $ghns := collection('/db/Profiles/GHN')//Resource/ID +let $ris := collection('/db/Profiles/RunningInstance')//Resource +for $ri in $ris +let $counter := index-of(($ghns//ID/string()), $ri/Profile/GHN/@UniqueID/string()) +where empty($counter) +return + \ No newline at end of file diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportBuilder.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportBuilder.java new file mode 100644 index 0000000..d746bfe --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportBuilder.java @@ -0,0 +1,56 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ReportBuilder.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.report; + +import java.util.List; +import java.util.Vector; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class ReportBuilder { + private List entries = null; + public ReportBuilder() { + entries = new Vector(); + } + + public final void addEntry(final ReportEntry entry) { + this.entries.add(entry); + } + + public final int size() { + return this.entries.size(); + } + + public final String getXML() { + StringBuilder builder = new StringBuilder(); + + builder.append("\n"); + for (ReportEntry entry : this.entries) { + builder.append(entry.toXML()); + } + builder.append("\n"); + return builder.toString(); + } + + @Override + public final String toString() { + return this.getXML(); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportEntry.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportEntry.java new file mode 100644 index 0000000..f69e687 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportEntry.java @@ -0,0 +1,100 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ReportEntry.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.report; + +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.managers.resources.AbstractResourceManager; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class ReportEntry { + private ReportOperation operation = null; + private AbstractResourceManager resource = null; + private boolean success = false; + private String message = null; + + public ReportEntry( + final ReportOperation operation, + final AbstractResourceManager resource + ) throws AbstractResourceException { + this(operation, resource, null, false); + } + + public ReportEntry( + final ReportOperation operation, + final AbstractResourceManager resource, + final boolean success + ) throws AbstractResourceException { + this(operation, resource, null, success); + } + + public ReportEntry( + final ReportOperation operation, + final AbstractResourceManager resource, + final String message, + final boolean success + ) throws AbstractResourceException { + this.operation = operation; + this.resource = resource; + this.success = success; + this.message = message; + } + public final ReportOperation getOperation() { + return operation; + } + public final AbstractResourceManager getResource() { + return resource; + } + public final boolean isSuccess() { + return success; + } + public final void setSuccess(final boolean success) { + this.success = success; + } + public final void setMessage(final String message) { + this.message = message; + } + public final void setMessage(final Throwable ex) { + this.message = ex.getMessage(); + } + + @Override + public final String toString() { + return this.toXML(); + } + + public final String toXML() { + return + "\t\n" + + "\t\t" + (this.isSuccess() ? "SUCCESS" : "FAILURE") + "\n" + + "\t\t\n" + + "\t\t\t" + this.getResource().getID() + "\n" + + // If the resource has a name + (this.getResource().getName() != null ? + "\t\t\t" + this.getResource().getName() + "\n" : "") + + + "\t\t\t" + this.getResource().getType() + "\n" + + // If a message is present + (this.message != null ? + "\t\t\t\n\t\t\t\t" + this.message.trim() + "\n\t\t\t\n" : "") + + + "\t\t\n" + + "\t\n"; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportOperation.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportOperation.java new file mode 100644 index 0000000..546bd76 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/report/ReportOperation.java @@ -0,0 +1,33 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ReportOperation.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.report; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public enum ReportOperation { + AddToScope("Add To Scope"); + + private String label = null; + private ReportOperation(final String label) { + this.label = label; + } + public final String getLabel() { + return this.label; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/AbstractResourceManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/AbstractResourceManager.java new file mode 100644 index 0000000..2015b89 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/AbstractResourceManager.java @@ -0,0 +1,578 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import static org.gcube.resources.discovery.icclient.ICFactory.client; + +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.common.scope.impl.ScopeBean.Type; +import org.gcube.informationsystem.publisher.AdvancedPublisher; +import org.gcube.informationsystem.publisher.RegistryPublisher; +import org.gcube.informationsystem.publisher.RegistryPublisherFactory; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.managers.report.ReportBuilder; +import org.gcube.resourcemanagement.support.server.managers.report.ReportEntry; +import org.gcube.resourcemanagement.support.server.managers.report.ReportOperation; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.Assertion; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.Query; +import org.gcube.resources.discovery.client.queries.impl.QueryBox; +import org.gcube.vremanagement.resourcemanager.client.RMBinderLibrary; +import org.gcube.vremanagement.resourcemanager.client.RMReportingLibrary; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.AddResourcesParameters; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.RemoveResourcesParameters; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceItem; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceList; +import org.gcube.vremanagement.resourcemanager.client.proxies.Proxies; + +/** + * The minimal interface all the resource managers must implement. + * Here is implemented the greatest part of the operations exposed in the + * + * official wiki. + * @author Daniele Strollo (ISTI-CNR) + * @author Massimiliano Assante (ISTI-CNR) + */ +public abstract class AbstractResourceManager { + private String id = null; + private String name = null; + private AllowedResourceTypes type = null; + private String subType = null; + private RegistryPublisher publisher = null; + private static final String LOG_PREFIX = "[AbstractResMgr]"; + + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. For internal use only. + */ + public AbstractResourceManager(final AllowedResourceTypes type) + throws ResourceParameterException, ResourceAccessException { + Assertion checker = new Assertion(); + checker.validate(type != null, new ResourceParameterException("Invalid Parameter type")); + + this.type = type; + + try { + this.publisher = RegistryPublisherFactory.create(); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + + /** + * Instantiate the handler of a resource given its identifier and its type. + * Notice that this constructor is implicitly invoked when instantiating the + * concrete resource manager (e.g. new GHNManager(id)). + * @param id the identifier of the resource the manage + * @param type the type (GHN, RI, ...). + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public AbstractResourceManager(String id, AllowedResourceTypes type) throws ResourceParameterException, ResourceAccessException { + this(type); + + Assertion checker = new Assertion(); + checker.validate(id != null && id.trim().length() > 0, new ResourceParameterException("Invalid Parameter id")); + + this.id = id.trim(); + } + + public AbstractResourceManager(String id, String name, AllowedResourceTypes type) throws ResourceParameterException, ResourceAccessException { + this(id, type); + Assertion checker = new Assertion(); + checker.validate(name != null && name.trim().length() > 0, new ResourceParameterException("Invalid Parameter name")); + this.name = name; + } + + public AbstractResourceManager(String id, String name, AllowedResourceTypes type, String subtype) throws ResourceParameterException, ResourceAccessException { + this(id, name, type); + if (subtype != null) { + this.subType = subtype.trim(); + } + } + + /** + * The singleton ISPublisher instance is preferred. + * All resource managers can internally access this instance + * to interact with ISPublisher to handle resources. + * @return + */ + public final RegistryPublisher getRegistryPublisher() { + return publisher; + } + + /** + * All resources must be identifiable through an unique ID. + *
+ * This field is mandatory + * @return + */ + public final String getID() { + return this.id; + } + + public final void setID(final String id) { + this.id = id; + } + + /** + * All resources must have a valid name. + *
+ * This field is mandatory + * @return + */ + public final String getName() { + return this.name; + } + + /** + * All resources have a type. + *
+ * This field is mandatory + * @return + */ + public final AllowedResourceTypes getType() { + return this.type; + } + + /** + * Resources can have a subtype (e.g. for GHNs is the domain). + *
+ * This field is optional + * @return + */ + public final String getSubType() { + return this.subType; + } + + /** + * The resource manager needed to handle the resource in a given scope. + * @param scope the scope in which to operate + * @return a random chosen manager from the avaiable ones + * @throws ResourceAccessException if no manager can be instantiated + * @throws ResourceParameterException if the parameters are invalid + */ + public final RMBinderLibrary getResourceManager(String scope) throws AbstractResourceException { + + ScopeBean bscope = new ScopeBean(scope); + if (bscope.is(Type.VRE)) { + scope = bscope.enclosingScope().toString(); + } + ScopeProvider.instance.set(scope); + ServerConsole.info(LOG_PREFIX, "Getting Resource Manager in scope [" + scope.toString() + "]"); + RMBinderLibrary rml = Proxies.binderService().build(); + if (rml == null) { // no managers found + throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getType() + " in scope: " + scope.toString()); + } + return rml; + } + + /** + * The report resource manager needed to handle the resource in a given scope. + * @param scope the scope in which to operate + * @return a random chosen manager from the avaiable ones + * @throws ResourceAccessException if no manager can be instantiated + * @throws ResourceParameterException if the parameters are invalid + */ + public final RMReportingLibrary getReportResourceManager(String scope) throws AbstractResourceException { + ScopeBean bscope = new ScopeBean(scope); + if (bscope.is(Type.VRE)) { + scope = bscope.enclosingScope().toString(); + } + ScopeProvider.instance.set(scope); + + ServerConsole.info(LOG_PREFIX, "Getting Resource Manager in scope [" + scope.toString() + "]"); + RMReportingLibrary rml = Proxies.reportingService().build(); + if (rml == null) { // no managers found + throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getType() + " in scope: " + scope.toString()); + } + return rml; + } + + /** + * Once the conditions for binding a resource to a target scope are satisfied + * (see the + * + * official wiki + * for scope binding rules) this method is internally called. + * @param targetScope + * @return + * @throws ResourceOperationException + */ + private String bindToScope(final String targetScope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(targetScope != null, new ResourceParameterException("Invalid parameter targetScope. null not allowed.")); + checker.validate(this.getID() != null, new ResourceOperationException("Invalid resource ID. null not allowed.")); + + ServerConsole.trace( + LOG_PREFIX, + "[BIND-SCOPE-ENTER] Adding " + this.getType() + " " + this.getID() + " to scope [" + + targetScope.toString() + "]"); + + System.out.println("***\n\n[BIND-SCOPE-ENTER] Adding " + this.getType() + " " + this.getID() + " to scope [" + + targetScope.toString() + "]"); + + + String curr = ScopeProvider.instance.get(); + ScopeProvider.instance.set(targetScope.toString()); + + AddResourcesParameters addParam = new AddResourcesParameters(); + ResourceItem toAdd = new ResourceItem(); + toAdd.setId(this.getID()); + toAdd.setType(this.getType().name()); + ResourceList r = new ResourceList(); + + ArrayList temp = new ArrayList(); + temp.add(toAdd); + r.setResource(temp); + addParam.setResources(r); + addParam.setTargetScope(targetScope.toString()); + + RMBinderLibrary manager = this.getResourceManager(targetScope); + + try { + ScopeBean scope = new ScopeBean(targetScope); + if (scope.is(Type.VRE)) { + ScopeProvider.instance.set(scope.enclosingScope().toString()); + } else + ScopeProvider.instance.set(targetScope); + System.out.println("***\n\nCalling manager.addResources(addParam) addParam.toString()=" + addParam.toString()); + + String reportID = manager.addResources(addParam); + + ServerConsole.trace( + LOG_PREFIX, + "[BIND-SCOPE-EXIT] Applyed Adding " + this.getType() + " " + this.getID() + " to scope [" + + targetScope.toString() + "]... reportID: " + reportID); + + System.out.println("***\n\n[BIND-SCOPE-EXIT] Applyed Adding " + this.getType() + " " + this.getID() + " to scope [" + + targetScope.toString() + "]... reportID: " + reportID); + + RMReportingLibrary pt = this.getReportResourceManager(scope.toString()); + + String toReturn = pt.getReport(reportID); + ScopeProvider.instance.set(curr); + return toReturn; + } catch (Exception e) { + e.printStackTrace(); + ServerConsole.trace( + LOG_PREFIX, + "[BIND-SCOPE-EXIT] [FAILURE]"); + System.out.println("***[BIND-SCOPE-EXIT] [FAILURE]" +e.getMessage()); + throw new ResourceOperationException("During resource::addToScope: "+ targetScope + " Message: \n" + e.getMessage()); + } + } + + + + /** + * Add a scope to a Resource + * @param nestingPublication true for resources different from gHN and RI. + * @return the reportID generated + */ + public final String addToExistingScope(final ScopeBean sourceScope, final ScopeBean targetScope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(sourceScope != null, new ResourceParameterException("Invalid parameter sourceScope. null not allowed.")); + checker.validate(targetScope != null, new ResourceParameterException("Invalid parameter targetScope. null not allowed.")); + checker.validate(this.getID() != null, new ResourceOperationException("Invalid resource ID. null not allowed.")); + + String curr = ScopeProvider.instance.get(); + ScopeProvider.instance.set(sourceScope.toString()); + ReportBuilder report = new ReportBuilder(); + + ServerConsole.trace( + LOG_PREFIX, + "[ADD-ToExistingScope] Adding from scope [" + + sourceScope.toString() + + "] to existing scope [" + + targetScope.toString() + + "] " + this.getType() + " " + this.getID()); + + // If not RI or GHN and the scopes are sibling and VO copyFromToVO + if (!(this.getType() == AllowedResourceTypes.GHN) && + !(this.getType() == AllowedResourceTypes.RunningInstance) && + sourceScope.type() == Type.VO && targetScope.type() == Type.VO) { + return copyFromToVO(sourceScope, targetScope); + } + + // Add a gCube Resource to + // (i) a VRE scope from the parent VO or + // (ii) a VO scope from the infrastructure scope + if (!targetScope.toString().contains(sourceScope.toString())) { + throw new ResourceOperationException( + "You are not allowed to apply to this scope. Target scope is not enclosed in the source one."); + } + + report.addEntry(new ReportEntry(ReportOperation.AddToScope, this, + "Added " + this.getType() + " " + this.getID() + " to parent scope " + + targetScope.toString() + " the remote report ID is: " + + this.bindToScope(targetScope.toString()), true)); + + + String toReturn = report.getXML(); + ScopeProvider.instance.set(curr); + return toReturn; + } + + + + /** + * Similar to the {@link AbstractResourceManager#addToExistingScope} method but involves + * two scopes of type VO. + * Notice that this operation in reserved for resources different from gHN and RI. + * See + * + * here for further details. + * @param sourceScope + * @param targetScope + * @return + * @throws AbstractResourceException + */ + public final String copyFromToVO(final ScopeBean sourceScope, final ScopeBean targetScope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate( + sourceScope != null && sourceScope.type() == Type.VO, + new ResourceParameterException("The sourceScope is invalid or not of type VO.")); + checker.validate( + targetScope != null && targetScope.type() == Type.VO, + new ResourceParameterException("The targetScope is invalid or not of type VO.")); + checker.validate( + sourceScope.enclosingScope() == targetScope.enclosingScope(), + new ResourceParameterException("The sourceScope and targetScope must be children of the same root VO.")); + checker.validate(this.getType() != AllowedResourceTypes.GHN && this.getType() != AllowedResourceTypes.RunningInstance, + new ResourceAccessException("Operation not allowed for RI and GHNs.")); + checker.validate(this.getID() != null, + new ResourceAccessException("Operation not allowed on resources with no ID.")); + + // Phase 1. retrieve the resource to copy + Resource resStub = this.getResource(sourceScope); + + // Phase 2. Before registering the resource, the scope must be + // bound to the local GCUBEResource + this.bindToScope(targetScope.toString()); + + // Phase 3. Register to the new VO through the ISPublisher + + String currentScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(targetScope.toString()); + Resource toReturn = null; + try { + toReturn = this.getRegistryPublisher().create(resStub); + } catch (Exception e) { + throw new ResourceAccessException(e.getMessage()); + } + ScopeProvider.instance.set(currentScope); + return toReturn.id(); + } + + /** + * Given the XML profile representation of a gcube resource, its GCUBEResource is built. + * Since it depends on the type of the resource, each concrete implementation of resource + * managers must implement it. + * @param xmlRepresentation + * @return + * @throws AbstractResourceException + */ + protected abstract Resource buildResource(final String xmlRepresentation) throws AbstractResourceException; + + /** + * From a resource retrieves its GCUBEResource depending on the scope in which it is + * published. + * @param scope + * @return + * @throws AbstractResourceException + */ + public final Resource getResource(final ScopeBean scope) throws AbstractResourceException { + return this.buildResource(this.getXMLDescription(scope)); + } + + /** + * Returns the XML profile of a resource (given its ID that is encapsulated inside the resource + * manager). + * @param scope + * @return + * @throws AbstractResourceException + */ + protected final String getXMLDescription(final ScopeBean scope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(this.getID() != null, new ResourceAccessException("Cannot execute on resources with no ID.")); + + ScopeProvider.instance.set(scope.toString()); + + // Phase 1. retrieve the resource to copy + Query query = new QueryBox("for $resource in collection('/db/Profiles/" + this.getType().name() + "')//Resource " + + "where ( $resource/ID/string() eq '" + + this.getID() + + "') " + + "return $resource"); + + DiscoveryClient client = client(); + + List results = client.submit(query); + if (results == null || results.isEmpty()) + throw new ResourceAccessException("Cannot retrieve the IS profile for resource: " + this.getID() + + " in scope: " + scope.toString()); + + return results.get(0).toString(); + } + + /** + * The first phase of remove from scope. + * This is common to all the resources (RI and GHNs). + * @param scope + * @return + * @throws AbstractResourceException + */ + private String basicRemoveFromScope(final ScopeBean scope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed.")); + checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed.")); + + ServerConsole.trace(LOG_PREFIX, "[REMOVE-FROM-SCOPE] Removing from scope [" + scope.toString() + "] " + this.getType() + " " + this.getID()); + + String retval = null; + + RemoveResourcesParameters params = new RemoveResourcesParameters(); + ResourceItem toRemove = new ResourceItem(); + toRemove.setId(this.getID()); + toRemove.setType(this.getType().name()); + + ResourceList resourcesToRemove = new ResourceList(); + ArrayList temp = new ArrayList(); + temp.add(toRemove); + resourcesToRemove.setResource(temp); + params.resources = resourcesToRemove; + params.targetScope = scope.toString(); + ServerConsole.trace(LOG_PREFIX, "[REMOVE-FROM-SCOPE] Sending the Remove Resource request...."); + try { + RMBinderLibrary manager = this.getResourceManager(scope.toString()); + ScopeProvider.instance.set(scope.toString()); + retval = manager.removeResources(params); + } catch (Exception e) { + throw new ResourceOperationException("During removeFrom scope of " + + this.getType() + + " " + this.getID() + ": " + e.getMessage()); + } + return retval; + } + + /** + * Removes the current resource from the scope. + * @param nestingRemoval true for resources different from gHN and RI + */ + public final String removeFromScope(final ScopeBean scope) throws AbstractResourceException { + ServerConsole.trace(LOG_PREFIX, "[BASIC-FROM-SCOPE] Removing from scope [" + scope.toString() + "] " + this.getType() + " " + this.getID()); + Assertion checker = new Assertion(); + checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed.")); + checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed.")); + + ScopeProvider.instance.set(scope.toString()); + String retval = this.basicRemoveFromScope(scope); + + return retval; + } + + /** + * Adds to scopes the required maps (if needed). + * Internally used to ensure that the scopes at Infrastructure or VO level + * have correctly setup the maps. + * @param scopes + * @return + */ + protected List validateScopes(final String[] scopes) { + List retval = new Vector(); + for (int i = 0; i < scopes.length; i++) { + retval.add(new ScopeBean(scopes[i])); + } + return retval; + } + + + /** + * @deprecated you must be sure before requiring this operation... take care + * @param scope where the resource is bound + * @throws AbstractResourceException + */ + public final void forceDelete(ScopeBean scope) throws AbstractResourceException { + ServerConsole.trace(LOG_PREFIX, "[FORCE DELETE] [DELETE-BRANCH] deleting resource from scope " + scope); + String currScope = ScopeProvider.instance.get(); + + Resource toDelete = this.getResource(scope); + + while (scope.enclosingScope() != null) + scope = scope.enclosingScope(); + + ScopeProvider.instance.set(scope.toString()); + AdvancedPublisher advancedPublisher = new AdvancedPublisher(this.getRegistryPublisher()); + advancedPublisher.forceRemove(toDelete); + ServerConsole.trace(LOG_PREFIX, "[FORCE DELETE] [DELETE-BRANCH] deleted resource from scope " + scope); + ScopeProvider.instance.set(currScope); + } + + /** + * Removes a resource. + * According to the + * + * official wiki the resource is deleted only if is not bound in other scopes. Otherwise this + * operation simply corresponds to remove from scope. + * @param scope + * @throws ResourceOperationException + */ + public final String delete(final ScopeBean scope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed.")); + checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed.")); + + System.out.println("DELETING TYPE: "+ this.getType()); + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(scope.toString()); + Resource resStub = this.getResource(scope); + + List boundedScopes = this.validateScopes(resStub.scopes().toArray(new String[0])); + + ServerConsole.trace(LOG_PREFIX, "[DELETE] " + this.getType() + " " + this.getID() + " in scope [" + scope + "]"); + + ServerConsole.trace(LOG_PREFIX, "[DELETE] " + this.getType() + " " + this.getID() + " is bound to (" + boundedScopes.size() + ") scopes"); + String toReturn = ""; + if (boundedScopes.size() > 1) { + ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource is a remove from scope since more than 1 scope is present " + resStub.id()); + toReturn = this.basicRemoveFromScope(scope); + } + else if (boundedScopes.size() == 1) { + ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource since is bound to 1 scope only " + resStub.id()); + try { + this.getRegistryPublisher().remove(resStub); + toReturn = "NO REPORT because with only one resource the RegistryPublisher().remove was called"; + } catch (Exception e) { + ScopeProvider.instance.set(currScope); + } + } + ScopeProvider.instance.set(currScope); + return toReturn; + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/CollectionManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/CollectionManager.java new file mode 100644 index 0000000..2280084 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/CollectionManager.java @@ -0,0 +1,75 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: CollectionManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import org.gcube.common.resources.gcore.Resource; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class CollectionManager extends AbstractResourceManager { + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. + */ + public CollectionManager() + throws ResourceParameterException, ResourceAccessException { + super(AllowedResourceTypes.Collection); + } + + public CollectionManager(final String id) + throws ResourceParameterException, ResourceAccessException { + super(id, AllowedResourceTypes.Collection); + } + + /** + * @param id + * @param name + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public CollectionManager(final String id, final String name) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.Collection); + } + + /** + * @param id + * @param name + * @param subtype + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public CollectionManager(final String id, final String name, final String subtype) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.Collection, subtype); + } + + + + @Override + protected Resource buildResource(String xmlRepresentation) + throws AbstractResourceException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GHNManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GHNManager.java new file mode 100644 index 0000000..afc6002 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GHNManager.java @@ -0,0 +1,201 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: GHNManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import java.io.StringReader; + +import org.gcube.common.resources.gcore.HostingNode; +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.resources.gcore.Resources; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.common.vremanagement.ghnmanager.client.GHNManagerLibrary; +import org.gcube.common.vremanagement.ghnmanager.client.fws.Types.AddScopeInputParams; +import org.gcube.common.vremanagement.ghnmanager.client.fws.Types.ShutdownOptions; +import org.gcube.common.vremanagement.ghnmanager.client.proxies.Proxies; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.Assertion; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; + + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class GHNManager extends AbstractResourceManager { + + private static final String LOG_PREFIX = "[GHN-MGR]"; + + + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. + */ + public GHNManager() + throws ResourceParameterException, ResourceAccessException { + super(AllowedResourceTypes.GHN); + } + + /** + * @param id the identifier of wrapper resource. + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public GHNManager(final String id) + throws ResourceParameterException, ResourceAccessException { + super(id, AllowedResourceTypes.GHN); + } + + /** + * @param id + * @param name + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public GHNManager(final String id, final String name) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.GHN); + } + + /** + * @param id + * @param name + * @param subtype + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public GHNManager(final String id, final String name, final String subtype) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.GHN, subtype); + } + + /** + * Add a scope to a gHN and the related Service Map that is not available on the gHN. + *

+ * Required information: + *
+ * The ID of the resource must be specified and valid.

+ * @param scope + * @param scopeMap + * @return the generated reportID + * @throws ResourceParameterException + * @throws ResourceOperationException + */ + public final String addToNewScope(final ScopeBean sourceScope, final ScopeBean targetScope, final String scopeMap) + throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(sourceScope != null, new ResourceParameterException("Parameter sourceScope null not allowed.")); + checker.validate(targetScope != null, new ResourceParameterException("Parameter targetScope null not allowed.")); + checker.validate(scopeMap != null && scopeMap.trim().length() > 0, new ResourceParameterException("Invalid scopeMap parameter.")); + checker.validate(this.getID() != null, new ResourceOperationException("This operation cannot be applied to resources with no ID.")); + + if (!sourceScope.toString().contains(targetScope.toString())) { + throw new ResourceOperationException( + "You are not allowed to apply to this scope. Target scope is not enclosed in the source one."); + } + ServerConsole.trace( + LOG_PREFIX, + "Adding from scope " + + sourceScope.toString() + + "Adding to existing scope " + + targetScope.toString() + + " " + this.getType() + " " + this.getID()); + + AddScopeInputParams params = new AddScopeInputParams(); + params.setScope(sourceScope.toString()); + params.setMap(scopeMap.trim()); //eventually, set here the new Service Map + try { + this.getGHNManager(sourceScope).addScope(params); + } catch (Exception e) { + throw new ResourceOperationException( + "Failed to add the new scope to the gHN " + this.getID() + ": " + e.getMessage()); + } + return this.addToExistingScope(sourceScope, targetScope); + } + + /** + *

+ * Required information: + *
+ * The name of the resource must be specified and valid. It is used to retrieve the GHN manager URL.

+ * @param scope the scope in which the manager is bound. + * @return + * @throws AbstractResourceException + */ + public final GHNManagerLibrary getGHNManager(final ScopeBean scope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(scope != null, new ResourceParameterException("Invalid scope")); + checker.validate(this.getName() != null, new ResourceOperationException("This operation cannot be applied to resources with no name.")); + + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(scope.toString()); + ServerConsole.info(LOG_PREFIX, "Getting Resource Manager in scope [" + scope.toString() + "]"); + GHNManagerLibrary ghnMan = Proxies.service().build(); + if (ghnMan == null) { // no managers found + throw new ResourceAccessException("Unable to find GHNManagers for resource " + this.getType() + " in scope: " + scope.toString()); + } + ScopeProvider.instance.set(currScope); + return ghnMan; + } + + /** + * Implements all the three possible shutdown policies according to + * restart and clean parameters. + *

+ * Required information: + *
+ * The ID of the resource must be specified and valid.

+ * @param scope + * @param restart + * @param clean + * @throws ResourceOperationException + * @throws ResourceAccessException + * @throws ResourceParameterException + */ + public final void shutDown(final ScopeBean scope, final boolean restart, final boolean clean) + throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(this.getID() != null, new ResourceAccessException("This operation cannot be applied to resources with no ID.")); + + GHNManagerLibrary ghnManager = this.getGHNManager(scope); + + ServerConsole.trace(LOG_PREFIX, "Shutting down " + scope.toString() + " " + this.getType() + " " + this.getID()); + + ShutdownOptions options = new ShutdownOptions(); + options.setRestart(restart); + options.setClean(clean); + try { + ghnManager.shutdown(options); + } catch (Exception e) { + throw new ResourceOperationException("Cannot shutdown ghn: " + this.getID()); + } + } + + @Override + protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException { + try { + HostingNode deserialised = Resources.unmarshal(HostingNode.class, new StringReader(xmlRepresentation)); + return deserialised; + } catch (Exception e) { + throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); + } + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GenericResourceManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GenericResourceManager.java new file mode 100644 index 0000000..aac6d53 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/GenericResourceManager.java @@ -0,0 +1,247 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: GenericResourceManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; + +import java.io.IOException; +import java.io.StringReader; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.gcube.common.resources.gcore.GenericResource; +import org.gcube.common.resources.gcore.GenericResource.Profile; +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.informationsystem.publisher.RegistryPublisher; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.Assertion; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.SimpleQuery; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + + +/** + * @author Massimiliano Assante (ISTI-CNR) + * @author Daniele Strollo (ISTI-CNR) + */ +public class GenericResourceManager extends AbstractResourceManager { + // Used internally to require static functionalities (e.g. deploy). + private static GenericResourceManager singleton = null; + private static final String LOG_PREFIX = "[GenericResource-MGR]"; + + static { + if (GenericResourceManager.singleton == null) { + try { + GenericResourceManager.singleton = new GenericResourceManager("dummyservice", "dummyservice"); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + } + + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. + */ + public GenericResourceManager() + throws ResourceParameterException, + ResourceAccessException { + super(AllowedResourceTypes.GenericResource); + } + + public GenericResourceManager(final String id) + throws ResourceParameterException, + ResourceAccessException { + super(id, AllowedResourceTypes.GenericResource); + } + + /** + * @param id + * @param name + * @param type + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public GenericResourceManager(final String id, final String name) + throws ResourceParameterException, + ResourceAccessException { + super(id, name, AllowedResourceTypes.GenericResource); + } + + /** + * @param id + * @param name + * @param type + * @param subtype + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public GenericResourceManager(final String id, final String name, final String subtype) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.GenericResource, subtype); + } + + /** + * Updates the resource. + * @param name (Mandatory) the name to assign to the resource + * @param description (optional) if null it will not be changed + * @param body (optional) if null it will not be changed + * @param subType (optional) if null it will not be changed + * @param scope (optional) if null it will not be changed + * @throws AbstractResourceException + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + */ + public final void update(final String name, final String description, final String body, final String subType, final ScopeBean scope) throws Exception { + + Assertion checker = new Assertion(); + checker.validate(name != null && name.trim().length() != 0, new ResourceParameterException("Invalid field name. Null or empty value not allowed")); + + ServerConsole.trace(LOG_PREFIX, "[RES-UPDATE] updating resource " + this.getType() + " " + this.getID()); + + GenericResource resource = getResourceToEditById(this.getID(), scope); + resource.profile().name(name.trim()); + + if (description != null) { + resource.profile().description(description.trim()); + } + if (body != null) { + appendXmlFragment(resource.profile(), body); + } + if (subType != null) + resource.profile().type(subType.trim()); + + ScopeProvider.instance.set(scope.toString()); + RegistryPublisher publisher = getRegistryPublisher(); + String id = publisher.update(resource).id(); + + if (id == null || id.length() == 0) { + throw new Exception("The GenericResource has not been updated"); + } + ServerConsole.info(LOG_PREFIX, "Resource Updated with ID: " + id); + } + + private GenericResource getResourceToEditById(String id, ScopeBean scope) throws Exception { + + ScopeProvider.instance.set(scope.toString()); + + SimpleQuery query = queryFor(GenericResource.class); + query.addCondition("$resource/ID/text() eq '"+ id +"'"); + + DiscoveryClient client = clientFor(GenericResource.class); + + List r = client.submit(query); + + if (r == null || r.isEmpty()) + throw new Exception("Could not retrieve GenericResource profile with id " + id + " in scope + " +scope); + else + return r.get(0); + } + /** + * Creates a Generic Resource and returns the ID given by the + * resource manager at creation phase. + * @return the id assigned to the newly created resource + */ + public static final synchronized String create(final String ID, final ScopeBean scope, final String name, final String description, final String body, final String subType) + throws Exception { + Assertion checker = new Assertion(); + checker.validate(name != null && name.trim().length() != 0, new ResourceParameterException("Invalid field name. Null or empty value not allowed")); + checker.validate(subType != null && subType.trim().length() != 0, new ResourceParameterException("Invalid field subType. Null or empty value not allowed")); + + GenericResource resource = new GenericResource(); + resource.newProfile().name(name.trim()); + + if (description != null) { + resource.profile().description(description.trim()); + } + if (body != null) { + appendXmlFragment(resource.profile(), body); + } + resource.profile().type(subType.trim()); + + + GenericResourceManager gm = new GenericResourceManager(); + + + ScopeProvider.instance.set(scope.toString()); + RegistryPublisher publisher = gm.getRegistryPublisher(); + String id = publisher.create(resource).id(); + + if (id == null || id.length() == 0) { + throw new Exception("The GenericResource has not been created"); + } + ServerConsole.info(LOG_PREFIX, "Resource Created with ID: " + id); + return id; + } + + @Override + protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException { + try { + JAXBContext ctx = JAXBContext.newInstance(GenericResource.class); + Unmarshaller unmarshaller = ctx.createUnmarshaller(); + StringReader reader = new StringReader(xmlRepresentation); + GenericResource deserialised = (GenericResource) unmarshaller.unmarshal(reader); + return deserialised; + } catch (Exception e) { + throw new ResourceAccessException("Cannot load the resource " + this.getType(), e); + } + } + + /** + * append a well formed xml string to the body + * @param parent + * @param fragment + * @throws IOException + * @throws SAXException + * @throws ParserConfigurationException + */ + public static void appendXmlFragment(Profile profile, String fragment) throws IOException, ParserConfigurationException { + + ServerConsole.debug(LOG_PREFIX, "Appending to " + fragment); + + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Element elem = profile.newBody(); + Node fragmentNode; + try { + fragmentNode = docBuilder.parse(new InputSource(new StringReader(fragment))).getDocumentElement(); + fragmentNode = elem.getOwnerDocument().importNode(fragmentNode, true); + elem.appendChild(fragmentNode); + } catch (SAXException e) { + //in case no xml is entered, just text + ServerConsole.warn("no valid xml appending this:" + fragment); + profile.newBody(fragment); + } + + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ManagementUtils.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ManagementUtils.java new file mode 100644 index 0000000..d92907c --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ManagementUtils.java @@ -0,0 +1,335 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ManagementUtils.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.resources.gcore.Software; +import org.gcube.common.resources.gcore.Software.Profile.ServicePackage; +import org.gcube.common.resources.gcore.Software.Profile.SoftwarePackage; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.common.scope.impl.ScopeBean.Type; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.Assertion; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.SimpleQuery; +import org.gcube.vremanagement.resourcemanager.client.RMBinderLibrary; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.AddResourcesParameters; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.PackageItem; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceItem; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceList; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.SoftwareList; + + +/** + * A support class containing operations to manage multiple resources. + * Here are provided the functionalities to delete/addToScope/deploy + * groups of homogeneous resources. + * @author Daniele Strollo (ISTI-CNR) + */ +public class ManagementUtils { + private static final String LOG_PREFIX = "[MANAGEMENT-UTILS]"; + + /** + * Applies the add to scope to multiple resources having the same type. + * @param type + * @param resources + * @param sourceScope + * @param targetScope + * @return the generated report ID + */ + public static final synchronized String addToExistingScope(AllowedResourceTypes type, String[] resourceIDs, ScopeBean sourceScope, ScopeBean targetScope) throws Exception { + ServerConsole.trace( + LOG_PREFIX, + "[ADD-ToExistingScope] Adding from scope [" + + sourceScope.toString() + + "] to existing scope [" + + targetScope.toString() + + "] resources having type " + type.name()); + + // 1 - If not RI or GHN and the scopes are sibling and VO copyFromToVO + if (!(type == AllowedResourceTypes.GHN) && + !(type == AllowedResourceTypes.RunningInstance) && + sourceScope.type() == Type.VO && targetScope.type() == Type.VO) { + // Phase 1. retrieve the resource to copy + //GCUBEResource resStub = this.getGCUBEResource(sourceScope); + + // Phase 2. Before to register the resource, the scope must be + // bound to the local GCUBEResource + String retval = bindToScope(type, resourceIDs, targetScope); + + // Phase 3. Register to the new VO through the ISPublisher + // applies a copy of old descriptors bound in other scopes. + try { + for (String id : resourceIDs) { + AbstractResourceManager res = ResourceFactory.createResourceManager(type, id); + Resource resStub = res.getResource(sourceScope); + + ScopeProvider.instance.set(targetScope.toString()); + res.getRegistryPublisher().update(resStub); + + } + } catch (Exception e) { + throw new ResourceAccessException(e.getMessage()); + } + return retval; + } + + // Add a gCube Resource to + // (i) a VRE scope from the parent VO or + // (ii) a VO scope from the infrastructure scope + if (sourceScope.toString().contains(targetScope.toString())) { + throw new ResourceOperationException( + "You are not allowed to apply to this scope. Target scope is not enclosed in the source one."); + } + + // 2 - Applies the normal scope binding + return bindToScope(type, resourceIDs, targetScope); + } + + /** + * Applies the remove from scope + * @param type + * @param resources + * @param sourceScope + * @param targetScope + * @return the generated report ID + */ + public static final synchronized String removeFromExistingScope(final AllowedResourceTypes type, final String[] resourceIDs, + final ScopeBean sourceScope, final ScopeBean targetScope) throws Exception { + + ServerConsole.trace( + LOG_PREFIX, + "[REMOVE-FromExistingScope] Removing scope [" + + targetScope.toString() + + "] from existing scope [" + + sourceScope.toString() + + "] resources having type " + type.name()); + // cannot remove a Scope if its the same + if (targetScope.toString().compareTo(sourceScope.toString()) == 0) { + return "You are not allowed to remove this scope. Current and Target scope are the same."; + } + String toReturn = ""; + AbstractResourceManager manager = ResourceFactory.createResourceManager(type); + for (String id : resourceIDs) { + try { + manager.setID(id); + toReturn = manager.delete(targetScope); + } catch (AbstractResourceException e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + + return toReturn; + } + + /** + * + * @param type + * @param resourceIDs + * @param targetScope + * @return the ID of generated report + * @throws AbstractResourceException + */ + private static synchronized String bindToScope(final AllowedResourceTypes type, final String[] resourceIDs, final ScopeBean targetScope)throws AbstractResourceException { + AddResourcesParameters addParam = new AddResourcesParameters(); + RMBinderLibrary manager = ResourceFactory.createResourceManager(type).getResourceManager(targetScope.toString()); + ArrayList resToBind = new ArrayList(); + + for (String id : resourceIDs) { + ResourceItem toAdd = new ResourceItem(); + toAdd.id = id; + toAdd.setType(type.name()); + resToBind.add(toAdd); + } + ResourceList r = new ResourceList(); + + r.setResource(resToBind); + addParam.setResources(r); + addParam.setTargetScope(targetScope.toString()); + + try { + String reportID = manager.addResources(addParam); + + ServerConsole.trace( + LOG_PREFIX, + "[BIND-SCOPE-EXIT] Applyed Adding of resources " + type.name() + " to scope [" + + targetScope.toString() + "]... reportID: " + reportID); + + return reportID; + } catch (Exception e) { + ServerConsole.trace( + LOG_PREFIX, + "[BIND-SCOPE-EXIT] [FAILURE]"); + throw new ResourceOperationException("During resource::addToScope: " + e.getMessage()); + } + } + + public static synchronized void delete(final AllowedResourceTypes type, final String[] resourceIDs, final ScopeBean scope) throws AbstractResourceException { + AbstractResourceManager resource = ResourceFactory.createResourceManager(type); + for (String id : resourceIDs) { + try { + resource.setID(id); + resource.delete(scope); + } catch (AbstractResourceException e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + } + + /** + * Makes the deployment of software on a list of ghns. + * @param ghnsID + * @param servicesID + * @return the generated report ID + * @throws Exception + */ + public static final synchronized String deploy(final ScopeBean scope, final String[] ghnsID, final String[] servicesID) throws Exception { + Assertion checker = new Assertion(); + checker.validate(ghnsID != null && ghnsID.length != 0, new ResourceParameterException("Invalid ghnsID parameter. It cannot be null or empty.")); + checker.validate(servicesID != null && servicesID.length != 0, new ResourceParameterException("Invalid servicesID parameter. It cannot be null or empty.")); + checker.validate(scope != null, new Exception("Cannot retrieve the scope.")); + + + RMBinderLibrary manager = ResourceFactory.createResourceManager(AllowedResourceTypes.Service).getResourceManager(scope.toString()); + + System.out.println("\n\n**** These are the service ids to deploy on SCOPE " + scope); + for (String sid : servicesID) { + System.out.println(sid); + } + System.out.println("\n\n**** These are the gHNs ids to deploy on SCOPE " + scope); + for (String ghn : ghnsID) { + System.out.println(ghn); + } + + ArrayList serviceProfiles = new ArrayList(); + + + // Retrieves the profiles of services + SimpleQuery query = null; + DiscoveryClient client = clientFor(Software.class); + + prepareServices: for (String serviceID : servicesID) { + System.out.println("\n\n**** Query the ICClient to get the profile"); + query = queryFor(Software.class); + query.addCondition("$resource/ID/text() eq '" + serviceID + "'"); + + System.out.println("**** Query : " + query.toString()); + String curr = ScopeProvider.instance.get(); + ScopeProvider.instance.set(scope.toString()); + List results = client.submit(query); + ScopeProvider.instance.set(curr); + System.out.println("**** results received : " + results.size()); + + Software ret = null; + if (results != null && results.size() > 0) { + ret = results.get(0); + } else { + continue prepareServices; + } + + if (ret == null || + ret.profile() == null || + ret.profile().softwareClass() == null || + ret.profile().softwareName() == null) { + ServerConsole.error(LOG_PREFIX, "found an invalid service profile"); + continue; + } + + PackageItem toAdd = new PackageItem(); + + toAdd.serviceClass = ret.profile().softwareClass(); + toAdd.serviceName = ret.profile().softwareName(); + toAdd.serviceVersion ="1.0.0"; + if (ret.profile().packages().size() == 1) { + toAdd.packageName = ret.profile().packages().iterator().next().name(); + toAdd.packageVersion = ret.profile().packages().iterator().next().version(); + } else { + for (SoftwarePackage p : ret.profile().packages()) { + if (p.getClass().isAssignableFrom(ServicePackage.class)) { + toAdd.packageName = p.name(); + toAdd.packageVersion = p.version(); + break; + } + } + } + + serviceProfiles.add(toAdd); + } + + SoftwareList serviceList = new SoftwareList(); + ArrayList arrayGHNSids = new ArrayList(); + for (int i = 0; i < ghnsID.length; i++) { + arrayGHNSids.add(ghnsID[i]); + } + serviceList.suggestedTargetGHNNames = arrayGHNSids; + serviceList.software = serviceProfiles; + + AddResourcesParameters addResourcesParameters = new AddResourcesParameters(); + addResourcesParameters.softwareList = serviceList; + addResourcesParameters.setTargetScope(scope.toString()); + + System.out.println("\n\n**** These is the ServiceList i pass to ResourceManagerPortType: "); + for (int i = 0; i < serviceList.software.size(); i++) { + System.out.println(serviceList.software.get(i)); + } + + String id = ""; + id = manager.addResources(addResourcesParameters); + ServerConsole.debug(LOG_PREFIX, "Report ID = " + id); + System.out.println("Returning.... no exceptions"); + return id; + } + + public static final void main(final String[] args) { + List ids = new Vector(); + ids.add(null); + ids.add("id2"); + ids.add(null); + + ScopeManager.setScopeConfigFile("test-suite" + File.separator + "scopes" + File.separator + "scopedata.xml"); + + try { + + + ManagementUtils.delete(AllowedResourceTypes.GenericResource, + new String[]{ + "3f7384a0-d51c-11df-80cc-ece35605c26c", + "975419b0-d2e1-11df-b0ed-f8e6e669b8ad", + null, + "test" + }, + new ScopeBean("/gcube/devsec/devVRE")); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ResourceFactory.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ResourceFactory.java new file mode 100644 index 0000000..8ad154a --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ResourceFactory.java @@ -0,0 +1,71 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceFactory.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; + +/** + * For lazy developers here given the facilities to instantiate the proper + * resource manager of a resource given its identifier and type. + * @author Daniele Strollo (ISTI-CNR) + */ +public class ResourceFactory { + private static final String LOG_PREFIX = "[RES-MGR-FACTORY]"; + + public static final AbstractResourceManager createResourceManager(final AllowedResourceTypes type) + throws ResourceOperationException { + return createResourceManager(type, null); + } + + /** + * + * @param type + * @param id if null the default constructor (empty params) will be used + * @return + * @throws ResourceOperationException + */ + public static final AbstractResourceManager createResourceManager(final AllowedResourceTypes type, final String id) + throws ResourceOperationException { + ServerConsole.info(LOG_PREFIX, "ResourceFactory building the " + type.name() + "Manager"); + String classToLoad = + // It is supposed that the other classes are in this package + ResourceFactory.class.getPackage().getName() + "." + + type.name() + "Manager"; + try { + if (id == null) { + return (AbstractResourceManager) Class.forName(classToLoad).newInstance(); + } + return (AbstractResourceManager) Class.forName(classToLoad).getConstructor(String.class).newInstance(id); + } catch (Exception e) { + throw new ResourceOperationException(e); + } + } + + public static final void main(final String[] args) throws Exception { + for (AllowedResourceTypes res : AllowedResourceTypes.values()) { + try { + ServerConsole.info(LOG_PREFIX, + "Loaded " + res.name() + " with ID: " + + ResourceFactory.createResourceManager(res, "HelloID").getID()); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, "[ERR] Failed to load: " + res.name()); + } + } + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RunningInstanceManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RunningInstanceManager.java new file mode 100644 index 0000000..fc981b4 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RunningInstanceManager.java @@ -0,0 +1,251 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: RunningInstanceManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; + +import org.gcube.common.resources.gcore.GCoreEndpoint; +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.resources.gcore.Software; +import org.gcube.common.resources.gcore.Software.Profile.ServicePackage; +import org.gcube.common.resources.gcore.Software.Profile.SoftwarePackage; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.Assertion; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.SimpleQuery; +import org.gcube.vremanagement.resourcemanager.client.RMBinderLibrary; +import org.gcube.vremanagement.resourcemanager.client.RMReportingLibrary; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.AddResourcesParameters; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.PackageItem; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.RemoveResourcesParameters; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceItem; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceList; +import org.gcube.vremanagement.resourcemanager.client.fws.Types.SoftwareList; + +/** + * @author Daniele Strollo (ISTI-CNR) + * @author Massimiliano Assante (ISTI-CNR) + */ +public class RunningInstanceManager extends AbstractResourceManager { + // Used internally to require static functionalities (e.g. deploy). + private static final String LOG_PREFIX = "[RI-MGR]"; + + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. + */ + public RunningInstanceManager() + throws ResourceParameterException, ResourceAccessException { + super(AllowedResourceTypes.RunningInstance); + } + + public RunningInstanceManager(final String id) + throws ResourceParameterException, ResourceAccessException { + super(id, AllowedResourceTypes.RunningInstance); + } + + public RunningInstanceManager(final String id, final String name) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.RunningInstance); + } + + public RunningInstanceManager(final String id, final String name, final String subType) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.RunningInstance, subType); + } + /** + * + * @param scope + * @param ghnsID + * @param servicesID + * @return + * @throws ResourceParameterException + * @throws ResourceOperationException + */ + public final String deploy(final ScopeBean scope, final String[] ghnsID, final String[] servicesID) throws ResourceParameterException, ResourceOperationException { + Assertion checker = new Assertion(); + checker.validate(servicesID != null && servicesID.length != 0, + new ResourceParameterException("Invalid servicesID parameter. It cannot be null or empty.")); + checker.validate(scope != null, + new ResourceParameterException("Cannot retrieve the scope.")); + + ArrayList serviceProfiles = new ArrayList(); + + try { + + SimpleQuery query = null; + DiscoveryClient client = clientFor(Software.class); + + prepareServices: for (String serviceID : servicesID) { + query = queryFor(Software.class); + query.addCondition("$resource/Profile/ID/text() eq '" + serviceID + "'"); + System.out.println("**** Query : " + query.toString()); + String curr = ScopeProvider.instance.get(); + ScopeProvider.instance.set(scope.toString()); + List results = client.submit(query); + ScopeProvider.instance.set(curr); + System.out.println("**** results received : " + results.size()); + Software ret = null; + if (results != null && results.size() > 0) { + ret = results.get(0); + } else { + continue prepareServices; + } + + if (ret == null || + ret.profile() == null || + ret.profile().softwareClass() == null || + ret.profile().softwareName() == null) { + ServerConsole.error(LOG_PREFIX, "found an invalid service profile"); + continue; + } + PackageItem toAdd = new PackageItem(); + + toAdd.serviceClass = ret.profile().softwareClass(); + toAdd.serviceName = ret.profile().softwareName(); + toAdd.serviceVersion ="1.0.0"; + if (ret.profile().packages().size() == 1) { + toAdd.packageName = ret.profile().packages().iterator().next().name(); + toAdd.packageVersion = ret.profile().packages().iterator().next().version(); + } else { + for (SoftwarePackage p : ret.profile().packages()) { + if (p.getClass().isAssignableFrom(ServicePackage.class)) { + toAdd.packageName = p.name(); + toAdd.packageVersion = p.version(); + break; + } + } + } + + serviceProfiles.add(toAdd); + } + + SoftwareList serviceList = new SoftwareList(); + + ArrayList arrayGHNSids = new ArrayList(); + for (int i = 0; i < ghnsID.length; i++) { + arrayGHNSids.add(ghnsID[i]); + } + serviceList.suggestedTargetGHNNames = arrayGHNSids; + serviceList.software = serviceProfiles; + + AddResourcesParameters addResourcesParameters = new AddResourcesParameters(); + addResourcesParameters.softwareList = serviceList; + addResourcesParameters.setTargetScope(scope.toString()); + + System.out.println("\n\n**** These is the ServiceList i pass to ResourceManagerPortType: "); + for (int i = 0; i < serviceList.software.size(); i++) { + System.out.println(serviceList.software.get(i)); + } + + String id = ""; + RMBinderLibrary manager = ResourceFactory.createResourceManager(AllowedResourceTypes.Service).getResourceManager(scope.toString()); + String curr = ScopeProvider.instance.get(); + ScopeProvider.instance.set(scope.toString()); + id = manager.addResources(addResourcesParameters); + ScopeProvider.instance.set(curr); + return id; + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, "Error during deployment.", e); + throw new ResourceOperationException("Software deployment failure: " + e.getMessage()); + } + } + /** + * + * @param scope + * @return + * @throws AbstractResourceException + */ + public final String undeploy(final ScopeBean scope) throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(scope != null, + new ResourceParameterException("Cannot retrieve the scope.")); + checker.validate(this.getID() != null, + new ResourceOperationException("Invalid ID.")); + + try { + RMBinderLibrary rm = ResourceFactory.createResourceManager(AllowedResourceTypes.Service).getResourceManager(scope.toString()); + //prepare the parameters + RemoveResourcesParameters params = new RemoveResourcesParameters(); + ResourceItem[] resourcelist = new ResourceItem[1]; + resourcelist[0] = new ResourceItem(); + resourcelist[0].id = this.getID(); + resourcelist[0].type = this.getType().name(); + ResourceList r = new ResourceList(); + ArrayList temp =new ArrayList(); + temp.add(resourcelist[0]); + r.setResource(temp); + params.resources = r; + params.targetScope = scope.toString(); + + //sending the request + ServerConsole.info(LOG_PREFIX, "Sending the Remove Resource request...."); + String reportID = rm.removeResources(params); + ServerConsole.info(LOG_PREFIX, "Returned report ID: " + reportID); + return reportID; + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, "Error during deployment.", e); + throw new ResourceOperationException("Software deployment failure: " + e.getMessage()); + } + } + + public final String checkDeployStatus(final ScopeBean scope, final String deployID) + throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(scope != null, + new ResourceParameterException("Invalid scope passed")); + checker.validate(deployID != null && deployID.trim().length() > 0, + new ResourceParameterException("Invalid reportID passed")); + + RMReportingLibrary vreManagerPortType = this.getReportResourceManager(scope.toString()); + + try { + return vreManagerPortType.getReport(deployID); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + throw new ResourceOperationException("Cannot retrieve the report: " + deployID + " " + e.getMessage()); + } + } + + @Override + protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException { + try { + JAXBContext ctx = JAXBContext.newInstance(GCoreEndpoint.class); + Unmarshaller unmarshaller = ctx.createUnmarshaller(); + StringReader reader = new StringReader(xmlRepresentation); + GCoreEndpoint deserialised = (GCoreEndpoint) unmarshaller.unmarshal(reader); + return deserialised; + } catch (Exception e) { + throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); + } + + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RuntimeResourceManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RuntimeResourceManager.java new file mode 100644 index 0000000..fe885e2 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/RuntimeResourceManager.java @@ -0,0 +1,112 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: RuntimeResourceManager.java + **************************************************************************** + * @author Massimiliano Assante + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import java.io.StringReader; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; + +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.resources.gcore.ServiceEndpoint; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.Assertion; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.vremanagement.resourcemanager.client.RMReportingLibrary; + + + +/** + * @author Massimiliano Assante (ISTI-CNR) + * + */ +public class RuntimeResourceManager extends AbstractResourceManager { + // Used internally to RuntimeResourceManager static functionalities (e.g. deploy). + private static RuntimeResourceManager singleton = null; + private static final String LOG_PREFIX = "[RR-MGR]"; + + static { + if (RuntimeResourceManager.singleton == null) { + try { + RuntimeResourceManager.singleton = new RuntimeResourceManager("dummyservice", "dummyservice"); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + } + + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. + */ + public RuntimeResourceManager() + throws ResourceParameterException, ResourceAccessException { + super(AllowedResourceTypes.RuntimeResource); + } + + public RuntimeResourceManager(final String id) + throws ResourceParameterException, ResourceAccessException { + super(id, AllowedResourceTypes.RuntimeResource); + } + + public RuntimeResourceManager(final String id, final String name) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.RuntimeResource); + } + + public RuntimeResourceManager(final String id, final String name, final String subType) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.RuntimeResource, subType); + } + + + public final String checkDeployStatus(final ScopeBean scope, final String deployID) + throws AbstractResourceException { + Assertion checker = new Assertion(); + checker.validate(scope != null, + new ResourceParameterException("Invalid scope passed")); + checker.validate(deployID != null && deployID.trim().length() > 0, + new ResourceParameterException("Invalid reportID passed")); + + RMReportingLibrary vreManagerPortType = this.getReportResourceManager(scope.name()); + + try { + return vreManagerPortType.getReport(deployID); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + throw new ResourceOperationException("Cannot retrieve the report: " + deployID + " " + e.getMessage()); + } + } + + @Override + protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException { + try { + JAXBContext ctx = JAXBContext.newInstance(ServiceEndpoint.class); + Unmarshaller unmarshaller = ctx.createUnmarshaller(); + StringReader reader = new StringReader(xmlRepresentation); + ServiceEndpoint deserialised = (ServiceEndpoint) unmarshaller.unmarshal(reader); + return deserialised; + } catch (Exception e) { + throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); + } + + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ServiceManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ServiceManager.java new file mode 100644 index 0000000..ad6259b --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/resources/ServiceManager.java @@ -0,0 +1,88 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ServiceManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.resources; + +import java.io.StringReader; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; + +import org.gcube.common.resources.gcore.Resource; +import org.gcube.common.resources.gcore.Software; +import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; +import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class ServiceManager extends AbstractResourceManager { + + /** + * @deprecated discouraged use. With no ID some operations cannot be accessed. + */ + public ServiceManager() throws ResourceParameterException, ResourceAccessException { + super(AllowedResourceTypes.Service); + } + + public ServiceManager(final String id) + throws ResourceParameterException, ResourceAccessException { + super(id, AllowedResourceTypes.Service); + } + + /** + * @param id + * @param name + * @param type + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public ServiceManager(final String id, final String name) + throws ResourceParameterException, ResourceAccessException { + super(id, name, AllowedResourceTypes.Service); + } + + /** + * @param id + * @param name + * @param type + * @param subtype + * @throws ResourceParameterException + * @throws ResourceAccessException + */ + public ServiceManager(final String id, final String name, final String subtype) + throws ResourceParameterException, + ResourceAccessException { + super(id, name, AllowedResourceTypes.Service, subtype); + } + + @Override + protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException { + try { + JAXBContext ctx = JAXBContext.newInstance(Software.class); + Unmarshaller unmarshaller = ctx.createUnmarshaller(); + StringReader reader = new StringReader(xmlRepresentation); + Software deserialised = (Software) unmarshaller.unmarshal(reader); + return deserialised; + } catch (Exception e) { + throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); + } + + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/managers/scope/ScopeManager.java b/src/main/java/org/gcube/resourcemanagement/support/server/managers/scope/ScopeManager.java new file mode 100644 index 0000000..0cd0e40 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/managers/scope/ScopeManager.java @@ -0,0 +1,232 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ScopeManager.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.managers.scope; + +import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.gcube.common.resources.gcore.GenericResource; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.SimpleQuery; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +/** + * Scopes and their maps are persisted in this structure. + * + * @author Massimiliano Assante (ISTI-CNR) + * @author Daniele Strollo + * + */ +public class ScopeManager { + private static final Map SCOPES = new LinkedHashMap(); + private static String confFile = null; + private static final String LOG_PREFIX = "[SCOPE-MGR]"; + + public static ScopeBean getScope(final String scope) throws Exception { + synchronized (SCOPES) { + if (getAvailableScopes().containsKey(scope)) { + return getAvailableScopes().get(scope); + } + } + ServerConsole.warn(LOG_PREFIX, "Using DEFAULT scope manager"); + return new ScopeBean(scope); + } + + public static void setScopeConfigFile(final String file) { + confFile = file; + } + + /** + * Refreshes the list of scopes and associated maps. + */ + + public static Map getAvailableScopes() + throws Exception { + if (SCOPES.size() == 0) { + update(); + } + return SCOPES; + } + + public static void clear() { + SCOPES.clear(); + } + + public static void update() throws Exception { + if (confFile == null) { + throw new NullPointerException("the scope file has not been defined"); + } + LinkedHashMap toCopy = readScopes(confFile); + for (String key : toCopy.keySet()) { + SCOPES.put(key, toCopy.get(key)); + } + } + /** + * + * @param confFile + * @return + * @throws Exception + */ + public static LinkedHashMap readScopes(String confFile) throws Exception { + if (confFile == null) { + throw new NullPointerException("the scope file has not been defined"); + } + LinkedHashMap toReturn = new LinkedHashMap(); + String scopeXML = fileToString(confFile); + + Document scopeDocument = getDocumentGivenXML(scopeXML); + NodeList voElements = scopeDocument.getElementsByTagName("vo"); + + for (int i = 0; i < voElements.getLength(); i++) { + NodeList voDetails = voElements.item(i).getChildNodes(); + String voString = voDetails.item(5).getFirstChild().getNodeValue(); + // String voName = voDetails.item(1).getFirstChild().getNodeValue(); + ScopeBean vo = new ScopeBean(voString); + + toReturn.put(vo.toString(), vo); + try { + for (String vre : getVREFromVO(vo)) { + // This operation overrides the vo map + toReturn.put(vre.toString(), new ScopeBean(vo.toString()+"/"+vre)); + } + } catch (Exception e) { + ServerConsole.error("Exception raised while loading VREs for VO : " + vo, e); + } + } + return toReturn; + + } + /** + * query the IS to get the VRE list given a VO + * @param vo + * @return + * @throws Exception + */ + protected static List getVREFromVO(final ScopeBean vo) throws Exception { + ServerConsole.info(LOG_PREFIX, "Starting Retrieving VREs for VO : " + vo); + List toReturn = new ArrayList(); + + ScopeProvider.instance.set(vo.toString()); + SimpleQuery query = queryFor(GenericResource.class); + query.addCondition("$resource/Profile/SecondaryType/text() eq 'VRE'"); + + DiscoveryClient client = clientFor(GenericResource.class); + + List gRes = client.submit(query); + + for (GenericResource res : gRes) { + ServerConsole.info(LOG_PREFIX, "Found: " + res.profile().name()); + toReturn.add(res.profile().name()); + } + return toReturn; + } + + /** + * Given a scope, if it is a VO or an infrastructure, the corresponding + * map file is retrieved from the globus location and the contained xml + * representation is returned. + * @param searchvo + * @return + * @throws Exception + */ + public static String getMapXML(final ScopeBean searchvo) throws Exception { + if (confFile == null) { + throw new NullPointerException("the scope file has not been defined"); + } + String scopeXML = fileToString(confFile); + ServerConsole.info(LOG_PREFIX, "Starting retrieving scopes.."); + Document scopeDocument = getDocumentGivenXML(scopeXML); + NodeList voElements = scopeDocument.getElementsByTagName("vo"); + for (int i = 0; i < voElements.getLength(); i++) { + NodeList voDetails = voElements.item(i).getChildNodes(); + String voString = voDetails.item(5).getFirstChild().getNodeValue(); + String fileName = voDetails.item(3).getFirstChild().getNodeValue(); + // String voName = voDetails.item(1).getFirstChild().getNodeValue(); + ScopeBean vo = new ScopeBean(voString); + + if (vo.equals(searchvo)) { + return fileToString(System.getenv("GLOBUS_LOCATION") + File.separator + "config" + File.separator + fileName); + } + } + ServerConsole.error(LOG_PREFIX, "*** maps for " + searchvo + " not found"); + return null; + } + + // private static ServiceMap loadServiceMap(final VO vo, final String fileName) throws Exception { + // ServiceMap map = new ServiceMap(); + // String filePath = System.getenv("GLOBUS_LOCATION") + File.separator + "config" + File.separator + fileName; + // ServerConsole.info(LOG_PREFIX, "--- Loading " + vo.getName() + " from: " + filePath); + // map.load(new FileReader(filePath)); + // return map; + // } + + public static String fileToString(final String path) throws IOException { + BufferedReader filebuf = null; + String nextStr = null; + StringBuilder ret = new StringBuilder(); + + filebuf = new BufferedReader(new FileReader(path)); + nextStr = filebuf.readLine(); // legge una riga dal file + while (nextStr != null) { + ret.append(nextStr); + nextStr = filebuf.readLine(); // legge la prossima riga + } + filebuf.close(); // chiude il file + + return ret.toString(); + } + + public static Document getDocumentGivenXML(final String result) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(false); + DocumentBuilder db; + Document document = null; + try { + db = dbf.newDocumentBuilder(); + document = db.parse(new ByteArrayInputStream(result.getBytes())); + } catch (ParserConfigurationException e1) { + e1.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return document; + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/sweeper/QueryParameter.java b/src/main/java/org/gcube/resourcemanagement/support/server/sweeper/QueryParameter.java new file mode 100644 index 0000000..d0e8496 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/sweeper/QueryParameter.java @@ -0,0 +1,17 @@ +package org.gcube.resourcemanagement.support.server.sweeper; + +public class QueryParameter { + protected String name; + protected String value; + + public QueryParameter(String name, String value) { + super(); + this.name = name; + this.value = value; + } + + @Override + public String toString() { + return "QueryParameter [name=" + name + ", value=" + value + "]"; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/sweeper/Sweeper.java b/src/main/java/org/gcube/resourcemanagement/support/server/sweeper/Sweeper.java new file mode 100644 index 0000000..f34232e --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/sweeper/Sweeper.java @@ -0,0 +1,174 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: Sweeper.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.sweeper; + +import static org.gcube.resources.discovery.icclient.ICFactory.client; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.gcube.common.resources.gcore.HostingNode; +import org.gcube.common.resources.gcore.utils.XPathHelper; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLoader; +import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLocation; +import org.gcube.resourcemanagement.support.server.managers.resources.GHNManager; +import org.gcube.resourcemanagement.support.server.managers.resources.RunningInstanceManager; +import org.gcube.resourcemanagement.support.shared.util.SweeperActions; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.impl.QueryTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +import com.extjs.gxt.ui.client.data.ModelData; + +/** + * @author Massimiliano Assante (ISTI-CNR) + * + */ +public class Sweeper { + //TODO: Make it configurable from a property file + public static String LIVE_GHN_MAX_MINUTES = "40"; + + private static final Logger _log = LoggerFactory.getLogger(Sweeper.class); + + + protected ArrayList applyQuery(ScopeBean queryScope, QueryLocation queryPath, QueryLocation returnPath, QueryParameter... params) throws Exception { + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + + QueryTemplate isQuery = new QueryTemplate(QueryLoader.getQuery(queryPath)); + DiscoveryClient client = client(); + + if (params != null && params.length > 0) { + for (int i = 0; i < params.length; i++) { + isQuery.addParameter(params[i].name, params[i].value); + } + } + isQuery.addParameter("RESOURCE", QueryLoader.getQuery(returnPath)); + + List results = client.submit(isQuery); + ArrayList retval = new ArrayList(); + + for (String elem : results) { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + // Removes the resources with no ID or empty + try { + if (helper.evaluate("//ID").get(0) != null && helper.evaluate("//ID").get(0).trim().length() > 0) { + retval.add(elem); + System.out.println(elem); + } else { + _log.debug("*** Found an invalid element with no ID"); + } + } catch (Exception e) { + _log.debug("[getResourcesByType] found a resource with empty ID"); + } + } + ScopeProvider.instance.set(currScope); + return retval; + } + /** + * this method used to read the MAXWAIT param from the resourcemanagement.properties files, currently it reads it from the static var defined on top of this class + * TODO: Make it configurable again from a property file + * @param queryScope + * @return the expired ghn list + */ + public ArrayList getExpiredGHNs(final ScopeBean queryScope) { + try { + return applyQuery( + queryScope, + QueryLocation.SWEEPER_EXPIRED_GHN, QueryLocation.RETURN_SWEEPER_EXPIRED_GHN, + new QueryParameter("MAXWAIT", LIVE_GHN_MAX_MINUTES)); + } catch (Exception e) { + _log.error(e.getMessage()); + return null; + } + } + public ArrayList getDeadGHNs(ScopeBean queryScope) { + try { + return applyQuery( + queryScope, + QueryLocation.SWEEPER_DEAD_GHN, QueryLocation.RETURN_SWEEPER_DEAD_GHN); + } catch (Exception e) { + _log.error(e.getMessage()); + return null; + } + } + + public ArrayList getOrphanRI(ScopeBean queryScope) { + try { + return applyQuery( + queryScope, + QueryLocation.SWEEPER_ORPHAN_RI, QueryLocation.RETURN_SWEEPER_ORPHAN_RI); + } catch (Exception e) { + _log.error(e.getMessage()); + return null; + } + } + + @SuppressWarnings("deprecation") + public Boolean applySweep(ScopeBean queryScope, List elems) { + //set the scope + String currScope = ScopeProvider.instance.get(); + ScopeProvider.instance.set(queryScope.toString()); + for (ModelData entry : elems) { + try { + System.out.println("Action->"+((Object) entry.get("Actions")).toString()); + SweeperActions action = SweeperActions.valueOf(((Object) entry.get("Actions")).toString()); + String resID = ((Object) entry.get("ID")).toString(); + + _log.info("Cleaning up " + resID + " " + action); + + switch(action) { + case APPLY_GHN_DELETE: + GHNManager manager = new GHNManager(resID); + manager.forceDelete(queryScope); + break; + case APPLY_GHN_MOVE_TO_UNREACHABLE: + GHNManager ghnManager = new GHNManager(resID); + HostingNode res = (HostingNode) ghnManager.getResource(queryScope); + _log.trace("*** Setting HostingNode " + resID + " status to unreachable"); + res.profile().description().status("unreachable"); + HostingNode hn = ghnManager.getRegistryPublisher().update(res); + _log.trace("*** getRegistryPublisher returned " + hn.toString()); + break; + case APPLY_RI_DELETE: + RunningInstanceManager riManager = new RunningInstanceManager(resID); + _log.trace("*** The running instance " + resID + " will be deleted"); + riManager.forceDelete(queryScope); + break; + default: + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + ScopeProvider.instance.set(currScope); + return true; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/tests/GenericTest.java b/src/main/java/org/gcube/resourcemanagement/support/server/tests/GenericTest.java new file mode 100644 index 0000000..2b33f53 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/tests/GenericTest.java @@ -0,0 +1,204 @@ +/**************************************************************************** + + + * + * + * + * + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: GenericTest.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.tests; + +import java.io.File; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.gcube.common.resources.gcore.HostingNode; +import org.gcube.common.resources.gcore.utils.XPathHelper; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.server.gcube.CacheManager; +import org.gcube.resourcemanagement.support.server.gcube.ISClientRequester; +import org.gcube.resourcemanagement.support.server.managers.resources.GHNManager; +import org.gcube.resourcemanagement.support.server.managers.resources.GenericResourceManager; +import org.gcube.resourcemanagement.support.server.managers.resources.ManagementUtils; +import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; +import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; +import org.gcube.resourcemanagement.support.shared.types.datamodel.ResourceDescriptor; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class GenericTest { + private static final String LOG_PREFIX = "[SW-SUPPORT-TEST]"; + + public static String testCreation() { + System.out.println("\n\n\n******************** TEST CREATION ***************"); + + String resID = null; + + try { + resID = GenericResourceManager.create( + null, + new ScopeBean("/gcube/devsec"), + "RMP Test " + new Date(), + "RMP Test Description", + "Hello", + "test"); + ServerConsole.trace(null, "Generic Resource Created with ID: " + resID); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } finally { + System.out.println("\n******************** TEST CREATION END ***************\n"); + } + return resID; + } + + public static void testScopeCopy(final String resID, final String fromScope, final String toScope) { + System.out.println("\n\n\n******************** TEST SCOPE COPY ***************"); + try { +// GenericResourceManager res = new GenericResourceManager(resID); +// ServerConsole.trace(null, +// res.addToExistingScope(new ScopeBean(fromScope), new ScopeBean(toScope)) +// ); + String[] ids = {resID}; + ManagementUtils.addToExistingScope(AllowedResourceTypes.GenericResource, ids, new ScopeBean(fromScope), new ScopeBean(toScope)); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } finally { + System.out.println("\n******************** TEST SCOPE COPY END ***************\n"); + } + } + + public static void testResourceEdit(final String resID, final ScopeBean scope) { + System.out.println("\n\n\n******************** TEST RESEDIT COPY ***************"); + try { + GenericResourceManager res = new GenericResourceManager(resID); + res.update(res.getName()+" Edited", "updated description", "updated body", "test2", scope); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } finally { + System.out.println("\n******************** TEST RESEDIT END ***************\n"); + } + } + + public static void testModeGHN(final String resID, final String scope) + throws Exception { + ScopeBean queryScope = new ScopeBean(scope); + GHNManager ghnManager = new GHNManager(resID); + HostingNode res = (HostingNode) ghnManager.getResource(queryScope); + res.profile().description().status("CERTIFIED"); + ScopeProvider.instance.set(queryScope.name()); + ghnManager.getRegistryPublisher().update(res); + } + + public static void testGHN() { + System.out.println("\n\n\n******************** TEST GHN ***************"); + try { + GHNManager ghn1 = new GHNManager("796f0680-3937-11e2-9d5f-ae6a92affb51", "pcd4science3.cern.ch"); + ghn1.addToExistingScope(new ScopeBean("/gcube"), new ScopeBean("/gcube/devsec")); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } finally { + System.out.println("\n******************** TEST GHN END ***************\n"); + } + } + + public static void testRemoveFromScope(final String resID, final ScopeBean scope) { + System.out.println("\n\n\n******************** TEST RESOURCE REMOVEFROMSCOPE ***************"); + try { + GenericResourceManager res = new GenericResourceManager(resID); + res.removeFromScope(scope); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } finally { + System.out.println("\n******************** TEST RESOURCE REMOVEFROMSCOPE END ***************\n"); + } + } + + + public static void testDelete(final String resID, final ScopeBean scope) { + System.out.println("\n\n\n******************** TEST RESOURCE DELETE ***************"); + try { + GenericResourceManager res = new GenericResourceManager(resID); + res.delete(scope); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } finally { + System.out.println("\n******************** TEST RESOURCE DELETE END ***************\n"); + } + } + + private static void testTree(ScopeBean scope) throws Exception { + + CacheManager cm = new CacheManager(); + cm.setUseCache(false); + HashMap> results = ISClientRequester.getResourcesTree(cm, scope); + for (String res : results.keySet()) { + System.out.println(res); + for (String sub : results.get(res)) { + System.out.println(sub); + } + } + + List descs = ISClientRequester.getResourcesByType(cm, scope, "GenericResource", "VRE"); + for (String resourceDescriptor : descs) { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Node node = docBuilder.parse(new InputSource(new StringReader(resourceDescriptor))).getDocumentElement(); + XPathHelper helper = new XPathHelper(node); + System.out.println(helper.evaluate("/Resource/Name/text()").get(0)); + } + } + + @SuppressWarnings("deprecation") + public static void main(final String[] args) throws Exception { + // The scopes must be initialized + ScopeManager.setScopeConfigFile("test-suite" + File.separator + "scopes" + File.separator + "scopedata_admin.xml"); + + ScopeProvider.instance.set("/gcube/devsec"); + + testTree( new ScopeBean("/gcube/devsec")); + +// boolean deepTest = true; +// +// // testGHN(); +// if (deepTest) { +// String resID = testCreation(); +// testScopeCopy(resID, "/gcube/devsec", "/gcube/devsec/devVRE"); +////// +// System.out.println("\n\nWaiting for resource refresh 20secs.\n\n\n"); +// Thread.sleep(20000); +// +// +// //testResourceEdit(resID, new ScopeBean("/gcube/devsec")); + //testDelete(resID, new ScopeBean("/gcube/devsec")); +// +// testRemoveFromScope(resID, new ScopeBean("/gcube/devsec/devVRE")); +// } else { +// testModeGHN("796f0680-3937-11e2-9d5f-ae6a92affb51", "/gcube/devsec/devVRE"); +// } + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/tests/ScopeTest.java b/src/main/java/org/gcube/resourcemanagement/support/server/tests/ScopeTest.java new file mode 100644 index 0000000..be16f8d --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/tests/ScopeTest.java @@ -0,0 +1,45 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ScopeTest.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.tests; + +import java.io.File; + +import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; + +/** + * Makes tests on ScopeManager. + * @author Daniele Strollo (ISTI-CNR) + */ +public class ScopeTest { + + public static final void testLoadScopes() { + ScopeManager.setScopeConfigFile("test-suite" + File.separator + "scopes" + File.separator + "scopedata_admin.xml"); + try { + ScopeManager.update(); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Scopes retrievial [ERR]"); + return; + } + System.out.println("Scopes retrievial [DONE]"); + } + + + public static void main(final String[] args) { + testLoadScopes(); + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/types/AllowedResourceTypes.java b/src/main/java/org/gcube/resourcemanagement/support/server/types/AllowedResourceTypes.java new file mode 100644 index 0000000..9d4fd4d --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/types/AllowedResourceTypes.java @@ -0,0 +1,31 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: AllowedResourceTypes.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.types; + +/** + * @author Massimiliano Assante (ISTI-CNR) + * + */ +public enum AllowedResourceTypes { + GHN(), + RunningInstance(), + Service(), + VIEW(), + GenericResource(), + RuntimeResource(), + Collection(); +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/utils/Assertion.java b/src/main/java/org/gcube/resourcemanagement/support/server/utils/Assertion.java new file mode 100644 index 0000000..9ab5668 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/utils/Assertion.java @@ -0,0 +1,65 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: Assertion.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.utils; + +import java.io.Serializable; + +/** + * General purpose assertion handler. + * Assertion can be generalized to check a boolean expression and + * to raise an exception in correspondence to a failure happening + * during checking. + *
+ * Example:
+ *
+ *     Assertion<TheExceptionType> assertion = new Assertion<ParamException> ();
+ *     assertion.validate (param != null, new TheExceptionType("invalid parameter null"));
+ *
+ * or, in a more compact form:
+ *    // The exception to throw in case of failure
+ *    // during the evaluation of the expected condition
+ *    new Assertion<TheExceptionType>().validate(
+ *    	i>5,                                                     // The expected boolean condition
+ *    	new TheExceptionType("Parameter must be greater than 5")); //The error message
+ *
+ * 
+ * + * @author Daniele Strollo (ISTI-CNR) + */ +public class Assertion implements Serializable { + private static final long serialVersionUID = -2007903339251667541L; + + /** + * Makes an assertion and if the expression evaluation fails, throws an + * exception of type T. + *
+	 * Example:
+	 * 	new Assertion<MyException>().validate(whatExpected, new MyException("guard failed"));
+	 * 
+ * @param assertion the boolean expression to evaluate + * @param exc the exception to throw if the condition does not hold + * @throws T the exception extending {@link java.lang.Throwable} + */ + public final void validate(final boolean assertion, final T exc) + throws T { + // TOCHECK junit.framework.Assert.assertTrue(assertion); + if (!assertion) { + throw exc; + } + } +} + diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/utils/ServerConsole.java b/src/main/java/org/gcube/resourcemanagement/support/server/utils/ServerConsole.java new file mode 100644 index 0000000..161aaf1 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/utils/ServerConsole.java @@ -0,0 +1,65 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ServerConsole.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.utils; + +import org.gcube.resourcemanagement.support.server.managers.resources.AbstractResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class ServerConsole { + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractResourceManager.class); + + private static final String LOG_PREFIX = "*** [RMP] "; + + public static void error(final String prefix, final String msg) { + LOGGER.error(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg); + } + public static void error(final String prefix, final Throwable exc) { + LOGGER.error(LOG_PREFIX + ((prefix != null) ? prefix : ""), exc); + } + public static void error(final String prefix, final String msg, final Throwable exc) { + LOGGER.error(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg, exc); + } + public static void warn(final String prefix, final String msg) { + LOGGER.warn(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg); + } + public static void warn(final String prefix, final String msg, final Throwable exc) { + LOGGER.warn(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg, exc); + } + public static void info(final String prefix, final String msg) { + LOGGER.info(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg); + } + public static void trace(final String prefix, final String msg) { + LOGGER.trace(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg); + } + public static void trace(final String msg) { + LOGGER.trace(msg); + } + public static void debug(final String msg) { + LOGGER.debug(msg); + } + public static void warn(final String msg) { + LOGGER.warn(msg); + } + public static void debug(final String prefix, final String msg) { + LOGGER.debug(LOG_PREFIX + ((prefix != null) ? prefix + " " : "") + msg); + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistenceHandler.java b/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistenceHandler.java new file mode 100644 index 0000000..c93e531 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistenceHandler.java @@ -0,0 +1,62 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: PersistenceHandler.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.utils.persistence; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public interface PersistenceHandler { + /** + * The code to execute once the persistent object is refreshed. + */ + void onRefresh(); + + /** + * Automatically invoked by the library at instantiation + * of persistent items. + * Used to make initializations before starting the persistence + * manager. + */ + void onLoad(); + + /** + * When the item need no more to be persisted + * the refresh loop is closed and this method is + * invoked. + */ + void onDestroy(); + + /** + * Requires the destroy of the persistent resource. + * The persistent file will be deleted and the onDestroy + * event will be raised. + */ + void destroy(); + + /** + * The implementation to retrieve data from the persistence manager. + * @return + */ + T getData(); + + /** + * Sets the new data to persist. + * @param data + */ + void setData(final T data); +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistentItem.java b/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistentItem.java new file mode 100644 index 0000000..89bcb47 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/PersistentItem.java @@ -0,0 +1,154 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: PersistentItem.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.server.utils.persistence; + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.Serializable; +import java.util.List; +import java.util.Vector; + +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.xml.StaxDriver; + +/** + * Wrapping for data that can be persisted on the filesystem. + *
+ * new PersistentItem<DataTypeToPersist>(fileToStore, refreshDelay) {
+ *  public void onLoad() {
+ *	 //...
+ *  }
+ *  
+ *  // The other methods to overload
+ *  // ...
+ *  
+ * }
+ * 
+ * @author Daniele Strollo (ISTI-CNR) + */ +public abstract class PersistentItem +implements PersistenceHandler { + protected static final String LOG_PREFIX = "[PERSISTENCE]"; + private long refreshDelay = -1; + private boolean processClosed = false; + private String persistenceFileName = null; + private XStream serializer = null; + + /** + * @deprecated for internal use only. + */ + public PersistentItem() { + } + + public PersistentItem(final String persistenceFileName) { + this(persistenceFileName, -1); + } + + public PersistentItem(final String persistenceFileName, final long refreshDelay) { + this.setRefreshDelay(refreshDelay); + this.setPersistenceFileName(persistenceFileName); + + this.onLoad(); + + // loops to retrieve the data to persist + if (this.refreshDelay > 0) { + new Thread() { + public void run() { + while (!processClosed) { + try { + sleep(refreshDelay); + } catch (final InterruptedException e) { + ServerConsole.error(LOG_PREFIX, e); + } + // time elapsed... do refresh + onRefresh(); + } + } + } .start(); + } + } + + public PersistentItem(final T data, final String persistenceFileName, final long refreshDelay) { + this(persistenceFileName, refreshDelay); + this.setData(data); + } + + protected final void setPersistenceFileName(final String persistenceFileName) { + this.persistenceFileName = persistenceFileName; + } + + protected final void setRefreshDelay(final long refreshDelay) { + this.refreshDelay = refreshDelay; + } + + private synchronized XStream getSerializer() { + if (this.serializer == null) { + StaxDriver driver = new StaxDriver(); + driver.setRepairingNamespace(false); + this.serializer = new XStream(driver); + this.serializer.addDefaultImplementation(Vector.class, List.class); + } + return this.serializer; + } + + public final void destroy() { + this.processClosed = true; + // Thread has finished... invoking destroy + onDestroy(); + } + + /** + * Returns the corresponding persistent data. + * @return + */ + @SuppressWarnings("unchecked") + public final T getData() { + try { + StringBuilder xml = new StringBuilder(); + BufferedReader reader = new BufferedReader(new FileReader(persistenceFileName)); + String currLine = null; + + while ((currLine = reader.readLine()) != null) { + xml.append(currLine); + } + reader.close(); + return (T) this.getSerializer().fromXML(xml.toString()); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + return null; + } + } + + public final void setData(final T data) { + String xmlData = this.getSerializer().toXML(data); + + BufferedOutputStream mine = null; + try { + mine = new BufferedOutputStream(new FileOutputStream(persistenceFileName)); + mine.write(xmlData.getBytes()); + //mine.flush(); + mine.close(); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + return; + } + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/TestPersistence.java b/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/TestPersistence.java new file mode 100644 index 0000000..3d00339 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/server/utils/persistence/TestPersistence.java @@ -0,0 +1,46 @@ +package org.gcube.resourcemanagement.support.server.utils.persistence; + +import java.io.File; + +import org.gcube.common.scope.impl.ScopeBean; +import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; +import org.gcube.resourcemanagement.support.server.utils.ServerConsole; + +public class TestPersistence { + + /** + * @param args + */ + public static void main(final String[] args) { + PersistentItem persistentScopes = new PersistentItem("data.xml", 10000) { + // Builds the data to persist + private void refreshData() { + try { + ScopeBean[] toStore = + ScopeManager.getAvailableScopes().values().toArray(new ScopeBean[]{}); + this.setData(toStore); + } catch (Exception e) { + ServerConsole.error(LOG_PREFIX, e); + } + } + + public void onLoad() { + ScopeManager.setScopeConfigFile("test-suite" + File.separator + "scopes" + File.separator + "scopedata_admin.xml"); + + this.refreshData(); + } + public void onRefresh() { + this.refreshData(); + + ScopeBean[] scopes = this.getData(); + System.out.println(scopes); + } + public void onDestroy() { + this.setData(null); + } + }; + + + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidParameterException.java b/src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidParameterException.java new file mode 100644 index 0000000..1755c7e --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidParameterException.java @@ -0,0 +1,44 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: InvalidParameterException.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.exceptions; + +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class InvalidParameterException extends Exception implements IsSerializable { + private static final long serialVersionUID = 1L; + + public InvalidParameterException() { + super(); + } + + public InvalidParameterException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidParameterException(String message) { + super(message); + } + + public InvalidParameterException(Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidPermissionsException.java b/src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidPermissionsException.java new file mode 100644 index 0000000..91871d5 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/exceptions/InvalidPermissionsException.java @@ -0,0 +1,44 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: InvalidPermissionsException.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.exceptions; + +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class InvalidPermissionsException extends Exception implements IsSerializable { + private static final long serialVersionUID = 1L; + + public InvalidPermissionsException() { + super(); + } + + public InvalidPermissionsException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidPermissionsException(String message) { + super(message); + } + + public InvalidPermissionsException(Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/operations/SupportedOperations.java b/src/main/java/org/gcube/resourcemanagement/support/shared/operations/SupportedOperations.java new file mode 100644 index 0000000..1d98126 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/operations/SupportedOperations.java @@ -0,0 +1,88 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: SupportedOperations.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.operations; + +import org.gcube.resourcemanagement.support.shared.types.UserGroup; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public enum SupportedOperations { + GHN_SHUTDOWN(UserGroup.ADMIN), + GHN_RESTART(UserGroup.ADMIN), + GHN_CLEAN_RESTART(UserGroup.ADMIN), + GHN_DELETE(UserGroup.ADMIN), + GHN_FORCE_DELETE(UserGroup.SUPERUSER, UserGroup.ADMIN), + + GENERIC_RESOURCE_CREATE(UserGroup.ADMIN), + GENERIC_RESOURCE_EDIT(UserGroup.ADMIN), + GENERIC_RESOURCE_DELETE(UserGroup.ADMIN), + GENERIC_RESOURCE_FORCE_DELETE(UserGroup.SUPERUSER, UserGroup.ADMIN), + + RUNTIME_RESOURCE_DELETE(UserGroup.ADMIN), + RUNTIME_RESOURCE_FORCE_DELETE(UserGroup.SUPERUSER, UserGroup.ADMIN), + + SERVICE_CREATE(UserGroup.ADMIN), + SERVICE_DEPLOY(UserGroup.ADMIN), + SERVICE_GET_REPORT(UserGroup.ADMIN, UserGroup.DEBUG), + SERVICE_GET_RESOURCE_BY_ID(UserGroup.ADMIN, UserGroup.DEBUG, UserGroup.USER), + + RUNNING_INSTANCE_UNDEPLOY(UserGroup.ADMIN), + + COLLECTION_DELETE(UserGroup.ADMIN), + COLLECTION_FORCE_DELETE(UserGroup.SUPERUSER, UserGroup.ADMIN), + + VIEW_DELETE(UserGroup.ADMIN), + VIEW_FORCE_DELETE(UserGroup.SUPERUSER, UserGroup.ADMIN), + + ADD_TO_SCOPE(UserGroup.ADMIN), + + SWEEP_GHN(UserGroup.ADMIN), + + CREATE_MENU_SHOW(UserGroup.ADMIN, UserGroup.DEBUG), + INFRASTRUCTURE_UPGRADE(UserGroup.ADMIN, UserGroup.DEBUG); + + private UserGroup[] permissions = null; + + private SupportedOperations(final UserGroup...permissions) { + this.permissions = permissions; + } + + public UserGroup[] getPermissions() { + return this.permissions; + } + + /** + * States if a group is allowed to execute an operation. + * @param permission + * @return + */ + public boolean isAllowed(final UserGroup permission) { + if (this.getPermissions() == null + || this.getPermissions().length == 0 + || permission == null) { + return false; + } + for (UserGroup g : this.getPermissions()) { + if (g.equals(permission)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/plugins/GenericResourcePlugin.java b/src/main/java/org/gcube/resourcemanagement/support/shared/plugins/GenericResourcePlugin.java new file mode 100644 index 0000000..6aaa333 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/plugins/GenericResourcePlugin.java @@ -0,0 +1,172 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: GenericResourcePlugin.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.plugins; + +import java.io.Serializable; +import java.util.List; +import java.util.Vector; +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class GenericResourcePlugin implements Serializable, IsSerializable { + public enum FieldType implements Serializable, IsSerializable { + string(), + number(), + XML(); + } + + public static class Field implements Serializable, IsSerializable { + private static final long serialVersionUID = 5921865866801474305L; + private FieldType type = null; + private String name = null; + private boolean required = true; + private String label = null; + private String defaultValue = ""; + + /** + * @deprecated for serialization only + */ + public Field() { + } + + public Field(final String name, final FieldType type) { + this(name, type, true); + } + + public Field(final String name, final FieldType type, final boolean required) { + this(name, null, type, required); + } + + public Field(final String name, final String label, final FieldType type, final boolean required) { + this.setName(name); + this.setLabel(label); + this.type = type; + this.setIsRequired(required); + } + + public final String getDefaultValue() { + return this.defaultValue; + } + + public final void setDefaultValue(final String defaultValue) { + if (defaultValue != null && defaultValue.trim().length() > 0) { + this.defaultValue = defaultValue; + } + } + + public final void setLabel(final String label) { + if (label != null && label.trim().length() > 0) { + this.label = label.trim(); + } else { + this.label = name; + } + } + + public final String getLabel() { + if (this.label == null || this.label.trim().length() == 0) { + return this.name; + } else { + return this.label; + } + } + + private void setName(final String name) { + if (name != null) { + this.name = name.trim(); + } + } + + /** + * Corresponds to the tag name in the body + * @return + */ + public final String getName() { + return this.name; + } + + public final FieldType getType() { + return this.type; + } + + public final void setType(final FieldType type) { + this.type = type; + } + + public final boolean isRequired() { + return this.required; + } + + public final void setIsRequired(final boolean required) { + this.required = required; + } + } + + private static final long serialVersionUID = 6070331744211410508L; + private String name = null; + private String description = null; + private String type = null; + private List params = new Vector(); +// private String namespace = null; + private String namespace = "xmlns:ns4=\"http://gcube-system.org/namespaces/data/oaiplugin\""; + + + /** + * @deprecated for serialization only + */ + public GenericResourcePlugin() { + } + + + public GenericResourcePlugin(final String name, final String namespace, final String description, final String type) { + super(); + this.name = name; + this.description = description; + this.type = type; + if (namespace != null && namespace.trim().length() > 0) { + this.namespace = "xmlns:ns4=\"" + namespace.trim() + "\""; + } + } + + public final void addParam(final Field param) { + this.params.add(param); + } + + + public final String getName() { + return name; + } + + public final String getDescription() { + return description; + } + + + public final String getType() { + return type; + } + + public final String getNamespace() { + return namespace; + } + + public final List getParams() { + return params; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/plugins/TMPluginFormField.java b/src/main/java/org/gcube/resourcemanagement/support/shared/plugins/TMPluginFormField.java new file mode 100644 index 0000000..2eea1ac --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/plugins/TMPluginFormField.java @@ -0,0 +1,64 @@ +package org.gcube.resourcemanagement.support.shared.plugins; + +import java.io.Serializable; +/** + * + * @author Massimiliano Assante, ISTI-CNR + * @version 1.0 Oct 2012 + * + */ +@SuppressWarnings("serial") +public class TMPluginFormField implements Serializable { + + private String label; + private String defaultValue; + private boolean required; + private boolean repeatable; + + public TMPluginFormField() { + super(); + } + + public TMPluginFormField(String label, String defaultValue, + boolean required, boolean repeatable) { + super(); + this.label = label; + this.defaultValue = defaultValue; + this.required = required; + this.repeatable = repeatable; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public boolean isRepeatable() { + return repeatable; + } + + public void setRepeatable(boolean repeatable) { + this.repeatable = repeatable; + } + + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/RunningMode.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/RunningMode.java new file mode 100644 index 0000000..69ca900 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/RunningMode.java @@ -0,0 +1,39 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: RunningMode.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types; + +import java.io.Serializable; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public enum RunningMode implements Serializable { + PORTAL("PortalMode"), + STANDALONE("StandaloneMode"), + NOTDEFINED("NotDefined"); + + private String mode = null; + + private RunningMode(final String mode) { + this.mode = mode; + } + @Override + public final String toString() { + return this.mode; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/Tuple.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/Tuple.java new file mode 100644 index 0000000..add7919 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/Tuple.java @@ -0,0 +1,166 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: Tuple.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * General purpose tuple representation. + * A tuple is a sequence (or ordered list) of finite length. + * + *
+ * Example:
+ *
+ * 1) Creation
+ * // single typed tuple
+ * Tuple<Long> nt = new Tuple<Long>(42L);
+ *
+ * // multi typed tuple
+ * Tuple<Object> ot = new Tuple<Object>("Lars Tackmann",
+ *    		"Age", 26);
+ *
+ * 2) Usage
+ * // get single element
+ * Integer val = (Integer) ot.get(2);
+ * // iterate tuple
+ * for (Object o : ot)
+ *   System.out.printf("'%s' ", o.toString());
+ * // print all elems
+ * System.out.printf("Object tuple: %s\n", ot.toString());
+ *
+ *
+ * 3) Operations
+ * // The elements of two tuples a and b can be joined with
+ * // union operation that returns a new tuple.
+ * Tuple c = a.union (b);
+ * 
+ * + */ +public class Tuple implements Iterable, Serializable, IsSerializable { + private static final long serialVersionUID = 5783359179069297888L; + private List content = new LinkedList(); + + /** + * @deprecated For serialization purpose use the other constructors + */ + public final List getContent() { + return content; + } + + /** + * @deprecated For serialization purpose use the other constructors + */ + public final void setContent(final List content) { + this.content = content; + } + + /** + * @deprecated For serialization purpose use the other constructors + */ + public Tuple() { + super(); + } + + public Tuple(final T... args) { + for (T t : args) { + content.add(t); + } + } + + /** + * Appends elements inside a tuple. + */ + public final void append(final T... args) { + if (content != null) { + for (T t : args) { + content.add(t); + } + } + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + public final Tuple union(final Tuple t) { + Tuple retval = new Tuple(); + for (T elem : content) { + retval.append(elem); + } + for (int i = 0; i < t.size(); i++) { + retval.append(t.get(i)); + } + return retval; + } + + public final T get(final int index) { + return content.get(index); + } + + public final Iterator iterator() { + return content.iterator(); + } + + public final int size() { + return content.size(); + } + + /** + * Compares two tuples. + * The comparison is applied to all the contained elements. + * + * @param obj the {@link Tuple} element to compare + * @return true if the number of contained elements is the same and + * all the elements are equals. + */ + @SuppressWarnings("unchecked") + public final boolean equals(final Object obj) { + if (!(obj instanceof Tuple)) { + return false; + } + Tuple tuple = (Tuple) obj; + if (tuple.size() != this.content.size()) { return false; } + Iterator internalElems = this.content.iterator(); + for (T elem : tuple) { + if (!elem.equals(internalElems.next())) { + return false; + } + } + return true; + } + + @Override + public final int hashCode() { + int retval = 0; + Iterator internalElems = this.content.iterator(); + while (internalElems.hasNext()) { + retval += internalElems.next().hashCode(); + } + return retval; + } + + @Override + public final String toString() { + StringBuilder retval = new StringBuilder(); + for (Object o : content) { + retval.append(o.toString() + "/"); + } + return "(" + retval.substring(0, retval.length() - 1) + ")"; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/UserGroup.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/UserGroup.java new file mode 100644 index 0000000..d1699eb --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/UserGroup.java @@ -0,0 +1,31 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: UserGroup.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types; + +import java.io.Serializable; +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public enum UserGroup implements Serializable, IsSerializable { + SUPERUSER(), + ADMIN(), + USER(), + DEBUG(); +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/AtomicTreeNode.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/AtomicTreeNode.java new file mode 100644 index 0000000..8916e6c --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/AtomicTreeNode.java @@ -0,0 +1,100 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: AtomicTreeNode.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types.datamodel; + +import com.extjs.gxt.ui.client.data.BaseTreeModel; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public class AtomicTreeNode extends BaseTreeModel { + private static final long serialVersionUID = 5094327834701967591L; + private static int ID = 0; + + /** + * @deprecated fr serialization only + */ + public AtomicTreeNode() { + set("id", ID++); + } + + public AtomicTreeNode(final String node) { + this(node, null); + } + + /** + * The node is used as original node of the element useful to retrieve it from the IS. + * The name is instead used for pretty printing (aliasing). + * @param node the corresponding IS node + * @param name if null the node will be used instead + */ + public AtomicTreeNode(final String node, final String name) { + set("id", ID++); + set("node", node); + if (name == null) { + set("name", node); + } else { + set("name", name); + } + } + + public AtomicTreeNode(final String node, final String name, final String icon) { + this(node, name); + set("icon", icon); + } + + public AtomicTreeNode(final String node, final String name, final AtomicTreeNode[] children) { + this(node, name); + for (int i = 0; i < children.length; i++) { + add(children[i]); + } + } + + public AtomicTreeNode(final String node, final String name, final String icon, final AtomicTreeNode[] children) { + this(node, name, children); + set("icon", icon); + } + + public final Integer getId() { + return (Integer) get("id"); + } + + public final String getName() { + return (String) get("name"); + } + + public final String getNode() { + return (String) get("node"); + } + + public final String getLabel() { + return (String) get("label"); + } + + public final String toString() { + return getName(); + } + + public final String getSubType() { + if (this.isLeaf() && this.getParent() != null) { + return this.getNode(); + } + return null; + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/CompleteResourceProfile.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/CompleteResourceProfile.java new file mode 100644 index 0000000..7a23cec --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/CompleteResourceProfile.java @@ -0,0 +1,81 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceProfile.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types.datamodel; + +import java.io.Serializable; + +import org.gcube.resourcemanagement.support.client.views.ResourceTypeDecorator; + +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * The profile of resources is represented by its + * xml and html representations and its title (the name + * or the ID) and the type (GHN, RI, ...). + * @author Daniele Strollo (ISTI-CNR) + * + */ +@SuppressWarnings("serial") +public class CompleteResourceProfile implements Serializable { + private String xmlRepresentation = null; + private String htmlRepresentation = null; + private ResourceTypeDecorator type = null; + private String title = null; + private String ID = null; + + /** + * @deprecated for serialization only + */ + public CompleteResourceProfile() { + } + + + public CompleteResourceProfile(String ID, ResourceTypeDecorator type, String title, String xmlRepresentation, + String htmlRepresentation) { + super(); + this.ID = ID; + this.type = type; + this.title = title; + this.xmlRepresentation = xmlRepresentation; + this.htmlRepresentation = htmlRepresentation; + } + + + public String getXmlRepresentation() { + return xmlRepresentation; + } + + + public String getHtmlRepresentation() { + return htmlRepresentation; + } + + + public ResourceTypeDecorator getType() { + return type; + } + + + public String getTitle() { + return title; + } + + public String getID() { + return ID; + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDescriptor.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDescriptor.java new file mode 100644 index 0000000..703e934 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDescriptor.java @@ -0,0 +1,120 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceDescriptor.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types.datamodel; + +import java.io.Serializable; + +import org.gcube.resourcemanagement.support.shared.exceptions.InvalidParameterException; +import org.gcube.resourcemanagement.support.shared.util.Assertion; + + + + +import com.extjs.gxt.ui.client.data.BaseModelData; +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * All the resources that want to access resource management + * operations must be described through this data type. + * @author Massimiliano Assante (ISTI-CNR) + * @author Daniele Strollo + */ +@SuppressWarnings("serial") +public class ResourceDescriptor extends BaseModelData implements Serializable { + + public ResourceDescriptor() { + super(); + } + + /** + * Creates a ResourceDescriptor + * @param type mandatory + * @param subtype can be null + * @param ID the identifier of the resource (mandatory). + * @param name the short name assigned to the resource (mandatory). + * @throws InvalidParameterException + */ + public ResourceDescriptor(String type, String subtype, String id, String name) throws InvalidParameterException { + super(); + Assertion checker = new Assertion(); + checker.validate(name != null && name.length() > 0, new InvalidParameterException("The ghnName is null or empty")); + checker.validate(id != null && id.length() > 0, new InvalidParameterException("The ID is null or empty")); + checker.validate(type != null && type.length() > 0, new InvalidParameterException("The type is null or empty")); + + this.setSubtype(subtype); + this.setType(type); + this.setID(id); + this.setName(name); + } + + public final String getType() { + return get("type"); + } + + public final String getSubtype() { + return get("subtype"); + } + + public final String getID() { + return get("ID"); + } + + public final String getName() { + return get("name"); + } + + public final void setType(final String type) { + if (type != null) { + set("type", type.trim()); + } + } + + public final void setSubtype(final String subtype) { + if (subtype != null) { + set("subtype", subtype.trim()); + } + } + + public final void setID(final String id) { + if (id != null) { + set("ID", id.trim()); + } + } + + public final void setName(final String name) { + if (name != null) { + set("name", name.trim()); + } + } + + public final void addProperty(final String property, final Object value) { + set(property, value); + } + + public final Object getProperty(final String property) { + return get(property); + } + + @Override + public String toString() { + return "ResourceDescriptor [getType()=" + getType() + ", getSubtype()=" + + getSubtype() + ", getID()=" + getID() + ", getName()=" + + getName() + "]"; + } + + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDetailModel.java b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDetailModel.java new file mode 100644 index 0000000..811ac35 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/types/datamodel/ResourceDetailModel.java @@ -0,0 +1,835 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: ResourceDetailDecorator.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.types.datamodel; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.gcube.resourcemanagement.support.client.views.ResourceTypeDecorator; + +import com.extjs.gxt.ui.client.Style.HorizontalAlignment; +import com.extjs.gxt.ui.client.data.BaseModelData; +import com.extjs.gxt.ui.client.data.ModelType; +import com.extjs.gxt.ui.client.store.ListStore; +import com.extjs.gxt.ui.client.widget.form.CheckBox; +import com.extjs.gxt.ui.client.widget.form.NumberField; +import com.extjs.gxt.ui.client.widget.grid.CellEditor; +import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig; +import com.extjs.gxt.ui.client.widget.grid.ColumnConfig; +import com.extjs.gxt.ui.client.widget.grid.ColumnData; +import com.extjs.gxt.ui.client.widget.grid.ColumnModel; +import com.extjs.gxt.ui.client.widget.grid.Grid; +import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer; +import com.google.gwt.core.client.GWT; +import com.google.gwt.i18n.client.NumberFormat; + +/** + * @author Massimiliano Assante (ISTI-CNR) + * @author Daniele Strollo + */ +public class ResourceDetailModel { + private static boolean initialized = false; + + public static final String SERVICE_INSTALL_KEY = "toDeploy"; + + private static HashMap RECORD_DEFINITION = null; + private static HashMap XML_MAPPING = null; + private static HashMap REQUIRED_FIELDS = null; + + private static void init() { + if (initialized) { + return; + } + initialized = true; + + RECORD_DEFINITION = new HashMap(); + XML_MAPPING = new HashMap(); + + /********************************************* + * GHN + ********************************************/ + // The column model for grid representation + List modelColumns = new ArrayList(); + + modelColumns.add(new ColumnConfig("Name", "Name", 250)); + + + + ColumnConfig status = new ColumnConfig("Status", "Status", 65); + + GridCellRenderer statusRender = new GridCellRenderer() { + @Override + public String render(BaseModelData model, String property, ColumnData config, + int rowIndex, int colIndex, ListStore store, Grid grid) { + String statusToCheck = (String)model.get(property); + String style = "gray"; + if (statusToCheck.compareTo("certified") == 0) + style = "green"; + else if (statusToCheck.compareTo("ready") == 0) + style = "orange"; + return "" + statusToCheck + ""; + } + }; + status.setRenderer(statusRender); + modelColumns.add(status); + + modelColumns.add(new ColumnConfig("LastUpdate", "Last Updated", 130)); + modelColumns.add(new ColumnConfig("gCoreVersion", "Version", 50)); + modelColumns.add(new ColumnConfig("ghnVersion", "Distro v.", 50)); + + + ColumnConfig ramLeft = new ColumnConfig("VirtualAvailable", "Mem avail.", 70); + ramLeft.setAlignment(HorizontalAlignment.RIGHT); + ramLeft.setEditor(new CellEditor(new NumberField())); + final NumberFormat number = NumberFormat.getFormat("#,##0;(#,##0)"); + + GridCellRenderer ramRender = new GridCellRenderer() { + @Override + public String render(BaseModelData model, String property, ColumnData config, + int rowIndex, int colIndex, ListStore store, Grid grid) { + int val = Integer.parseInt((String)model.get(property)); + + int tot = Integer.parseInt((String) model.get("VirtualSize")); + + int percentage = (val * 100) / tot; + + String style = val < 100 ? "red" : "green"; + String toDisplay = number.format(val).replaceAll(",", "."); + toDisplay += " MB"; + + return "" + percentage + "% ("+toDisplay+")"; + } + }; + ramLeft.setRenderer(ramRender); + + modelColumns.add(ramLeft); + + + ColumnConfig localSpace = new ColumnConfig("LocalAvailableSpace", "HD Space left", 70); + localSpace.setAlignment(HorizontalAlignment.RIGHT); + localSpace.setEditor(new CellEditor(new NumberField())); + + GridCellRenderer mbRender = new GridCellRenderer() { + @Override + public String render(BaseModelData model, String property, ColumnData config, + int rowIndex, int colIndex, ListStore store, Grid grid) { + int val = 0; + try { + val = Integer.parseInt((String)model.get(property)); + } catch (NumberFormatException e) { + val = 0; + } + String style = val < 1000000 ? "red" : "green"; + String toDisplay = number.format(val); + if (toDisplay.length() > 4) + toDisplay = toDisplay.substring(0, toDisplay.length()-4).replaceAll(",", "."); + toDisplay += " MB"; + return "" + toDisplay + ""; + } + }; + + localSpace.setRenderer(mbRender); + modelColumns.add(localSpace); + + + //Optional + ColumnConfig ramTotal = new ColumnConfig("VirtualSize", "V. Memory total", 70); + ramTotal.setAlignment(HorizontalAlignment.RIGHT); + ramTotal.setEditor(new CellEditor(new NumberField())); + + GridCellRenderer ramTotRender = new GridCellRenderer() { + @Override + public String render(BaseModelData model, String property, ColumnData config, + int rowIndex, int colIndex, ListStore store, Grid grid) { + int val = Integer.parseInt((String)model.get(property)); + String toDisplay = number.format(val).replaceAll(",", "."); + toDisplay += " MB"; + return toDisplay; + } + }; + ramTotal.setRenderer(ramTotRender); + modelColumns.add(ramTotal); + + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + modelColumns.add(new ColumnConfig("Uptime", "Up Time", 100)); + modelColumns.add(new ColumnConfig("LoadLast15Min", "Load Last 15 Min", 100)); + modelColumns.add(new ColumnConfig("LoadLast1Min", "Load Last 1 Min", 100)); + modelColumns.add(new ColumnConfig("LoadLast5Min", "Load Last 5 Min", 100)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + ColumnModel cm = new ColumnModel(modelColumns); + // The hidden fields after the 5 column + for (int i = 7; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.GHN.name(), cm); + + // defines the xml structure + ModelType type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("Status"); + type.addField("Name"); + type.addField("Uptime"); + type.addField("LastUpdate"); + type.addField("VirtualAvailable"); + type.addField("VirtualSize"); + type.addField("gCoreVersion", "gcf-version"); + type.addField("ghnVersion", "ghn-version"); + type.addField("LocalAvailableSpace"); + type.addField("LoadLast15Min"); + type.addField("LoadLast1Min"); + type.addField("LoadLast5Min"); + type.addField("Scopes"); + + // These fields are internally used and not showable + type.addField("SubType"); + type.addField("Type"); + + XML_MAPPING.put(ResourceTypeDecorator.GHN.name(), type); + + + /********************************************* + * Collection + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("Name", "Name", 470)); + modelColumns.add(new ColumnConfig("NumberOfMembers", "Cardinality", 70)); + modelColumns.add(new ColumnConfig("LastUpdateTime", "Last Updated", 170)); + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + + //Optional + modelColumns.add(new ColumnConfig("CreationTime", "Creation Time", 170)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + //modelColumns.add(new ColumnConfig("NumberOfMembers", "Number Of Members", 115)); //not available anymore + + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 4; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.Collection.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("Name"); + type.addField("CreationTime"); + type.addField("LastUpdateTime"); + type.addField("NumberOfMembers"); + type.addField("Scopes"); + type.addField("SubType"); + type.addField("Type"); + + + XML_MAPPING.put(ResourceTypeDecorator.Collection.name(), type); + + + /********************************************* + * Service + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + + modelColumns.add(new ColumnConfig("ServiceClass", "Service Class", 200)); + modelColumns.add(new ColumnConfig("ServiceName", "Service Name", 260)); + modelColumns.add(new ColumnConfig("Version", "Main Package Version", 100)); + //Optional + modelColumns.add(new ColumnConfig("Shareable", "Shareable", 100)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 3; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.Service.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("Version"); + type.addField("Shareable"); + type.addField("Scopes"); + + // These fields are internally used and not showable + type.addField("SubType"); + type.addField("Type"); + + + XML_MAPPING.put(ResourceTypeDecorator.Service.name(), type); + + + + /********************************************* + * InstallableSoftware + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + + // adds the checkbox to the model + CheckColumnConfig checkColumn = + new CheckColumnConfig(ResourceDetailModel.SERVICE_INSTALL_KEY, "Deploy", 60); + CellEditor checkBoxEditor = new CellEditor(new CheckBox()); + checkColumn.setEditor(checkBoxEditor); + modelColumns.add(checkColumn); + + modelColumns.add(new ColumnConfig("ServiceClass", "Service Class", 250)); + modelColumns.add(new ColumnConfig("ServiceName", "Service Name", 250)); + modelColumns.add(new ColumnConfig("Version", "Main Package Version", 100)); + //Optional + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 3; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.InstallableSoftware.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("Version"); + type.addField("Scopes"); + + // These fields are internally used and not showable + type.addField("SubType"); + type.addField("Type"); + + + XML_MAPPING.put(ResourceTypeDecorator.InstallableSoftware.name(), type); + + + + /********************************************* + * RunningInstance + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("ServiceClass", "Service Class", 200)); + modelColumns.add(new ColumnConfig("ServiceName", "Service Name", 260)); + modelColumns.add(new ColumnConfig("Version", "Version", 100)); + modelColumns.add(new ColumnConfig("Status", "Status", 65)); + modelColumns.add(new ColumnConfig("GHN", "GHN", 300)); + //Optional + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 5; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.RunningInstance.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("Version"); + type.addField("Status"); + // a) This is the GHNID type.addField("GHN", "/Profile/GHN/@UniqueID"); + // b) While this is its name + type.addField("GHN", "ghn-name"); + type.addField("Scopes"); + + // These fields are internally used and not showable + type.addField("SubType"); + type.addField("Type"); + + + XML_MAPPING.put(ResourceTypeDecorator.RunningInstance.name(), type); + + + + /********************************************* + * VIEW + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("ViewName", "View Name", 200)); + modelColumns.add(new ColumnConfig("SourceKey", "Source Key", 200)); + modelColumns.add(new ColumnConfig("LastUpdate", "Last Update", 270)); + modelColumns.add(new ColumnConfig("Cardinality", "Cardinality", 100)); + //Optional + modelColumns.add(new ColumnConfig("ViewType", "View Type", 170)); + modelColumns.add(new ColumnConfig("RelatedCollectionId", "Related Collection Id", 220)); + modelColumns.add(new ColumnConfig("ServiceName", "Service Name", 170)); + modelColumns.add(new ColumnConfig("Termination", "Termination Time", 270)); + + modelColumns.add(new ColumnConfig("Source", "Source", 230)); + modelColumns.add(new ColumnConfig("ServiceClass", "Service Class", 170)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("RI", "RI", 220)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 4; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.VIEW.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("ViewName"); + type.addField("Cardinality"); + type.addField("ViewType"); + type.addField("RelatedCollectionId"); + type.addField("Source"); + type.addField("SourceKey"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("Termination", "TerminationTimeHuman"); + type.addField("LastUpdate", "LastUpdateHuman"); + type.addField("Scopes", "/scopes"); + type.addField("SubType", "SubType"); + type.addField("RI"); + type.addField("Type"); + + + GWT.log("VIew Name: " + ResourceTypeDecorator.VIEW.name()); + XML_MAPPING.put(ResourceTypeDecorator.VIEW.name(), type); + + + /********************************************* + * GenericResource + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("Name", "Name", 200)); + modelColumns.add(new ColumnConfig("Description", "Description", 400)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + + //Optional + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + modelColumns.add(new ColumnConfig("SubType", "Secondary Type", 170)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 3; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.GenericResource.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("Name"); + type.addField("Description"); + type.addField("Scopes"); + type.addField("SubType"); + type.addField("Type"); + + XML_MAPPING.put(ResourceTypeDecorator.GenericResource.name(), type); + + /********************************************* + * RuntimeResource + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("Name", "Name", 200)); + modelColumns.add(new ColumnConfig("Host", "Host", 250)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + + + //Optional + modelColumns.add(new ColumnConfig("ID", "ID", 100)); + modelColumns.add(new ColumnConfig("SubType", "Category", 370)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 4; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.RuntimeResource.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("Name"); + type.addField("Scopes"); + type.addField("Host"); + type.addField("SubType"); + type.addField("Type"); + + XML_MAPPING.put(ResourceTypeDecorator.RuntimeResource.name(), type); + + + + /********************************************* + * WSResources + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("SourceKey", "Source Key", 230)); + modelColumns.add(new ColumnConfig("ServiceName", "Service Name", 170)); + modelColumns.add(new ColumnConfig("Termination", "Termination Time", 270)); + modelColumns.add(new ColumnConfig("LastUpdate", "Last Update", 270)); + //Optional + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + modelColumns.add(new ColumnConfig("Source", "Source", 230)); + modelColumns.add(new ColumnConfig("ServiceClass", "Service Class", 170)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 300)); + modelColumns.add(new ColumnConfig("RI", "RI", 220)); + modelColumns.add(new ColumnConfig("SubType", "SubType", 200)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 4; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.WSResource.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName(ResourceTypeDecorator.WSResource.name()); + + type.addField("ID"); + type.addField("Source"); + type.addField("SourceKey"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("Termination", "TerminationTimeHuman"); + type.addField("LastUpdate", "LastUpdateHuman"); + type.addField("Scopes", "/scopes"); + type.addField("SubType", "SubType"); + type.addField("RI"); + type.addField("Type"); + XML_MAPPING.put(ResourceTypeDecorator.WSResource.name(), type); + + + /********************************************* + * PROFILES OF RELATED RESOURCES: GHN + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("ServiceClass", "Service Class", 200)); + modelColumns.add(new ColumnConfig("ServiceName", "Service Name", 260)); + modelColumns.add(new ColumnConfig("ServiceVersion", "Service Version", 100)); + modelColumns.add(new ColumnConfig("MainVersion", "Main Version", 100)); + modelColumns.add(new ColumnConfig("Status", "Status", 65)); + //Optional + modelColumns.add(new ColumnConfig("ID", "ID", 220)); + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 5; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.GHNRelated.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("ServiceVersion"); + type.addField("MainVersion"); + type.addField("Status"); + XML_MAPPING.put(ResourceTypeDecorator.GHNRelated.name(), type); + + + /********************************************* + * PROFILES OF RELATED RESOURCES: RunningInstance + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("Key", "Name", 200)); + modelColumns.add(new ColumnConfig("Value", "Value", 260)); + // create the column model + cm = new ColumnModel(modelColumns); + RECORD_DEFINITION.put(ResourceTypeDecorator.RunningInstanceRelated.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("Key"); + type.addField("Value"); + XML_MAPPING.put(ResourceTypeDecorator.RunningInstanceRelated.name(), type); + + + /********************************************* + * PROFILES OF RELATED RESOURCES: Service + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + modelColumns.add(new ColumnConfig("RIID", "RI ID", 90)); + modelColumns.add(new ColumnConfig("ServiceStatus", "RI Status", 70)); + modelColumns.add(new ColumnConfig("RIVersion", "Serv.Version", 70)); + modelColumns.add(new ColumnConfig("ActivationTime", "RI ActivationTime", 170)); + modelColumns.add(new ColumnConfig("GHNName", "GHN Name", 100)); + modelColumns.add(new ColumnConfig("GHNStatus", "GHN Status", 70)); + + modelColumns.add(new ColumnConfig("GHNID", "GHN ID", 100)); + modelColumns.add(new ColumnConfig("GHNSite", "GHN Site", 100)); + modelColumns.add(new ColumnConfig("GHNLoad15Min", "GHNLoad15Min", 50)); + modelColumns.add(new ColumnConfig("GHNLoad5Min", "GHNLoad5Min", 50)); + modelColumns.add(new ColumnConfig("GHNLoad1Min", "GHNLoad1Min", 50)); + modelColumns.add(new ColumnConfig("GHNActivationTime", "GHNActivationTime", 100)); + modelColumns.add(new ColumnConfig("GHNLastUpdate", "GHNLastUpdate", 100)); + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 6; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + RECORD_DEFINITION.put(ResourceTypeDecorator.ServiceRelated.name(), cm); + + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("RIID"); + type.addField("ServiceStatus"); + type.addField("ActivationTime"); + type.addField("GHNID"); + type.addField("RIVersion"); + type.addField("GHNName"); + type.addField("GHNSite"); + type.addField("GHNStatus"); + type.addField("GHNLoad15Min"); + type.addField("GHNLoad5Min"); + type.addField("GHNLoad1Min"); + type.addField("GHNActivationTime"); + type.addField("GHNLastUpdate"); + XML_MAPPING.put(ResourceTypeDecorator.ServiceRelated.name(), type); + + /********************************************* + * MODEL FOR SWEEPER GHN + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + + modelColumns.add(new ColumnConfig("Name", "Name", 130)); + modelColumns.add(new ColumnConfig("Status", "Status", 50)); + ColumnConfig minElapsed = (new ColumnConfig("UpdateMinutesElapsed", "Minutes from Update", 130)); + minElapsed.setAlignment(HorizontalAlignment.CENTER); + modelColumns.add(minElapsed); + modelColumns.add(new ColumnConfig("AllocatedRI", "#RI", 40)); + modelColumns.add(new ColumnConfig("LastUpdate", "LastUpdate", 130)); + + // hidden fields + modelColumns.add(new ColumnConfig("Actions", "Actions", 260)); + modelColumns.add(new ColumnConfig("ID", "ID", 200)); + modelColumns.add(new ColumnConfig("Type", "Type", 100)); + modelColumns.add(new ColumnConfig("Location", "Location", 100)); + modelColumns.add(new ColumnConfig("Domain", "Domain", 100)); + modelColumns.add(new ColumnConfig("IPAddress", "IPAddress", 100)); + modelColumns.add(new ColumnConfig("Scopes", "Scopes", 100)); + + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 5; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + + + RECORD_DEFINITION.put(ResourceTypeDecorator.Sweeper_GHN.name(), cm); + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("Name"); + type.addField("Actions"); + + type.addField("Status"); + type.addField("AllocatedRI"); + type.addField("Type"); + type.addField("Location"); + type.addField("Domain"); + type.addField("IPAddress"); + type.addField("Scopes"); + type.addField("LastUpdate"); + type.addField("UpdateMinutesElapsed"); + XML_MAPPING.put(ResourceTypeDecorator.Sweeper_GHN.name(), type); + + + /********************************************* + * MODEL FOR SWEEPER RI + ********************************************/ + // The column model for grid representation + modelColumns = new ArrayList(); + + modelColumns.add(new ColumnConfig("ID", "ID", 120)); + modelColumns.add(new ColumnConfig("ServiceClass", "ServiceClass", 100)); + modelColumns.add(new ColumnConfig("ServiceName", "ServiceName", 100)); + modelColumns.add(new ColumnConfig("ghnid", "GHN ID", 120)); + + // hidden fields + modelColumns.add(new ColumnConfig("Actions", "Actions", 260)); + modelColumns.add(new ColumnConfig("ServiceStatus", "Status", 90)); + modelColumns.add(new ColumnConfig("ActivationTime", "Activation Time", 140)); + + + // create the column model + cm = new ColumnModel(modelColumns); + for (int i = 4; i < modelColumns.size(); i++) { + cm.setHidden(i, true); + } + + RECORD_DEFINITION.put(ResourceTypeDecorator.Sweeper_RI.name(), cm); + // defines the xml structure + type = new ModelType(); + type.setRoot("Resources"); + type.setRecordName("Resource"); + type.addField("ID"); + type.addField("ServiceStatus"); + type.addField("ServiceClass"); + type.addField("ServiceName"); + type.addField("ActivationTime"); + type.addField("ghnid"); + type.addField("Actions"); + XML_MAPPING.put(ResourceTypeDecorator.Sweeper_RI.name(), type); + + + + /********************************************* + * VALIDATORS + ********************************************/ + /* + * REQUIRED FIELDS + */ + + REQUIRED_FIELDS = new HashMap(); + + REQUIRED_FIELDS.put( + ResourceTypeDecorator.GHN.name(), + new String[] { + "Name", + "SubType", + "ID", + "Scopes" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.Collection.name(), + new String[] { + "Name", + "SubType", + "ID", + "Scopes" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.GenericResource.name(), + new String[] { + "Name", + "SubType", + "ID", + "Scopes" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.RuntimeResource.name(), + new String[] { + "Name", + "SubType", + "ID", + "Host", + "Scopes" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.VIEW.name(), + new String[] { + "Name", + "SubType", + "ID", + "Scopes" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.RunningInstance.name(), + new String[] { + "ServiceClass", + "ServiceName", + "ID", + "SubType", + "Scopes", + "GHN" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.Service.name(), + new String[] { + "ServiceClass", + "ServiceName", + "ID", + "SubType", + "Scopes" + }); + REQUIRED_FIELDS.put( + ResourceTypeDecorator.WSResource.name(), + new String[] { + "SourceKey", + "ServiceName", + "ID", + "SubType", + "Scopes" + }); + } + + + public static final ColumnModel getRecordDefinition(final String nodeID) { + init(); + return RECORD_DEFINITION.get(nodeID); + } + + public static final ModelType getXMLMapping(final String nodeID) { + init(); + return XML_MAPPING.get(nodeID); + } + + public static final String[] getRequiredFields(final String type) { + init(); + return REQUIRED_FIELDS.get(type); + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/util/Assertion.java b/src/main/java/org/gcube/resourcemanagement/support/shared/util/Assertion.java new file mode 100644 index 0000000..5410c00 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/util/Assertion.java @@ -0,0 +1,66 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: Assertion.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.util; + +import java.io.Serializable; + +import com.google.gwt.user.client.rpc.IsSerializable; + +/** + * General purpose assertion handler. + * Assertion can be generalized to check a boolean expression and + * to raise an exception in correspondence to a failure happening + * during checking. + *
+ * Example:
+ *
+ *     Assertion<TheExceptionType> assertion = new Assertion<ParamException> ();
+ *     assertion.validate (param != null, new TheExceptionType("invalid parameter null"));
+ *
+ * or, in a more compact form:
+ *    // The exception to throw in case of failure
+ *    // during the evaluation of the expected condition
+ *    new Assertion<TheExceptionType>().validate(
+ *    	i>5,                                                     // The expected boolean condition
+ *    	new TheExceptionType("Parameter must be greater than 5")); //The error message
+ *
+ * 
+ * + * @author Daniele Strollo (ISTI-CNR) + */ +public class Assertion implements Serializable, IsSerializable { + private static final long serialVersionUID = -2007903339251667541L; + + /** + * Makes an assertion and if the expression evaluation fails, throws an + * exception of type T. + *
+	 * Example:
+	 * 	new Assertion<MyException>().validate(whatExpected, new MyException("guard failed"));
+	 * 
+ * @param assertion the boolean expression to evaluate + * @param exc the exception to throw if the condition does not hold + * @throws T the exception extending {@link java.lang.Throwable} + */ + public final void validate(final boolean assertion, final T exc) + throws T { + if (!assertion) { + throw exc; + } + } +} + diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/util/Configuration.java b/src/main/java/org/gcube/resourcemanagement/support/shared/util/Configuration.java new file mode 100644 index 0000000..b7525a9 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/util/Configuration.java @@ -0,0 +1,39 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: Configuration.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.util; + +/** + * The client side UI configuration. + * @author Daniele Strollo (ISTI-CNR) + */ +public class Configuration { + // Delay of popups in mills + public static final int popupDelay = 4000; + // Configuration parameters that can be changed through options + // menu. + public static boolean openProfileOnLoad = false; + public static boolean allowMultipleProfiles = false; + //public static String scopeFile = null; + + public static final String CODE = "$2a$12$B7ftdRmQLDlKdTkcQWHcxeS8goiMT15nQbullMsjYcltQhUOt9lhi"; + /* + * Forces to use flash based charts also in portal mode. + * Due to conflicts in the portal with the flash based + * charts this functionality usually is avoided. + */ + public static final boolean DISABLE_FLASH = false; +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/util/DelayedOperation.java b/src/main/java/org/gcube/resourcemanagement/support/shared/util/DelayedOperation.java new file mode 100644 index 0000000..6cf8e9f --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/util/DelayedOperation.java @@ -0,0 +1,57 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: DelayedOperation.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.util; + +import com.google.gwt.user.client.Timer; + +/** + * Performs a delayed action on client side. + * Usage: + *
+ *  new DelayedOperation() {
+ *    // @Override
+ *    public void doJob() {
+ *      // Here the code...
+ *    }
+ *  }.start(5000); // the operation will start after 5 secs.
+ * 
+ * @author Daniele Strollo (ISTI-CNR) + */ +public abstract class DelayedOperation { + public final void start(final int delayMills) { + Timer t = new Timer() { + @Override + public void run() { + doJob(); + } + }; + t.schedule(delayMills); + } + + public final void loop(final int delayMills) { + Timer t = new Timer() { + @Override + public void run() { + doJob(); + this.schedule(delayMills); + } + }; + t.schedule(delayMills); + } + + public abstract void doJob(); +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/util/PerformanceMonitor.java b/src/main/java/org/gcube/resourcemanagement/support/shared/util/PerformanceMonitor.java new file mode 100644 index 0000000..9d4a503 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/util/PerformanceMonitor.java @@ -0,0 +1,96 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: PerformanceMonitor.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class has been introduced to internally check the + * performance of method calls and operations in general. + * + * @author Daniele Strollo (ISTI-CNR) + */ +public class PerformanceMonitor { + private long startMills = 0; + private long stopMills = 0; + private long lastInterval = 0; + private long intermediateInterval = 0; + private StackTraceElement caller = null; + public String ownerID = null; + private final static Map clocks = new HashMap(); + + private StackTraceElement getCaller(final int depth) { + final StackTraceElement[] ste = new Throwable().getStackTrace(); + StackTraceElement position = ste[ste.length - 1 - depth]; + return position; + } + + public static PerformanceMonitor getClock(String ownerID) { + if (clocks.containsKey(ownerID)) { + return clocks.get(ownerID); + } + PerformanceMonitor retval = new PerformanceMonitor(ownerID); + clocks.put(ownerID, retval); + return retval; + } + + public static PerformanceMonitor getClock(Class owner) { + return getClock(owner.getName()); + } + + private PerformanceMonitor(String owner) { + this.ownerID = owner; + this.caller = this.getCaller(1); + } + + public final void start() { + this.startMills = System.currentTimeMillis(); + this.stopMills = 0; + this.lastInterval = 0; + this.intermediateInterval = 0; + } + public final float stop(final boolean relative) { + this.stopMills = System.currentTimeMillis(); + this.intermediateInterval = (this.stopMills - this.startMills) - this.lastInterval; + this.lastInterval = this.stopMills - this.startMills; + + if (relative) { + return this.getIntermediateIntervalSecs(); + } + return this.getLastIntervalSecs(); + } + private final float getIntermediateIntervalSecs() { + if (this.intermediateInterval == 0) { + return 0; + } + return this.intermediateInterval / 1000F; + } + private final float getLastIntervalSecs() { + if (this.lastInterval == 0) { + return 0; + } + return this.lastInterval / 1000F; + } + public final StackTraceElement getCaller() { + return this.caller; + } + public final String getOwnerID() { + return this.ownerID; + } + +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/util/SweeperActions.java b/src/main/java/org/gcube/resourcemanagement/support/shared/util/SweeperActions.java new file mode 100644 index 0000000..42eaf14 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/util/SweeperActions.java @@ -0,0 +1,72 @@ +/**************************************************************************** + * This software is part of the gCube Project. + * Site: http://www.gcube-system.org/ + **************************************************************************** + * The gCube/gCore software is licensed as Free Open Source software + * conveying to the EUPL (http://ec.europa.eu/idabc/eupl). + * The software and documentation is provided by its authors/distributors + * "as is" and no expressed or + * implied warranty is given for its use, quality or fitness for a + * particular case. + **************************************************************************** + * Filename: Actions.java + **************************************************************************** + * @author Daniele Strollo + ***************************************************************************/ + +package org.gcube.resourcemanagement.support.shared.util; + +import java.io.Serializable; + +/** + * @author Daniele Strollo (ISTI-CNR) + * + */ +public enum SweeperActions implements Serializable { + // Declarations for getting resources to cleanup + GET_GHN_MOVE_TO_UNREACHABLE( + "Expired GHNs", + "GHNs no more updated for a long time", + "Changes the status of GHNs to unreachable"), + GET_GHN_DELETE("Dead GHNs", + "GHNs having status down or unreachable", + "Removes the GHNs from the IS"), + GET_RI_DELETE("Orphan RIs", + "RIs related to no more available GHNs", + "Removes the RIs from the IS"), + + // Be sure the names are reported in xq files. + // Declarations for applying resources cleanup + APPLY_GHN_MOVE_TO_UNREACHABLE("Change GHN Status"), + APPLY_GHN_DELETE("Remove Dead GHN"), + APPLY_RI_DELETE("Remove Orphan RI"); + + private String opDescription = null; + private String label = null; + private String tooltip = null; + + private SweeperActions(final String label) { + this.label = label; + } + + private SweeperActions(final String label, final String opDescription) { + this(label); + this.opDescription = opDescription; + } + + private SweeperActions(final String label, final String tooltip, final String opDescription) { + this(label, opDescription); + this.tooltip = tooltip; + } + + public String getTooltip() { + return this.tooltip; + } + + public String getLabel() { + return label; + } + public String getOperationDescription() { + return opDescription; + } +} diff --git a/src/main/java/org/gcube/resourcemanagement/support/shared/util/TokenFilter.java b/src/main/java/org/gcube/resourcemanagement/support/shared/util/TokenFilter.java new file mode 100644 index 0000000..c96ffc9 --- /dev/null +++ b/src/main/java/org/gcube/resourcemanagement/support/shared/util/TokenFilter.java @@ -0,0 +1,35 @@ +package org.gcube.resourcemanagement.support.shared.util; + + + import java.io.IOException; + + import javax.servlet.Filter; + import javax.servlet.FilterChain; + import javax.servlet.FilterConfig; + import javax.servlet.ServletException; + import javax.servlet.ServletRequest; + import javax.servlet.ServletResponse; + + import org.gcube.common.authorization.library.provider.SecurityTokenProvider; + + public class TokenFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + SecurityTokenProvider.instance.reset(); + chain.doFilter(request, response); + SecurityTokenProvider.instance.reset(); + } + + @Override + public void destroy() { + + } + + } + diff --git a/test-suite/scopes/scopedata.xml b/test-suite/scopes/scopedata.xml new file mode 100644 index 0000000..035aafa --- /dev/null +++ b/test-suite/scopes/scopedata.xml @@ -0,0 +1,57 @@ + + + + + gcube + + + gcube + ServiceMap_gcube.xml + /gcube + + + gcube/devsec + ServiceMap_devsec.xml + /gcube/devsec + + + + + diff --git a/test-suite/scopes/scopedata_admin.xml b/test-suite/scopes/scopedata_admin.xml new file mode 100644 index 0000000..2fad2ce --- /dev/null +++ b/test-suite/scopes/scopedata_admin.xml @@ -0,0 +1,56 @@ + + + + + d4science + + + d4science + ServiceMap_d4science.research-infrastructures.eu.xml + /d4science.research-infrastructures.eu + + + d4science/FARM + ServiceMap_FARM.xml + /d4science.research-infrastructures.eu/FARM + + + d4science/Ecosystem + ServiceMap_Ecosystem.xml + /d4science.research-infrastructures.eu/Ecosystem + + + d4science/INSPIRE + ServiceMap_INSPIRE.xml + /d4science.research-infrastructures.eu/INSPIRE + + + d4science/Arts-Humanities + ServiceMap_Arts-Humanities.xml + /d4science.research-infrastructures.eu/Arts-Humanities + + + + + + gcube + + + gcube + ServiceMap_gcube.xml + /gcube + + + gcube/devsec + ServiceMap_devsec.xml + /gcube/devsec + + + gcube/devNext + ServiceMap_devNext.xml + /gcube/devNext + + + + +