in the way to the FWS, 50 percent ported so far

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portlets/admin/rmp-common-library@81279 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Massimiliano Assante 2013-09-11 16:40:58 +00:00
parent 274dbf124a
commit 878cc7ffc5
37 changed files with 1051 additions and 1173 deletions

View File

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

30
pom.xml
View File

@ -11,7 +11,7 @@
<groupId>org.gcube.portlets.admin</groupId> <groupId>org.gcube.portlets.admin</groupId>
<artifactId>rmp-common-library</artifactId> <artifactId>rmp-common-library</artifactId>
<version>1.2.0-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
<name>Resource Management Library</name> <name>Resource Management Library</name>
<description> <description>
gCube Resource Management Library is a common library containing shared code for Information System Operations gCube Resource Management Library is a common library containing shared code for Information System Operations
@ -24,7 +24,7 @@
</scm> </scm>
<properties> <properties>
<!-- Convenience property to set the GWT version --> <!-- Convenience property to set the GWT version -->
<gwtVersion>2.4.0</gwtVersion> <gwtVersion>2.5.1</gwtVersion>
<distroDirectory>distro</distroDirectory> <distroDirectory>distro</distroDirectory>
<!-- GWT needs at least java 1.6 --> <!-- GWT needs at least java 1.6 -->
<maven.compiler.source>1.6</maven.compiler.source> <maven.compiler.source>1.6</maven.compiler.source>
@ -61,11 +61,33 @@
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version> <version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- <dependency> -->
<!-- <groupId>org.gcube.resourcemanagement</groupId> -->
<!-- <artifactId>resource-manager-stubs</artifactId> -->
<!-- <version>[2.0.1-SNAPSHOT, 3.0.0-SNAPSHOT)</version> -->
<!-- </dependency> -->
<!-- FWS DEPS -->
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
<dependency> <dependency>
<groupId>org.gcube.resourcemanagement</groupId> <groupId>org.gcube.resourcemanagement</groupId>
<artifactId>resource-manager-stubs</artifactId> <artifactId>resourcemanager-client</artifactId>
<version>[2.0.1-SNAPSHOT, 3.0.0-SNAPSHOT)</version> <version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency> </dependency>
<dependency>
<groupId>org.gcube.resources</groupId>
<artifactId>registry-publisher</artifactId>
<version>[1.1.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>ghn-manager-client</artifactId>
<version>[1.1.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
<!-- END FWS -->
<dependency> <dependency>
<groupId>org.gcube.resourcemanagement</groupId> <groupId>org.gcube.resourcemanagement</groupId>
<artifactId>ghnmanager-stubs</artifactId> <artifactId>ghnmanager-stubs</artifactId>

View File

@ -24,53 +24,52 @@ public enum ResourceTypeDecorator {
/**************************************** /****************************************
* RESOURCES IN THE TREE * RESOURCES IN THE TREE
****************************************/ ****************************************/
GHN("gCube Hosting Node", "ghn-icon"), GHN("gCube Hosting Node", "ghn-icon","Hosting Node"),
RunningInstance("Running Instances", "runninginstance-icon"), RunningInstance("Running Instances", "runninginstance-icon", "GCore Endpoint"),
Service("Software", "service-icon"), Service("Software", "service-icon","Software"),
VIEW("View", "metadatacollection-icon"), VIEW("View", "metadatacollection-icon",""),
GenericResource("Generic Resources", "genericresource-icon"), GenericResource("Generic Resources", "genericresource-icon","Generic Resource"),
Collection("Collection", "collection-icon"), Collection("Collection", "collection-icon",""),
WSResource("WSResource", "wsresources-icon"), WSResource("WSResource", "wsresources-icon",""),
Empty("Empty Tree", "empty-icon"), Empty("Empty Tree", "empty-icon",""),
RuntimeResource("Runtime Resources", "runtimeresource-icon"), RuntimeResource("Runtime Resources", "runtimeresource-icon", "Service Endpoint"),
/**************************************** /****************************************
* Other components * Other components
****************************************/ ****************************************/
// For deploying services - similar to the software but with an // For deploying services - similar to the software but with an
// extension to handle checkbox for install // extension to handle checkbox for install
InstallableSoftware("InstallableSoftware", "empty-icon"), InstallableSoftware("InstallableSoftware", "empty-icon",""),
// In the taskbar for handlig the refresh of deployment reports // In the taskbar for handlig the refresh of deployment reports
DeployReport("Deploy Report", "report-big-icon"), DeployReport("Deploy Report", "report-big-icon",""),
AddScopeReport("Add Scope Report", "report-big-icon"), AddScopeReport("Add Scope Report", "report-big-icon",""),
/**************************************** /****************************************
* Related resources * Related resources
****************************************/ ****************************************/
GHNRelated("Running Instances", "runninginstance-icon"), GHNRelated("Running Instances", "runninginstance-icon",""),
ServiceRelated("Running Instances", "runninginstance-icon"), ServiceRelated("Running Instances", "runninginstance-icon",""),
RunningInstanceRelated("Running Instances", "runninginstance-icon"), RunningInstanceRelated("Running Instances", "runninginstance-icon",""),
/**************************************** /****************************************
* Models for SWEEPER * Models for SWEEPER
***************************************/ ***************************************/
Sweeper_GHN("gCube Hosting Node", "ghn-icon"), Sweeper_GHN("gCube Hosting Node", "ghn-icon",""),
Sweeper_RI("Running Instance", "runninginstance-icon"), Sweeper_RI("Running Instance", "runninginstance-icon",""),
Sweeper_RI_Orphan("Orphan Running Instance", "orphan-runninginstance-icon"), Sweeper_RI_Orphan("Orphan Running Instance", "orphan-runninginstance-icon",""),
Sweeper_GHN_Expired("Expired gHN", "expired-ghn-icon"), Sweeper_GHN_Expired("Expired gHN", "expired-ghn-icon",""),
Sweeper_GHN_Dead("Dead gHN", "dead-ghn-icon"); Sweeper_GHN_Dead("Dead gHN", "dead-ghn-icon","");
private String fwsName = null;
private String label = null; private String label = null;
private String icon = null; private String icon = null;
ResourceTypeDecorator( ResourceTypeDecorator(final String label, final String icon, final String fwsName) {
final String label,
final String icon) {
this.label = label; this.label = label;
this.icon = icon; this.icon = icon;
this.fwsName = fwsName;
} }
public String getLabel() { public String getLabel() {
@ -80,4 +79,10 @@ public enum ResourceTypeDecorator {
public String getIcon() { public String getIcon() {
return this.icon; return this.icon;
} }
public String getFWSName() {
if (this.fwsName == null || this.fwsName.equals(""))
return this.label;
return this.fwsName;
}
} }

View File

@ -16,9 +16,12 @@
package org.gcube.resourcemanagement.support.server.gcube; package org.gcube.resourcemanagement.support.server.gcube;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.StringReader; import java.io.StringReader;
@ -30,6 +33,8 @@ import java.util.Map;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector; import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
import javax.xml.transform.Templates; import javax.xml.transform.Templates;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
@ -39,17 +44,16 @@ import javax.xml.transform.stream.StreamSource;
import org.gcube.common.core.contexts.GHNContext; import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.ISClient; import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.QueryParameter;
import org.gcube.common.core.informationsystem.client.XMLResult; import org.gcube.common.core.informationsystem.client.XMLResult;
import org.gcube.common.core.informationsystem.client.XMLResult.ISResultEvaluationException;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericQuery; import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericQuery;
import org.gcube.common.core.scope.GCUBEScope; import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBEClientLog; import org.gcube.common.core.utils.logging.GCUBEClientLog;
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.client.views.ResourceTypeDecorator;
import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLoader; import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLoader;
import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLocation; import org.gcube.resourcemanagement.support.server.gcube.queries.QueryLocation;
import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager;
import org.gcube.resourcemanagement.support.server.utils.ServerConsole; import org.gcube.resourcemanagement.support.server.utils.ServerConsole;
import org.gcube.resourcemanagement.support.shared.plugins.GenericResourcePlugin; import org.gcube.resourcemanagement.support.shared.plugins.GenericResourcePlugin;
@ -57,10 +61,16 @@ import org.gcube.resourcemanagement.support.shared.plugins.TMPluginFormField;
import org.gcube.resourcemanagement.support.shared.types.Tuple; 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.CompleteResourceProfile;
import org.gcube.resourcemanagement.support.shared.types.datamodel.ResourceDescriptor; 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.Document;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/** /**
@ -78,43 +88,47 @@ public class ISClientRequester {
CACHE.empty(); CACHE.empty();
} }
private static final ArrayList<String> getResourceTypes( private static final ArrayList<String> getResourceTypes(final CacheManager status, final ScopeBean queryScope) throws Exception {
final CacheManager status,
final GCUBEScope queryScope) List<String> resultz = null;
throws Exception {
List<XMLResult> results = null; //set the scope
ISClient client = GHNContext.getImplementation(ISClient.class); String currScope = ScopeProvider.instance.get();
GCUBEGenericQuery isQuery = null; ScopeProvider.instance.set(queryScope.toString());
isQuery = client.getQuery(GCUBEGenericQuery.class);
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_TREE_TYPES)); Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_TREE_TYPES));
DiscoveryClient<String> client = client();
// Handles the cache // Handles the cache
ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(),
isQuery.getExpression(), isQuery.expression(),
"getResourcesTypes"); "getResourcesTypes");
if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) {
results = CACHE.get(cacheKey); resultz = CACHE.get(cacheKey);
} else { } else {
try { try {
results = client.execute(isQuery, queryScope);
resultz = client.submit(isQuery);
if (status.isUsingCache()) { if (status.isUsingCache()) {
CACHE.insert(cacheKey, results); CACHE.insert(cacheKey, resultz);
} }
} catch (Exception e) { } catch (Exception e) {
throw new Exception(e.getMessage()); throw new Exception(e.getMessage());
} }
} }
if (results == null || results.size() == 0) { if (resultz == null || resultz.size() == 0) {
return null; return null;
} }
String type = null; String type = null;
ArrayList<String> types = new ArrayList<String>(); ArrayList<String> types = new ArrayList<String>();
try { try {
for (XMLResult elem : results) { for (String elem : resultz) {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
type = elem.evaluate("/type/text()").get(0); 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) { if (type != null && type.trim().length() > 0) {
types.add(type.trim()); types.add(type.trim());
} }
@ -122,37 +136,39 @@ public class ISClientRequester {
//**** CHANGES TO KNOW IF VIEWS AND GCUBECollection are present //**** CHANGES TO KNOW IF VIEWS AND GCUBECollection are present
types.remove("MetadataCollection"); types.remove("MetadataCollection");
isQuery.setExpression("declare namespace vm = 'http://gcube-system.org/namespaces/contentmanagement/viewmanager';"+ 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 gc = 'http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider';"+
"declare namespace is = 'http://gcube-system.org/namespaces/informationsystem/registry';" + "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\" " + "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>"); " and $view/gc:ServiceClass/string() eq \"ContentManagement\" and count($view//vm:View)>0 return <a>true</a>");
if (client.execute(isQuery, queryScope).size() > 0) if (client.submit(isQuery).size() > 0)
types.add("VIEW"); types.add("VIEW");
isQuery.setExpression("declare namespace gc = 'http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider';"+ 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';" + "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\" " + "for $data in collection(\"/db/Profiles/GenericResource\")//Document/Data/is:Profile/Resource where $data/Profile/SecondaryType eq \"GCUBECollection\" " +
" return <a>true</a>"); " return <a>true</a>");
if (client.execute(isQuery, queryScope).size() > 0) if (client.submit(isQuery).size() > 0)
types.add("Collection"); types.add("Collection");
} catch (ISResultEvaluationException e) {
_log.error("error during getResourcesTypes");
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// ignore exception // ignore exception
} }
ScopeProvider.instance.set(currScope);
return types; return types;
} }
private static final ArrayList<String> getResourceSubTypes( /**
final CacheManager status, *
final GCUBEScope queryScope, * @param status
final String resourceType) * @param queryScope
throws Exception { * @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>(); ArrayList<String> subtypes = new ArrayList<String>();
if (resourceType.equals("Collection")) { if (resourceType.equals("Collection")) {
@ -165,52 +181,58 @@ public class ISClientRequester {
return subtypes; return subtypes;
} }
List<XMLResult> results = null;
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGenericQuery isQuery = null;
isQuery = client.getQuery(GCUBEGenericQuery.class);
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_TREE_SUBTYPES));
isQuery.addParameters(new QueryParameter("RES_TYPE", resourceType)); 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 // Handles the cache
ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(),
isQuery.getExpression(), isQuery.expression(),
"getResourcesSubTypes"); "getResourcesSubTypes");
if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) {
results = CACHE.get(cacheKey); resultz = CACHE.get(cacheKey);
} else { } else {
try { try {
results = client.execute(isQuery, queryScope); resultz = client.submit(isQuery);
if (status.isUsingCache()) { if (status.isUsingCache()) {
CACHE.insert(cacheKey, results); CACHE.insert(cacheKey, resultz);
} }
} catch (Exception e) { } catch (Exception e) {
throw new Exception(e.getMessage()); throw new Exception(e.getMessage());
} }
} }
if (results == null || results.size() == 0) { if (resultz == null || resultz.size() == 0)
return null; return null;
}
String subtype = null; for (String elem : resultz) {
for (XMLResult elem : results) {
try { try {
subtype = elem.evaluate("/subtype/text()").get(0); 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) { if (subtype != null && subtype.trim().length() > 0) {
subtypes.add(subtype.trim()); subtypes.add(subtype.trim());
} }
} catch (ISResultEvaluationException e) {
_log.error("error during getResourcesTypes");
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// ignore exception // ignore exception
} }
} }
ScopeProvider.instance.set(currScope);
return subtypes; return subtypes;
} }
/** /**
* For all the resource in the scope retrieves their * For all the resource in the scope retrieves their
* (type, subtype) values. * (type, subtype) values.
@ -218,10 +240,7 @@ public class ISClientRequester {
* @return a list of string tuples (type, subtype) * @return a list of string tuples (type, subtype)
* @throws Exception * @throws Exception
*/ */
public static final HashMap<String, ArrayList<String>> getResourcesTree( //qui si perde public static final HashMap<String, ArrayList<String>> getResourcesTree(final CacheManager status, final ScopeBean queryScope) throws Exception {
final CacheManager status,
final GCUBEScope queryScope)
throws Exception {
HashMap<String, ArrayList<String>> retval = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> retval = new HashMap<String, ArrayList<String>>();
// Loads the Resources // Loads the Resources
@ -240,35 +259,32 @@ public class ISClientRequester {
} }
// Loads the WSResources // Loads the WSResources
// This types is statically handled since it is a particular // This types is statically handled since it is a particular case of resource.
// case of resource.
List<XMLResult> results = null;
ISClient client = GHNContext.getImplementation(ISClient.class); List<String> resultz = null;
GCUBEGenericQuery isQuery = null;
isQuery = client.getQuery(GCUBEGenericQuery.class); //set the scope
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_WSRES_TYPES)); String currScope = ScopeProvider.instance.get();
results = client.execute(isQuery, queryScope); ScopeProvider.instance.set(queryScope.toString());
if (results == null || results.size() == 0) {
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; return retval;
} }
subtypes = new ArrayList<String>(); subtypes = new ArrayList<String>();
for (XMLResult elem : results) { for (String elem : resultz) {
subtypes.add(elem.toString()); subtypes.add(elem.toString());
} }
retval.put("WSResource", subtypes); retval.put("WSResource", subtypes);
ScopeProvider.instance.set(currScope);
return retval; return retval;
} }
public static final List<String> getRelatedResources( public static final List<String> getRelatedResources(final CacheManager status, final String type, final String id, final ScopeBean queryScope) throws Exception {
final CacheManager status,
final String type,
final String id,
final GCUBEScope queryScope)
throws Exception {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGenericQuery isQuery = null;
isQuery = client.getQuery(GCUBEGenericQuery.class);
QueryLocation queryPath = null; QueryLocation queryPath = null;
try { try {
queryPath = QueryLocation.valueOf("LIST_RELATED_" + type); queryPath = QueryLocation.valueOf("LIST_RELATED_" + type);
@ -276,31 +292,38 @@ public class ISClientRequester {
ServerConsole.error(LOG_PREFIX, "Getting the resource query.", e); ServerConsole.error(LOG_PREFIX, "Getting the resource query.", e);
throw new Exception(e.getMessage()); throw new Exception(e.getMessage());
} }
isQuery.setExpression(QueryLoader.getQuery(queryPath));
isQuery.addParameters(new QueryParameter("RES_ID", id.trim()));
ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), //set the scope
isQuery.getExpression(), String currScope = ScopeProvider.instance.get();
"getResourceRelated"); ScopeProvider.instance.set(queryScope.toString());
List<XMLResult> results = null; QueryTemplate isQuery = new QueryTemplate(QueryLoader.getQuery(queryPath));
DiscoveryClient<String> client = client();
isQuery.addParameter("RES_ID", id.trim());
ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), isQuery.expression(), "getResourceRelated");
List<String> resultz = null;
// Handle cache // Handle cache
if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) {
results = CACHE.get(cacheKey); resultz = CACHE.get(cacheKey);
} else { } else {
results = client.execute(isQuery, queryScope); resultz = client.submit(isQuery);
if (status.isUsingCache()) { if (status.isUsingCache()) {
CACHE.insert(cacheKey, results); CACHE.insert(cacheKey, resultz);
} }
} }
if (results == null || results.size() == 0) { if (resultz == null || resultz.size() == 0) {
return null; return null;
} }
// ENDOF Handle cache // ENDOF Handle cache
List<String> retval = new Vector<String>(); List<String> retval = new ArrayList<String>();
for (XMLResult elem : results) { for (String elem : resultz) {
// Removes the resources with no ID or empty // Removes the resources with no ID or empty
try { try {
String toAdd = elem.toString(); String toAdd = elem.toString();
@ -313,71 +336,83 @@ public class ISClientRequester {
ServerConsole.debug(LOG_PREFIX, "[getResourcesRelated] found and invalid resource"); ServerConsole.debug(LOG_PREFIX, "[getResourcesRelated] found and invalid resource");
} }
} }
//ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type); ScopeProvider.instance.set(currScope);
ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type);
return retval; return retval;
} }
/**
public static final List<String> getResourcesByType( *
final CacheManager status, * @param status
final GCUBEScope queryScope, * @param queryScope
final String type, * @param type
final String subType) * @param subType
throws Exception { * @return
ISClient client = GHNContext.getImplementation(ISClient.class); * @throws Exception
GCUBEGenericQuery isQuery = null; */
isQuery = client.getQuery(GCUBEGenericQuery.class); public static final List<String> getResourcesByType(final CacheManager status, final ScopeBean queryScope, final String type, final String subType) throws Exception {
QueryLocation queryPath = null; QueryLocation queryPath = null;
QueryLocation returnPath = null;
try { try {
if (type.equals(ResourceTypeDecorator.WSResource.name())) { if (type.equals(ResourceTypeDecorator.WSResource.name())) {
queryPath = QueryLocation.GET_WSRES_DETAILS_BYSUBTYPE; queryPath = QueryLocation.GET_WSRES_DETAILS_BYSUBTYPE;
} else { } else {
queryPath = QueryLocation.valueOf("LIST_" + type); queryPath = QueryLocation.valueOf("LIST_" + type);
returnPath = QueryLocation.valueOf("RETURN_" + type);
} }
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, "Getting the resource query.", e); ServerConsole.error(LOG_PREFIX, "Getting the resource query.", e);
throw new Exception(e.getMessage()); throw new Exception(e.getMessage());
} }
isQuery.setExpression(QueryLoader.getQuery(queryPath)); //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 (type.equals(ResourceTypeDecorator.WSResource.name())) {
if (subType != null && subType.length() > 0) { if (subType != null && subType.length() > 0) {
isQuery.addParameters(new QueryParameter("RES_SUBTYPE", isQuery.addParameter("RES_SUBTYPE", subType.trim());
subType.trim()));
} }
} else { } else {
if (subType != null && subType.length() > 0) { if (subType != null && subType.length() > 0) {
if (subType.equalsIgnoreCase("User") || subType.equalsIgnoreCase("System")) { if (subType.equalsIgnoreCase("User") || subType.equalsIgnoreCase("System")) {
isQuery.addParameters(new QueryParameter("RES_SUBTYPE", " and $profiles/Profile/Body/CollectionInfo/user/text() = \"" + ((subType.trim().equals("User")) ? "true" : "false") + "\"")); isQuery.addParameter("RES_SUBTYPE", " and $profiles/Profile/Body/CollectionInfo/user/text() = \"" + ((subType.trim().equals("User")) ? "true" : "false") + "\"");
} }
else else
isQuery.addParameters(new QueryParameter("RES_SUBTYPE", "where $subtype = \"" + subType.trim() + "\"")); isQuery.addParameter("RES_SUBTYPE", "where $subtype = \"" + subType.trim() + "\"");
} }
} }
//add the return statement
isQuery.addParameter("RESOURCE", QueryLoader.getQuery(returnPath));
ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), ISQueryCacheKeyT cacheKey = new ISQueryCacheKeyT(queryScope.toString(), isQuery.expression(), "getResourcesTypes");
isQuery.getExpression(),
"getResourcesTypes");
List<XMLResult> results = null; List<String> resultz = null;
if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) { if (status.isUsingCache() && CACHE.contains(cacheKey) && CACHE.get(cacheKey) != null) {
results = CACHE.get(cacheKey); resultz = CACHE.get(cacheKey);
} else { } else {
results = client.execute(isQuery, queryScope); resultz = client.submit(isQuery);
if (status.isUsingCache()) { if (status.isUsingCache()) {
CACHE.insert(cacheKey, results); CACHE.insert(cacheKey, resultz);
} }
} }
if (results == null || results.size() == 0) { if (resultz == null || resultz.size() == 0) {
return null; return null;
} }
List<String> retval = new Vector<String>(); List<String> retval = new Vector<String>();
for (XMLResult elem : results) { for (String elem : resultz) {
// Removes the resources with no ID or empty // 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 { try {
if (elem.evaluate("//ID").get(0) != null && elem.evaluate("//ID").get(0).trim().length() > 0) { if (helper.evaluate("//ID").get(0) != null && helper.evaluate("//ID").get(0).trim().length() > 0) {
retval.add(elem.toString()); retval.add(elem.toString());
//ServerConsole.debug("", elem.toString());// Print the result //ServerConsole.debug("", elem.toString());// Print the result
} else { } else {
@ -389,45 +424,54 @@ public class ISClientRequester {
} }
} }
//ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type); //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type);
ScopeProvider.instance.set(currScope);
return retval; 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();
public static final List<ResourceDescriptor> getResourceModels(
final GCUBEScope queryScope,
final String type,
final String subType,
final List<Tuple<String>> additionalMaps)
throws Exception {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGenericQuery isQuery = null;
isQuery = client.getQuery(GCUBEGenericQuery.class);
if (subType != null && subType.trim().length() > 0) { if (subType != null && subType.trim().length() > 0) {
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_RES_DETAILS_BYSUBTYPE)); isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RES_DETAILS_BYSUBTYPE));
isQuery.addParameters( isQuery.addParameter("RES_TYPE", type.trim());
new QueryParameter("RES_TYPE", type) isQuery.addParameter("RES_SUBTYPE", subType.trim());
); //add the return statement
isQuery.addParameters( isQuery.addParameter("RESOURCE", QueryLoader.getQuery(QueryLocation.RETURN_GET_RES_DETAILS_BYSUBTYPE));
new QueryParameter("RES_SUBTYPE", subType)
);
} else { } else {
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_RES_DETAILS_BYTYPE)); isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RES_DETAILS_BYTYPE));
isQuery.addParameters( isQuery.addParameter("RES_TYPE", type);
new QueryParameter("RES_TYPE", type) isQuery.addParameter("RESOURCE", QueryLoader.getQuery(QueryLocation.RETURN_GET_RES_DETAILS_BYTYPE));
);
} }
List<XMLResult> results = client.execute(isQuery, queryScope); List<String> resultz = client.submit(isQuery);
List<ResourceDescriptor> retval = new Vector<ResourceDescriptor>(); List<ResourceDescriptor> retval = new Vector<ResourceDescriptor>();
ResourceDescriptor toAdd = null; ResourceDescriptor toAdd = null;
for (XMLResult elem : results) { for (String elem : resultz) {
// Removes the resources with no ID or empty // Removes the resources with no ID or empty
try { try {
if (elem.evaluate("//ID").get(0) != null) { 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( toAdd = new ResourceDescriptor(
elem.evaluate("//Type/text()").get(0), helper.evaluate("//Type/text()").get(0),
elem.evaluate("//SubType/text()").get(0), helper.evaluate("//SubType/text()").get(0),
elem.evaluate("//ID/text()").get(0), helper.evaluate("//ID/text()").get(0),
elem.evaluate("//Name/text()").get(0)); helper.evaluate("//Name/text()").get(0));
// Additional mappings can be defined by the requester. // Additional mappings can be defined by the requester.
// e.g. new Tuple("description", "//Profile/Description/text()"); // e.g. new Tuple("description", "//Profile/Description/text()");
@ -435,7 +479,7 @@ public class ISClientRequester {
for (Tuple<String> map : additionalMaps) { for (Tuple<String> map : additionalMaps) {
try { try {
toAdd.addProperty(map.get(0), toAdd.addProperty(map.get(0),
elem.evaluate(map.get(1)).get(0)); helper.evaluate(map.get(1)).get(0));
} catch (final Exception e) { } catch (final Exception e) {
toAdd.addProperty(map.get(0), toAdd.addProperty(map.get(0),
""); "");
@ -450,55 +494,68 @@ public class ISClientRequester {
} }
} }
//ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type); //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + type);
ScopeProvider.instance.set(currScope);
return retval; return retval;
} }
/**
*
* @param queryScope
* @return
* @throws Exception
*/
public static final List<String> getWSResources(final ScopeBean queryScope) throws Exception {
public static final List<String> getWSResources( List<String> resultz = null;
final GCUBEScope queryScope)
throws Exception { //set the scope
ISClient client = GHNContext.getImplementation(ISClient.class); String currScope = ScopeProvider.instance.get();
GCUBEGenericQuery isQuery = null; ScopeProvider.instance.set(queryScope.toString());
isQuery = client.getQuery(GCUBEGenericQuery.class);
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_WSRES_DETAILS_BYTYPE)); Query isQuery = new QueryBox(QueryLoader.getQuery(QueryLocation.GET_WSRES_DETAILS_BYTYPE));
List<XMLResult> results = client.execute(isQuery, queryScope); DiscoveryClient<String> client = client();
List<String> retval = new Vector<String>(); List<String> retval = new Vector<String>();
resultz = client.submit(isQuery);
for (XMLResult elem : results) { for (String elem : resultz) {
retval.add(elem.toString()); retval.add(elem.toString());
} }
//ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + ResourceTypeDecorator.WSResource.name()); //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") ServiceDetails for type: " + ResourceTypeDecorator.WSResource.name());
ScopeProvider.instance.set(currScope);
return retval; 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();
public static final CompleteResourceProfile getResourceByID(
final String xmlFilePath,
final GCUBEScope queryScope,
final String resType,
final String resID)
throws Exception {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGenericQuery isQuery = null;
isQuery = client.getQuery(GCUBEGenericQuery.class);
if (resType == null) { if (resType == null) {
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_RESOURCE_BYID)); isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RESOURCE_BYID));
isQuery.addParameters( isQuery.addParameter("RES_ID", resID);
new QueryParameter("RES_ID", resID)
);
} else if (resType.equalsIgnoreCase(ResourceTypeDecorator.WSResource.name())) { } else if (resType.equalsIgnoreCase(ResourceTypeDecorator.WSResource.name())) {
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_WSRESOURCE_BYID)); isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_WSRESOURCE_BYID));
isQuery.addParameters( isQuery.addParameter("RES_ID", resID);
new QueryParameter("RES_ID", resID)
);
} else { } else {
isQuery.setExpression(QueryLoader.getQuery(QueryLocation.GET_RESOURCE_BYID)); isQuery = new QueryTemplate(QueryLoader.getQuery(QueryLocation.GET_RESOURCE_BYID));
isQuery.addParameters( isQuery.addParameter("RES_ID", resID);
new QueryParameter("RES_ID", resID), isQuery.addParameter("RES_TYPE", resType);
new QueryParameter("RES_TYPE", resType)
);
} }
List<XMLResult> results = client.execute(isQuery, queryScope); List<String> results = client.submit(isQuery);
//ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") Resource for ID: " + resID); //ServerConsole.trace(LOG_PREFIX, "Retrieved (" + retval.size() + ") Resource for ID: " + resID);
@ -507,7 +564,10 @@ public class ISClientRequester {
String type = null; String type = null;
if (resType == null) { if (resType == null) {
try { try {
type = results.get(0).evaluate("/Resource/Type/text()").get(0); 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) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
} }
@ -516,8 +576,10 @@ public class ISClientRequester {
} }
String xmlRepresentation = results.get(0).toString(); String xmlRepresentation = results.get(0).toString();
String htmlRepresentation = XML2HTML(xmlRepresentation, xmlFilePath); String htmlRepresentation = XML2HTML(xmlRepresentation, xmlFilePath);
ScopeProvider.instance.set(currScope);
return new CompleteResourceProfile(resID, ResourceTypeDecorator.valueOf(type), getResourceName(type, resID, results.get(0)), xmlRepresentation, htmlRepresentation); return new CompleteResourceProfile(resID, ResourceTypeDecorator.valueOf(type), getResourceName(type, resID, results.get(0)), xmlRepresentation, htmlRepresentation);
} }
ScopeProvider.instance.set(currScope);
return null; return null;
} }
@ -656,7 +718,7 @@ public class ISClientRequester {
NodeList params = doc.getElementsByTagName("param"); NodeList params = doc.getElementsByTagName("param");
ArrayList<TMPluginFormField> formFields = new ArrayList<TMPluginFormField>(); ArrayList<TMPluginFormField> formFields = new ArrayList<TMPluginFormField>();
for (int i = 0; i < params.getLength(); i++) { for (int i = 0; i < params.getLength(); i++) {
NodeList paramTree = params.item(i).getChildNodes(); NodeList paramTree = params.item(i).getChildNodes();
@ -683,14 +745,14 @@ public class ISClientRequester {
formFields = getPluginFormFromXml(xmlToParse); formFields = getPluginFormFromXml(xmlToParse);
} }
} }
// if (params.getLength()>1) // if (params.getLength()>1)
retval.put(name + ":" + requestName, formFields); retval.put(name + ":" + requestName, formFields);
} }
if (foundRequest == false){ if (foundRequest == false){
retval.put(name, formFields); retval.put(name, formFields);
} }
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
continue gonext; continue gonext;
@ -762,69 +824,80 @@ public class ISClientRequester {
* @param ID the identifier of the resource * @param ID the identifier of the resource
* @param node the XML node from which retrieve the information * @param node the XML node from which retrieve the information
* @return * @return
* @throws IOException
* @throws SAXException
*/ */
private static String getResourceName(String type, String ID, XMLResult node) { 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())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.GHN.name())) {
try { try {
return node.evaluate("/Resource/Profile/GHNDescription/Name/text()").get(0); return helper.evaluate("/Resource/Profile/GHNDescription/Name/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.Collection.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.Collection.name())) {
try { try {
return node.evaluate("/Resource/Profile/Name/text()").get(0); return helper.evaluate("/Resource/Profile/Name/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.Service.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.Service.name())) {
try { try {
return node.evaluate("/Resource/Profile/Name/text()").get(0); return helper.evaluate("/Resource/Profile/Name/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.RunningInstance.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.RunningInstance.name())) {
try { try {
return node.evaluate("/Resource/Profile/ServiceName/text()").get(0); return helper.evaluate("/Resource/Profile/ServiceName/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.VIEW.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.VIEW.name())) {
try { try {
return node.evaluate("/Resource/Profile/Name/text()").get(0); return helper.evaluate("/Resource/Profile/Name/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.RuntimeResource.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.RuntimeResource.name())) {
try { try {
return node.evaluate("/Resource/Profile/Name/text()").get(0); return helper.evaluate("/Resource/Profile/Name/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.GenericResource.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.GenericResource.name())) {
try { try {
return node.evaluate("/Resource/Profile/Name/text()").get(0); return helper.evaluate("/Resource/Profile/Name/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
if (type.equalsIgnoreCase(ResourceTypeDecorator.WSResource.name())) { if (type.equalsIgnoreCase(ResourceTypeDecorator.WSResource.name())) {
try { try {
return node.evaluate("/Document/Data/child::*[local-name()='ServiceName']/text()").get(0); return helper.evaluate("/Document/Data/child::*[local-name()='ServiceName']/text()").get(0);
} catch (Exception e) { } catch (Exception e) {
return ID; return ID;
} }
} }
return null; return null;
} }
/**
public static String XML2HTML(final String xml, final String xslt) * transform an xml in a readable xml by using HTML
throws Exception { * @param xml
* @param xslt
* @return
* @throws Exception
*/
public static String XML2HTML(final String xml, final String xslt) throws Exception {
TransformerFactory tf = TransformerFactory.newInstance(); TransformerFactory tf = TransformerFactory.newInstance();
InputStream stream = new FileInputStream(xslt); InputStream stream = new FileInputStream(xslt);

View File

@ -67,9 +67,9 @@ class ISQueryCacheKeyT {
* *
*/ */
public class ISQueryCache { public class ISQueryCache {
Map<ISQueryCacheKeyT, List<XMLResult>> results = new HashMap<ISQueryCacheKeyT, List<XMLResult>>(); Map<ISQueryCacheKeyT, List<String>> results = new HashMap<ISQueryCacheKeyT, List<String>>();
public void insert(ISQueryCacheKeyT key, List<XMLResult> elem) { public void insert(ISQueryCacheKeyT key, List<String> elem) {
this.results.put(key, elem); this.results.put(key, elem);
} }
@ -80,7 +80,7 @@ public class ISQueryCache {
return this.results.containsKey(key); return this.results.containsKey(key);
} }
public List<XMLResult> get(ISQueryCacheKeyT key) { public List<String> get(ISQueryCacheKeyT key) {
if (key != null && this.results.containsKey(key)) { if (key != null && this.results.containsKey(key)) {
return this.results.get(key); return this.results.get(key);
} }

View File

@ -33,12 +33,18 @@ public enum QueryLocation {
// Customized queries to retrieve the relevant data from resources // Customized queries to retrieve the relevant data from resources
// according to their type // according to their type
LIST_GHN("resources/GHN.xq"), LIST_GHN("resources/GHN.xq"),
RETURN_GHN("resources/RETURN_GHN.xq"),
LIST_Collection("resources/Collection.xq"), LIST_Collection("resources/Collection.xq"),
RETURN_Collection("resources/RETURN_Collection.xq"),
LIST_VIEW("resources/VIEW.xq"), LIST_VIEW("resources/VIEW.xq"),
LIST_Service("resources/Service.xq"), LIST_Service("resources/Service.xq"),
RETURN_Service("resources/RETURN_Service.xq"),
LIST_GenericResource("resources/GenericResource.xq"), LIST_GenericResource("resources/GenericResource.xq"),
RETURN_GenericResource("resources/RETURN_GenericResource.xq"),
LIST_RunningInstance("resources/RunningInstance.xq"), LIST_RunningInstance("resources/RunningInstance.xq"),
RETURN_RunningInstance("resources/RETURN_RunningInstance.xq"),
LIST_RuntimeResource("resources/RuntimeResource.xq"), LIST_RuntimeResource("resources/RuntimeResource.xq"),
RETURN_RuntimeResource("resources/RETURN_RuntimeResource.xq"),
// To retrieve the list of generic resources publishing plugins // To retrieve the list of generic resources publishing plugins
// to deploy activation records // to deploy activation records
@ -60,7 +66,9 @@ public enum QueryLocation {
// Used to build the gwt model representation inside dialogs. // Used to build the gwt model representation inside dialogs.
// see getResourceModels inside ISClientRequester. // see getResourceModels inside ISClientRequester.
GET_RES_DETAILS_BYTYPE("getResourcesDetails.xq"), GET_RES_DETAILS_BYTYPE("getResourcesDetails.xq"),
RETURN_GET_RES_DETAILS_BYTYPE("RETURN_getResourcesDetails.xq"),
GET_RES_DETAILS_BYSUBTYPE("getResourcesDetailsSubtype.xq"), GET_RES_DETAILS_BYSUBTYPE("getResourcesDetailsSubtype.xq"),
RETURN_GET_RES_DETAILS_BYSUBTYPE("RETURN_getResourcesDetailsSubtype.xq"),
GET_RESOURCE_BYID("getResourceByID.xq"), GET_RESOURCE_BYID("getResourceByID.xq"),
GET_WSRES_TYPES("getWSResourcesTypes.xq"), GET_WSRES_TYPES("getWSResourcesTypes.xq"),

View File

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

View File

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

View File

@ -1,8 +1,3 @@
# for $resource in collection('/db/Profiles/<RES_TYPE ISdefault ='' />')//Resource
# Params: RES_ID the ID of looked up resource
# RES_TYPE (option) the type of searched resource
for $resource in collection('/db/Profiles/<RES_TYPE ISdefault =''>')//Resource
where $resource/ID/string() eq '<RES_ID/>' where $resource/ID/string() eq '<RES_ID/>'
return $resource return $resource

View File

@ -4,7 +4,7 @@
# RES_TYPE the main type of the resource # RES_TYPE the main type of the resource
# This query is used by forms # This query is used by forms
for $profiles in collection('/db/Profiles/<RES_TYPE ISdefault ='GHN'>')//Resource for $profiles in collection('/db/Profiles/<RES_TYPE ISdefault ='GHN' />')//Resource
let $ghn-name := $profiles//Resource/Profile/GHN/@UniqueID/string() 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 $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 $ghn-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'GHN-distribution-version']/Value/text()
@ -26,11 +26,4 @@ let $subtype :=
then "System" then "System"
else "" else ""
return return
<Resource> <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>

View File

@ -4,7 +4,7 @@
# RES_TYPE the main type of the resource # RES_TYPE the main type of the resource
# This query is used by forms # This query is used by forms
for $profiles in collection('/db/Profiles/<RES_TYPE ISdefault ='GHN'>')//Resource for $profiles in collection('/db/Profiles/<RES_TYPE ISdefault ='GHN' />')//Resource
let $ghn-name := $profiles//Resource/Profile/GHN/@UniqueID/string() 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 $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 $ghn-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'GHN-distribution-version']/Value/text()
@ -27,11 +27,4 @@ let $subtype :=
else "" else ""
where $subtype eq '<RES_SUBTYPE ISdefault='isti.cnr.it'/>' where $subtype eq '<RES_SUBTYPE ISdefault='isti.cnr.it'/>'
return return
<Resource> <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>

View File

@ -24,4 +24,4 @@ let $subtypes :=
--> -->
for $subtype in distinct-values($subtypes) for $subtype in distinct-values($subtypes)
return return
<subtype>{$subtype}</subtype> <SUBTYPE/>

View File

@ -1,23 +1,8 @@
<!--
RES_SUBTYPE subtype parameters can be passed by expressing:
where $subtype = "TheSubType" and $wsresource/Data//child::*[local-name()='Type'][0]/string() eq 'gDocRead'
-->
for $profiles in collection('/db/Profiles/GenericResource')//Resource, $wsresource in collection('/db/Properties')//Document for $profiles in collection('/db/Profiles/GenericResource')//Resource, $wsresource in collection('/db/Properties')//Document
let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') let $scopes := string-join( $profiles/Scopes//Scope/text(), ';')
let $subtype := $profiles//Resource/Profile/SecondaryType/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' 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 =''/> <RES_SUBTYPE ISdefault =''/>
return return
<Resource> <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>

View File

@ -1,8 +1,3 @@
<!--
gets the compressed description of all GHNs published in a scope
-->
for $profiles in collection('/db/Profiles/GHN')//Resource for $profiles in collection('/db/Profiles/GHN')//Resource
let $gcf-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'gCF-version']/Value/text() 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 $ghn-version := $profiles//Resource/Profile/GHNDescription/RunTimeEnv/Variable[Key/text() = 'GHN-distribution-version']/Value/text()
@ -10,21 +5,4 @@ let $scopes := string-join( $profiles/Scopes//Scope/text(), ';')
let $subtype := $profiles//Resource/Profile/Site/Domain/text() let $subtype := $profiles//Resource/Profile/Site/Domain/text()
<RES_SUBTYPE ISdefault =''/> <RES_SUBTYPE ISdefault =''/>
return return
<Resource> <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>

View File

@ -1,16 +1,6 @@
for $profiles in collection('/db/Profiles/GenericResource')//Resource for $profiles in collection('/db/Profiles/GenericResource')//Resource
let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') let $scopes := string-join( $profiles/Scopes//Scope/text(), ';')
let $subtype := $profiles//Resource/Profile/SecondaryType/text() let $subtype := $profiles//Resource/Profile/SecondaryType/text()
<RES_SUBTYPE ISdefault =''/> <RES_SUBTYPE ISdefault =''/>
return return
<Resource> <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>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,9 +1,4 @@
for $profiles in collection('/db/Profiles/RunningInstance')//Resource for $profiles in collection('/db/Profiles/RunningInstance')//Resource
<!--
let $ghn-name := $profiles/Profile/GHN/@UniqueID/string()
-->
let $ghns := collection('/db/Profiles/GHN')//Resource let $ghns := collection('/db/Profiles/GHN')//Resource
let $_ghn-name := for $ghn in $ghns let $_ghn-name := for $ghn in $ghns
where $ghn/ID/string() eq $profiles/Profile/GHN/@UniqueID/string() where $ghn/ID/string() eq $profiles/Profile/GHN/@UniqueID/string()
@ -13,14 +8,4 @@ let $scopes := string-join( $profiles/Scopes//Scope/text(), ';')
let $subtype := $profiles/Profile/ServiceClass/text() let $subtype := $profiles/Profile/ServiceClass/text()
<RES_SUBTYPE ISdefault =''/> <RES_SUBTYPE ISdefault =''/>
return return
<Resource> <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>

View File

@ -3,10 +3,5 @@ let $scopes := string-join( $profiles/Scopes//Scope/text(), ';')
let $subtype := $profiles//Resource/Profile/Category/text() let $subtype := $profiles//Resource/Profile/Category/text()
<RES_SUBTYPE ISdefault =''/> <RES_SUBTYPE ISdefault =''/>
return return
<Resource> <RESOURCE/>
{$profiles//Resource/ID}
<Type>{$profiles//Resource/Type/text()}</Type>
<SubType>{$subtype}</SubType>
<Scopes>{$scopes}</Scopes>
<Name>{$profiles//Resource/Profile/Name/text()}</Name>
</Resource>

View File

@ -1,18 +1,6 @@
for $profiles in collection('/db/Profiles/Service')//Resource for $profiles in collection('/db/Profiles/Service')//Resource
let $scopes := string-join( $profiles/Scopes//Scope/text(), ';') let $scopes := string-join( $profiles/Scopes//Scope/text(), ';')
let $subtype := $profiles//Resource/Profile/Class/text() let $subtype := $profiles//Resource/Profile/Class/text()
<RES_SUBTYPE ISdefault =''/> <RES_SUBTYPE ISdefault =''/>
return return
<Resource> <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>
<!-- if many software defined takes the version of the first one -->
<Version>{$profiles//Resource/Profile/Packages/Software[1]/Version/text()}</Version>
<Shareable>{$profiles//Resource/Profile/Packages/Software/Shareable/string(@level)}</Shareable>
</Resource>

View File

@ -16,24 +16,20 @@
package org.gcube.resourcemanagement.support.server.managers.resources; package org.gcube.resourcemanagement.support.server.managers.resources;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random;
import java.util.Vector; import java.util.Vector;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.XMLResult;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBERIQuery;
import org.gcube.common.core.informationsystem.publisher.ISPublisher;
import org.gcube.common.core.resources.GCUBEResource;
import org.gcube.common.core.resources.GCUBERunningInstance;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.scope.GCUBEScope.Type;
import org.gcube.common.core.security.GCUBESecurityManagerImpl; import org.gcube.common.core.security.GCUBESecurityManagerImpl;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.resources.gcore.ScopeGroup;
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.RegistryPublisher;
import org.gcube.informationsystem.publisher.RegistryPublisherFactory;
import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException;
@ -41,20 +37,19 @@ import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterE
import org.gcube.resourcemanagement.support.server.managers.report.ReportBuilder; 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.ReportEntry;
import org.gcube.resourcemanagement.support.server.managers.report.ReportOperation; import org.gcube.resourcemanagement.support.server.managers.report.ReportOperation;
import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager;
import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes;
import org.gcube.resourcemanagement.support.server.utils.Assertion; import org.gcube.resourcemanagement.support.server.utils.Assertion;
import org.gcube.resourcemanagement.support.server.utils.ServerConsole; import org.gcube.resourcemanagement.support.server.utils.ServerConsole;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.vremanagement.resourcemanager.stubs.binder.AddResourcesParameters; import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.vremanagement.resourcemanager.stubs.binder.RemoveResourcesParameters; import org.gcube.resources.discovery.client.queries.impl.QueryBox;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceBinderPortType; import org.gcube.vremanagement.resourcemanager.client.RMBinderLibrary;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceItem; import org.gcube.vremanagement.resourcemanager.client.RMReportingLibrary;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceList; import org.gcube.vremanagement.resourcemanager.client.fws.Types.AddResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.binder.service.ResourceBinderServiceAddressingLocator; import org.gcube.vremanagement.resourcemanager.client.fws.Types.RemoveResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.reporting.ReportingPortType; import org.gcube.vremanagement.resourcemanager.client.fws.Types.ResourceItem;
import org.gcube.vremanagement.resourcemanager.stubs.reporting.service.ReportingServiceAddressingLocator; 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. * The minimal interface all the resource managers must implement.
@ -68,16 +63,15 @@ public abstract class AbstractResourceManager {
private String name = null; private String name = null;
private AllowedResourceTypes type = null; private AllowedResourceTypes type = null;
private String subType = null; private String subType = null;
private ISClient client = null;
private GCUBESecurityManagerImpl managerSec = null; private GCUBESecurityManagerImpl managerSec = null;
private ISPublisher publisher = null; private RegistryPublisher publisher = null;
private static final String LOG_PREFIX = "[AbstractResMgr]"; private static final String LOG_PREFIX = "[AbstractResMgr]";
/** /**
* @deprecated discouraged use. With no ID some operations cannot be accessed. For internal use only. * @deprecated discouraged use. With no ID some operations cannot be accessed. For internal use only.
*/ */
public AbstractResourceManager(final AllowedResourceTypes type) public AbstractResourceManager(final AllowedResourceTypes type)
throws ResourceParameterException, ResourceAccessException { throws ResourceParameterException, ResourceAccessException {
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>(); Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(type != null, new ResourceParameterException("Invalid Parameter type")); checker.validate(type != null, new ResourceParameterException("Invalid Parameter type"));
@ -93,13 +87,7 @@ public abstract class AbstractResourceManager {
}; };
try { try {
client = GHNContext.getImplementation(ISClient.class); this.publisher = RegistryPublisherFactory.create();
} catch (Exception e) {
throw new ResourceAccessException("Cannot instantiate the ISClient");
}
try {
this.publisher = GHNContext.getImplementation(ISPublisher.class);
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
} }
@ -114,10 +102,7 @@ public abstract class AbstractResourceManager {
* @throws ResourceParameterException * @throws ResourceParameterException
* @throws ResourceAccessException * @throws ResourceAccessException
*/ */
public AbstractResourceManager( public AbstractResourceManager(String id, AllowedResourceTypes type) throws ResourceParameterException, ResourceAccessException {
final String id,
final AllowedResourceTypes type)
throws ResourceParameterException, ResourceAccessException {
this(type); this(type);
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>(); Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
@ -126,45 +111,27 @@ public abstract class AbstractResourceManager {
this.id = id.trim(); this.id = id.trim();
} }
public AbstractResourceManager( public AbstractResourceManager(String id, String name, AllowedResourceTypes type) throws ResourceParameterException, ResourceAccessException {
final String id,
final String name,
final AllowedResourceTypes type) throws ResourceParameterException, ResourceAccessException {
this(id, type); this(id, type);
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>(); Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(name != null && name.trim().length() > 0, new ResourceParameterException("Invalid Parameter name")); checker.validate(name != null && name.trim().length() > 0, new ResourceParameterException("Invalid Parameter name"));
this.name = name; this.name = name;
} }
public AbstractResourceManager( public AbstractResourceManager(String id, String name, AllowedResourceTypes type, String subtype) throws ResourceParameterException, ResourceAccessException {
final String id,
final String name,
final AllowedResourceTypes type,
final String subtype)
throws ResourceParameterException, ResourceAccessException {
this(id, name, type); this(id, name, type);
if (subtype != null) { if (subtype != null) {
this.subType = subtype.trim(); this.subType = subtype.trim();
} }
} }
/**
* The singleton ISClient instance is preferred.
* All resource managers can internally access this instance
* to make queries to the IS.
* @return
*/
protected final ISClient getISClient() {
return this.client;
}
/** /**
* The singleton ISPublisher instance is preferred. * The singleton ISPublisher instance is preferred.
* All resource managers can internally access this instance * All resource managers can internally access this instance
* to interact with ISPublisher to handle resources. * to interact with ISPublisher to handle resources.
* @return * @return
*/ */
public final ISPublisher getISPublisher() { public final RegistryPublisher getRegistryPublisher() {
return publisher; return publisher;
} }
@ -226,134 +193,6 @@ public abstract class AbstractResourceManager {
return this.subType; return this.subType;
} }
/**
* Internally used by {@link AbstractResourceManager#getResourceManager(GCUBEScope)}.
* @param scope
* @return a raw list of resource manager descriptors.
* @throws Exception
*/
private List<GCUBERunningInstance> getResourceManagerFromScope(final GCUBEScope scope) throws Exception {
System.out.println("Looking for ResourceManager in scope: " + scope);
GCUBERIQuery query = this.client.getQuery(GCUBERIQuery.class);
query.addAtomicConditions(new AtomicCondition("//Profile/ServiceClass", "VREManagement"));
query.addAtomicConditions(new AtomicCondition("//Profile/ServiceName", "ResourceManager"));
List<GCUBERunningInstance> result = client.execute(query, scope);
List<GCUBERunningInstance> toReturn = new ArrayList<GCUBERunningInstance>();
for (GCUBERunningInstance ri : result) {
if (ri.getScopes().containsValue(scope)) {
toReturn.add(ri);
}
}
System.out.println("Found " + toReturn.size() +" ResourceManager in scope: " + scope);
return toReturn;
}
/**
* The the list of resource managers able to handle the resource in a given scope.
* @param scope the scope in which to operate
* @return all the available managers
* @throws ResourceAccessException if no manager can be instantiated
* @throws ResourceParameterException if the parameters are invalid
*/
public final List<ResourceBinderPortType> getResourceManagers(final GCUBEScope scope) throws ResourceAccessException, ResourceParameterException {
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(scope != null, new ResourceParameterException("Invalid scope"));
List<GCUBERunningInstance> resourceManagerList = null;
try {
resourceManagerList = this.getResourceManagerFromScope(scope);
} catch (Exception e) {
e.printStackTrace();
throw new ResourceAccessException("Cannot retrieve the managers for resource: " + this.getID());
}
List<ResourceBinderPortType> retval = new Vector<ResourceBinderPortType>();
if (resourceManagerList.isEmpty()) {
System.out.println("\n\n\n\n\n****** Schianta qui size: " + resourceManagerList.size() + " scope: " + scope);
throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getType() + " in scope: " + scope.toString());
}
EndpointReferenceType endpoint = null;
ResourceBinderPortType pt = null;
for (GCUBERunningInstance resourceManager : resourceManagerList) {
try {
endpoint = resourceManager.getAccessPoint().getEndpoint("gcube/vremanagement/resourcemanager/binder");
pt = GCUBERemotePortTypeContext.getProxy(
new ResourceBinderServiceAddressingLocator()
.getResourceBinderPortTypePort(endpoint),
scope,
this.managerSec);
if (pt != null) {
retval.add(pt);
}
} catch (Throwable e) {
// trying on next entry
ServerConsole.error(LOG_PREFIX, e);
}
}
if (retval != null && retval.size() > 0) {
// Return a random manager from the available ones
return retval;
}
// no managers found
throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getID() + "in scope: " + scope.toString());
}
/**
* The the list of resource report managers able to handle the resource in a given scope.
* @param scope the scope in which to operate
* @return all the available managers
* @throws ResourceAccessException if no manager can be instantiated
* @throws ResourceParameterException if the parameters are invalid
*/
public final List<ReportingPortType> getResourceReportManagers(final GCUBEScope scope) throws ResourceAccessException, ResourceParameterException {
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(scope != null, new ResourceParameterException("Invalid scope"));
List<GCUBERunningInstance> resourceManagerList = null;
try {
resourceManagerList = this.getResourceManagerFromScope(scope);
} catch (Exception e) {
e.printStackTrace();
throw new ResourceAccessException("Cannot retrieve the managers for resource: " + this.getID());
}
List<ReportingPortType> retval = new Vector<ReportingPortType>();
if (resourceManagerList.isEmpty()) {
throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getType() + " in scope: " + scope.toString());
}
EndpointReferenceType endpoint = null;
ReportingPortType pt = null;
for (GCUBERunningInstance resourceManager : resourceManagerList) {
try {
endpoint = resourceManager.getAccessPoint().getEndpoint("gcube/vremanagement/resourcemanager/reporting");
pt = GCUBERemotePortTypeContext.getProxy(
new ReportingServiceAddressingLocator().getReportingPortTypePort(endpoint),
scope,
this.managerSec);
if (pt != null) {
retval.add(pt);
}
} catch (Throwable e) {
// trying on next entry
ServerConsole.error(LOG_PREFIX, e);
}
}
if (retval != null && retval.size() > 0) {
// Return a random report manager from the available ones
return retval;
}
// no managers found
throw new ResourceAccessException("Unable to find ReportResourceManagers for resource " + this.getID() + "in scope: " + scope.toString());
}
/** /**
* The resource manager needed to handle the resource in a given scope. * The resource manager needed to handle the resource in a given scope.
* @param scope the scope in which to operate * @param scope the scope in which to operate
@ -361,21 +200,22 @@ public abstract class AbstractResourceManager {
* @throws ResourceAccessException if no manager can be instantiated * @throws ResourceAccessException if no manager can be instantiated
* @throws ResourceParameterException if the parameters are invalid * @throws ResourceParameterException if the parameters are invalid
*/ */
public final ResourceBinderPortType getResourceManager(final GCUBEScope scope) public final RMBinderLibrary getResourceManager(String scope) throws AbstractResourceException {
throws AbstractResourceException { String currScope = ScopeProvider.instance.get();
ServerConsole.info(LOG_PREFIX, "Getting Resource Manager in scope [" + scope.toString() + "]"); ScopeBean bscope = new ScopeBean(scope);
if (bscope.is(Type.VRE)) {
List<ResourceBinderPortType> retval = this.getResourceManagers(scope); scope = bscope.enclosingScope().toString();
if (retval != null && retval.size() > 0) {
Random generator = new Random();
// Return a random manager from the available ones
ResourceBinderPortType manager = retval.get(generator.nextInt(retval.size()));
return manager;
} }
// no managers found ScopeProvider.instance.set(scope);
throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getType() + " in scope: " + scope.toString()); 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());
}
ScopeProvider.instance.set(currScope);
return rml;
} }
/** /**
* The report resource manager needed to handle the resource in a given scope. * The report resource manager needed to handle the resource in a given scope.
* @param scope the scope in which to operate * @param scope the scope in which to operate
@ -383,19 +223,21 @@ public abstract class AbstractResourceManager {
* @throws ResourceAccessException if no manager can be instantiated * @throws ResourceAccessException if no manager can be instantiated
* @throws ResourceParameterException if the parameters are invalid * @throws ResourceParameterException if the parameters are invalid
*/ */
public final ReportingPortType getReportResourceManager(final GCUBEScope scope) public final RMReportingLibrary getReportResourceManager(String scope) throws AbstractResourceException {
throws AbstractResourceException { String currScope = ScopeProvider.instance.get();
ServerConsole.info(LOG_PREFIX, "Getting Resource Manager in scope [" + scope.toString() + "]"); ScopeBean bscope = new ScopeBean(scope);
if (bscope.is(Type.VRE)) {
List<ReportingPortType> retval = this.getResourceReportManagers(scope); scope = bscope.enclosingScope().toString();
if (retval != null && retval.size() > 0) {
Random generator = new Random();
// Return a random manager from the available ones
ReportingPortType manager = retval.get(generator.nextInt(retval.size()));
return manager;
} }
// no managers found ScopeProvider.instance.set(scope);
throw new ResourceAccessException("Unable to find ResourceManagers for resource " + this.getType() + " in scope: " + scope.toString());
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());
}
ScopeProvider.instance.set(currScope);
return rml;
} }
/** /**
@ -408,7 +250,7 @@ public abstract class AbstractResourceManager {
* @return * @return
* @throws ResourceOperationException * @throws ResourceOperationException
*/ */
private String bindToScope(final GCUBEScope targetScope) throws AbstractResourceException { private String bindToScope(final String targetScope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(targetScope != null, new ResourceParameterException("Invalid parameter targetScope. 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.")); checker.validate(this.getID() != null, new ResourceOperationException("Invalid resource ID. null not allowed."));
@ -416,37 +258,47 @@ public abstract class AbstractResourceManager {
ServerConsole.trace( ServerConsole.trace(
LOG_PREFIX, LOG_PREFIX,
"[BIND-SCOPE-ENTER] Adding " + this.getType() + " " + this.getID() + " to scope [" + "[BIND-SCOPE-ENTER] Adding " + this.getType() + " " + this.getID() + " to scope [" +
targetScope.toString() + "]"); targetScope.toString() + "]");
AddResourcesParameters addParam = new AddResourcesParameters(); AddResourcesParameters addParam = new AddResourcesParameters();
ResourceItem toAdd = new ResourceItem(); ResourceItem toAdd = new ResourceItem();
toAdd.setID(this.getID()); toAdd.setId(this.getID());
toAdd.setType(this.getType().name()); toAdd.setType(this.getType().name());
ResourceList r = new ResourceList(); ResourceList r = new ResourceList();
ArrayList<ResourceItem> temp = new ArrayList<ResourceItem>();
r.setResource(new ResourceItem[]{toAdd}); temp.add(toAdd);
r.setResource(temp);
addParam.setResources(r); addParam.setResources(r);
addParam.setTargetScope(targetScope.toString()); addParam.setTargetScope(targetScope.toString());
ResourceBinderPortType manager = this.getResourceManager(targetScope); RMBinderLibrary manager = this.getResourceManager(targetScope);
try { try {
String curr = ScopeProvider.instance.get();
ScopeBean scope = new ScopeBean(targetScope);
if (scope.is(Type.VRE)) {
ScopeProvider.instance.set(scope.enclosingScope().toString());
} else
ScopeProvider.instance.set(targetScope);
String reportID = manager.addResources(addParam); String reportID = manager.addResources(addParam);
ServerConsole.trace( ServerConsole.trace(
LOG_PREFIX, LOG_PREFIX,
"[BIND-SCOPE-EXIT] Applyed Adding " + this.getType() + " " + this.getID() + " to scope [" + "[BIND-SCOPE-EXIT] Applyed Adding " + this.getType() + " " + this.getID() + " to scope [" +
targetScope.toString() + "]... reportID: " + reportID); targetScope.toString() + "]... reportID: " + reportID);
RMReportingLibrary pt = this.getReportResourceManager(scope.toString());
ReportingPortType pt = this.getReportResourceManager(targetScope); String toReturn = pt.getReport(reportID);
return pt.getReport(reportID); ScopeProvider.instance.set(curr);
return toReturn;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ServerConsole.trace( ServerConsole.trace(
LOG_PREFIX, LOG_PREFIX,
"[BIND-SCOPE-EXIT] [FAILURE]"); "[BIND-SCOPE-EXIT] [FAILURE]");
throw new ResourceOperationException("During resource::addToScope: " + e.getMessage()); throw new ResourceOperationException("During resource::addToScope: "+ targetScope + " Message: \n" + e.getMessage());
} }
} }
@ -457,9 +309,7 @@ public abstract class AbstractResourceManager {
* @param nestingPublication true for resources different from gHN and RI. * @param nestingPublication true for resources different from gHN and RI.
* @return the reportID generated * @return the reportID generated
*/ */
public final String addToExistingScope( public final String addToExistingScope(final ScopeBean sourceScope, final ScopeBean targetScope) throws AbstractResourceException {
final GCUBEScope sourceScope, final GCUBEScope targetScope)
throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(sourceScope != null, new ResourceParameterException("Invalid parameter sourceScope. null not allowed.")); 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(targetScope != null, new ResourceParameterException("Invalid parameter targetScope. null not allowed."));
@ -470,34 +320,36 @@ public abstract class AbstractResourceManager {
ServerConsole.trace( ServerConsole.trace(
LOG_PREFIX, LOG_PREFIX,
"[ADD-ToExistingScope] Adding from scope [" + "[ADD-ToExistingScope] Adding from scope [" +
sourceScope.toString() + sourceScope.toString() +
"] to existing scope [" + "] to existing scope [" +
targetScope.toString() + targetScope.toString() +
"] " + this.getType() + " " + this.getID()); "] " + this.getType() + " " + this.getID());
// If not RI or GHN and the scopes are sibling and VO copyFromToVO // If not RI or GHN and the scopes are sibling and VO copyFromToVO
if (!(this.getType() == AllowedResourceTypes.GHN) && if (!(this.getType() == AllowedResourceTypes.GHN) &&
!(this.getType() == AllowedResourceTypes.RunningInstance) && !(this.getType() == AllowedResourceTypes.RunningInstance) &&
sourceScope.getType() == Type.VO && targetScope.getType() == Type.VO) { sourceScope.type() == Type.VO && targetScope.type() == Type.VO) {
return copyFromToVO(sourceScope, targetScope); return copyFromToVO(sourceScope, targetScope);
} }
// Add a gCube Resource to // Add a gCube Resource to
// (i) a VRE scope from the parent VO or // (i) a VRE scope from the parent VO or
// (ii) a VO scope from the infrastructure scope // (ii) a VO scope from the infrastructure scope
if (!targetScope.isEnclosedIn(sourceScope)) { if (!targetScope.toString().contains(sourceScope.toString())) {
throw new ResourceOperationException( throw new ResourceOperationException(
"You are not allowed to apply to this scope. Target scope is not enclosed in the source one."); "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, report.addEntry(new ReportEntry(ReportOperation.AddToScope, this,
"Added " + this.getType() + " " + this.getID() + " to parent scope " + "Added " + this.getType() + " " + this.getID() + " to parent scope " +
targetScope.toString() + " the remote report ID is: " + targetScope.toString() + " the remote report ID is: " +
this.bindToScope(targetScope), true)); this.bindToScope(targetScope.toString()), true));
return report.getXML(); return report.getXML();
} }
/** /**
* Similar to the {@link AbstractResourceManager#addToExistingScope} method but involves * Similar to the {@link AbstractResourceManager#addToExistingScope} method but involves
* two scopes of type VO. * two scopes of type VO.
@ -510,17 +362,16 @@ public abstract class AbstractResourceManager {
* @return * @return
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
public final String copyFromToVO(final GCUBEScope sourceScope, final GCUBEScope targetScope) public final String copyFromToVO(final ScopeBean sourceScope, final ScopeBean targetScope) throws AbstractResourceException {
throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate( checker.validate(
sourceScope != null && sourceScope.getType() == Type.VO, sourceScope != null && sourceScope.type() == Type.VO,
new ResourceParameterException("The sourceScope is invalid or not of type VO.")); new ResourceParameterException("The sourceScope is invalid or not of type VO."));
checker.validate( checker.validate(
targetScope != null && targetScope.getType() == Type.VO, targetScope != null && targetScope.type() == Type.VO,
new ResourceParameterException("The targetScope is invalid or not of type VO.")); new ResourceParameterException("The targetScope is invalid or not of type VO."));
checker.validate( checker.validate(
sourceScope.getEnclosingScope() == targetScope.getEnclosingScope(), sourceScope.enclosingScope() == targetScope.enclosingScope(),
new ResourceParameterException("The sourceScope and targetScope must be children of the same root VO.")); new ResourceParameterException("The sourceScope and targetScope must be children of the same root VO."));
checker.validate(this.getType() != AllowedResourceTypes.GHN && this.getType() != AllowedResourceTypes.RunningInstance, checker.validate(this.getType() != AllowedResourceTypes.GHN && this.getType() != AllowedResourceTypes.RunningInstance,
new ResourceAccessException("Operation not allowed for RI and GHNs.")); new ResourceAccessException("Operation not allowed for RI and GHNs."));
@ -528,18 +379,24 @@ public abstract class AbstractResourceManager {
new ResourceAccessException("Operation not allowed on resources with no ID.")); new ResourceAccessException("Operation not allowed on resources with no ID."));
// Phase 1. retrieve the resource to copy // Phase 1. retrieve the resource to copy
GCUBEResource resStub = this.getGCUBEResource(sourceScope); Resource resStub = this.getResource(sourceScope);
// Phase 2. Before to register the resource, the scope must be // Phase 2. Before registering the resource, the scope must be
// bound to the local GCUBEResource // bound to the local GCUBEResource
this.bindToScope(targetScope); this.bindToScope(targetScope.toString());
// Phase 3. Register to the new VO through the ISPublisher // Phase 3. Register to the new VO through the ISPublisher
String currentScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(targetScope.toString());
Resource toReturn = null;
try { try {
return this.getISPublisher().registerGCUBEResource(resStub, targetScope, this.getSecurityManager()); toReturn = this.getRegistryPublisher().create(resStub);
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException(e.getMessage()); throw new ResourceAccessException(e.getMessage());
} }
ScopeProvider.instance.set(currentScope);
return toReturn.id();
} }
/** /**
@ -550,7 +407,7 @@ public abstract class AbstractResourceManager {
* @return * @return
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
protected abstract GCUBEResource buildGCUBEResource(final String xmlRepresentation) 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 * From a resource retrieves its GCUBEResource depending on the scope in which it is
@ -559,8 +416,8 @@ public abstract class AbstractResourceManager {
* @return * @return
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
public final GCUBEResource getGCUBEResource(final GCUBEScope scope) throws AbstractResourceException { public final Resource getResource(final ScopeBean scope) throws AbstractResourceException {
return this.buildGCUBEResource(this.getXMLDescription(scope)); return this.buildResource(this.getXMLDescription(scope));
} }
/** /**
@ -570,44 +427,39 @@ public abstract class AbstractResourceManager {
* @return * @return
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
protected final String getXMLDescription(final GCUBEScope scope) throws AbstractResourceException { protected final String getXMLDescription(final ScopeBean scope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(this.getID() != null, new ResourceAccessException("Cannot execute on resources with no ID.")); checker.validate(this.getID() != null, new ResourceAccessException("Cannot execute on resources with no ID."));
String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(scope.toString());
// Phase 1. retrieve the resource to copy // Phase 1. retrieve the resource to copy
GCUBEGenericQuery query = null; Query query = new QueryBox("for $resource in collection('/db/Profiles/" + this.getType().name() + "')//Resource " +
try { "where ( $resource/ID/string() eq '" +
query = this.getISClient().getQuery(GCUBEGenericQuery.class); this.getID() +
query.setExpression( "') " +
"for $resource in collection('/db/Profiles/" + this.getType().name() + "')//Resource " + "return $resource");
"where ( $resource/ID/string() eq '" +
this.getID() +
"') " +
"return $resource"
);
} catch (Exception e) {
throw new ResourceAccessException(e);
}
XMLResult resDescription = null; DiscoveryClient<String> client = client();
try {
resDescription = this.getISClient().execute(query, scope).get(0); List<String> results = client.submit(query);
return resDescription.toString(); if (results == null || results.isEmpty())
} catch (Exception e) {
throw new ResourceAccessException("Cannot retrieve the IS profile for resource: " + this.getID() + throw new ResourceAccessException("Cannot retrieve the IS profile for resource: " + this.getID() +
" in scope: " + scope.toString()); " in scope: " + scope.toString());
} ScopeProvider.instance.set(currScope);
return results.get(0).toString();
} }
/** /**
* The first phase of remove form scope. * The first phase of remove from scope.
* This is common to all the resources (RI and GHNs). * This is common to all the resources (RI and GHNs).
* @param scope * @param scope
* @return * @return
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
private String basicRemoveFromScope(final GCUBEScope scope) private String basicRemoveFromScope(final ScopeBean scope) throws AbstractResourceException {
throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed.")); checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed."));
checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed.")); checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed."));
@ -618,17 +470,22 @@ public abstract class AbstractResourceManager {
RemoveResourcesParameters params = new RemoveResourcesParameters(); RemoveResourcesParameters params = new RemoveResourcesParameters();
ResourceItem toRemove = new ResourceItem(); ResourceItem toRemove = new ResourceItem();
toRemove.setID(this.getID()); toRemove.setId(this.getID());
toRemove.setType(this.getType().name()); toRemove.setType(this.getType().name());
ResourceList resourcesToRemove = new ResourceList(); ResourceList resourcesToRemove = new ResourceList();
resourcesToRemove.setResource(new ResourceItem[]{toRemove}); ArrayList<ResourceItem> temp = new ArrayList<ResourceItem>();
params.setResources(resourcesToRemove); temp.add(toRemove);
params.setTargetScope(scope.toString()); resourcesToRemove.setResource(temp);
params.resources = resourcesToRemove;
params.targetScope = scope.toString();
ServerConsole.trace(LOG_PREFIX, "[REMOVE-FROM-SCOPE] Sending the Remove Resource request...."); ServerConsole.trace(LOG_PREFIX, "[REMOVE-FROM-SCOPE] Sending the Remove Resource request....");
try { try {
ResourceBinderPortType manager = this.getResourceManager(scope); RMBinderLibrary manager = this.getResourceManager(scope.toString());
String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(scope.toString());
retval = manager.removeResources(params); retval = manager.removeResources(params);
ScopeProvider.instance.set(currScope);
} catch (Exception e) { } catch (Exception e) {
throw new ResourceOperationException("During removeFrom scope of " throw new ResourceOperationException("During removeFrom scope of "
+ this.getType() + this.getType()
@ -641,59 +498,17 @@ public abstract class AbstractResourceManager {
* Removes the current resource from the scope. * Removes the current resource from the scope.
* @param nestingRemoval true for resources different from gHN and RI * @param nestingRemoval true for resources different from gHN and RI
*/ */
public final String removeFromScope(final GCUBEScope scope) public final String removeFromScope(final ScopeBean scope) throws AbstractResourceException {
throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed.")); checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed."));
checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed.")); checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed."));
String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(scope.toString());
String retval = this.basicRemoveFromScope(scope); String retval = this.basicRemoveFromScope(scope);
// -- PHASE 2 - optional ScopeProvider.instance.set(currScope);
// Builds the stub without the removed scope
GCUBEResource resStub = this.getGCUBEResource(scope);
// Refreshes the local profile
resStub.removeScope(scope);
/*
* These steps are for resources different from GHN and RI
*/
if (!this.getType().equals(AllowedResourceTypes.GHN.name()) &&
!this.getType().equals(AllowedResourceTypes.RunningInstance.name())) {
// Phase 1
// if the resource joins only the current scope, after the removal it has also to be deleted
try {
List<GCUBEScope> boundedScopes = this.validateScopes(resStub.getScopes().values().toArray(new GCUBEScope[]{}));
if (boundedScopes == null) {
ServerConsole.warn(LOG_PREFIX, "[REMOVE-FROM-SCOPE] The resource " + this.getType() + " has no bound scopes");
return retval;
}
if (boundedScopes.size() == 0) {
ServerConsole.trace(LOG_PREFIX, "[REMOVE-FROM-SCOPE] [DELETE-BRANCH] deleting resource since no more scopes remained");
this.getISPublisher().removeGCUBEResource(
this.getID(), this.getType().name(), scope, this.getSecurityManager());
return retval;
} else {
// requires the update of the resources in all other scopes
for (GCUBEScope _scope : boundedScopes) {
if (!scope.equals(_scope)) {
try {
ServerConsole.trace(LOG_PREFIX, "[REMOVE-FROM-SCOPE] [UPDATE-BRANCH] Updating profile in scope [" + _scope.toString() + "]");
this.getISPublisher().updateGCUBEResource(resStub, _scope, getSecurityManager());
} catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e);
}
}
}
}
} catch (Exception e) {
throw new ResourceOperationException(e);
}
}
return retval; return retval;
} }
@ -704,14 +519,10 @@ public abstract class AbstractResourceManager {
* @param scopes * @param scopes
* @return * @return
*/ */
protected List<GCUBEScope> validateScopes(final GCUBEScope[] scopes) { protected List<ScopeBean> validateScopes(final String[] scopes) {
List<GCUBEScope> retval = new Vector<GCUBEScope>(); List<ScopeBean> retval = new Vector<ScopeBean>();
for (GCUBEScope scope : scopes) { for (int i = 0; i < scopes.length; i++) {
try { retval.add(new ScopeBean(scopes[i]));
retval.add(ScopeManager.getScope(scope.toString()));
} catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e);
}
} }
return retval; return retval;
} }
@ -722,11 +533,11 @@ public abstract class AbstractResourceManager {
* @param scope where the resource is bound * @param scope where the resource is bound
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
public final void forceDelete(final GCUBEScope scope) throws AbstractResourceException { public final void forceDelete(final ScopeBean scope) throws AbstractResourceException {
ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource since no more scopes remained"); ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource since no more scopes remained");
Resource resStub = this.getResource(scope);
try { try {
this.getISPublisher().removeGCUBEResource( this.getRegistryPublisher().remove(resStub);
this.getID(), this.getType().name(), scope, this.getSecurityManager());
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
} }
@ -737,64 +548,37 @@ public abstract class AbstractResourceManager {
* According to the * According to the
* <a href="https://gcube.wiki.gcube-system.org/gcube/index.php/Programmatic_Administration_Interface"> * <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 * official wiki</a> the resource is deleted only if is not bound in other scopes. Otherwise this
* operation simply corresponds to the in deep remove from scope. * operation simply corresponds to remove from scope.
* @param scope * @param scope
* @throws ResourceOperationException * @throws ResourceOperationException
*/ */
public final void delete(final GCUBEScope scope) throws AbstractResourceException { public final void delete(final ScopeBean scope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed.")); checker.validate(scope != null, new ResourceParameterException("Invalid parameter scope. null not allowed."));
checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed.")); checker.validate(this.getID() != null, new ResourceOperationException("Invalid ID. null not allowed."));
System.out.println("DELETING TYPE: "+ this.getType()); System.out.println("DELETING TYPE: "+ this.getType());
String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(scope.toString());
GCUBEResource resStub = this.getGCUBEResource(scope); Resource resStub = this.getResource(scope);
List<GCUBEScope> boundedScopes = this.validateScopes(resStub.getScopes().values().toArray(new GCUBEScope[]{}));
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() + " in scope [" + scope + "]");
ServerConsole.trace(LOG_PREFIX, "[DELETE] " + this.getType() + " " + this.getID() + " is bound to (" + boundedScopes.size() + ") scopes"); ServerConsole.trace(LOG_PREFIX, "[DELETE] " + this.getType() + " " + this.getID() + " is bound to (" + boundedScopes.size() + ") scopes");
/* if (boundedScopes.size() > 1)
* Removefromscope accetta un boolean piu la resource gia ottenuta. ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource is a remove from scope since more than 1 scope is present " + resStub.id());
* boolean per decidere se saltare fase due di update che la ripeto piu volte else if (boundedScopes.size() == 1)
* rispetto a qui che lo faccio una volta sola. ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource since is bound to 1 scope only " + resStub.id());
*/ try {
for (GCUBEScope _scope : boundedScopes) { this.getRegistryPublisher().remove(resStub);
// Removing from the children scopes } catch (Exception e) {
if (_scope.isEnclosedIn(scope) || scope.equals(_scope)) {
this.basicRemoveFromScope(_scope);
resStub.removeScope(_scope);
}
}
// Phase 2
// after the removal, the resource must be also updated in the other scopes it belongs to,
// otherwise it will wrongly report there a scope where actually it is not registered anymore.
// In order to do so, the just removed scope must be removed from the local
// GCUBEResource object by invoking the method GCUBEResource.removeScope(<scope to remove>)
// and then the resource must be updated in all the remaining scopes.
if (resStub.getScopes().isEmpty()) {
ServerConsole.trace(LOG_PREFIX, "[DELETE] [DELETE-BRANCH] deleting resource since no more scopes remained");
try {
this.getISPublisher().removeGCUBEResource(
this.getID(), this.getType().name(), scope, this.getSecurityManager());
} catch (Exception e) {
}
} else {
boundedScopes = this.validateScopes(resStub.getScopes().values().toArray(new GCUBEScope[]{}));
for (GCUBEScope _scope : boundedScopes) {
try {
ServerConsole.trace(LOG_PREFIX, "[DELETE] [UPDATE-BRANCH]" + this.getType() + " " + this.getID() + " in scope [" + _scope + "]");
this.getISPublisher().updateGCUBEResource(resStub, _scope, getSecurityManager());
} catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e);
}
}
} }
ScopeProvider.instance.set(currScope);
} }
} }

View File

@ -17,9 +17,11 @@
package org.gcube.resourcemanagement.support.server.managers.resources; package org.gcube.resourcemanagement.support.server.managers.resources;
import java.io.StringReader; import java.io.StringReader;
import org.gcube.common.core.contexts.GHNContext; import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.resources.GCUBECollection; import org.gcube.common.core.resources.GCUBECollection;
import org.gcube.common.core.resources.GCUBEResource; import org.gcube.common.core.resources.GCUBEResource;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException;
@ -66,19 +68,13 @@ public class CollectionManager extends AbstractResourceManager {
super(id, name, AllowedResourceTypes.Collection, subtype); super(id, name, AllowedResourceTypes.Collection, subtype);
} }
/**
* {@inheritDoc}
*/
@Override @Override
protected final GCUBEResource buildGCUBEResource(final String xmlRepresentation) protected Resource buildResource(String xmlRepresentation)
throws AbstractResourceException { throws AbstractResourceException {
try { // TODO Auto-generated method stub
GCUBECollection impl = GHNContext.getImplementation(GCUBECollection.class); return null;
impl.load(new StringReader(xmlRepresentation));
return impl;
} catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e);
}
} }
} }

View File

@ -18,17 +18,17 @@ package org.gcube.resourcemanagement.support.server.managers.resources;
import java.io.StringReader; import java.io.StringReader;
import org.apache.axis.message.addressing.Address; import javax.xml.bind.JAXBContext;
import org.apache.axis.message.addressing.EndpointReferenceType; import javax.xml.bind.Unmarshaller;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.contexts.GHNContext; import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.common.core.resources.GCUBEHostingNode; import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.core.resources.GCUBEResource; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.core.scope.GCUBEScope; import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.vremanagement.ghnmanager.stubs.AddScopeInputParams; import org.gcube.common.vremanagement.ghnmanager.client.GHNManagerLibrary;
import org.gcube.common.vremanagement.ghnmanager.stubs.GHNManagerPortType; import org.gcube.common.vremanagement.ghnmanager.client.fws.Types.AddScopeInputParams;
import org.gcube.common.vremanagement.ghnmanager.stubs.ShutdownOptions; import org.gcube.common.vremanagement.ghnmanager.client.fws.Types.ShutdownOptions;
import org.gcube.common.vremanagement.ghnmanager.stubs.service.GHNManagerServiceAddressingLocator; import org.gcube.common.vremanagement.ghnmanager.client.proxies.Proxies;
import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException;
@ -100,10 +100,7 @@ public class GHNManager extends AbstractResourceManager {
* @throws ResourceParameterException * @throws ResourceParameterException
* @throws ResourceOperationException * @throws ResourceOperationException
*/ */
public final String addToNewScope( public final String addToNewScope(final ScopeBean sourceScope, final ScopeBean targetScope, final String scopeMap)
final GCUBEScope sourceScope,
final GCUBEScope targetScope,
final String scopeMap)
throws AbstractResourceException { throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(sourceScope != null, new ResourceParameterException("Parameter sourceScope null not allowed.")); checker.validate(sourceScope != null, new ResourceParameterException("Parameter sourceScope null not allowed."));
@ -111,7 +108,7 @@ public class GHNManager extends AbstractResourceManager {
checker.validate(scopeMap != null && scopeMap.trim().length() > 0, new ResourceParameterException("Invalid scopeMap parameter.")); 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.")); checker.validate(this.getID() != null, new ResourceOperationException("This operation cannot be applied to resources with no ID."));
if (!targetScope.isEnclosedIn(sourceScope)) { if (!sourceScope.toString().contains(targetScope.toString())) {
throw new ResourceOperationException( throw new ResourceOperationException(
"You are not allowed to apply to this scope. Target scope is not enclosed in the source one."); "You are not allowed to apply to this scope. Target scope is not enclosed in the source one.");
} }
@ -144,22 +141,20 @@ public class GHNManager extends AbstractResourceManager {
* @return * @return
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
public final GHNManagerPortType getGHNManager(final GCUBEScope scope) public final GHNManagerLibrary getGHNManager(final ScopeBean scope) throws AbstractResourceException {
throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(scope != null, new ResourceParameterException("Invalid scope")); 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.")); checker.validate(this.getName() != null, new ResourceOperationException("This operation cannot be applied to resources with no name."));
EndpointReferenceType endpoint = new EndpointReferenceType(); String currScope = ScopeProvider.instance.get();
try { ScopeProvider.instance.set(scope.toString());
endpoint.setAddress(new Address("http://" + this.getName() + "/wsrf/services/gcube/common/vremanagement/GHNManager")); ServerConsole.info(LOG_PREFIX, "Getting Resource Manager in scope [" + scope.toString() + "]");
GHNManagerServiceAddressingLocator locator = new GHNManagerServiceAddressingLocator(); GHNManagerLibrary ghnMan = Proxies.service().build();
GHNManagerPortType pt = locator.getGHNManagerPortTypePort(endpoint); if (ghnMan == null) { // no managers found
pt = GCUBERemotePortTypeContext.getProxy(pt, scope, this.getSecurityManager()); throw new ResourceAccessException("Unable to find GHNManagers for resource " + this.getType() + " in scope: " + scope.toString());
return pt;
} catch (Exception e) {
throw new ResourceAccessException(e.getMessage());
} }
ScopeProvider.instance.set(currScope);
return ghnMan;
} }
/** /**
@ -176,12 +171,12 @@ public class GHNManager extends AbstractResourceManager {
* @throws ResourceAccessException * @throws ResourceAccessException
* @throws ResourceParameterException * @throws ResourceParameterException
*/ */
public final void shutDown(final GCUBEScope scope, final boolean restart, final boolean clean) public final void shutDown(final ScopeBean scope, final boolean restart, final boolean clean)
throws AbstractResourceException { throws AbstractResourceException {
Assertion<ResourceAccessException> checker = new Assertion<ResourceAccessException>(); Assertion<ResourceAccessException> checker = new Assertion<ResourceAccessException>();
checker.validate(this.getID() != null, new ResourceAccessException("This operation cannot be applied to resources with no ID.")); checker.validate(this.getID() != null, new ResourceAccessException("This operation cannot be applied to resources with no ID."));
GHNManagerPortType ghnManager = this.getGHNManager(scope); GHNManagerLibrary ghnManager = this.getGHNManager(scope);
ServerConsole.trace(LOG_PREFIX, "Shutting down " + scope.toString() + " " + this.getType() + " " + this.getID()); ServerConsole.trace(LOG_PREFIX, "Shutting down " + scope.toString() + " " + this.getType() + " " + this.getID());
@ -196,12 +191,13 @@ public class GHNManager extends AbstractResourceManager {
} }
@Override @Override
protected final GCUBEResource buildGCUBEResource(final String xmlRepresentation) protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException {
throws AbstractResourceException {
try { try {
GCUBEHostingNode impl = GHNContext.getImplementation(GCUBEHostingNode.class); JAXBContext ctx = JAXBContext.newInstance(HostingNode.class);
impl.load(new StringReader(xmlRepresentation)); Unmarshaller unmarshaller = ctx.createUnmarshaller();
return impl; StringReader reader = new StringReader(xmlRepresentation);
HostingNode deserialised = (HostingNode) unmarshaller.unmarshal(reader);
return deserialised;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e);
} }

View File

@ -16,21 +16,36 @@
package org.gcube.resourcemanagement.support.server.managers.resources; 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.io.StringReader;
import org.gcube.common.core.contexts.GHNContext; import java.util.List;
import org.gcube.common.core.informationsystem.publisher.ISPublisher;
import org.gcube.common.core.resources.GCUBEGenericResource; import javax.xml.bind.JAXBContext;
import org.gcube.common.core.resources.GCUBEResource; import javax.xml.bind.Unmarshaller;
import org.gcube.common.core.scope.GCUBEScope; 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.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.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; 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.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.types.AllowedResourceTypes;
import org.gcube.resourcemanagement.support.server.utils.Assertion; import org.gcube.resourcemanagement.support.server.utils.Assertion;
import org.gcube.resourcemanagement.support.server.utils.ServerConsole; 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.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/** /**
@ -101,103 +116,123 @@ public class GenericResourceManager extends AbstractResourceManager {
* @param subType (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 * @param scope (optional) if null it will not be changed
* @throws AbstractResourceException * @throws AbstractResourceException
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/ */
public final void update( public final void update(final String name, final String description, final String body, final String subType, final ScopeBean scope) throws Exception {
final String name,
final String description,
final String body,
final String subType,
final GCUBEScope scope)
throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); 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(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()); ServerConsole.trace(LOG_PREFIX, "[RES-UPDATE] updating resource " + this.getType() + " " + this.getID());
GCUBEGenericResource res = (GCUBEGenericResource) this.getGCUBEResource(scope); GenericResource resource = getResourceToEditById(this.getID(), scope);
res.setName(name.trim()); resource.profile().name(name.trim());
if (description != null) { if (description != null) {
res.setDescription(description.trim()); resource.profile().description(description.trim());
} }
if (body != null) { if (body != null) {
res.setBody(body.trim()); appendXmlFragment(resource.profile().newBody(), body);
} }
if (subType != null) { if (subType != null)
res.setSecondaryType(subType.trim()); resource.profile().type(subType.trim());
}
try { String currScope = ScopeProvider.instance.get();
this.getISPublisher().updateGCUBEResource(res, scope, this.getSecurityManager()); ScopeProvider.instance.set(scope.toString());
RegistryPublisher publisher = getRegistryPublisher();
/* FIXME old release String id = publisher.update(resource).id();
* List<GCUBEScope> boundedScopes = this.validateScopes(res.getScopes().values().toArray(new GCUBEScope[]{}));
if (id == null || id.length() == 0) {
throw new Exception("The GenericResource has not been updated");
for (GCUBEScope _scope : boundedScopes) {
ServerConsole.trace(LOG_PREFIX, "[RES-UPDATE] ISPublisher updating resource " + this.getType() + " " + this.getID() + " in scope: [" + _scope + "]");
this.getISPublisher().updateGCUBEResource(res, _scope, this.getSecurityManager());
}
*/
} catch (Exception e) {
throw new ResourceOperationException(e.getMessage());
} }
ScopeProvider.instance.set(currScope);
ServerConsole.info(LOG_PREFIX, "Resource Updated with ID: " + id);
} }
private GenericResource getResourceToEditById(String id, ScopeBean scope) throws Exception {
String currScope = ScopeProvider.instance.get();
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);
ScopeProvider.instance.set(currScope);
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 * Creates a Generic Resource and returns the ID given by the
* resource manager at creation phase. * resource manager at creation phase.
* @return the id assigned to the newly created resource * @return the id assigned to the newly created resource
*/ */
public static final synchronized String create( public static final synchronized String create(final String ID, final ScopeBean scope, final String name, final String description, final String body, final String subType)
final String ID,
final GCUBEScope scope,
final String name,
final String description,
final String body,
final String subType)
throws Exception { throws Exception {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); 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(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")); checker.validate(subType != null && subType.trim().length() != 0, new ResourceParameterException("Invalid field subType. Null or empty value not allowed"));
GCUBEGenericResource resource = GHNContext.getImplementation(GCUBEGenericResource.class); GenericResource resource = new GenericResource();
if (ID != null) { resource.newProfile().name(name.trim());
resource.setID(ID);
}
resource.setName(name.trim());
if (description != null) { if (description != null) {
resource.setDescription(description.trim()); resource.profile().description(description.trim());
} }
if (body != null) { if (body != null) {
resource.setBody(body.trim()); appendXmlFragment(resource.profile().newBody(), body);
} }
resource.setSecondaryType(subType.trim()); resource.profile().type(subType.trim());
resource.addScope(scope);
GenericResourceManager gm = new GenericResourceManager(); GenericResourceManager gm = new GenericResourceManager();
ISPublisher publisher = gm.getISPublisher();
String retval = publisher.registerGCUBEResource(resource, scope, gm.getSecurityManager()); String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(scope.toString());
if (retval == null || retval.length() == 0) { 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"); throw new Exception("The GenericResource has not been created");
} }
ScopeProvider.instance.set(currScope);
Document doc = ScopeManager.getDocumentGivenXML(retval);
String id = doc.getElementsByTagName("ID").item(0).getFirstChild().getNodeValue();
ServerConsole.info(LOG_PREFIX, "Resource Created with ID: " + id); ServerConsole.info(LOG_PREFIX, "Resource Created with ID: " + id);
return id; return id;
} }
@Override @Override
protected final GCUBEResource buildGCUBEResource( protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException {
final String xmlRepresentation) throws AbstractResourceException {
try { try {
GCUBEGenericResource impl = GHNContext.getImplementation(GCUBEGenericResource.class); JAXBContext ctx = JAXBContext.newInstance(GenericResource.class);
impl.load(new StringReader(xmlRepresentation)); Unmarshaller unmarshaller = ctx.createUnmarshaller();
return impl; StringReader reader = new StringReader(xmlRepresentation);
GenericResource deserialised = (GenericResource) unmarshaller.unmarshal(reader);
return deserialised;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), 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(Node parent, String fragment) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = parent.getOwnerDocument();
Node fragmentNode = docBuilder.parse(new InputSource(new StringReader(fragment))).getDocumentElement();
fragmentNode = doc.importNode(fragmentNode, true);
parent.appendChild(fragmentNode);
}
} }

View File

@ -16,18 +16,21 @@
package org.gcube.resourcemanagement.support.server.managers.resources; 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.io.File;
import java.rmi.RemoteException; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Vector; import java.util.Vector;
import org.gcube.common.core.faults.GCUBEFault; import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.core.informationsystem.client.AtomicCondition; import org.gcube.common.resources.gcore.Software;
import org.gcube.common.core.informationsystem.client.queries.GCUBEServiceQuery; import org.gcube.common.resources.gcore.Software.Profile.ServicePackage;
import org.gcube.common.core.resources.GCUBEResource; import org.gcube.common.resources.gcore.Software.Profile.SoftwarePackage;
import org.gcube.common.core.resources.GCUBEService; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.core.scope.GCUBEScope; import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.core.scope.GCUBEScope.Type; import org.gcube.common.scope.impl.ScopeBean.Type;
import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException; import org.gcube.resourcemanagement.support.server.exceptions.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException;
@ -36,12 +39,15 @@ import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager;
import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes;
import org.gcube.resourcemanagement.support.server.utils.Assertion; import org.gcube.resourcemanagement.support.server.utils.Assertion;
import org.gcube.resourcemanagement.support.server.utils.ServerConsole; import org.gcube.resourcemanagement.support.server.utils.ServerConsole;
import org.gcube.vremanagement.resourcemanager.stubs.binder.AddResourcesParameters; import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.vremanagement.resourcemanager.stubs.binder.PackageItem; import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceBinderPortType; import org.gcube.vremanagement.resourcemanager.client.RMBinderLibrary;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceItem; import org.gcube.vremanagement.resourcemanager.client.fws.Types.AddResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceList; import org.gcube.vremanagement.resourcemanager.client.fws.Types.PackageItem;
import org.gcube.vremanagement.resourcemanager.stubs.binder.SoftwareList; 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. * A support class containing operations to manage multiple resources.
@ -63,8 +69,8 @@ public class ManagementUtils {
public static final synchronized String addToExistingScope( public static final synchronized String addToExistingScope(
final AllowedResourceTypes type, final AllowedResourceTypes type,
final String[] resourceIDs, final String[] resourceIDs,
final GCUBEScope sourceScope, final ScopeBean sourceScope,
final GCUBEScope targetScope) final ScopeBean targetScope)
throws Exception { throws Exception {
ServerConsole.trace( ServerConsole.trace(
LOG_PREFIX, LOG_PREFIX,
@ -77,7 +83,7 @@ public class ManagementUtils {
// 1 - If not RI or GHN and the scopes are sibling and VO copyFromToVO // 1 - If not RI or GHN and the scopes are sibling and VO copyFromToVO
if (!(type == AllowedResourceTypes.GHN) && if (!(type == AllowedResourceTypes.GHN) &&
!(type == AllowedResourceTypes.RunningInstance) && !(type == AllowedResourceTypes.RunningInstance) &&
sourceScope.getType() == Type.VO && targetScope.getType() == Type.VO) { sourceScope.type() == Type.VO && targetScope.type() == Type.VO) {
// Phase 1. retrieve the resource to copy // Phase 1. retrieve the resource to copy
//GCUBEResource resStub = this.getGCUBEResource(sourceScope); //GCUBEResource resStub = this.getGCUBEResource(sourceScope);
@ -90,8 +96,11 @@ public class ManagementUtils {
try { try {
for (String id : resourceIDs) { for (String id : resourceIDs) {
AbstractResourceManager res = ResourceFactory.createResourceManager(type, id); AbstractResourceManager res = ResourceFactory.createResourceManager(type, id);
GCUBEResource resStub = res.getGCUBEResource(sourceScope); Resource resStub = res.getResource(sourceScope);
res.getISPublisher().registerGCUBEResource(resStub, targetScope, res.getSecurityManager()); String curr = ScopeProvider.instance.get();
ScopeProvider.instance.set(targetScope.toString());
res.getRegistryPublisher().update(resStub);
ScopeProvider.instance.set(curr);
} }
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException(e.getMessage()); throw new ResourceAccessException(e.getMessage());
@ -102,7 +111,7 @@ public class ManagementUtils {
// Add a gCube Resource to // Add a gCube Resource to
// (i) a VRE scope from the parent VO or // (i) a VRE scope from the parent VO or
// (ii) a VO scope from the infrastructure scope // (ii) a VO scope from the infrastructure scope
if (!targetScope.isEnclosedIn(sourceScope)) { if (sourceScope.toString().contains(targetScope.toString())) {
throw new ResourceOperationException( throw new ResourceOperationException(
"You are not allowed to apply to this scope. Target scope is not enclosed in the source one."); "You are not allowed to apply to this scope. Target scope is not enclosed in the source one.");
} }
@ -120,7 +129,7 @@ public class ManagementUtils {
* @return the generated report ID * @return the generated report ID
*/ */
public static final synchronized String removeFromExistingScope(final AllowedResourceTypes type, final String[] resourceIDs, public static final synchronized String removeFromExistingScope(final AllowedResourceTypes type, final String[] resourceIDs,
final GCUBEScope sourceScope, final GCUBEScope targetScope) throws Exception { final ScopeBean sourceScope, final ScopeBean targetScope) throws Exception {
ServerConsole.trace( ServerConsole.trace(
LOG_PREFIX, LOG_PREFIX,
@ -154,23 +163,20 @@ public class ManagementUtils {
* @return the ID of generated report * @return the ID of generated report
* @throws AbstractResourceException * @throws AbstractResourceException
*/ */
private static synchronized String bindToScope( private static synchronized String bindToScope(final AllowedResourceTypes type, final String[] resourceIDs, final ScopeBean targetScope)throws AbstractResourceException {
final AllowedResourceTypes type,
final String[] resourceIDs,
final GCUBEScope targetScope)
throws AbstractResourceException {
AddResourcesParameters addParam = new AddResourcesParameters(); AddResourcesParameters addParam = new AddResourcesParameters();
ResourceBinderPortType manager = ResourceFactory.createResourceManager(type).getResourceManager(targetScope); RMBinderLibrary manager = ResourceFactory.createResourceManager(type).getResourceManager(targetScope.toString());
List<ResourceItem> resToBind = new Vector<ResourceItem>(); ArrayList<ResourceItem> resToBind = new ArrayList<ResourceItem>();
for (String id : resourceIDs) { for (String id : resourceIDs) {
ResourceItem toAdd = new ResourceItem(); ResourceItem toAdd = new ResourceItem();
toAdd.setID(id); toAdd.id = id;
toAdd.setType(type.name()); toAdd.setType(type.name());
resToBind.add(toAdd); resToBind.add(toAdd);
} }
ResourceList r = new ResourceList(); ResourceList r = new ResourceList();
r.setResource(resToBind.toArray(new ResourceItem[]{}));
r.setResource(resToBind);
addParam.setResources(r); addParam.setResources(r);
addParam.setTargetScope(targetScope.toString()); addParam.setTargetScope(targetScope.toString());
@ -191,11 +197,7 @@ public class ManagementUtils {
} }
} }
public static synchronized void delete( public static synchronized void delete(final AllowedResourceTypes type, final String[] resourceIDs, final ScopeBean scope) throws AbstractResourceException {
final AllowedResourceTypes type,
final String[] resourceIDs,
final GCUBEScope scope)
throws AbstractResourceException {
AbstractResourceManager resource = ResourceFactory.createResourceManager(type); AbstractResourceManager resource = ResourceFactory.createResourceManager(type);
for (String id : resourceIDs) { for (String id : resourceIDs) {
try { try {
@ -214,18 +216,14 @@ public class ManagementUtils {
* @return the generated report ID * @return the generated report ID
* @throws Exception * @throws Exception
*/ */
public static final synchronized String deploy( public static final synchronized String deploy(final ScopeBean scope, final String[] ghnsID, final String[] servicesID) throws Exception {
final GCUBEScope scope,
final String[] ghnsID,
final String[] servicesID)
throws Exception {
Assertion<Exception> checker = new Assertion<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(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(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.")); checker.validate(scope != null, new Exception("Cannot retrieve the scope."));
AbstractResourceManager resource = ResourceFactory.createResourceManager(AllowedResourceTypes.Service); AbstractResourceManager resource = ResourceFactory.createResourceManager(AllowedResourceTypes.Service);
ResourceBinderPortType manager = ResourceFactory.createResourceManager(AllowedResourceTypes.Service).getResourceManager(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); System.out.println("\n\n**** These are the service ids to deploy on SCOPE " + scope);
for (String sid : servicesID) { for (String sid : servicesID) {
@ -236,21 +234,26 @@ public class ManagementUtils {
System.out.println(ghn); System.out.println(ghn);
} }
List<PackageItem> serviceProfiles = new Vector<PackageItem>(); ArrayList<PackageItem> serviceProfiles = new ArrayList<PackageItem>();
// Retrieves the profiles of services // Retrieves the profiles of services
final GCUBEServiceQuery query = resource.getISClient().getQuery(GCUBEServiceQuery.class); SimpleQuery query = null;
DiscoveryClient<Software> client = clientFor(Software.class);
prepareServices: for (String serviceID : servicesID) { prepareServices: for (String serviceID : servicesID) {
System.out.println("\n\n**** Query the IsClient to get the profile"); System.out.println("\n\n**** Query the ICClient to get the profile");
query.clearConditions(); query = queryFor(Software.class);
query.addAtomicConditions(new AtomicCondition("/ID", serviceID)); query.addCondition("$resource/Profile/ID/text() eq '" + serviceID + "'");
System.out.println("**** Query : " + query.getExpression());
List<GCUBEService> results = resource.getISClient().execute(query, scope);
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()); System.out.println("**** results received : " + results.size());
GCUBEService ret = null; Software ret = null;
if (results != null && results.size() > 0) { if (results != null && results.size() > 0) {
ret = results.get(0); ret = results.get(0);
} else { } else {
@ -258,26 +261,26 @@ public class ManagementUtils {
} }
if (ret == null || if (ret == null ||
ret.getServiceClass() == null || ret.profile() == null ||
ret.getServiceName() == null || ret.profile().softwareClass() == null ||
ret.getVersion() == null) { ret.profile().softwareName() == null) {
ServerConsole.error(LOG_PREFIX, "found an invalid service profile"); ServerConsole.error(LOG_PREFIX, "found an invalid service profile");
continue; continue;
} }
PackageItem toAdd = new PackageItem(); PackageItem toAdd = new PackageItem();
toAdd.setServiceClass(ret.getServiceClass()); toAdd.serviceClass = ret.profile().softwareClass();
toAdd.setServiceName(ret.getServiceName()); toAdd.serviceName = ret.profile().softwareName();
toAdd.setServiceVersion(ret.getVersion()); toAdd.serviceVersion ="1.0.0";
if (ret.getPackages().size() == 1) { if (ret.profile().packages().size() == 1) {
toAdd.setPackageName(ret.getPackages().get(0).getName()); toAdd.packageName = ret.profile().packages().iterator().next().name();
toAdd.setPackageVersion(ret.getPackages().get(0).getVersion()); toAdd.packageVersion = ret.profile().packages().iterator().next().version();
} else { } else {
for (org.gcube.common.core.resources.service.Package p : ret.getPackages()) { for (SoftwarePackage p : ret.profile().packages()) {
if (p.getClass().isAssignableFrom(org.gcube.common.core.resources.service.MainPackage.class)) { if (p.getClass().isAssignableFrom(ServicePackage.class)) {
toAdd.setPackageName(p.getName()); toAdd.packageName = p.name();
toAdd.setPackageVersion(p.getVersion()); toAdd.packageVersion = p.version();
break; break;
} }
} }
@ -287,29 +290,25 @@ public class ManagementUtils {
} }
SoftwareList serviceList = new SoftwareList(); SoftwareList serviceList = new SoftwareList();
serviceList.setSuggestedTargetGHNNames(ghnsID); ArrayList<String> arrayGHNSids = new ArrayList<String>();
serviceList.setSoftware(serviceProfiles.toArray(new PackageItem[0])); for (int i = 0; i < ghnsID.length; i++) {
arrayGHNSids.add(ghnsID[i]);
}
serviceList.suggestedTargetGHNNames = arrayGHNSids;
serviceList.software = serviceProfiles;
AddResourcesParameters addResourcesParameters = new AddResourcesParameters(); AddResourcesParameters addResourcesParameters = new AddResourcesParameters();
addResourcesParameters.setSoftware(serviceList); addResourcesParameters.softwareList = serviceList;
addResourcesParameters.setTargetScope(scope.toString()); addResourcesParameters.setTargetScope(scope.toString());
System.out.println("\n\n**** These is the ServiceList i pass to ResourceManagerPortType: "); System.out.println("\n\n**** These is the ServiceList i pass to ResourceManagerPortType: ");
for (int i = 0; i < serviceList.getSoftware().length; i++) { for (int i = 0; i < serviceList.software.size(); i++) {
System.out.println(serviceList.getSoftware()[i]); System.out.println(serviceList.software.get(i));
} }
String id = ""; String id = "";
try { id = manager.addResources(addResourcesParameters);
id = manager.addResources(addResourcesParameters); ServerConsole.debug(LOG_PREFIX, "Report ID = " + id);
ServerConsole.debug(LOG_PREFIX, "Report ID = " + id);
} catch (GCUBEFault e) {
ServerConsole.error(LOG_PREFIX, "during deployment.", e);
throw e;
} catch (RemoteException e) {
ServerConsole.error(LOG_PREFIX, "during deployment.", e);
throw e;
}
System.out.println("Returning.... no exceptions"); System.out.println("Returning.... no exceptions");
return id; return id;
} }
@ -332,7 +331,7 @@ public class ManagementUtils {
null, null,
"test" "test"
}, },
ScopeManager.getScope("/gcube/devsec/devVRE")); new ScopeBean("/gcube/devsec/devVRE"));
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
} }

View File

@ -16,17 +16,23 @@
package org.gcube.resourcemanagement.support.server.managers.resources; package org.gcube.resourcemanagement.support.server.managers.resources;
import java.io.StringReader; import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import java.util.List; import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Vector;
import org.gcube.common.core.contexts.GHNContext; import java.io.StringReader;
import org.gcube.common.core.informationsystem.client.AtomicCondition; import java.util.ArrayList;
import org.gcube.common.core.informationsystem.client.queries.GCUBEServiceQuery; import java.util.List;
import org.gcube.common.core.resources.GCUBEResource;
import org.gcube.common.core.resources.GCUBERunningInstance; import javax.xml.bind.JAXBContext;
import org.gcube.common.core.resources.GCUBEService; import javax.xml.bind.Unmarshaller;
import org.gcube.common.core.scope.GCUBEScope;
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.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException;
@ -34,15 +40,16 @@ import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterE
import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes;
import org.gcube.resourcemanagement.support.server.utils.Assertion; import org.gcube.resourcemanagement.support.server.utils.Assertion;
import org.gcube.resourcemanagement.support.server.utils.ServerConsole; import org.gcube.resourcemanagement.support.server.utils.ServerConsole;
import org.gcube.vremanagement.resourcemanager.stubs.binder.AddResourcesParameters; import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.vremanagement.resourcemanager.stubs.binder.PackageItem; import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.vremanagement.resourcemanager.stubs.binder.RemoveResourcesParameters; import org.gcube.vremanagement.resourcemanager.client.RMBinderLibrary;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceBinderPortType; import org.gcube.vremanagement.resourcemanager.client.RMReportingLibrary;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceItem; import org.gcube.vremanagement.resourcemanager.client.fws.Types.AddResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceList; import org.gcube.vremanagement.resourcemanager.client.fws.Types.PackageItem;
import org.gcube.vremanagement.resourcemanager.stubs.binder.SoftwareList; import org.gcube.vremanagement.resourcemanager.client.fws.Types.RemoveResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.reporting.ReportingPortType; 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 Daniele Strollo (ISTI-CNR)
@ -56,43 +63,57 @@ public class RunningInstanceManager extends AbstractResourceManager {
* @deprecated discouraged use. With no ID some operations cannot be accessed. * @deprecated discouraged use. With no ID some operations cannot be accessed.
*/ */
public RunningInstanceManager() public RunningInstanceManager()
throws ResourceParameterException, ResourceAccessException { throws ResourceParameterException, ResourceAccessException {
super(AllowedResourceTypes.RunningInstance); super(AllowedResourceTypes.RunningInstance);
} }
public RunningInstanceManager(final String id) public RunningInstanceManager(final String id)
throws ResourceParameterException, ResourceAccessException { throws ResourceParameterException, ResourceAccessException {
super(id, AllowedResourceTypes.RunningInstance); super(id, AllowedResourceTypes.RunningInstance);
} }
public RunningInstanceManager(final String id, final String name) public RunningInstanceManager(final String id, final String name)
throws ResourceParameterException, ResourceAccessException { throws ResourceParameterException, ResourceAccessException {
super(id, name, AllowedResourceTypes.RunningInstance); super(id, name, AllowedResourceTypes.RunningInstance);
} }
public RunningInstanceManager(final String id, final String name, final String subType) public RunningInstanceManager(final String id, final String name, final String subType)
throws ResourceParameterException, ResourceAccessException { throws ResourceParameterException, ResourceAccessException {
super(id, name, AllowedResourceTypes.RunningInstance, subType); super(id, name, AllowedResourceTypes.RunningInstance, subType);
} }
/**
public final String deploy( *
final GCUBEScope scope, final String[] ghnsID, final String[] servicesID) * @param scope
throws ResourceParameterException, ResourceOperationException { * @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>(); Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(servicesID != null && servicesID.length != 0, checker.validate(servicesID != null && servicesID.length != 0,
new ResourceParameterException("Invalid servicesID parameter. It cannot be null or empty.")); new ResourceParameterException("Invalid servicesID parameter. It cannot be null or empty."));
checker.validate(scope != null, checker.validate(scope != null,
new ResourceParameterException("Cannot retrieve the scope.")); new ResourceParameterException("Cannot retrieve the scope."));
List<PackageItem> serviceProfiles = new Vector<PackageItem>(); ArrayList<PackageItem> serviceProfiles = new ArrayList<PackageItem>();
try { try {
// Retrieves the profiles of services
final GCUBEServiceQuery query = this.getISClient().getQuery(GCUBEServiceQuery.class); SimpleQuery query = null;
DiscoveryClient<Software> client = clientFor(Software.class);
prepareServices: for (String serviceID : servicesID) { prepareServices: for (String serviceID : servicesID) {
query.addAtomicConditions(new AtomicCondition("/ID", serviceID)); query = queryFor(Software.class);
List<GCUBEService> results = this.getISClient().execute(query, scope); query.addCondition("$resource/Profile/ID/text() eq '" + serviceID + "'");
GCUBEService ret = null; 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) { if (results != null && results.size() > 0) {
ret = results.get(0); ret = results.get(0);
} else { } else {
@ -100,26 +121,25 @@ public class RunningInstanceManager extends AbstractResourceManager {
} }
if (ret == null || if (ret == null ||
ret.getServiceClass() == null || ret.profile() == null ||
ret.getServiceName() == null || ret.profile().softwareClass() == null ||
ret.getVersion() == null) { ret.profile().softwareName() == null) {
ServerConsole.error(LOG_PREFIX, "found an invalid service profile"); ServerConsole.error(LOG_PREFIX, "found an invalid service profile");
continue; continue;
} }
PackageItem toAdd = new PackageItem(); PackageItem toAdd = new PackageItem();
toAdd.setServiceClass(ret.getServiceClass()); toAdd.serviceClass = ret.profile().softwareClass();
toAdd.setServiceName(ret.getServiceName()); toAdd.serviceName = ret.profile().softwareName();
toAdd.setServiceVersion(ret.getVersion()); toAdd.serviceVersion ="1.0.0";
if (ret.getPackages().size() == 1) { if (ret.profile().packages().size() == 1) {
toAdd.setPackageName(ret.getPackages().get(0).getName()); toAdd.packageName = ret.profile().packages().iterator().next().name();
toAdd.setPackageVersion(ret.getPackages().get(0).getVersion()); toAdd.packageVersion = ret.profile().packages().iterator().next().version();
} else { } else {
for (org.gcube.common.core.resources.service.Package p : ret.getPackages()) { for (SoftwarePackage p : ret.profile().packages()) {
if (p.getClass().isAssignableFrom(org.gcube.common.core.resources.service.MainPackage.class)) { if (p.getClass().isAssignableFrom(ServicePackage.class)) {
toAdd.setPackageName(p.getName()); toAdd.packageName = p.name();
toAdd.setPackageVersion(p.getVersion()); toAdd.packageVersion = p.version();
break; break;
} }
} }
@ -130,29 +150,41 @@ public class RunningInstanceManager extends AbstractResourceManager {
SoftwareList serviceList = new SoftwareList(); SoftwareList serviceList = new SoftwareList();
// The GHNs are optional, suggested gHNs to use. ArrayList<String> arrayGHNSids = new ArrayList<String>();
if (ghnsID != null && ghnsID.length > 0) { for (int i = 0; i < ghnsID.length; i++) {
serviceList.setSuggestedTargetGHNNames(ghnsID); arrayGHNSids.add(ghnsID[i]);
} }
serviceList.suggestedTargetGHNNames = arrayGHNSids;
serviceList.setSoftware(serviceProfiles.toArray(new PackageItem[0])); serviceList.software = serviceProfiles;
AddResourcesParameters addResourcesParameters = new AddResourcesParameters(); AddResourcesParameters addResourcesParameters = new AddResourcesParameters();
addResourcesParameters.setSoftware(serviceList); addResourcesParameters.softwareList = serviceList;
addResourcesParameters.setTargetScope(scope.toString()); addResourcesParameters.setTargetScope(scope.toString());
String reportID = this.getResourceManager(scope).addResources(addResourcesParameters); System.out.println("\n\n**** These is the ServiceList i pass to ResourceManagerPortType: ");
ServerConsole.debug(LOG_PREFIX, "Report ID = " + reportID); for (int i = 0; i < serviceList.software.size(); i++) {
return reportID; 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) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, "Error during deployment.", e); ServerConsole.error(LOG_PREFIX, "Error during deployment.", e);
throw new ResourceOperationException("Software deployment failure: " + e.getMessage()); throw new ResourceOperationException("Software deployment failure: " + e.getMessage());
} }
} }
/**
public final String undeploy( *
final GCUBEScope scope) * @param scope
throws AbstractResourceException { * @return
* @throws AbstractResourceException
*/
public final String undeploy(final ScopeBean scope) throws AbstractResourceException {
Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>(); Assertion<AbstractResourceException> checker = new Assertion<AbstractResourceException>();
checker.validate(scope != null, checker.validate(scope != null,
new ResourceParameterException("Cannot retrieve the scope.")); new ResourceParameterException("Cannot retrieve the scope."));
@ -160,17 +192,19 @@ public class RunningInstanceManager extends AbstractResourceManager {
new ResourceOperationException("Invalid ID.")); new ResourceOperationException("Invalid ID."));
try { try {
ResourceBinderPortType rm = this.getResourceManager(scope); RMBinderLibrary rm = ResourceFactory.createResourceManager(AllowedResourceTypes.Service).getResourceManager(scope.toString());
//prepare the parameters //prepare the parameters
RemoveResourcesParameters params = new RemoveResourcesParameters(); RemoveResourcesParameters params = new RemoveResourcesParameters();
ResourceItem[] resourcelist = new ResourceItem[1]; ResourceItem[] resourcelist = new ResourceItem[1];
resourcelist[0] = new ResourceItem(); resourcelist[0] = new ResourceItem();
resourcelist[0].setID(this.getID()); resourcelist[0].id = this.getID();
resourcelist[0].setType(this.getType().name()); resourcelist[0].type = this.getType().name();
ResourceList r = new ResourceList(); ResourceList r = new ResourceList();
r.setResource(resourcelist); ArrayList<ResourceItem> temp =new ArrayList<ResourceItem>();
params.setResources(r); temp.add(resourcelist[0]);
params.setTargetScope(scope.toString()); r.setResource(temp);
params.resources = r;
params.targetScope = scope.toString();
//sending the request //sending the request
ServerConsole.info(LOG_PREFIX, "Sending the Remove Resource request...."); ServerConsole.info(LOG_PREFIX, "Sending the Remove Resource request....");
@ -183,15 +217,15 @@ public class RunningInstanceManager extends AbstractResourceManager {
} }
} }
public final String checkDeployStatus(final GCUBEScope scope, final String deployID) public final String checkDeployStatus(final ScopeBean scope, final String deployID)
throws AbstractResourceException { throws AbstractResourceException {
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>(); Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(scope != null, checker.validate(scope != null,
new ResourceParameterException("Invalid scope passed")); new ResourceParameterException("Invalid scope passed"));
checker.validate(deployID != null && deployID.trim().length() > 0, checker.validate(deployID != null && deployID.trim().length() > 0,
new ResourceParameterException("Invalid reportID passed")); new ResourceParameterException("Invalid reportID passed"));
ReportingPortType vreManagerPortType = this.getReportResourceManager(scope); RMReportingLibrary vreManagerPortType = this.getReportResourceManager(scope.toString());
try { try {
return vreManagerPortType.getReport(deployID); return vreManagerPortType.getReport(deployID);
@ -202,14 +236,16 @@ public class RunningInstanceManager extends AbstractResourceManager {
} }
@Override @Override
protected final GCUBEResource buildGCUBEResource(final String xmlRepresentation) protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException {
throws AbstractResourceException {
try { try {
GCUBERunningInstance impl = GHNContext.getImplementation(GCUBERunningInstance.class); JAXBContext ctx = JAXBContext.newInstance(GCoreEndpoint.class);
impl.load(new StringReader(xmlRepresentation)); Unmarshaller unmarshaller = ctx.createUnmarshaller();
return impl; StringReader reader = new StringReader(xmlRepresentation);
GCoreEndpoint deserialised = (GCoreEndpoint) unmarshaller.unmarshal(reader);
return deserialised;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e);
} }
} }
} }

View File

@ -18,10 +18,12 @@ package org.gcube.resourcemanagement.support.server.managers.resources;
import java.io.StringReader; import java.io.StringReader;
import org.gcube.common.core.contexts.GHNContext; import javax.xml.bind.JAXBContext;
import org.gcube.common.core.resources.GCUBEResource; import javax.xml.bind.Unmarshaller;
import org.gcube.common.core.resources.GCUBERuntimeResource;
import org.gcube.common.core.scope.GCUBEScope; 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.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceOperationException;
@ -29,8 +31,7 @@ import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterE
import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes; import org.gcube.resourcemanagement.support.server.types.AllowedResourceTypes;
import org.gcube.resourcemanagement.support.server.utils.Assertion; import org.gcube.resourcemanagement.support.server.utils.Assertion;
import org.gcube.resourcemanagement.support.server.utils.ServerConsole; import org.gcube.resourcemanagement.support.server.utils.ServerConsole;
import org.gcube.vremanagement.resourcemanager.stubs.binder.ResourceBinderPortType; import org.gcube.vremanagement.resourcemanager.client.RMReportingLibrary;
import org.gcube.vremanagement.resourcemanager.stubs.reporting.ReportingPortType;
@ -77,7 +78,7 @@ public class RuntimeResourceManager extends AbstractResourceManager {
} }
public final String checkDeployStatus(final GCUBEScope scope, final String deployID) public final String checkDeployStatus(final ScopeBean scope, final String deployID)
throws AbstractResourceException { throws AbstractResourceException {
Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>(); Assertion<ResourceParameterException> checker = new Assertion<ResourceParameterException>();
checker.validate(scope != null, checker.validate(scope != null,
@ -85,7 +86,7 @@ public class RuntimeResourceManager extends AbstractResourceManager {
checker.validate(deployID != null && deployID.trim().length() > 0, checker.validate(deployID != null && deployID.trim().length() > 0,
new ResourceParameterException("Invalid reportID passed")); new ResourceParameterException("Invalid reportID passed"));
ReportingPortType vreManagerPortType = this.getReportResourceManager(scope); RMReportingLibrary vreManagerPortType = this.getReportResourceManager(scope.name());
try { try {
return vreManagerPortType.getReport(deployID); return vreManagerPortType.getReport(deployID);
@ -96,14 +97,16 @@ public class RuntimeResourceManager extends AbstractResourceManager {
} }
@Override @Override
protected final GCUBEResource buildGCUBEResource(final String xmlRepresentation) protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException {
throws AbstractResourceException {
try { try {
GCUBERuntimeResource impl = GHNContext.getImplementation(GCUBERuntimeResource.class); JAXBContext ctx = JAXBContext.newInstance(ServiceEndpoint.class);
impl.load(new StringReader(xmlRepresentation)); Unmarshaller unmarshaller = ctx.createUnmarshaller();
return impl; StringReader reader = new StringReader(xmlRepresentation);
ServiceEndpoint deserialised = (ServiceEndpoint) unmarshaller.unmarshal(reader);
return deserialised;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e);
} }
} }
} }

View File

@ -17,9 +17,12 @@
package org.gcube.resourcemanagement.support.server.managers.resources; package org.gcube.resourcemanagement.support.server.managers.resources;
import java.io.StringReader; import java.io.StringReader;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.resources.GCUBEResource; import javax.xml.bind.JAXBContext;
import org.gcube.common.core.resources.GCUBEService; 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.AbstractResourceException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceAccessException;
import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException; import org.gcube.resourcemanagement.support.server.exceptions.ResourceParameterException;
@ -70,14 +73,16 @@ public class ServiceManager extends AbstractResourceManager {
} }
@Override @Override
protected final GCUBEResource buildGCUBEResource(final String xmlRepresentation) protected final Resource buildResource(final String xmlRepresentation) throws AbstractResourceException {
throws AbstractResourceException {
try { try {
GCUBEService impl = GHNContext.getImplementation(GCUBEService.class); JAXBContext ctx = JAXBContext.newInstance(Software.class);
impl.load(new StringReader(xmlRepresentation)); Unmarshaller unmarshaller = ctx.createUnmarshaller();
return impl; StringReader reader = new StringReader(xmlRepresentation);
Software deserialised = (Software) unmarshaller.unmarshal(reader);
return deserialised;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e); throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e);
} }
} }
} }

View File

@ -1,86 +0,0 @@
/****************************************************************************
* This software is part of the gCube System.
* 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: MetadataCollectionManager.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.core.contexts.GHNContext;
import org.gcube.common.core.resources.GCUBEMCollection;
import org.gcube.common.core.resources.GCUBEResource;
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 ViewManager extends AbstractResourceManager {
/**
* @deprecated discouraged use. With no ID some operations cannot be accessed.
*/
public ViewManager()
throws ResourceParameterException,
ResourceAccessException {
super(AllowedResourceTypes.VIEW);
}
public ViewManager(final String id)
throws ResourceParameterException,
ResourceAccessException {
super(id, AllowedResourceTypes.VIEW);
}
/**
* @param id
* @param name
* @param type
* @throws ResourceParameterException
* @throws ResourceAccessException
*/
public ViewManager(final String id, final String name)
throws ResourceParameterException,
ResourceAccessException {
super(id, name, AllowedResourceTypes.VIEW);
}
/**
* @param id
* @param name
* @param type
* @param subtype
* @throws ResourceParameterException
* @throws ResourceAccessException
*/
public ViewManager(final String id, final String name, final String subtype)
throws ResourceParameterException, ResourceAccessException {
super(id, name, AllowedResourceTypes.VIEW, subtype);
}
@Override
protected final GCUBEResource buildGCUBEResource(final String xmlRepresentation)
throws AbstractResourceException {
try {
GCUBEMCollection impl = GHNContext.getImplementation(GCUBEMCollection.class);
impl.load(new StringReader(xmlRepresentation));
return impl;
} catch (Exception e) {
throw new ResourceAccessException("Cannot load the stub for resource " + this.getType(), e);
}
}
}

View File

@ -1,4 +1,10 @@
/**************************************************************************** /****************************************************************************
*
*
*
*
* This software is part of the gCube Project. * This software is part of the gCube Project.
* Site: http://www.gcube-system.org/ * Site: http://www.gcube-system.org/
**************************************************************************** ****************************************************************************
@ -16,19 +22,30 @@
package org.gcube.resourcemanagement.support.server.tests; package org.gcube.resourcemanagement.support.server.tests;
import java.io.File; import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.util.Map;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.gcube.common.core.contexts.GHNContext.Status;
import org.gcube.common.core.resources.GCUBEHostingNode;
import org.gcube.common.core.scope.GCUBEScope; import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.scope.GCUBEScope.Type; import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.resourcemanagement.support.client.utils.StatusHandler;
import org.gcube.resourcemanagement.support.server.gcube.CacheManager;
import org.gcube.resourcemanagement.support.server.gcube.ISClientRequester;
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.GHNManager;
import org.gcube.resourcemanagement.support.server.managers.resources.GenericResourceManager; import org.gcube.resourcemanagement.support.server.managers.resources.GenericResourceManager;
import org.gcube.resourcemanagement.support.server.managers.resources.ResourceFactory;
import org.gcube.resourcemanagement.support.server.managers.scope.ScopeManager; 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.server.utils.ServerConsole;
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;
/** /**
* @author Daniele Strollo (ISTI-CNR) * @author Daniele Strollo (ISTI-CNR)
@ -37,37 +54,6 @@ import org.gcube.resourcemanagement.support.server.utils.ServerConsole;
public class GenericTest { public class GenericTest {
private static final String LOG_PREFIX = "[SW-SUPPORT-TEST]"; private static final String LOG_PREFIX = "[SW-SUPPORT-TEST]";
public static void testScope() {
try {
Map<String, GCUBEScope> scopes = ScopeManager.getAvailableScopes();
System.out.println("\n\n\n******************** TEST SCOPE ***************\n");
for (GCUBEScope scope : scopes.values()) {
if ((scope.getType().compareTo(Type.INFRASTRUCTURE) == 0)
|| (scope.getType().compareTo(Type.VO) == 0)) {
if (scope.getServiceMap() != null) {
ServerConsole.trace(null, "*** Map loaded for " + scope.getType() + " " + scope.toString() + " [OK]");
} else {
ServerConsole.trace(null, "*** Map loaded for " + scope.getType() + " " + scope.toString() + " [ERR]");
}
} else {
try {
if (scope.getEnclosingScope().getServiceMap() != null) {
ServerConsole.trace(null, "*** Map loaded for " + scope.getType() + scope.toString() + " [OK]");
}
} catch (Exception e) {
ServerConsole.trace(null, "*** Map loaded for " + scope.getType() + scope.toString() + " [ERR]");
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("\n******************** TEST SCOPE END ***************\n");
}
}
public static String testCreation() { public static String testCreation() {
System.out.println("\n\n\n******************** TEST CREATION ***************"); System.out.println("\n\n\n******************** TEST CREATION ***************");
@ -76,11 +62,11 @@ public class GenericTest {
try { try {
resID = GenericResourceManager.create( resID = GenericResourceManager.create(
null, null,
ScopeManager.getScope("/gcube/devsec"), new ScopeBean("/gcube/devsec"),
"GR Test", "RMP Test",
"GR Test Description", "RMP Test Description",
"<TestBody>Hello</TestBody>", "<TestBody>Hello</TestBody>",
"XXX"); "test");
ServerConsole.trace(null, "Generic Resource Created with ID: " + resID); ServerConsole.trace(null, "Generic Resource Created with ID: " + resID);
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
@ -95,7 +81,7 @@ public class GenericTest {
try { try {
GenericResourceManager res = new GenericResourceManager(resID); GenericResourceManager res = new GenericResourceManager(resID);
ServerConsole.trace(null, ServerConsole.trace(null,
res.addToExistingScope(ScopeManager.getScope(fromScope), ScopeManager.getScope(toScope)) res.addToExistingScope(new ScopeBean(fromScope), new ScopeBean(toScope))
); );
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
@ -104,11 +90,11 @@ public class GenericTest {
} }
} }
public static void testResourceEdit(final String resID, final GCUBEScope scope) { public static void testResourceEdit(final String resID, final ScopeBean scope) {
System.out.println("\n\n\n******************** TEST RESEDIT COPY ***************"); System.out.println("\n\n\n******************** TEST RESEDIT COPY ***************");
try { try {
GenericResourceManager res = new GenericResourceManager(resID); GenericResourceManager res = new GenericResourceManager(resID);
res.update("New Name", "updated description", null, null, scope); res.update(res.getName()+" Edited", "updated description", "<update>updated body</update>", "test2", scope);
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
} finally { } finally {
@ -118,18 +104,19 @@ public class GenericTest {
public static void testModeGHN(final String resID, final String scope) public static void testModeGHN(final String resID, final String scope)
throws Exception { throws Exception {
GCUBEScope queryScope = ScopeManager.getScope(scope); ScopeBean queryScope = new ScopeBean(scope);
GHNManager ghnManager = new GHNManager(resID); GHNManager ghnManager = new GHNManager(resID);
GCUBEHostingNode res = (GCUBEHostingNode) ghnManager.getGCUBEResource(queryScope); HostingNode res = (HostingNode) ghnManager.getResource(queryScope);
res.getNodeDescription().setStatus(Status.UNREACHABLE); res.profile().description().status("CERTIFIED");
ghnManager.getISPublisher().updateGCUBEResource(res, queryScope, ghnManager.getSecurityManager()); ScopeProvider.instance.set(queryScope.name());
ghnManager.getRegistryPublisher().update(res);
} }
public static void testGHN() { public static void testGHN() {
System.out.println("\n\n\n******************** TEST GHN ***************"); System.out.println("\n\n\n******************** TEST GHN ***************");
try { try {
GHNManager ghn1 = new GHNManager("20ddb210-b779-11df-96c9-a66904b26e27", "pc-strollo"); GHNManager ghn1 = new GHNManager("796f0680-3937-11e2-9d5f-ae6a92affb51", "pcd4science3.cern.ch");
ghn1.addToExistingScope(ScopeManager.getScope("/gcube"), ScopeManager.getScope("/gcube/devsec")); ghn1.addToExistingScope(new ScopeBean("/gcube"), new ScopeBean("/gcube/devsec"));
} catch (Exception e) { } catch (Exception e) {
ServerConsole.error(LOG_PREFIX, e); ServerConsole.error(LOG_PREFIX, e);
} finally { } finally {
@ -137,7 +124,7 @@ public class GenericTest {
} }
} }
public static void testRemoveFromScope(final String resID, final GCUBEScope scope) { public static void testRemoveFromScope(final String resID, final ScopeBean scope) {
System.out.println("\n\n\n******************** TEST RESOURCE REMOVEFROMSCOPE ***************"); System.out.println("\n\n\n******************** TEST RESOURCE REMOVEFROMSCOPE ***************");
try { try {
GenericResourceManager res = new GenericResourceManager(resID); GenericResourceManager res = new GenericResourceManager(resID);
@ -148,8 +135,9 @@ public class GenericTest {
System.out.println("\n******************** TEST RESOURCE REMOVEFROMSCOPE END ***************\n"); System.out.println("\n******************** TEST RESOURCE REMOVEFROMSCOPE END ***************\n");
} }
} }
public static void testDelete(final String resID, final GCUBEScope scope) { public static void testDelete(final String resID, final ScopeBean scope) {
System.out.println("\n\n\n******************** TEST RESOURCE DELETE ***************"); System.out.println("\n\n\n******************** TEST RESOURCE DELETE ***************");
try { try {
GenericResourceManager res = new GenericResourceManager(resID); GenericResourceManager res = new GenericResourceManager(resID);
@ -161,27 +149,50 @@ public class GenericTest {
} }
} }
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<ResourceDescriptor> descs = ISClientRequester.getResourceModels(scope, "GenericResource", null, null);
for (ResourceDescriptor resourceDescriptor : descs) {
System.out.println(resourceDescriptor);
}
}
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void main(final String[] args) throws Exception { public static void main(final String[] args) throws Exception {
// The scopes must be initialized // The scopes must be initialized
ScopeManager.setScopeConfigFile("test-suite" + File.separator + "scopes" + File.separator + "scopedata_admin.xml"); ScopeManager.setScopeConfigFile("test-suite" + File.separator + "scopes" + File.separator + "scopedata_admin.xml");
boolean deepTest = false; ScopeProvider.instance.set("/gcube/devsec");
// testScope();
// testGHN(); //testTree( new ScopeBean("/gcube"));
if (deepTest) {
// boolean deepTest = true;
//
// // testGHN();
// if (deepTest) {
String resID = testCreation(); String resID = testCreation();
testScopeCopy(resID, "/gcube/devsec", "/gcube/devsec/devVRE"); testScopeCopy(resID, "/gcube/devsec", "/gcube/devsec/devVRE");
//////
System.out.println("\n\nWaiting for resource refresh 60secs.\n\n\n"); // System.out.println("\n\nWaiting for resource refresh 20secs.\n\n\n");
Thread.sleep(60000); // Thread.sleep(20000);
//
//testResourceEdit(resID, ScopeManager.getScope("/gcube/devsec")); //
testDelete(resID, ScopeManager.getScope("/gcube/devsec/devVRE")); // //testResourceEdit(resID, new ScopeBean("/gcube/devsec"));
// //testDelete(resID, new ScopeBean("/gcube/devsec"));
// testRemoveFromScope(resID, ScopeManager.getScope("/gcube/devsec")); //
} else { // testRemoveFromScope(resID, new ScopeBean("/gcube/devsec/devVRE"));
testModeGHN("f5cb0640-f1a7-11df-93d0-fc409084cf46", "/gcube/devsec/devVRE"); // } else {
} // testModeGHN("796f0680-3937-11e2-9d5f-ae6a92affb51", "/gcube/devsec/devVRE");
// }
} }
} }

View File

@ -20,7 +20,6 @@ import java.io.Serializable;
import org.gcube.resourcemanagement.support.client.views.ResourceTypeDecorator; import org.gcube.resourcemanagement.support.client.views.ResourceTypeDecorator;
import com.google.gwt.user.client.rpc.IsSerializable; import com.google.gwt.user.client.rpc.IsSerializable;
/** /**
@ -30,8 +29,8 @@ import com.google.gwt.user.client.rpc.IsSerializable;
* @author Daniele Strollo (ISTI-CNR) * @author Daniele Strollo (ISTI-CNR)
* *
*/ */
public class CompleteResourceProfile implements Serializable, IsSerializable { @SuppressWarnings("serial")
private static final long serialVersionUID = 1L; public class CompleteResourceProfile implements Serializable {
private String xmlRepresentation = null; private String xmlRepresentation = null;
private String htmlRepresentation = null; private String htmlRepresentation = null;
private ResourceTypeDecorator type = null; private ResourceTypeDecorator type = null;

View File

@ -23,16 +23,18 @@ import org.gcube.resourcemanagement.support.shared.util.Assertion;
import com.extjs.gxt.ui.client.data.BaseModelData; import com.extjs.gxt.ui.client.data.BaseModelData;
import com.google.gwt.user.client.rpc.IsSerializable; import com.google.gwt.user.client.rpc.IsSerializable;
/** /**
* All the resources that want to access resource management * All the resources that want to access resource management
* operations must be described through this data type. * operations must be described through this data type.
* @author Daniele Strollo (ISTI-CNR) * @author Massimiliano Assante (ISTI-CNR)
* @author Daniele Strollo
*/ */
public class ResourceDescriptor extends BaseModelData implements Serializable, IsSerializable { @SuppressWarnings("serial")
private static final long serialVersionUID = 6435512868470974421L; public class ResourceDescriptor extends BaseModelData implements Serializable {
public ResourceDescriptor() { public ResourceDescriptor() {
super(); super();
@ -46,11 +48,7 @@ public class ResourceDescriptor extends BaseModelData implements Serializable, I
* @param name the short name assigned to the resource (mandatory). * @param name the short name assigned to the resource (mandatory).
* @throws InvalidParameterException * @throws InvalidParameterException
*/ */
public ResourceDescriptor( public ResourceDescriptor(String type, String subtype, String id, String name) throws InvalidParameterException {
final String type,
final String subtype,
final String id,
final String name) throws InvalidParameterException {
super(); super();
Assertion<InvalidParameterException> checker = new Assertion<InvalidParameterException>(); Assertion<InvalidParameterException> checker = new Assertion<InvalidParameterException>();
checker.validate(name != null && name.length() > 0, new InvalidParameterException("The ghnName is null or empty")); checker.validate(name != null && name.length() > 0, new InvalidParameterException("The ghnName is null or empty"));
@ -110,4 +108,13 @@ public class ResourceDescriptor extends BaseModelData implements Serializable, I
public final Object getProperty(final String property) { public final Object getProperty(final String property) {
return get(property); return get(property);
} }
@Override
public String toString() {
return "ResourceDescriptor [getType()=" + getType() + ", getSubtype()="
+ getSubtype() + ", getID()=" + getID() + ", getName()="
+ getName() + "]";
}
} }

Binary file not shown.