Massimiliano Assante 7 years ago
commit e38b27b97c

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
<fileset name="all" enabled="true" check-config-name="CustomChecks" local="false">
<file-match-pattern match-pattern="." include-pattern="true"/>
</fileset>
<filter name="UnOpenedFiles" enabled="true"/>
</fileset-config>

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry including="**/*.java" kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.nondependency" value=""/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>rmp-common-library</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.gdt.eclipse.core.webAppProjectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.gwt.eclipse.core.gwtProjectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
<nature>com.google.gwt.eclipse.core.gwtNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>

@ -0,0 +1,4 @@
eclipse.preferences.version=1
entryPointModules=
filesCopiedToWebInfLib=gwt-servlet.jar
gwtCompileSettings=PGd3dC1jb21waWxlLXNldHRpbmdzPjxsb2ctbGV2ZWw+SU5GTzwvbG9nLWxldmVsPjxvdXRwdXQtc3R5bGU+T0JGVVNDQVRFRDwvb3V0cHV0LXN0eWxlPjxleHRyYS1hcmdzPjwhW0NEQVRBW11dPjwvZXh0cmEtYXJncz48dm0tYXJncz48IVtDREFUQVstWG14NTEybV1dPjwvdm0tYXJncz48ZW50cnktcG9pbnQtbW9kdWxlPm9yZy5nY3ViZS5yZXNvdXJjZW1hbmFnZW1lbnQuc3VwcG9ydC5SZXNvdXJjZV9zdXBwb3J0PC9lbnRyeS1wb2ludC1tb2R1bGU+PC9nd3QtY29tcGlsZS1zZXR0aW5ncz4\=

@ -0,0 +1,4 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8

@ -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

@ -0,0 +1,5 @@
#Wed Dec 19 12:41:58 CET 2012
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="rmp-common-library">
<wb-resource deploy-path="/" source-path="/src/main/java"/>
</wb-module>
</project-modules>

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="jst.utility" version="1.0"/>
<installed facet="java" version="1.7"/>
</faceted-project>

@ -0,0 +1,2 @@
disabled=06target
eclipse.preferences.version=1

@ -0,0 +1 @@
${gcube.license}

@ -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.

@ -0,0 +1,63 @@
<ReleaseNotes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="xsd/changelog.xsd">
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-7-1"
date="2017-02-24">
<Change>Changed codes for AuthZ framework</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-6-0"
date="2015-11-24">
<Change>Added support for new AuthZ framework, Feature #1496</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-5-0"
date="2015-09-28">
<Change>Refactored code to promote reuse of sweeper features</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-4-0"
date="2015-08-04">
<Change>Implemented Feature #187, remove scope operation with Report</Change>
<Change>Implemented Feature #446 Show SmartGearsDistribution version instead of SmartGearsDistributionBundle version for Distro Version</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-3-0"
date="2015-06-09">
<Change>Fix for Incident #187, remove scope operation not passing
through Resource Manager</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-2-1"
date="2014-05-25">
<Change>Fix for Incident #148, Resource Sweeper does not sweep GHN
Resources
</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-2-0"
date="2014-12-09">
<Change>Modified xqueries for showing SmartGears and SmarGearsBundle
version
</Change>
<Change>Updated label names for the gHN grid columns</Change>
<Change>Modified xquery to fix bug about wrong scoped generic resource
</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-1-0"
date="2014-12-09">
<Change>Modified xquery to get also the hostname info about service
endpoints in a given scope
</Change>
<Change>Modified the Resource detail model class to in shared package
to support the change explained above
</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.2-0-0"
date="2013-10-21">
<Change>Ported to Feather Weight Stack</Change>
<Change>Removed GCF Dependency</Change>
<Change>Logging with sl4j Enabled</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.1-2-0"
date="2013-04-19">
<Change>Create valid request for TM-plugins</Change>
</Changeset>
<Changeset component="org.gcube.portlets-admin.rmp-common-library.1-0-0"
date="2010-10-15">
<Change>First release</Change>
</Changeset>
</ReleaseNotes>

@ -0,0 +1,42 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>changelog.xml</include>
<include>profile.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>target/apidocs</directory>
<outputDirectory>/${artifactId}/doc/api</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
<files>
<file>
<source>${distroDirectory}/profile.xml</source>
<outputDirectory>./</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>target/${build.finalName}.jar</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID></ID>
<Type>Library</Type>
<Profile>
<Description>${description}</Description>
<Class>PortletsAdmin</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>${build.finalName}.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

