diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java index d93dd93..b82e89b 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java @@ -2,29 +2,40 @@ package org.gcube.informationsystem.resourceregistry.er.entity; import java.util.HashMap; import java.util.Map; +import java.util.UUID; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.AccessType; +import org.gcube.informationsystem.model.embedded.Header; import org.gcube.informationsystem.model.entity.Entity; +import org.gcube.informationsystem.model.entity.Facet; +import org.gcube.informationsystem.model.entity.Resource; +import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.utils.Utility; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.orient.OrientEdge; +import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientVertex; +import com.tinkerpop.blueprints.impls.orient.OrientVertexType; /** * @author Luca Frosini (ISTI - CNR) @@ -171,7 +182,8 @@ public abstract class EntityManagement extends ERManagement extends ERManagement edges = getElement().getEdges(Direction.OUT); @@ -221,4 +234,175 @@ public abstract class EntityManagement extends ERManagement constraint) throws ResourceRegistryException { + JSONArray jsonArray = new JSONArray(); + + + + // TODO check types + + /* + * SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT + * FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor')) + * + * WHERE @class='EService' // Only is not polymorphic + */ + + boolean first = true; + + StringBuilder selectStringBuilder = new StringBuilder("SELECT FROM (TRAVERSE "); + selectStringBuilder.append(direction.name().toLowerCase()); + selectStringBuilder.append("E('"); + selectStringBuilder.append(relationType); + selectStringBuilder.append("'), "); + selectStringBuilder.append(direction.opposite().name().toLowerCase()); + selectStringBuilder.append("V('"); + selectStringBuilder.append(erType); + selectStringBuilder.append("') FROM (SELECT FROM "); + selectStringBuilder.append(referenceType); + for(String key : constraint.keySet()) { + if(first) { + selectStringBuilder.append(" WHERE "); + first = false; + } else { + selectStringBuilder.append(" AND "); + } + selectStringBuilder.append(key); + selectStringBuilder.append("="); + String value = constraint.get(key).trim(); + selectStringBuilder.append("'"); + selectStringBuilder.append(value); + selectStringBuilder.append("'"); + } + selectStringBuilder.append(" ))"); + + if(!polymorphic) { + selectStringBuilder.append(" WHERE @class='"); + selectStringBuilder.append(erType); + selectStringBuilder.append("'"); + } + + String select = selectStringBuilder.toString(); + logger.trace(select); + + OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); + Iterable elements = orientGraph.command(osqlSynchQuery).execute(); + + for(Element element : elements) { + + if(polymorphic) { + OrientVertexType orientVertexType = null; + try { + OrientElement orientElement = ((OrientElement) element); + if(orientElement instanceof OrientEdge) { + continue; + } + orientVertexType = ((OrientVertex) orientElement).getType(); + } catch(Exception e) { + String error = String.format("Unable to detect type of %s. %s", element.toString(), + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + logger.error(error, e); + throw new ResourceRegistryException(error); + } + + if(orientVertexType.getName().compareTo(erType) != 0) { + if(!orientVertexType.isSubClassOf(erType)) { + continue; + } + } + + } + + Vertex vertex = (Vertex) element; + + @SuppressWarnings("rawtypes") + EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), + orientGraph, vertex); + try { + JSONObject jsonObject = entityManagement.serializeAsJson(); + jsonArray.put(jsonObject); + } catch(ResourceRegistryException e) { + logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", + vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + } + } + + return jsonArray.toString(); + } + + public String query(String relationType, String referenceType, UUID referenceUUID, Direction direction, + boolean polymorphic, Map constraint) throws ResourceRegistryException { + try { + orientGraph = getWorkingContext().getGraph(PermissionMode.READER); + + AccessType relationAccessType = ERManagementUtility.getBaseAccessType(relationType); + if(relationAccessType != AccessType.IS_RELATED_TO || relationAccessType != AccessType.CONSISTS_OF) { + String error = String.format("%s must be a relation type", relationType); + throw new ResourceRegistryException(error); + } + + AccessType referenceAccessType = ERManagementUtility.getBaseAccessType(referenceType); + if(referenceAccessType != AccessType.RESOURCE || relationAccessType != AccessType.FACET) { + String error = String.format("%s must be a en entity type", referenceType); + throw new ResourceRegistryException(error); + } + + if(constraint==null) { + constraint = new HashMap<>(); + } + + switch(accessType) { + case RESOURCE: + + if(relationAccessType == AccessType.CONSISTS_OF) { + + if(direction != Direction.OUT) { + String error = String.format("%s can only goes %s from %s.", relationType, + Direction.OUT.name(), erType); + throw new InvalidQueryException(error); + } else { + if(referenceAccessType != AccessType.FACET) { + String error = String.format("%s can only has as target a %s. Provided instead %s : %s", + relationType, Facet.NAME, referenceAccessType, referenceType); + throw new InvalidQueryException(error); + } + } + } + + break; + + case FACET: + if(relationAccessType != AccessType.CONSISTS_OF || direction != Direction.IN + || referenceAccessType != AccessType.RESOURCE) { + String error = String.format("%s can only has %s %s from a %s.", erType, Direction.IN.name(), + ConsistsOf.NAME, Resource.NAME); + throw new InvalidQueryException(error); + } + + break; + + default: + break; + } + + if(referenceUUID!=null) { + constraint.put(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY, referenceUUID.toString()); + } + + return reallyQuery(relationType, referenceType, direction, polymorphic, constraint); + + } catch(ResourceRegistryException e) { + throw e; + } catch(Exception e) { + throw new ResourceRegistryException(e); + } finally { + if(orientGraph != null) { + orientGraph.shutdown(); + } + } + } + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java index 943cc0e..3b748f1 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java @@ -1,9 +1,7 @@ package org.gcube.informationsystem.resourceregistry.er.entity; import java.util.Iterator; -import java.util.Map; -import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.entity.Resource; @@ -14,27 +12,20 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; -import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.utils.Utility; import com.fasterxml.jackson.databind.JsonNode; -import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientEdge; import com.tinkerpop.blueprints.impls.orient.OrientEdgeType; -import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientGraph; -import com.tinkerpop.blueprints.impls.orient.OrientVertex; -import com.tinkerpop.blueprints.impls.orient.OrientVertexType; /** * @author Luca Frosini (ISTI - CNR) @@ -235,11 +226,11 @@ public class ResourceManagement extends EntityManagement { return true; } - public String all(boolean polymorphic, Map constraint) throws ResourceRegistryException { + public String all(boolean polymorphic) throws ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - return reallyGetAll(polymorphic, constraint); + return reallyGetAll(polymorphic); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { @@ -251,13 +242,14 @@ public class ResourceManagement extends EntityManagement { } } + /* public String reallyGetAll(boolean polymorphic, Map constraint) throws ResourceRegistryException { JSONArray jsonArray = new JSONArray(); - String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART); - constraint.remove(AccessPath.RELATION_TYPE_PATH_PART); - String facetType = constraint.get(AccessPath.FACET_TYPE_PATH_PART); - constraint.remove(AccessPath.FACET_TYPE_PATH_PART); + String consistsOfType = constraint.get(ConsistsOf.NAME); + constraint.remove(ConsistsOf.NAME); + String facetType = constraint.get(Facet.NAME); + constraint.remove(Facet.NAME); // TODO check types @@ -266,12 +258,12 @@ public class ResourceManagement extends EntityManagement { * FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor')) * * WHERE @class='EService' // Only is not polymorphic - */ + * / boolean first = true; StringBuilder selectStringBuilder = new StringBuilder("SELECT FROM (TRAVERSE inE('"); - selectStringBuilder.append(relationType); + selectStringBuilder.append(consistsOfType); selectStringBuilder.append("'), outV('"); selectStringBuilder.append(erType); selectStringBuilder.append("') FROM (SELECT FROM "); @@ -345,5 +337,5 @@ public class ResourceManagement extends EntityManagement { return jsonArray.toString(); } - + */ } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java index 1915b69..08198cd 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java @@ -493,6 +493,7 @@ public abstract class RelationManagement pathValues, Map map) { + public static void setCalledMethod(HTTPMETHOD httpMethod, List pathValues, Map map) { StringWriter stringWriter = new StringWriter(); stringWriter.append(httpMethod.name()); boolean first = true; - for(String value : pathValues){ + for(String value : pathValues) { stringWriter.append(first ? " /" : "/"); stringWriter.append(value); } first = true; - if(map!=null) { + if(map != null) { for(String key : map.keySet()) { stringWriter.append(first ? "?" : "&"); stringWriter.append(key); @@ -76,14 +71,14 @@ public class Access { stringWriter.append(map.get(key)); } } - CalledMethodProvider.instance.set(stringWriter.toString()); + CalledMethodProvider.instance.set(stringWriter.toString()); } protected void setCalledMethodLocal(HTTPMETHOD httpMethod, String path) { setCalledMethodLocal(httpMethod, path, null); } - protected void setCalledMethodLocal(HTTPMETHOD httpMethod, String path, Map map) { + protected void setCalledMethodLocal(HTTPMETHOD httpMethod, String path, Map map) { List list = new ArrayList<>(); list.add(path); setCalledMethodLocal(httpMethod, list, map); @@ -93,7 +88,8 @@ public class Access { setCalledMethodLocal(httpMethod, pathValues, null); } - protected void setCalledMethodLocal(HTTPMETHOD httpMethod, List pathValues, Map map) { + + protected void setCalledMethodLocal(HTTPMETHOD httpMethod, List pathValues, Map map) { List list = new ArrayList<>(); list.add(AccessPath.ACCESS_PATH_PART); list.addAll(pathValues); @@ -106,8 +102,7 @@ public class Access { @GET @Path(AccessPath.CONTEXTS_PATH_PART) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getAllContexts() - throws ResourceRegistryException { + public String getAllContexts() throws ResourceRegistryException { logger.info("Requested to read all {}s", org.gcube.informationsystem.model.entity.Context.NAME); setCalledMethodLocal(HTTPMETHOD.GET, AccessPath.CONTEXTS_PATH_PART); ContextManagement contextManagement = new ContextManagement(); @@ -134,7 +129,6 @@ public class Access { return contextManagement.read(); } - /* * GET /access/types/{TYPE_NAME}[?polymorphic=false] * e.g. GET /access/types/ContactFacet?polymorphic=true @@ -151,15 +145,14 @@ public class Access { List pathValues = new ArrayList<>(); pathValues.add(AccessPath.TYPES_PATH_PART); pathValues.add(type); - Map map = new HashMap(); - map.put(InstancePath.POLYMORPHIC_PARAM, polymorphic.toString()); + Map map = new HashMap(); + map.put(AccessPath.POLYMORPHIC_PARAM, polymorphic.toString()); setCalledMethodLocal(HTTPMETHOD.GET, pathValues, map); SchemaManagement schemaManagement = new SchemaManagementImpl(); return schemaManagement.read(type, polymorphic); } - /* * GET /access/instances/{TYPE_NAME}[?polymorphic=true] * e.g. GET /access/instances/ContactFacet?polymorphic=true @@ -169,26 +162,23 @@ public class Access { @Path(AccessPath.INSTANCES_PATH_PART + "/{" + AccessPath.TYPE_PATH_PARAM + "}") @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getAllInstances(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, - @QueryParam(InstancePath.POLYMORPHIC_PARAM) @DefaultValue("true") Boolean polymorphic) + public String getAllInstances(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, + @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("true") Boolean polymorphic) throws NotFoundException, ResourceRegistryException { + logger.info("Requested all {}instances of {}", polymorphic ? AccessPath.POLYMORPHIC_PARAM + " " : "", type); - logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_PARAM + " ": "", type); List pathValues = new ArrayList<>(); pathValues.add(AccessPath.INSTANCES_PATH_PART); pathValues.add(type); - Map map = new HashMap(); - map.put(InstancePath.POLYMORPHIC_PARAM, polymorphic.toString()); + Map map = new HashMap(); + map.put(AccessPath.POLYMORPHIC_PARAM, polymorphic.toString()); setCalledMethodLocal(HTTPMETHOD.GET, pathValues, map); - - @SuppressWarnings("rawtypes") ERManagement erManagement = ERManagementUtility.getERManagement(type); return erManagement.all(polymorphic); } - /* * HEAD /access/instances/{TYPE_NAME}/{UUID} * e.g. HEAD /access/instances/ContactFacet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 @@ -198,8 +188,8 @@ public class Access { @Path("/{" + AccessPath.TYPE_PATH_PARAM + "}" + "/{" + AccessPath.UUID_PATH_PARAM + "}") @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public Response instanceExists(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, @PathParam(AccessPath.UUID_PATH_PARAM) String uuid) - throws NotFoundException, ResourceRegistryException { + public Response instanceExists(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, + @PathParam(AccessPath.UUID_PATH_PARAM) String uuid) throws NotFoundException, ResourceRegistryException { logger.info("Requested to check if {} with id {} exists", type, uuid); List pathValues = new ArrayList<>(); @@ -239,8 +229,8 @@ public class Access { @Path("/{" + AccessPath.TYPE_PATH_PARAM + "}" + "/{" + AccessPath.UUID_PATH_PARAM + "}") @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getInstance(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, @PathParam(AccessPath.UUID_PATH_PARAM) String uuid) - throws NotFoundException, ResourceRegistryException { + public String getInstance(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, + @PathParam(AccessPath.UUID_PATH_PARAM) String uuid) throws NotFoundException, ResourceRegistryException { logger.info("Requested to read {} with id {}", type, uuid); List pathValues = new ArrayList<>(); pathValues.add(AccessPath.INSTANCES_PATH_PART); @@ -256,20 +246,6 @@ public class Access { return erManagement.read(); } - - - - - - - - - - - - - - /** * It includeSubtypes to query Entities and Relations in the current Context.
* It accepts idempotent query only..
@@ -280,135 +256,102 @@ public class Access { * https://orientdb.com/docs/last/SQL-Syntax.html
*
* - * e.g. GET /resource-registry/access?query=SELECT FROM V + * e.g. GET /access/query?q=SELECT FROM V&limit=20&fetchPlan=*:-1 * - * @param query - * Defines the query to send to the backend. - * @param limit - * Defines the number of results you want returned, defaults to includeSubtypes results. + * @param query Defines the query to send to the backend. + * @param limit Defines the number of results you want returned (default 20, use -1 to unbounded results) * @param fetchPlan * Defines the fetching strategy you want to use. See * * https://orientdb.com/docs/last/Fetching-Strategies.html * * @return The JSON representation of the result - * @throws InvalidQueryException - * if the query is invalid or no idempotent + * @throws InvalidQueryException if the query is invalid or not idempotent */ @GET @Path(AccessPath.QUERY_PATH_PART) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String query(@QueryParam(AccessPath.QUERY_PARAM) String query, @QueryParam(AccessPath.LIMIT_PARAM) Integer limit, - @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) throws InvalidQueryException { + @QueryParam(AccessPath.FETCH_PLAN_PARAM) @DefaultValue(AccessPath.DEFAULT_FETCH_PLAN) String fetchPlan) + throws InvalidQueryException { logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query); + setCalledMethodLocal(HTTPMETHOD.GET, AccessPath.QUERY_PATH_PART); + Query queryManager = new QueryImpl(); return queryManager.query(query, limit, fetchPlan); } - - /* - * e.g. - * GET /resource-registry/access/instances/EService?polymorphic=true - * &reference=4d28077b-566d-4132-b073-f4edaf61dcb9 &direction=(in|out|both) + * /access/query/{RESOURCE_TYPE_PATH_PART}/{RELATION_TYPE_PATH_PART}/{ENTITY_TYPE_NAME}[?reference=&polymorphic=true&direction=out] + * e.g. GET /access/query/EService/isIdentifiedBy/SoftwareFacet?reference=16032d09-3823-444e-a1ff-a67de4f350a8&polymorphic=true&direction=out */ @SuppressWarnings({"rawtypes"}) @GET - @Path(AccessPath.INSTANCES_PATH_PART + "/" + "{" + AccessPath.TYPE_PATH_PARAM + "}") + @Path(AccessPath.QUERY_PATH_PART + "/" + "{" + AccessPath.RESOURCE_TYPE_PATH_PART + "}" + "/" + "{" + + AccessPath.RELATION_TYPE_PATH_PART + "}" + "/" + "{" + AccessPath.REFERENCE_TYPE_PATH_PART + "}") @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getInstances(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, - @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic, + public String getAllResourcesHavingFacet(@PathParam(AccessPath.RESOURCE_TYPE_PATH_PART) String resourcetype, + @PathParam(AccessPath.RELATION_TYPE_PATH_PART) String relationType, + @PathParam(AccessPath.REFERENCE_TYPE_PATH_PART) String referenceType, @QueryParam(AccessPath.REFERENCE) String reference, - @QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction) throws ResourceRegistryException { - logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic); - - ERManagement erManagement = ERManagementUtility.getERManagement(type); - - if(erManagement instanceof EntityManagement) { - return erManagement.all(polymorphic); - } - - if(erManagement instanceof RelationManagement) { - if(reference != null) { - UUID uuid = null; - try { - uuid = UUID.fromString(reference); - } catch(Exception e) { - String errror = String.format("Provided %s (%s) is not a valid %s", AccessPath.REFERENCE, reference, - UUID.class.getSimpleName()); - throw new ResourceRegistryException(errror); - } - - Direction directionEnum; - if(direction == null) { - directionEnum = Direction.BOTH; - } else { - try { - directionEnum = Enum.valueOf(Direction.class, direction.trim().toUpperCase()); - } catch(Exception e) { - String errror = String.format("Provided %s (%s) is not valid. Allowed values are %s", - AccessPath.DIRECTION, direction, Arrays.toString(Direction.values()).toLowerCase()); - throw new ResourceRegistryException(errror); - } - } - - return ((RelationManagement) erManagement).allFrom(uuid, directionEnum, polymorphic); - - } else { - return erManagement.all(polymorphic); - } - } - - throw new ResourceRegistryException("Invalid Request"); - } - - /* - * e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet - * ?polymorphic=true - */ - @SuppressWarnings({"rawtypes"}) - @GET - @Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + AccessPath.TYPE_PATH_PARAM + "}" + "/" + "{" - + AccessPath.RELATION_TYPE_PATH_PART + "}" + "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}") - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getFilteredInstances(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, - @PathParam(AccessPath.RELATION_TYPE_PATH_PART) @DefaultValue(ConsistsOf.NAME) String relationType, - @PathParam(AccessPath.FACET_TYPE_PATH_PART) @DefaultValue(Facet.NAME) String facetType, @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic, + @QueryParam(AccessPath.DIRECTION) @DefaultValue("out") String direction, @Context UriInfo uriInfo) throws ResourceRegistryException { - logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic); - MultivaluedMap multivaluedMap = uriInfo.getQueryParameters(); + logger.info("Requested {} instances having a(n) {} ({}={}} with {} ({}={})", resourcetype, relationType, + AccessPath.DIRECTION, direction, referenceType, AccessPath.POLYMORPHIC_PARAM, polymorphic); - Map constraint = new HashMap<>(); - for(String key : multivaluedMap.keySet()) { - if(key.compareTo(AccessPath.POLYMORPHIC_PARAM) == 0) { - continue; - } - if(key.compareTo("gcube-token") == 0) { - continue; - } - if(key.compareTo("gcube-scope") == 0) { - continue; - } - constraint.put(key, multivaluedMap.getFirst(key)); - } - constraint.put(AccessPath.RELATION_TYPE_PATH_PART, relationType); - constraint.put(AccessPath.FACET_TYPE_PATH_PART, facetType); + List pathValues = new ArrayList<>(); + pathValues.add(AccessPath.QUERY_PATH_PART); + pathValues.add(resourcetype); + pathValues.add(relationType); + pathValues.add(referenceType); + setCalledMethodLocal(HTTPMETHOD.GET, pathValues); - ERManagement erManagement = ERManagementUtility.getERManagement(type); + ERManagement erManagement = ERManagementUtility.getERManagement(resourcetype); if(erManagement instanceof ResourceManagement) { - return ((ResourceManagement) erManagement).all(polymorphic, constraint); + UUID refereceUUID = null; + Direction directionEnum = Direction.OUT; + + Map constraint = new HashMap<>(); + + MultivaluedMap multivaluedMap = uriInfo.getQueryParameters(); + for(String key : multivaluedMap.keySet()) { + if(key.compareTo(AccessPath.POLYMORPHIC_PARAM) == 0) { + continue; + } + if(key.compareTo("gcube-token") == 0) { + continue; + } + if(key.compareTo("gcube-scope") == 0) { + continue; + } + constraint.put(key, multivaluedMap.getFirst(key)); + } + + if(reference != null) { + try { + refereceUUID = UUID.fromString(reference); + } catch(Exception e) { + String error = String.format("%s is not a valid %s", reference, UUID.class.getSimpleName()); + throw new InvalidQueryException(error); + } + } + try { + directionEnum = Direction.valueOf(direction); + } catch(Exception e) { + String error = String.format("%s is not a valid. Allowed values are %s", direction, Direction.values()); + throw new InvalidQueryException(error); + } + + return ((ResourceManagement) erManagement).query(relationType, referenceType, refereceUUID, directionEnum, + polymorphic, constraint); } - throw new ResourceRegistryException("Invalid Request"); + String error = String.format("%s is not a %s type", resourcetype, Resource.NAME); + throw new InvalidQueryException(error); } - - - - - } \ No newline at end of file diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java deleted file mode 100644 index 76ebb00..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java +++ /dev/null @@ -1,338 +0,0 @@ -package org.gcube.informationsystem.resourceregistry.rest; - -import java.util.UUID; - -import javax.mail.Header; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -import org.gcube.common.authorization.library.provider.CalledMethodProvider; -import org.gcube.informationsystem.model.entity.Context; -import org.gcube.informationsystem.model.entity.Facet; -import org.gcube.informationsystem.model.entity.Resource; -import org.gcube.informationsystem.model.relation.ConsistsOf; -import org.gcube.informationsystem.model.relation.IsRelatedTo; -import org.gcube.informationsystem.resourceregistry.ResourceInitializer; -import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAlreadyPresentException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.rest.ERPath; -import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall.HTTPMETHOD; -import org.gcube.informationsystem.resourceregistry.context.ContextUtility; -import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; -import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; -import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; -import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Luca Frosini (ISTI - CNR) - */ -@Deprecated -@Path(ERPath.ER_PATH_PART) -public class ERManager { - - private static Logger logger = LoggerFactory.getLogger(ERManager.class); - - public static final String ID_PATH_PARAM = "id"; - public static final String TYPE_PATH_PARAM = "type"; - - /** - * e.g. POST /resource-registry/er/facets/ContactFacet - * - * BODY: {...} - * - */ - @POST - @Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json) - throws FacetAlreadyPresentException, ResourceRegistryException { - CalledMethodProvider.instance - .set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/" + type); - logger.info("Requested to create {} of type {}", Facet.NAME, type); - logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json); - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setElementType(type); - facetManagement.setJSON(json); - - UUID uuid = facetManagement.getUUID(); - if(uuid != null) { - String error = String.format( - "Could not specify an UUID in % to create a %s using POST. Please use PUT instead and specify the UUID as path argument.", - Header.class.getSimpleName(), Facet.NAME); - logger.info(error); - throw new ContextCreationException(error); - } - - String ret = facetManagement.create(); - return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - .build(); - } - - /** - * e.g. PUT /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 - * - * BODY: {...} - * - */ - @PUT - @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") - @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json) - throws FacetNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to update {} with id {}", Facet.NAME, uuid); - logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json); - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setUUID(UUID.fromString(uuid)); - facetManagement.setJSON(json); - - - - return facetManagement.update(); - } - - /** - * e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 - * - */ - @DELETE - @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) - throws FacetNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to delete {} with id {}", Facet.NAME, uuid); - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setUUID(UUID.fromString(uuid)); - return facetManagement.delete(); - } - - /* Resources Methods */ - - /** - * e.g. PUT /resource-registry/er/resource/HostingNode - * - * BODY: {...} - * - */ - @PUT - @Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json) - throws ResourceAlreadyPresentException, ResourceRegistryException { - CalledMethodProvider.instance - .set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/" + type); - logger.info("Requested to create {} of type {}", Resource.NAME, type); - logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json); - ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setElementType(type); - resourceManagement.setJSON(json); - String ret = resourceManagement.create(); - return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - .build(); - } - - /** - * e.g. POST /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 - * - * BODY: {...} - * - */ - @POST - @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") - @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json) - throws ResourceNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to update {} with id {}", Resource.NAME, uuid); - logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json); - ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setUUID(UUID.fromString(uuid)); - resourceManagement.setJSON(json); - return resourceManagement.update(); - } - - /** - * e.g. DELETE - * /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 - * - */ - @DELETE - @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception { - CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to delete {} with id {}", Resource.NAME, uuid); - ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setUUID(UUID.fromString(uuid)); - return resourceManagement.delete(); - } - - /** - * e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy - * - * BODY: {...} - * - */ - @PUT - @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json) - throws ResourceAlreadyPresentException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type); - logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type); - logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json); - ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setElementType(type); - consistsOfManagement.setJSON(json); - String ret = consistsOfManagement.create(); - return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - .build(); - } - - /** - * e.g. DELETE - * /resource-registry/er/consistsOf/9bff49c8-c0a7-45de-827c-accb71defbd3 - * - */ - @DELETE - @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID); - ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setUUID(UUID.fromString(consistOfUUID)); - return consistsOfManagement.delete(); - } - - /** - * e.g. PUT /resource-registry/er/isRelatedTo/Hosts - * - * BODY: {...} - * - */ - @PUT - @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) - @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json) - throws ResourceAlreadyPresentException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type); - logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json); - IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); - isRelatedToManagement.setElementType(type); - isRelatedToManagement.setJSON(json); - String ret = isRelatedToManagement.create(); - return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - .build(); - } - - /** - * e.g. DELETE - * /resource-registry/er/isRelatedTo/b3982715-a7aa-4530-9a5f-2f60008d256e - * - */ - @DELETE - @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID); - IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); - isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID)); - return isRelatedToManagement.delete(); - } - - /** - * e.g POST - * /resource-registry/er/add/resource/67062c11-9c3a-4906-870d-7df6a43408b0 - * - */ - @POST - @Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid) - throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME); - ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setUUID(UUID.fromString(uuid)); - return resourceManagement.addToContext(ContextUtility.getCurrentSecurityContext().getUUID()); - } - - /** - * e.g POST /resource-registry/er/add/facet/f6931232-c034-4979-9b2f-7193d3fba7df - * - */ - @POST - @Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid) - throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME); - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setUUID(UUID.fromString(uuid)); - return facetManagement.addToContext(ContextUtility.getCurrentSecurityContext().getUUID()); - } - - /** - * e.g POST - * /resource-registry/er/remove/resource/67062c11-9c3a-4906-870d-7df6a43408b0 - * - */ - @POST - @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid) - throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME); - ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setUUID(UUID.fromString(uuid)); - return resourceManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID()); - } - - /** - * e.g POST - * /resource-registry/er/remove/facet/f6931232-c034-4979-9b2f-7193d3fba7df - * - */ - @POST - @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") - public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid) - throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" - + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME); - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setUUID(UUID.fromString(uuid)); - return facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID()); - } - -} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java index 0ca8dfb..0f88f40 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java @@ -51,6 +51,7 @@ import org.gcube.informationsystem.model.entity.facet.StateFacet; import org.gcube.informationsystem.model.entity.resource.Configuration; import org.gcube.informationsystem.model.entity.resource.EService; import org.gcube.informationsystem.model.entity.resource.HostingNode; +import org.gcube.informationsystem.model.entity.resource.Service; import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.IsIdentifiedBy; import org.gcube.informationsystem.model.relation.IsRelatedTo; @@ -59,6 +60,7 @@ import org.gcube.informationsystem.model.relation.isrelatedto.Hosts; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; @@ -619,6 +621,7 @@ public class ERManagementTest extends ScopedTest { @Test public void testGetAllFrom() throws Exception{ + Map map = createHostingNodeAndEService(); EService eService = (EService) map.get(EService.NAME); @@ -628,11 +631,11 @@ public class ERManagementTest extends ScopedTest { UUID hostingNodeUUID = hostingNode.getHeader().getUUID(); - IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); - isRelatedToManagement.setElementType(IsRelatedTo.NAME); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setElementType(Service.NAME); - /* EService */ - String json = isRelatedToManagement.allFrom(eServiceUUID, Direction.BOTH, true); + /* Getting Hosting Node */ + String json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.BOTH, true, null); List resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==1); Resource sourceResource = resourceList.get(0); @@ -640,8 +643,7 @@ public class ERManagementTest extends ScopedTest { Assert.assertTrue(sourceResource.getHeader().getUUID().compareTo(hostingNodeUUID)==0); Assert.assertTrue(targetResource.getHeader().getUUID().compareTo(eServiceUUID)==0); - - json = isRelatedToManagement.allFrom(eServiceUUID, Direction.IN, true); + json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.OUT, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==1); sourceResource = resourceList.get(0); @@ -649,70 +651,66 @@ public class ERManagementTest extends ScopedTest { Assert.assertTrue(sourceResource.getHeader().getUUID().compareTo(hostingNodeUUID)==0); Assert.assertTrue(targetResource.getHeader().getUUID().compareTo(eServiceUUID)==0); - - json = isRelatedToManagement.allFrom(eServiceUUID, Direction.OUT, true); + json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.IN, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - json = isRelatedToManagement.allFrom(eServiceUUID, Direction.BOTH, false); + json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.BOTH, false, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - json = isRelatedToManagement.allFrom(eServiceUUID, Direction.IN, false); + json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.OUT, false, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - json = isRelatedToManagement.allFrom(eServiceUUID, Direction.OUT, false); + json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.IN, false, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - /* END EService */ + /* END Getting Hosting Node */ + - - /* Hosting Node */ - json = isRelatedToManagement.allFrom(hostingNodeUUID, Direction.BOTH, true); + /* Getting EService */ + json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.BOTH, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==1); - sourceResource = resourceList.get(0); - targetResource = sourceResource.getIsRelatedTo().get(0).getTarget(); - Assert.assertTrue(sourceResource.getHeader().getUUID().compareTo(hostingNodeUUID)==0); - Assert.assertTrue(targetResource.getHeader().getUUID().compareTo(eServiceUUID)==0); + Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID)==0); - - json = isRelatedToManagement.allFrom(hostingNodeUUID, Direction.IN, true); - resourceList = ISMapper.unmarshalList(Resource.class, json); - Assert.assertTrue(resourceList.size()==0); - - json = isRelatedToManagement.allFrom(hostingNodeUUID, Direction.OUT, true); + json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.OUT, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==1); - sourceResource = resourceList.get(0); - targetResource = sourceResource.getIsRelatedTo().get(0).getTarget(); - Assert.assertTrue(sourceResource.getHeader().getUUID().compareTo(hostingNodeUUID)==0); - Assert.assertTrue(targetResource.getHeader().getUUID().compareTo(eServiceUUID)==0); + Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID)==0); + Assert.assertTrue(resourceList.size()==0); - - json = isRelatedToManagement.allFrom(hostingNode.getHeader().getUUID(), Direction.BOTH, false); + json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.IN, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - json = isRelatedToManagement.allFrom(hostingNode.getHeader().getUUID(), Direction.IN, false); + + json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.BOTH, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - json = isRelatedToManagement.allFrom(hostingNode.getHeader().getUUID(), Direction.OUT, false); + json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.OUT, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); - /* END HostingNode */ + json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.IN, true, null); + resourceList = ISMapper.unmarshalList(Resource.class, json); + Assert.assertTrue(resourceList.size()==0); + /* END Getting HostingNode */ - ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setElementType(ConsistsOf.NAME); Facet identificationFacet = eService.getIdentificationFacets().get(0); UUID identificationFacetUUID = identificationFacet.getHeader().getUUID(); - /* SoftwareFacet of Eservice */ - json = consistsOfManagement.allFrom(identificationFacetUUID, Direction.BOTH, true); + /* EService --ConsistsOf--> SoftwareFacet*/ + try { + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.BOTH, true, null); + }catch(InvalidQueryException e) { + // Ok expected + } + + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.OUT, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==1); sourceResource = resourceList.get(0); @@ -720,45 +718,39 @@ public class ERManagementTest extends ScopedTest { Assert.assertTrue(sourceResource.getHeader().getUUID().compareTo(eServiceUUID)==0); Assert.assertTrue(targetIdentificationFacet.getHeader().getUUID().compareTo(identificationFacetUUID)==0); - json = consistsOfManagement.allFrom(identificationFacetUUID, Direction.IN, true); - resourceList = ISMapper.unmarshalList(Resource.class, json); - Assert.assertTrue(resourceList.size()==1); - sourceResource = resourceList.get(0); - targetIdentificationFacet = sourceResource.getIdentificationFacets().get(0); - Assert.assertTrue(sourceResource.getHeader().getUUID().compareTo(eServiceUUID)==0); - Assert.assertTrue(targetIdentificationFacet.getHeader().getUUID().compareTo(identificationFacetUUID)==0); + try { + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.IN, true, null); + }catch(InvalidQueryException e) { + // Ok expected + } - json = consistsOfManagement.allFrom(identificationFacetUUID, Direction.OUT, true); + try { + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.BOTH, true, null); + }catch(InvalidQueryException e) { + // Ok expected + } + + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.OUT, true, null); resourceList = ISMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size()==0); + try { + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.IN, true, null); + }catch(InvalidQueryException e) { + // Ok expected + } - - json = consistsOfManagement.allFrom(identificationFacetUUID, Direction.BOTH, false); - resourceList = ISMapper.unmarshalList(Resource.class, json); - Assert.assertTrue(resourceList.size()==0); - - json = consistsOfManagement.allFrom(identificationFacetUUID, Direction.IN, false); - resourceList = ISMapper.unmarshalList(Resource.class, json); - Assert.assertTrue(resourceList.size()==0); - - - json = consistsOfManagement.allFrom(identificationFacetUUID, Direction.OUT, false); - resourceList = ISMapper.unmarshalList(Resource.class, json); - Assert.assertTrue(resourceList.size()==0); - /* END SoftwareFacet of Eservice */ + /* END EService --ConsistsOf--> SoftwareFacet*/ /* Removing created Entity and Relation to have a clean DB */ - - ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement = new ResourceManagement(); resourceManagement.setUUID(hostingNode.getHeader().getUUID()); boolean deleted = resourceManagement.delete(); Assert.assertTrue(deleted); - } public static final String TEST_RESOURCE = "test-resource.json"; diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java index 77a0c45..be2f038 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java @@ -15,7 +15,6 @@ import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.IsIdentifiedBy; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; -import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.junit.Assert; @@ -23,6 +22,8 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.tinkerpop.blueprints.Direction; + public class ResourceManagementTest extends ScopedTest { private static Logger logger = LoggerFactory.getLogger(ResourceManagementTest.class); @@ -86,15 +87,11 @@ public class ResourceManagementTest extends ScopedTest { @Test - public void testAllWithCostraint() throws ResourceRegistryException { + public void testQuery() throws ResourceRegistryException { String relationType = ConsistsOf.NAME; String facetType = SoftwareFacet.NAME; Map constraint = new HashMap<>(); - constraint.put(AccessPath.RELATION_TYPE_PATH_PART, relationType); - constraint.put(AccessPath.FACET_TYPE_PATH_PART, facetType); - - constraint.put(SoftwareFacet.GROUP_PROPERTY, "Gis"); constraint.put(SoftwareFacet.NAME_PROPERTY, "Thredds"); @@ -104,13 +101,12 @@ public class ResourceManagementTest extends ScopedTest { ERManagement erManagement = ERManagementUtility.getERManagement(type); if (erManagement instanceof ResourceManagement) { - String ret = ((ResourceManagement) erManagement).all(false, constraint); - logger.debug(ret); - - constraint.put(AccessPath.RELATION_TYPE_PATH_PART, relationType); - constraint.put(AccessPath.FACET_TYPE_PATH_PART, facetType); - ret = ((ResourceManagement) erManagement).all(true, constraint); - logger.debug(ret); + boolean[] booleans = new boolean[] {true, false}; + for(boolean bool : booleans) { + String ret = ((ResourceManagement) erManagement).query(relationType, facetType, null, Direction.OUT, bool, constraint); + logger.debug("Result of query for {}polymorphic {} --{}--> {} with constaint {} is {}", bool ? "" : "NOT ", + type, relationType, facetType, constraint, ret); + } }