@ -0,0 +1,208 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
<relativePath />
</parent>
<groupId>org.gcube.portlets.admin</groupId>
<artifactId>rmp-common-library</artifactId>
<version>2.7.1-SNAPSHOT</version>
<name>Resource Management Library</name>
<description>
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.
</description>
<scm>
<connection>scm:svn:http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId}</connection>
<developerConnection>scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId}</developerConnection>
<url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/portlets/admin/${project.artifactId}</url>
</scm>
<properties>
<!-- Convenience property to set the GWT version -->
<gwtVersion>2.7.0</gwtVersion>
<distroDirectory>distro</distroDirectory>
<!-- GWT needs at least java 1.6 -->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Google Web Toolkit (GWT) -->
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwtVersion}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sencha.gxt</groupId>
<artifactId>gxt2.2.5-gwt2.X</artifactId>
<version>2.7.0</version>
<scope>compile</scope>
</dependency>
<!-- Auth Framework -->
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
<scope>provided</scope>
</dependency>
<!-- FWS DEPS -->
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>resourcemanager-client</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.resources</groupId>
<artifactId>registry-publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>ghn-manager-client</artifactId>
<version>[1.1.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>provided</scope>
</dependency>
<!-- END FWS -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-profile</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
<includes>
<include>profile.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='resource_support'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User' />
<!-- Specify the app entry point class. -->
<entry-point
class='org.gcube.resourcemanagement.support.client.Resource_support' />
<!-- Specify the paths for translatable code -->
<source path='client' />
<source path='shared' />
</module>

@ -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() {
}
}

@ -0,0 +1,28 @@
package org.gcube.resourcemanagement.support.client.events;
import com.google.gwt.event.shared.GwtEvent;
public class SetScopeEvent extends GwtEvent<SetScopeEventHandler> {
public static Type<SetScopeEventHandler> TYPE = new Type<SetScopeEventHandler>();
private String scope2Set;
public String getScope() {
return scope2Set;
}
public SetScopeEvent(String scope2Set) {
this.scope2Set = scope2Set;
}
@Override
public Type<SetScopeEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(SetScopeEventHandler handler) {
handler.onSetScope(this);
}
}

@ -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);
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:massimiliano,assante@isti.cnr.it">Massimiliano Assante</a>
***************************************************************************/
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<String> availableScopes = new ArrayList<String>();
private final ArrayList<String> deployReports = new ArrayList<String>();
private static final LocalStatus INSTANCE = new LocalStatus();
public static synchronized LocalStatus getInstance() {
return INSTANCE;
}
public final ArrayList<String> getAvailableScopes() {
return this.availableScopes;
}
public final List<String> getDeployReports() {
return this.deployReports;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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 + "</" + this.rootNode + ">");
} catch (DOMParseException e) {
return "Not a valid XML document";
}
return null;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<String> getResourceTypes(final CacheManager status, final ScopeBean queryScope) throws Exception {
List<String> 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<String> 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<String> types = new ArrayList<String>();
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 <a>true</a>");
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 <a>true</a>");
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<String> getResourceSubTypes(final CacheManager status, final ScopeBean queryScope, final String resourceType) throws Exception {
ArrayList<String> subtypes = new ArrayList<String>();
if (resourceType.equals("Collection")) {
subtypes.add("System");
subtypes.add("User");
return subtypes;
}
if (resourceType.equals("VIEW")) {
subtypes.add("Not supported");
return subtypes;
}
List<String> 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<String> client = client();
isQuery.addParameter("RES_TYPE", resourceType);
isQuery.addParameter("SUBTYPE", "<subtype>{$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<String, ArrayList<String>> getResourcesTree(final CacheManager status, final ScopeBean queryScope) throws Exception {
HashMap<String, ArrayList<String>> retval = new HashMap<String, ArrayList<String>>();
// Loads the Resources
ArrayList<String> types = getResourceTypes(status, queryScope);
ArrayList<String> 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<String> 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<String> client = client();
resultz = client.submit(isQuery);
if (resultz == null || resultz.size() == 0) {
return retval;
}
subtypes = new ArrayList<String>();
for (String elem : resultz) {
subtypes.add(elem.toString());
}
retval.put("WSResource", subtypes);
ScopeProvider.instance.set(currScope);
return retval;
}
public static final List<String> 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<String> 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<String> 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<String> retval = new ArrayList<String>();
for (String elem : resultz) {
// Removes the resources with no ID or empty
try {
String toAdd = elem.toString();
if (toAdd != null) {
toAdd = toAdd.replace("<Resources>", "");
toAdd = toAdd.replace("</Resources>", "");
}
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<String> 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<String> 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<String> 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<String> retval = new Vector<String>();
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<ResourceDescriptor> getResourceModels(final ScopeBean queryScope, final String type, final String subType, final List<Tuple<String>> additionalMaps) throws Exception {
//set the scope
String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(queryScope.toString());
QueryTemplate isQuery = null;
DiscoveryClient<String> 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<String> resultz = client.submit(isQuery);
List<ResourceDescriptor> retval = new Vector<ResourceDescriptor>();
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<String> 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<String> getWSResources(final ScopeBean queryScope) throws Exception {
List<String> 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<String> client = client();
List<String> retval = new Vector<String>();
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<String> 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<String> 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<String, GenericResourcePlugin> 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<String> client = client();
List<String> resultz= client.submit(isQuery);
Map<String, GenericResourcePlugin> retval = new HashMap<String, GenericResourcePlugin>();
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<String, ArrayList<TMPluginFormField>> 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<String> client = client();
List<String> resultz= client.submit(isQuery);
HashMap<String, ArrayList<TMPluginFormField>> retval = new HashMap<String, ArrayList<TMPluginFormField>>();
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<TMPluginFormField> formFields = new ArrayList<TMPluginFormField>();
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("&lt;", "<");
xmlToParse = xmlToParse.replaceAll("&gt;", "<");
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
* <speciesRequest>
* <name>Parachela collection</name>
* <description>Parachela collection from Itis</description>
* <scientificNames repeatable="true">Parachela</scientificNames>
* <datasources repeatable="true">ITIS</datasources>
* <strictMatch>true</strictMatch>
* <refreshPeriod>5</refreshPeriod>
* <timeUnit>MINUTES</timeUnit>
* </speciesRequest>
*
* @param xmlToParse
* @return the list
*/
private static ArrayList<TMPluginFormField> getPluginFormFromXml(String xmlToParse) {
ArrayList<TMPluginFormField> toReturn = new ArrayList<TMPluginFormField>();
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();
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<ISQueryCacheKeyT, List<String>> results = new HashMap<ISQueryCacheKeyT, List<String>>();
public void insert(ISQueryCacheKeyT key, List<String> elem) {
this.results.put(key, elem);
}
public boolean contains(ISQueryCacheKeyT key) {
if (key == null) {
return false;
}
return this.results.containsKey(key);
}
public List<String> get(ISQueryCacheKeyT key) {
if (key != null && this.results.containsKey(key)) {
return this.results.get(key);
}
return null;
}
public void empty() {
this.results.clear();
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<QueryLocation, String> cachedQueries = new HashMap<QueryLocation, String>();
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -0,0 +1,8 @@
<Resource>
{$profiles//Resource/child::*}
<SubType>{$subtype}</SubType>
<gcf-version>{$gcf-version}</gcf-version>
<ghn-version>{$ghn-version}</ghn-version>
<scopes>{$scopes}</scopes>
<ghn-name>{$ghn-name}</ghn-name>
</Resource>

@ -0,0 +1,8 @@
<Resource>
{$profiles//Resource/child::*}
<SubType>{$subtype}</SubType>
<gcf-version>{$gcf-version}</gcf-version>
<ghn-version>{$ghn-version}</ghn-version>
<scopes>{$scopes}</scopes>
<ghn-name>{$ghn-name}</ghn-name>
</Resource>

@ -0,0 +1,13 @@
<WSResource>
{$outer//Document/ID}
{$outer//Document/Source}
{$outer//Document/SourceKey}
<ServiceClass>{$outer//Document/Data/child::*[local-name()='ServiceClass']/text()}</ServiceClass>
<ServiceName>{$outer//Document/Data/child::*[local-name()='ServiceName']/text()}</ServiceName>
<SubType>{$outer//Document/Data/child::*[local-name()='ServiceClass']/text()}</SubType>
{$outer//Document/TerminationTimeHuman}
{$outer//Document/LastUpdateHuman}
<RI>{$outer//Document/Data/child::*[local-name()='RI']/text()}</RI>
<Type>WSResource</Type>
<scopes>{$scopes}</scopes>
</WSResource>

@ -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
<CMPlugins>
{
for $plugin in $_outer/Data/child::*[local-name()='Plugin']
return
<Plugin>
{
for $elem in $plugin/parameters/child::*
return
<Entry>
{$plugin/name}
{$plugin/description}
<namespace>{namespace-uri($elem)}</namespace>
<Type>{local-name($elem)}</Type>
<Params>
{
for $p in $elem/child::*
return
<param>
<param-name>{$p/name()}</param-name>
<param-definition>{$p/text()}</param-definition>
</param>
}
</Params>
</Entry>
}
</Plugin>
}
</CMPlugins>

@ -0,0 +1,4 @@
declare namespace ic = 'http://gcube-system.org/namespaces/informationsystem/registry';
for $resource in collection('/db/Profiles/<RES_TYPE ISdefault ='' />')//Document/Data/ic:Profile/Resource
where $resource/ID/string() eq '<RES_ID/>'
return $resource

@ -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/<RES_TYPE ISdefault ='GHN' />')//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
<RESOURCE/>

@ -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/<RES_TYPE ISdefault ='GHN' />')//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 '<RES_SUBTYPE ISdefault='isti.cnr.it'/>'
return
<RESOURCE/>

@ -0,0 +1,27 @@
let $type := '<RES_TYPE ISdefault ='MetadataCollection'/>'
let $subtypes :=
for $_profiles in collection('/db/Profiles/<RES_TYPE ISdefault ='MetadataCollection'/>')//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
<!--
return $elem
-->
for $subtype in distinct-values($subtypes)
return
<SUBTYPE/>

@ -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
<TMPlugins>
{
for $plugin in $_outer/Data/child::*[local-name()='Plugin']
return
<Plugin>
<Entry>
{$plugin/name}
{$plugin/description}
<namespace>{namespace-uri($plugin)}</namespace>
<Type>treeManagerPlugin</Type>
<Params>
{
for $elem in $plugin/child::*[local-name()='property']
return
<param>
<param-name>{$elem/name/text()}</param-name>
<param-definition>{$elem/value/text()}</param-definition>
</param>
}
</Params>
</Entry>
</Plugin>
}
</TMPlugins>

@ -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 <type>{$types}</type>

@ -0,0 +1,4 @@
for $resource in collection("/db/Properties")//Document
where $resource/ID/string() eq '<RES_ID/>'
return $resource

@ -0,0 +1,16 @@
for $_outer in collection("/db/Properties")//Document
let $_scopes := string-join( $_outer//Document/Data/child::*[local-name()='Scope']/text(), ';')
return
<WSResource>
{$_outer//Document/ID}
{$_outer//Document/Source}
{$_outer//Document/SourceKey}
<ServiceClass>{$_outer//Document/Data/child::*[local-name()='ServiceClass']/text()}</ServiceClass>
<ServiceName>{$_outer//Document/Data/child::*[local-name()='ServiceName']/text()}</ServiceName>
<SubType>{$_outer//Document/Data/child::*[local-name()='ServiceClass']/text()}</SubType>
{$_outer//Document/TerminationTimeHuman}
{$_outer//Document/LastUpdateHuman}
<RI>{$_outer//Document/Data/child::*[local-name()='RI']/text()}</RI>
<Type>WSResource</Type>
<scopes>{$_scopes}</scopes>
</WSResource>

@ -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 '<RES_SUBTYPE/>'
return
<WSRESOURCE/>

@ -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

@ -0,0 +1,18 @@
<!--
Retrieves the list of RunningInstances on a GHN.
Params:
RES_ID - the GHN id on which lookup the RIs
Result sample:
<Resource>
<ID>8ced4e40-ecf1-11df-95dd-c203e806a114</ID>
<ServiceName>ResourceManager</ServiceName>
<ServiceClass>VREManagement</ServiceClass>
<ServiceVersion>1.0.1</ServiceVersion>
<MainVersion>2.00.00</MainVersion>
<Status>ready</Status>
</Resource>
-->
for $ris in collection('/db/Profiles/RunningInstance')//Resource
where $ris//Resource/Profile/GHN/@UniqueID/string() eq '<RES_ID/>'
return
<RESOURCE/>

@ -0,0 +1,8 @@
<Resource>
{$ris/ID}
{$ris/Profile/ServiceName}
{$ris/Profile/ServiceClass}
<ServiceVersion>{$ris//Resource/@version/string()}</ServiceVersion>
<MainVersion>{$ris/Profile/Version/text()}</MainVersion>
<Status>{$ris/Profile/DeploymentData/Status/text()}</Status>
</Resource>

@ -0,0 +1,45 @@
<Resources>
<Resource>
<Key>ID</Key>
<Value>{$ri//Resource/ID/string()}</Value>
</Resource>
<Resource>
<Key>ServiceStatus</Key>
<Value>{$ri/Profile/DeploymentData/Status/string()}</Value>
</Resource>
<Resource>
<Key>ActivationTime</Key>
<Value>{$ri/Profile/DeploymentData/ActivationTime/@value/string()}</Value>
</Resource>
<Resource>
<Key>GHNName</Key>
<Value>{$ghn-name}</Value>
</Resource>
<Resource>
<Key>GHNSite</Key>
<Value>{$relatedghn/Profile/Site/Domain/string()}</Value>
</Resource>
<Resource>
<Key>GHNStatus</Key>
<Value>{$relatedghn/Profile/GHNDescription/Status/string()}</Value>
</Resource>
<Resource>
<Key>GHNActivationTime</Key>
<Value>{$relatedghn/Profile/GHNDescription/ActivationTime/string()}</Value>
</Resource>
<Resource>
<Key>GHNLastUpdate</Key>
<Value>{$relatedghn/Profile/GHNDescription/LastUpdate/string()}</Value>
</Resource>
<Resource>
<Key>GHNLoad15Min</Key>
<Value>{$relatedghn/Profile/GHNDescription/Load/@Last15Min/string()}</Value>
</Resource>
<Resource>
<Key>GHNLoad5Min</Key>
<Value>{$relatedghn/Profile/GHNDescription/Load/@Last5Min/string()}</Value>
</Resource><Resource>
<Key>GHNLoad1Min</Key>
<Value>{$relatedghn/Profile/GHNDescription/Load/@Last1Min/string()}</Value>
</Resource>
</Resources>

@ -0,0 +1,21 @@
<Resource>
<!-- INFORMATION ABOUT THE RI -->
<RIID>{$ri/ID/string()}</RIID>
<ServiceStatus>{$ri/Profile/DeploymentData/Status/string()}</ServiceStatus>
<ActivationTime>{$ri/Profile/DeploymentData/ActivationTime/@value/string()}</ActivationTime>
<RIVersion>{$ri/Profile/Version/string()}</RIVersion>
<!-- INFORMATION about GHN -->
<GHNID>{$ghn-id}</GHNID>
<GHNName>{$ghn/Profile/GHNDescription/Name/string()}</GHNName>
<GHNSite>{$ghn/Profile/Site/Domain/string()}</GHNSite>
<GHNStatus>{$ghn/Profile/GHNDescription/Status/string()}</GHNStatus>
<GHNLoad15Min>{$ghn/Profile/GHNDescription/Load/@Last15Min/string()}</GHNLoad15Min>
<GHNLoad5Min>{$ghn/Profile/GHNDescription/Load/@Last15Min/string()}</GHNLoad5Min>
<GHNLoad1Min>{$ghn/Profile/GHNDescription/Load/@Last15Min/string()}</GHNLoad1Min>
<GHNActivationTime>{$ghn/Profile/GHNDescription/ActivationTime/string()}</GHNActivationTime>
<GHNLastUpdate>{$ghn/Profile/GHNDescription/LastUpdate/string()}</GHNLastUpdate>
</Resource>
return
<Resources>
{$relatedris}
</Resources>

@ -0,0 +1,11 @@
<!--
Notice: the <Resources> node must be removed in using the resource grid factory.
-->
let $profiles := collection('/db/Profiles/<RES_TYPE ISdefault ='RunningInstance'/>')//Resource[ID/string() eq '<RES_ID/>']
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
<RESOURCE/>

@ -0,0 +1,16 @@
<!--
PARAMETS:
RES_ID the ID of the Service
-->
let $service := collection('/db/Profiles/Service')//Resource//Resource[ID/text() eq '<RES_ID/>']
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]
<!-- and $ri//Profile/Version/string() eq $ServiceVersion -->
return
<RESOURCE/>

@ -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'
<RES_SUBTYPE ISdefault =''/>
return
<RESOURCE/>

@ -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()
<RES_SUBTYPE ISdefault =''/>
return
<RESOURCE/>

@ -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()
<RES_SUBTYPE ISdefault =''/>
return
<RESOURCE/>

@ -0,0 +1,11 @@
<Resource>
{$profiles//Resource/ID}
<Type>{$profiles//Resource/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Scopes>{$scopes}</Scopes>
<Name>{$profiles//Resource/Profile/Name/text()}</Name>
<CreationTime>{$profiles//Resource/Profile/Body/SourceProperties/creationTime/text()}</CreationTime>
<UserCollection>{$profiles//Resource/Profile/Body/SourceProperties/user/text()}</UserCollection>
<LastUpdateTime>{$wsresource/LastUpdateHuman/text()}</LastUpdateTime>
<NumberOfMembers>{$wsresource//child::*[local-name()='Cardinality']/text()}</NumberOfMembers>
</Resource>

@ -0,0 +1,18 @@
<Resource>
{$profiles//Resource/ID}
<Type>{$profiles//Resource/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Status>{$profiles//Resource/Profile/GHNDescription/Status/text()}</Status>
<Name>{$profiles//Resource/Profile/GHNDescription/Name/text()}</Name>
<Uptime>{$profiles//Resource/Profile/GHNDescription/Uptime/text()}</Uptime>
<LastUpdate>{$profiles//Resource/Profile/GHNDescription/LastUpdate/text()}</LastUpdate>
<LocalAvailableSpace>{$profiles//Resource/Profile/GHNDescription/LocalAvailableSpace/text()}</LocalAvailableSpace>
<VirtualSize>{$profiles//Resource/Profile/GHNDescription/MainMemory/string(@VirtualSize)}</VirtualSize>
<VirtualAvailable>{$profiles//Resource/Profile/GHNDescription/MainMemory/string(@VirtualAvailable)}</VirtualAvailable>
<LoadLast1Min>{$profiles//Resource/Profile/GHNDescription/Load/string(@Last1Min)}</LoadLast1Min>
<LoadLast5Min>{$profiles//Resource/Profile/GHNDescription/Load/string(@Last5Min)}</LoadLast5Min>
<LoadLast15Min>{$profiles//Resource/Profile/GHNDescription/Load/string(@Last15Min)}</LoadLast15Min>
<gcf-version>{$gcf-version}</gcf-version>
<ghn-version>{$ghn-version}</ghn-version>
<Scopes>{$scopes}</Scopes>
</Resource>

@ -0,0 +1,8 @@
<Resource>
{$profiles//Resource/ID}
<Type>{$profiles//Resource/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Scopes>{$scopes}</Scopes>
<Name>{$profiles//Resource/Profile/Name/text()}</Name>
<Description>{$profiles//Resource/Profile/Description/text()}</Description>
</Resource>

@ -0,0 +1,11 @@
<Resource>
{$profiles/ID}
<Type>{$profiles/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Scopes>{$scopes}</Scopes>
<ServiceClass>{$profiles/Profile/ServiceClass/text()}</ServiceClass>
<ServiceName>{$profiles/Profile/ServiceName/text()}</ServiceName>
<Version>{$profiles/Profile/Version/text()}</Version>
<Status>{$profiles/Profile/DeploymentData/Status/text()}</Status>
<ghn-name>{$ghn-name}</ghn-name>
</Resource>

@ -0,0 +1,8 @@
<Resource>
{$profiles//Resource/ID}
<Type>{$profiles//Resource/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Scopes>{$scopes}</Scopes>
<Name>{$profiles//Resource/Profile/Name/text()}</Name>
<Host>{$profiles//Resource/Profile/RunTime/HostedOn/text()}</Host>
</Resource>

@ -0,0 +1,10 @@
<Resource>
{$profiles//Resource/ID}
<Type>{$profiles//Resource/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Scopes>{$scopes}</Scopes>
<ServiceClass>{$profiles//Resource/Profile/Class/text()}</ServiceClass>
<ServiceName>{$profiles//Resource/Profile/Name/text()}</ServiceName>
<Version>{$profiles//Resource/Profile/Packages/Software[1]/Version/text()}</Version>
<Shareable>{$profiles//Resource/Profile/Packages/Software/Shareable/string(@level)}</Shareable>
</Resource>

@ -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()
<RES_SUBTYPE ISdefault =''/>
return
<RESOURCE/>

@ -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()
<RES_SUBTYPE ISdefault =''/>
return
<RESOURCE/>

@ -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()
<RES_SUBTYPE ISdefault =''/>
return
<RESOURCE/>

@ -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
<Resource>
{$outer//Document/ID}
{$outer//Document/Source}
{$outer//Document/SourceKey}
<ViewName>{$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='property']/child::*[local-name()='name' and text()='name']/../child::*[local-name()='value']/text()}</ViewName>
<Cardinality>{$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='cardinality']/text()}</Cardinality>
<ViewType>{$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='type']/text()}</ViewType>
<RelatedCollectionId>{$outer//Document/Data/child::*[local-name()='View']/child::*[local-name()='collectionID']/text()}</RelatedCollectionId>
<ServiceClass>{$outer//Document/Data/child::*[local-name()='ServiceClass']/text()}</ServiceClass>
<ServiceName>{$outer//Document/Data/child::*[local-name()='ServiceName']/text()}</ServiceName>
<SubType>{$outer//Document/Data/child::*[local-name()='ServiceClass']/text()}</SubType>
{$outer//Document/TerminationTimeHuman} {$outer//Document/LastUpdateHuman}
<RI>{$outer//Document/Data/child::*[local-name()='RI']/text()}</RI>
<Type>WSResource</Type>
<scopes>{$outer//Document/Data/child::*[local-name()='Scope']/text()}</scopes>
</Resource>

@ -0,0 +1,14 @@
<Resource>
{$GHNs/ID}
{$GHNs/Profile/GHNDescription/Name}
{$GHNs/Profile/GHNDescription/Status}
{$GHNs/Profile/GHNDescription/Type}
{$GHNs/Profile/Site/Location}
{$GHNs/Profile/Site/Domain}
<IPAddress>{$GHNs/Profile/GHNDescription/NetworkAdapter/@IPAddress/string()}</IPAddress>
<Scopes>{$scopes}</Scopes>
<AllocatedRI>{count($RIinstalled)}</AllocatedRI>
{$GHNs/Profile/GHNDescription/LastUpdate}
<UpdateMinutesElapsed>{$totalminutes}</UpdateMinutesElapsed>
<Actions>APPLY_GHN_DELETE</Actions>
</Resource>

@ -0,0 +1,13 @@
<Resource>
{$GHNs/ID}
{$GHNs/Profile/GHNDescription/Name}
{$GHNs/Profile/GHNDescription/Status}
{$GHNs/Profile/GHNDescription/Type}
{$GHNs/Profile/Site/Location}
{$GHNs/Profile/Site/Domain}
<IPAddress>{$GHNs/Profile/GHNDescription/NetworkAdapter/@IPAddress/string()}</IPAddress>
<Scopes>{$scopes}</Scopes>
<AllocatedRI>{count($RIinstalled)}</AllocatedRI>
{$GHNs/Profile/GHNDescription/LastUpdate}
<Actions>APPLY_GHN_MOVE_TO_UNREACHABLE</Actions>
</Resource>

@ -0,0 +1,9 @@
<Resource>
<ID>{$ri//Resource/ID/string()}</ID>
<ServiceStatus>{$ri/Profile/DeploymentData/Status/string()}</ServiceStatus>
<ActivationTime>{$ri/Profile/DeploymentData/ActivationTime/@value/string()}</ActivationTime>
<ghnid>{$ri/Profile/GHN/@UniqueID/string()}</ghnid>
<ServiceClass>{$ri/Profile/ServiceClass/string()}</ServiceClass>
<ServiceName>{$ri/Profile/ServiceName/string()}</ServiceName>
<Actions>APPLY_RI_DELETE</Actions>
</Resource>

@ -0,0 +1,13 @@
<!--
These are the GHNs that are declared certified and must be passed to
down status.
The choice is done by minutes elapsed from last update.
-->
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
<RESOURCE/>

@ -0,0 +1,12 @@
<!--
These are the GHNs that are declared certified and must be passed to
down status.
The choice is done by minutes elapsed from last update.
-->
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
<RESOURCE/>

@ -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
<RESOURCE/>

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<ReportEntry> entries = null;
public ReportBuilder() {
entries = new Vector<ReportEntry>();
}
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("<Report>\n");
for (ReportEntry entry : this.entries) {
builder.append(entry.toXML());
}
builder.append("</Report>\n");
return builder.toString();
}
@Override
public final String toString() {
return this.getXML();
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<Operation type=\"" + this.getOperation().getLabel() + "\">\n" +
"\t\t<Status>" + (this.isSuccess() ? "SUCCESS" : "FAILURE") + "</Status>\n" +
"\t\t<Resource>\n" +
"\t\t\t<ID>" + this.getResource().getID() + "</ID>\n" +
// If the resource has a name
(this.getResource().getName() != null ?
"\t\t\t<Name>" + this.getResource().getName() + "</Name>\n" : "") +
"\t\t\t<Type>" + this.getResource().getType() + "</Type>\n" +
// If a message is present
(this.message != null ?
"\t\t\t<Message>\n\t\t\t\t" + this.message.trim() + "\n\t\t\t</Message>\n" : "") +
"\t\t</Resource>\n" +
"\t</Operation>\n";
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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
* <a href="https://gcube.wiki.gcube-system.org/gcube/index.php/Programmatic_Administration_Interface">
* official wiki</a>.
* @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<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
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<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
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<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
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.
* <br/>
* <b>This field is mandatory</b>
* @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.
* </br>
* <b>This field is mandatory</b>
* @return
*/
public final String getName() {
return this.name;
}
/**
* All resources have a type.
* </br>
* <b>This field is mandatory</b>
* @return
*/
public final AllowedResourceTypes getType() {
return this.type;
}
/**
* Resources can have a subtype (e.g. for GHNs is the domain).
* </br>
* <b>This field is optional</b>
* @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
* <a href="https://gcube.wiki.gcube-system.org/gcube/index.php/Programmatic_Administration_Interface">
* official wiki</a>
* for scope binding rules) this method is internally called.
* @param targetScope
* @return
* @throws ResourceOperationException
*/
private String bindToScope(final String targetScope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<ResourceItem> temp = new ArrayList<ResourceItem>();
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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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
* <a href="https://gcube.wiki.gcube-system.org/gcube/index.php/Programmatic_Administration_Interface#Add_a_gCube_Resource_from_a_VO_to_another_VO">
* here</a> for further details.
* @param sourceScope
* @param targetScope
* @return
* @throws AbstractResourceException
*/
public final String copyFromToVO(final ScopeBean sourceScope, final ScopeBean targetScope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<String> client = client();
List<String> 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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<ResourceItem> temp = new ArrayList<ResourceItem>();
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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<ScopeBean> validateScopes(final String[] scopes) {
List<ScopeBean> retval = new Vector<ScopeBean>();
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
* <a href="https://gcube.wiki.gcube-system.org/gcube/index.php/Programmatic_Administration_Interface">
* official wiki</a> 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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<ScopeBean> 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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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.
* <p>
* <b>Required information:</b>
* <br/>
* The <i>ID</i> of the resource must be specified and valid.</p>
* @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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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);
}
/**
* <p>
* <b>Required information:</b>
* <br/>
* The <i>name</i> of the resource must be specified and valid. It is used to retrieve the GHN manager URL.</p>
* @param scope the scope in which the manager is bound.
* @return
* @throws AbstractResourceException
*/
public final GHNManagerLibrary getGHNManager(final ScopeBean scope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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.
* <p>
* <b>Required information:</b>
* <br/>
* The <i>ID</i> of the resource must be specified and valid.</p>
* @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<ResourceAccessException> checker = new Assertion<ResourceAccessException>();
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);
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<GenericResource> client = clientFor(GenericResource.class);
List<GenericResource> 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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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 <Body> " + 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);
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<ResourceItem> resToBind = new ArrayList<ResourceItem>();
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<Exception> checker = new Assertion<Exception>();
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<PackageItem> serviceProfiles = new ArrayList<PackageItem>();
// Retrieves the profiles of services
SimpleQuery query = null;
DiscoveryClient<Software> 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<Software> 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<String> arrayGHNSids = new ArrayList<String>();
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<String> ids = new Vector<String>();
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);
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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());
}
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
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<PackageItem> serviceProfiles = new ArrayList<PackageItem>();
try {
SimpleQuery query = null;
DiscoveryClient<Software> 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<Software> 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<String> arrayGHNSids = new ArrayList<String>();
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<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
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<ResourceItem> temp =new ArrayList<ResourceItem>();
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<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
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);
}
}
}

@ -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 <a href="mailto:assante@isti.cnr.it">Massimiliano Assante</a>
***************************************************************************/
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<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
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);
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<String, ScopeBean> SCOPES = new LinkedHashMap<String, ScopeBean>();
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<String, ScopeBean> 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<String, ScopeBean> toCopy = readScopes(confFile);
for (String key : toCopy.keySet()) {
SCOPES.put(key, toCopy.get(key));
}
}
/**
*
* @param confFile
* @return
* @throws Exception
*/
public static LinkedHashMap<String, ScopeBean> readScopes(String confFile) throws Exception {
if (confFile == null) {
throw new NullPointerException("the scope file has not been defined");
}
LinkedHashMap<String, ScopeBean> toReturn = new LinkedHashMap<String, ScopeBean>();
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<String> getVREFromVO(final ScopeBean vo) throws Exception {
ServerConsole.info(LOG_PREFIX, "Starting Retrieving VREs for VO : " + vo);
List<String> toReturn = new ArrayList<String>();
ScopeProvider.instance.set(vo.toString());
SimpleQuery query = queryFor(GenericResource.class);
query.addCondition("$resource/Profile/SecondaryType/text() eq 'VRE'");
DiscoveryClient<GenericResource> client = clientFor(GenericResource.class);
List<GenericResource> 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;
}
}

@ -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 + "]";
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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<String> 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<String> 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<String> results = client.submit(isQuery);
ArrayList<String> retval = new ArrayList<String>();
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<String> 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<String> 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<String> 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<ModelData> 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;
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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", "<update>updated body</update>", "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<String, ArrayList<String>> 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<String> 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");
// }
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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();
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
package org.gcube.resourcemanagement.support.server.types;
/**
* @author Massimiliano Assante (ISTI-CNR)
*
*/
public enum AllowedResourceTypes {
GHN(),
RunningInstance(),
Service(),
VIEW(),
GenericResource(),
RuntimeResource(),
Collection();
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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.
* <pre>
* <b>Example:</b>
*
* <b>Assertion</b>&lt;<i>TheExceptionType</i>&gt; assertion = new Assertion&lt;ParamException&gt; ();
* assertion.<b>validate</b> (param != null, new <i>TheExceptionType</i>("invalid parameter null"));
*
* <b>or</b>, in a more compact form:
* <i>// The exception to throw in case of failure
* // during the evaluation of the expected condition</i>
* new <b>Assertion</b>&lt;<i>TheExceptionType</i>&gt;().<b>validate</b>(
* i>5, <i>// The expected boolean <b>condition</b></i>
* new <i>TheExceptionType</i>("Parameter must be greater than 5")); <i>//The <b>error</b> message</i>
*
* </pre>
*
* @author Daniele Strollo (ISTI-CNR)
*/
public class Assertion <T extends Throwable> implements Serializable {
private static final long serialVersionUID = -2007903339251667541L;
/**
* Makes an assertion and if the expression evaluation fails, throws an
* exception of type T.
* <pre>
* Example:
* new Assertion&lt;MyException&gt;().validate(whatExpected, new MyException("guard failed"));
* </pre>
* @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;
}
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
package org.gcube.resourcemanagement.support.server.utils.persistence;
/**
* @author Daniele Strollo (ISTI-CNR)
*
*/
public interface PersistenceHandler<T> {
/**
* 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);
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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.
* <pre>
* new <b>PersistentItem</b><i>&lt;DataTypeToPersist&gt;</i>(fileToStore, refreshDelay) {
* <b>public void</b> onLoad() {
* <i>//...</i>
* }
* <i>
* // The other methods to overload
* // ...
* </i>
* }
* </pre>
* @author Daniele Strollo (ISTI-CNR)
*/
public abstract class PersistentItem<T extends Serializable>
implements PersistenceHandler<T> {
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;
}
}
}

@ -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<ScopeBean[]> persistentScopes = new PersistentItem<ScopeBean[]>("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);
}
};
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

@ -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 <a href="mailto:daniele.strollo@isti.cnr.it">Daniele Strollo</a>
***************************************************************************/
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);
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save