From 1078b43fcf5dc15626b4310c15417ace386c3ce6 Mon Sep 17 00:00:00 2001 From: "luca.frosini" Date: Fri, 30 Dec 2016 16:31:12 +0000 Subject: [PATCH] Reorganizing code git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@141436 82a268e6-3cf1-43bd-a215-b396298e98cf --- .../dbinitialization/SchemaActionImpl.java | 4 +- .../resourceregistry/er/ERManagement.java | 380 ++++++++++++++- .../er/entity/EntityManagement.java | 384 ++-------------- .../er/entity/FacetManagement.java | 8 +- .../er/entity/ResourceManagement.java | 37 +- .../er/relation/RelationManagement.java | 432 +++--------------- .../resourceregistry/rest/Access.java | 356 +++++++++++---- .../resourceregistry/rest/AccessType.java | 45 ++ .../resourceregistry/rest/ERManager.java | 46 +- .../resourceregistry/rest/SchemaManager.java | 20 +- .../schema/EntitySchemaManagement.java | 12 + .../schema/SchemaManagement.java | 51 +-- .../schema/SchemaManagementImpl.java | 206 +++++---- .../context/MultiContextTest.java | 6 +- .../resourceregistry/er/ERManagementTest.java | 18 +- .../er/SmartgearResourcesTest.java | 6 +- .../schema/SchemaManagementImplTest.java | 26 +- 17 files changed, 1002 insertions(+), 1035 deletions(-) create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/rest/AccessType.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/schema/EntitySchemaManagement.java diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java index 4c5ea3a..db99063 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java @@ -57,11 +57,11 @@ public class SchemaActionImpl implements SchemaAction { String json = TypeBinder.serializeType(e); logger.trace(json); if (Facet.class.isAssignableFrom(e)) { - schemaManagement.registerFacetSchema(json); + schemaManagement.createFacetSchema(json); } else if(Resource.class.isAssignableFrom(e)){ schemaManagement.registerResourceSchema(json); } else { - schemaManagement.registerEntitySchema(json); + schemaManagement.createEntitySchema(json); } } catch(Exception ex){ logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage()); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java index eb8ede6..c9a69ef 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java @@ -12,30 +12,388 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import java.util.UUID; +import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.impl.utils.Entities; +import org.gcube.informationsystem.model.embedded.Header; +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.model.relation.Relation; 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.EntityNotFoundException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; +import org.gcube.informationsystem.resourceregistry.context.ContextUtility; +import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; +import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; +import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; +import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientElement; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; /** * @author Luca Frosini (ISTI - CNR) * */ -public class ERManagement { +public abstract class ERManagement { private static Logger logger = LoggerFactory.getLogger(ERManagement.class); - public static String lowerCaseFirstCharacter(String string) { - return string.substring(0, 1).toLowerCase() + string.substring(1); + public final String AT = "@"; + public final String UNDERSCORE = "_"; + + protected final Set ignoreKeys; + protected final Set ignoreStartWithKeys; + + protected Class erClass; + protected String baseType; + + protected OrientGraph orientGraph; + + protected UUID uuid; + protected JsonNode jsonNode; + protected String erType; + + protected Class elementClass; + protected El element; + + protected ERManagement(Class erClass) { + this.erClass = erClass; + + this.ignoreKeys = new HashSet(); + + this.ignoreStartWithKeys = new HashSet(); + + this.ignoreStartWithKeys.add(AT); + this.ignoreStartWithKeys.add(UNDERSCORE); + + } + + protected ERManagement(Class erClass, OrientGraph orientGraph) { + this(erClass); + this.orientGraph = orientGraph; + } + + public void setUUID(UUID uuid) throws ResourceRegistryException { + this.uuid = uuid; + if (jsonNode != null) { + checkUUIDMatch(); + } + } + + public void setJSON(JsonNode jsonNode) throws ResourceRegistryException { + this.jsonNode = jsonNode; + checkJSON(); + } + + public void setJSON(String jsonRepresentation) + throws ResourceRegistryException { + ObjectMapper mapper = new ObjectMapper(); + try { + this.jsonNode = mapper.readTree(jsonRepresentation); + } catch (IOException e) { + throw new ResourceRegistryException(e); + } + checkJSON(); + } + + public void setElementType(String erType) throws ResourceRegistryException { + this.erType = erType; + if (erType == null || erType.compareTo("") == 0) { + if (Facet.class.isAssignableFrom(erClass)) { + this.erType = Facet.NAME; + } + if (Resource.class.isAssignableFrom(erClass)) { + this.erType = Resource.NAME; + } + if (ConsistsOf.class.isAssignableFrom(erClass)) { + this.erType = ConsistsOf.NAME; + } + if (IsRelatedTo.class.isAssignableFrom(erClass)) { + this.erType = IsRelatedTo.NAME; + } + throw new ResourceRegistryException("Invalid type " + erType + + " provided"); + } + if (jsonNode != null) { + checkERMatch(); + } + } + + protected void checkJSON() throws ResourceRegistryException { + if (uuid == null) { + try { + uuid = org.gcube.informationsystem.impl.utils.Utility + .getUUIDFromJsonNode(jsonNode); + } catch (Exception e) { + + } + } else { + checkUUIDMatch(); + } + + if (this.erType == null) { + this.erType = getClassProperty(jsonNode); + } else { + checkERMatch(); + } + } + + protected void checkERMatch() throws ResourceRegistryException { + String type = getClassProperty(jsonNode); + if (type != null && type.compareTo(erType) != 0) { + String error = String + .format("Declared resourceType does not match with json representation %s!=%s", + erType, type); + logger.trace(error); + throw new ResourceRegistryException(error); + } + + try { + SchemaManagementImpl.getTypeSchema(erType, baseType); + } catch (SchemaNotFoundException e) { + throw e; + } + } + + protected void checkUUIDMatch() throws ResourceRegistryException { + Header header = null; + try { + header = HeaderUtility.getHeader(jsonNode, false); + } catch (Exception e) { + throw new ResourceRegistryException(e); + } + + if (header != null) { + UUID resourceUUID = header.getUUID(); + if (resourceUUID.compareTo(uuid) != 0) { + String error = String + .format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance", + resourceUUID.toString(), uuid.toString(), + erType); + throw new ResourceRegistryException(error); + + } + } + } + + public abstract String serialize() throws ResourceRegistryException; + + public abstract JSONObject serializeAsJson() + throws ResourceRegistryException; + + public abstract El reallyUpdate() throws EntityNotFoundException, + ResourceRegistryException; + + public abstract boolean reallyDelete() throws EntityNotFoundException, + ResourceRegistryException; + + public abstract boolean reallyAddToContext() throws ContextException, + ResourceRegistryException; + + public abstract boolean reallyRemoveFromContext() throws ContextException, + ResourceRegistryException; + + public void setElement(El element) throws ResourceRegistryException { + if (element == null) { + throw new ResourceRegistryException("Trying to set null " + + elementClass.getSimpleName() + " in " + this); + } + this.element = element; + this.uuid = HeaderUtility.getHeader(element).getUUID(); + } + + protected void throwElementNotFoundException(ResourceRegistryException e) + throws EntityNotFoundException, RelationNotFoundException, + ResourceRegistryException { + + if (Resource.class.isAssignableFrom(erClass)) { + throw new ResourceNotFoundException(e); + } else if (Facet.class.isAssignableFrom(erClass)) { + throw new FacetNotFoundException(e); + } else if (Relation.class.isAssignableFrom(erClass)) { + throw new RelationNotFoundException(e); + } + + throw e; + + } + + public El getElement() throws ResourceRegistryException { + try { + if (element == null) { + element = Utility.getElementByUUID(orientGraph, + erType == null ? baseType : erType, uuid, elementClass); + } + } catch (ResourceRegistryException e) { + throwElementNotFoundException(e); + } + return element; + } + + public String read() throws EntityNotFoundException, + ResourceRegistryException { + try { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.READER); + + getElement(); + + return serialize(); + } catch (ResourceRegistryException e) { + throw e; + } catch (Exception e) { + throw new ResourceRegistryException(e); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public String update() throws RelationNotFoundException, + ResourceRegistryException { + try { + + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.WRITER); + + element = reallyUpdate(); + + orientGraph.commit(); + + return serialize(); + + } catch (ResourceRegistryException e) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw e; + } catch (Exception e) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ResourceRegistryException(e); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public boolean delete() throws FacetNotFoundException, + ResourceRegistryException { + logger.debug("Going to delete {} with UUID {}", baseType, uuid); + + try { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.WRITER); + + boolean deleted = reallyDelete(); + + orientGraph.commit(); + + logger.info("{} with UUID {} was successfully deleted.", baseType, + uuid); + + return deleted; + + } catch (ResourceRegistryException e) { + logger.error("Unable to delete {} with UUID {}", baseType, uuid, e); + if (orientGraph != null) { + orientGraph.rollback(); + } + throw e; + } catch (Exception e) { + logger.error("Unable to delete {} with UUID {}", baseType, uuid, e); + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ResourceRegistryException(e); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public boolean addToContext() throws ContextException { + logger.debug("Going to add {} with UUID {} to actual Context", + baseType, uuid); + + try { + orientGraph = SecurityContextMapper.getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER).getTx(); + + boolean added = reallyAddToContext(); + + orientGraph.commit(); + logger.info("{} with UUID {} successfully added to actual Context", + baseType, uuid); + + return added; + } catch (Exception e) { + logger.error("Unable to add {} with UUID {} to actual Context", + baseType, uuid, e); + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ContextException(e); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public boolean removeFromContext() throws ContextException { + logger.debug("Going to remove {} with UUID {} from actual Context", + baseType, uuid); + + try { + orientGraph = SecurityContextMapper.getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER).getTx(); + + boolean removed = reallyRemoveFromContext(); + + orientGraph.commit(); + logger.info( + "{} with UUID {} successfully removed from actual Context", + baseType, uuid); + + return removed; + } catch (Exception e) { + logger.error( + "Unable to remove {} with UUID {} from actual Context", + baseType, uuid, e); + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ContextException(e); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } } public static String getClassProperty(JsonNode jsonNode) { @@ -45,8 +403,6 @@ public class ERManagement { return null; } - - public static Object getObjectFromElement(JsonNode value) throws ResourceRegistryException { JsonNodeType jsonNodeType = value.getNodeType(); @@ -152,17 +508,18 @@ public class ERManagement { return map; } - public static Element updateProperties(Element element, JsonNode jsonNode, Set ignoreKeys, Set ignoreStartWithKeys) + public static Element updateProperties(Element element, JsonNode jsonNode, + Set ignoreKeys, Set ignoreStartWithKeys) throws ResourceRegistryException { - Set oldKeys = element.getPropertyKeys(); Map properties; if (element instanceof Vertex || element instanceof Edge) { try { - properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys); - } catch ( IOException e) { + properties = getPropertyMap(jsonNode, ignoreKeys, + ignoreStartWithKeys); + } catch (IOException e) { throw new ResourceRegistryException(e); } } else { @@ -201,11 +558,8 @@ public class ERManagement { } ((OrientElement) element).save(); - + return element; } - - - } 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 d5e54c8..e2a5f7b 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 @@ -3,12 +3,6 @@ */ package org.gcube.informationsystem.resourceregistry.er.entity; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.embedded.Header; import org.gcube.informationsystem.model.entity.Entity; import org.gcube.informationsystem.model.entity.Facet; @@ -16,23 +10,15 @@ import org.gcube.informationsystem.model.entity.Resource; 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.entity.EntityNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; -import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; -import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; @@ -43,32 +29,19 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType; /** * @author Luca Frosini (ISTI - CNR) */ -public abstract class EntityManagement { +public abstract class EntityManagement extends + ERManagement { private static Logger logger = LoggerFactory .getLogger(EntityManagement.class); - public final String AT = "@"; - public final String UNDERSCORE = "_"; - - protected final Set ignoreKeys; - protected final Set ignoreStartWithKeys; - - protected final Class entityClass; - protected final String baseType; - - protected OrientGraph orientGraph; - - protected UUID uuid; - protected JsonNode jsonNode; - protected String entityType; - protected Vertex vertex; + protected Vertex element; protected EntityManagement(Class entityClass) { - this.ignoreKeys = new HashSet(); + super(entityClass); + this.ignoreKeys.add(Entity.HEADER_PROPERTY); - this.ignoreStartWithKeys = new HashSet(); this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX .toLowerCase()); this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX @@ -77,10 +50,7 @@ public abstract class EntityManagement { .toUpperCase()); this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX .toUpperCase()); - this.ignoreStartWithKeys.add(AT); - this.ignoreStartWithKeys.add(UNDERSCORE); - this.entityClass = entityClass; if (Facet.class.isAssignableFrom(entityClass)) { this.baseType = Facet.NAME; } else if (Resource.class.isAssignableFrom(entityClass)) { @@ -95,150 +65,22 @@ public abstract class EntityManagement { this.orientGraph = orientGraph; } - public void setVertex(Vertex vertex) throws ResourceRegistryException { - if (vertex == null) { - throw new ResourceRegistryException("Trying to set null Vertex in " - + this); - } - this.vertex = vertex; - this.uuid = HeaderUtility.getHeader(vertex).getUUID(); - } - - public void setUUID(UUID uuid) throws ResourceRegistryException { - this.uuid = uuid; - if (jsonNode != null) { - checkUUIDMatch(); - } - } - - public void setJSON(JsonNode jsonNode) throws ResourceRegistryException { - this.jsonNode = jsonNode; - - checkJSON(); - } - - public void setJSON(String jsonRepresentation) - throws ResourceRegistryException { - ObjectMapper mapper = new ObjectMapper(); - try { - this.jsonNode = mapper.readTree(jsonRepresentation); - } catch (IOException e) { - throw new ResourceRegistryException(e); - } - - checkJSON(); - } - - protected void checkJSON() throws ResourceRegistryException { - if (uuid == null) { - try { - uuid = org.gcube.informationsystem.impl.utils.Utility - .getUUIDFromJsonNode(jsonNode); - } catch (Exception e) { - - } - } else { - checkUUIDMatch(); - } - - if (this.entityType == null) { - this.entityType = ERManagement.getClassProperty(jsonNode); - } else { - checkEntityMatch(); - } - } - - public void setEntityType(String entityType) - throws ResourceRegistryException { - this.entityType = entityType; - if (entityType == null || entityType.compareTo("") == 0) { - if (Facet.class.isAssignableFrom(entityClass)) { - entityType = Facet.NAME; - } - if (Resource.class.isAssignableFrom(entityClass)) { - entityType = Resource.NAME; - } - } - if (jsonNode != null) { - checkEntityMatch(); - } - } - - protected void checkEntityMatch() throws ResourceRegistryException { - String type = ERManagement.getClassProperty(jsonNode); - if (type != null && type.compareTo(entityType) != 0) { - String error = String - .format("Declared resourceType does not match with json representation %s!=%s", - entityType, type); - logger.trace(error); - throw new ResourceRegistryException(error); - } - - try { - SchemaManagementImpl.getTypeSchema(entityType, baseType); - } catch (SchemaNotFoundException e) { - throw e; - } - } - - protected void checkUUIDMatch() throws ResourceRegistryException { - Header header = null; - try { - header = HeaderUtility.getHeader(jsonNode, false); - } catch (Exception e) { - throw new ResourceRegistryException(e); - } - - if (header != null) { - UUID resourceUUID = header.getUUID(); - if (resourceUUID.compareTo(uuid) != 0) { - String error = String - .format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance", - resourceUUID.toString(), uuid.toString(), - entityType); - throw new ResourceRegistryException(error); - - } - } - } - - public Vertex getVertex() throws EntityNotFoundException, - ResourceRegistryException { - try { - if (vertex == null) { - vertex = Utility.getElementByUUID(orientGraph, - entityType == null ? baseType : entityType, uuid, - Vertex.class); - } - return vertex; - } catch (ResourceRegistryException e) { - if (Resource.class.isAssignableFrom(entityClass)) { - throw new ResourceNotFoundException(e); - } else if (Facet.class.isAssignableFrom(entityClass)) { - throw new FacetNotFoundException(e); - } else { - throw e; - } - } - - } - protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { logger.trace("Going to create {} for {} ({}) using {}", - Vertex.class.getSimpleName(), baseType, entityType, jsonNode); + Vertex.class.getSimpleName(), baseType, erType, jsonNode); try { - Vertex vertexEntity = orientGraph.addVertex("class:" + entityType); + Vertex vertexEntity = orientGraph.addVertex("class:" + erType); try { - Vertex v = getVertex(); + Vertex v = getElement(); if (v != null) { String error = String.format( - "A %s with UUID %s already exist", entityType, + "A %s with UUID %s already exist", erType, uuid.toString()); throw new EntityAlreadyPresentException(error); } @@ -249,61 +91,47 @@ public abstract class EntityManagement { // no header or no header with uuid is provided and it is fine } - this.vertex = vertexEntity; + this.element = vertexEntity; Header entityHeader = HeaderUtility.getHeader(jsonNode, true); if (entityHeader != null) { - vertex.setProperty(Entity.HEADER_PROPERTY, entityHeader); + element.setProperty(Entity.HEADER_PROPERTY, entityHeader); } else { - entityHeader = HeaderUtility.addHeader(vertex, null); + entityHeader = HeaderUtility.addHeader(element, null); } - if (Resource.class.isAssignableFrom(entityClass)) { + if (Resource.class.isAssignableFrom(erClass)) { // Facet and relation are created in calling method } else { - ERManagement.updateProperties(vertex, jsonNode, ignoreKeys, + ERManagement.updateProperties(element, jsonNode, ignoreKeys, ignoreStartWithKeys); } - ContextUtility.addToActualContext(orientGraph, vertex); + ContextUtility.addToActualContext(orientGraph, element); - ((OrientVertex) vertex).save(); + ((OrientVertex) element).save(); logger.info("Created {} is {}", Vertex.class.getSimpleName(), - Utility.toJsonString((OrientVertex) vertex, true)); + Utility.toJsonString((OrientVertex) element, true)); - return vertex; + return element; } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { logger.trace("Error while creating {} for {} ({}) using {}", - Vertex.class.getSimpleName(), baseType, entityType, - jsonNode, e); - throw new ResourceRegistryException("Error Creating " + entityType + Vertex.class.getSimpleName(), baseType, erType, jsonNode, e); + throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause()); } } - public abstract String serialize() throws ResourceRegistryException; - - public abstract JSONObject serializeAsJson() - throws ResourceRegistryException; - - public abstract Vertex reallyCreate() throws EntityAlreadyPresentException, - ResourceRegistryException; - - public abstract Vertex reallyUpdate() throws EntityNotFoundException, - ResourceRegistryException; - - public abstract boolean reallyDelete() throws EntityNotFoundException, - ResourceRegistryException; - + @Override public boolean reallyAddToContext() throws ContextException, ResourceRegistryException { - ContextUtility.addToActualContext(orientGraph, getVertex()); + ContextUtility.addToActualContext(orientGraph, getElement()); - Iterable edges = vertex.getEdges(Direction.OUT); + Iterable edges = element.getEdges(Direction.OUT); for (Edge edge : edges) { @SuppressWarnings("rawtypes") @@ -315,12 +143,13 @@ public abstract class EntityManagement { return true; } + @Override public boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException { - - ContextUtility.removeFromActualContext(orientGraph, getVertex()); - Iterable edges = vertex.getEdges(Direction.OUT); + ContextUtility.removeFromActualContext(orientGraph, getElement()); + + Iterable edges = element.getEdges(Direction.OUT); for (Edge edge : edges) { @SuppressWarnings("rawtypes") @@ -332,7 +161,7 @@ public abstract class EntityManagement { return true; } - @SuppressWarnings("rawtypes") + @SuppressWarnings({ "rawtypes", "unchecked" }) public static EntityManagement getEntityManagement(OrientGraph orientGraph, Vertex vertex) throws ResourceRegistryException { OrientVertexType orientVertexType = ((OrientVertex) vertex).getType(); @@ -348,10 +177,13 @@ public abstract class EntityManagement { Facet.NAME); throw new ResourceRegistryException(error); } - entityManagement.setVertex(vertex); + entityManagement.setElement(vertex); return entityManagement; } + public abstract Vertex reallyCreate() throws EntityAlreadyPresentException, + ResourceRegistryException; + public String create() throws EntityAlreadyPresentException, ResourceRegistryException { @@ -359,7 +191,7 @@ public abstract class EntityManagement { orientGraph = ContextUtility .getActualSecurityContextGraph(PermissionMode.WRITER); - reallyCreate(); + element = reallyCreate(); orientGraph.commit(); @@ -382,154 +214,6 @@ public abstract class EntityManagement { } } - public String read() throws EntityNotFoundException, - ResourceRegistryException { - try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.READER); - - getVertex(); - - return serialize(); - } catch (ResourceRegistryException e) { - throw e; - } catch (Exception e) { - throw new ResourceRegistryException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - - public String update() throws EntityNotFoundException, - ResourceRegistryException { - try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.WRITER); - - reallyUpdate(); - - orientGraph.commit(); - - return serialize(); - - } catch (ResourceRegistryException e) { - if (orientGraph != null) { - orientGraph.rollback(); - } - throw e; - } catch (Exception e) { - logger.debug("Unable to update {} with UUID {} usign {}", baseType, - uuid, jsonNode, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ResourceRegistryException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - - } - - public boolean delete() throws FacetNotFoundException, - ResourceRegistryException { - logger.debug("Going to delete {} with UUID {}", baseType, uuid); - - try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.WRITER); - - boolean deleted = reallyDelete(); - - orientGraph.commit(); - - logger.info("{} with UUID {} was successfully deleted.", baseType, - uuid); - - return deleted; - - } catch (ResourceRegistryException e) { - logger.error("Unable to delete {} with UUID {}", baseType, uuid, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw e; - } catch (Exception e) { - logger.error("Unable to delete {} with UUID {}", baseType, uuid, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ResourceRegistryException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - - public boolean addToContext() throws ContextException { - logger.debug("Going to add {} with UUID {} to actual Context", - baseType, uuid); - - try { - orientGraph = SecurityContextMapper.getSecurityContextFactory( - SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, - PermissionMode.WRITER).getTx(); - - boolean added = reallyAddToContext(); - - orientGraph.commit(); - logger.info("{} with UUID {} successfully added to actual Context", - baseType, uuid); - - return added; - } catch (Exception e) { - logger.error("Unable to add {} with UUID {} to actual Context", - baseType, uuid, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ContextException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - - public boolean removeFromContext() throws ContextException { - logger.debug("Going to remove {} with UUID {} from actual Context", - baseType, uuid); - - try { - orientGraph = SecurityContextMapper.getSecurityContextFactory( - SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, - PermissionMode.WRITER).getTx(); - - boolean removed = reallyRemoveFromContext(); - - orientGraph.commit(); - logger.info( - "{} with UUID {} successfully removed from actual Context", - baseType, uuid); - - return removed; - } catch (Exception e) { - logger.error( - "Unable to remove {} with UUID {} from actual Context", - baseType, uuid, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ContextException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java index d014c3f..6e8ec81 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java @@ -31,12 +31,12 @@ public class FacetManagement extends EntityManagement { @Override public String serialize() throws ResourceRegistryException { - return Utility.toJsonString((OrientVertex) vertex, true); + return Utility.toJsonString((OrientVertex) element, true); } @Override public JSONObject serializeAsJson() throws ResourceRegistryException { - return Utility.toJsonObject((OrientVertex) vertex, true); + return Utility.toJsonObject((OrientVertex) element, true); } public Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { @@ -45,14 +45,14 @@ public class FacetManagement extends EntityManagement { @Override public Vertex reallyUpdate() throws ResourceRegistryException { - Vertex facet = getVertex(); + Vertex facet = getElement(); facet = (Vertex) ERManagement.updateProperties(facet, jsonNode, ignoreKeys, ignoreStartWithKeys); ((OrientVertex) facet).save(); return facet; } public boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException { - getVertex().remove(); + getElement().remove(); return true; } 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 984f3f8..e94719a 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 @@ -14,10 +14,10 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; -import org.gcube.informationsystem.resourceregistry.er.ERManagement; 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.rest.AccessType; import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,7 +78,7 @@ public class ResourceManagement extends EntityManagement { } try { - jsonObject.put(ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME), + jsonObject.put(AccessType.CONSISTS_OF.lowerCaseFirstCharacter(), consistsOfArray); } catch (JSONException e) { throw new ResourceRegistryException(e); @@ -93,12 +93,12 @@ public class ResourceManagement extends EntityManagement { @Override public String serialize() throws ResourceRegistryException { - return marshallResource(orientGraph, getVertex()).toString(); + return marshallResource(orientGraph, getElement()).toString(); } @Override public JSONObject serializeAsJson() throws ResourceRegistryException { - return marshallResource(orientGraph, getVertex()); + return marshallResource(orientGraph, getElement()); } @Override @@ -106,36 +106,36 @@ public class ResourceManagement extends EntityManagement { ResourceRegistryException { createVertex(); - String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME); + String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter(); if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode consistOfJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); com.setJSON(consistOfJsonNode); - com.reallyCreate(vertex); + com.reallyCreate(element); } } - property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME); + property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter(); if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement( orientGraph); irtm.setJSON(relationJsonNode); - irtm.reallyCreate(vertex); + irtm.reallyCreate(element); } } - return vertex; + return element; } @Override public Vertex reallyUpdate() throws ResourceRegistryException { - getVertex(); + getElement(); - String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME); + String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter(); if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode relationJsonNode : jsonNodeArray) { @@ -145,7 +145,7 @@ public class ResourceManagement extends EntityManagement { } } - property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME); + property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter(); if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode relationJsonNode : jsonNodeArray) { @@ -156,19 +156,20 @@ public class ResourceManagement extends EntityManagement { } } - ((OrientVertex) vertex).save(); + ((OrientVertex) element).save(); - return vertex; + return element; } + @SuppressWarnings("unchecked") @Override public boolean reallyDelete() throws ResourceNotFoundException, ResourceRegistryException { //internalDeleteResource(orientGraph, uuid, null); - getVertex(); + getElement(); - Iterable iterable = vertex.getEdges(Direction.OUT); + Iterable iterable = element.getEdges(Direction.OUT); Iterator iterator = iterable.iterator(); while(iterator.hasNext()){ Edge edge = iterator.next(); @@ -187,13 +188,13 @@ public class ResourceManagement extends EntityManagement { IsRelatedTo.NAME, ConsistsOf.NAME); } if(relationManagement!=null){ - relationManagement.setEdge(edge); + relationManagement.setElement(edge); relationManagement.reallyDelete(); } } - vertex.remove(); + element.remove(); return true; } 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 663582a..7a87d94 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 @@ -3,15 +3,11 @@ */ package org.gcube.informationsystem.resourceregistry.er.relation; -import java.io.IOException; -import java.util.HashSet; import java.util.Iterator; -import java.util.Set; import java.util.UUID; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; -import org.gcube.informationsystem.model.embedded.Header; import org.gcube.informationsystem.model.embedded.PropagationConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint; @@ -24,22 +20,18 @@ import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; -import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; -import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; @@ -53,30 +45,18 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; * */ @SuppressWarnings("rawtypes") -public abstract class RelationManagement { +public abstract class RelationManagement extends ERManagement { private static Logger logger = LoggerFactory .getLogger(RelationManagement.class); - public final Set ignoreKeys; - public final Set ignoreStartWithKeys; - - public static final String AT = "@"; - public static final String UNDERSCORE = "_"; - - protected final Class relationClass; - protected final String baseType; protected final Class targetEntityClass; - protected OrientGraph orientGraph; - - protected UUID uuid; - protected JsonNode jsonNode; - protected String relationType; - protected Edge edge; + protected Edge element; protected RelationManagement(Class relationClass) { - this.ignoreKeys = new HashSet(); + super(relationClass); + this.ignoreKeys.add(Relation.HEADER_PROPERTY); this.ignoreKeys.add(Relation.TARGET_PROPERTY); this.ignoreKeys.add(Relation.SOURCE_PROPERTY); @@ -85,12 +65,6 @@ public abstract class RelationManagement { this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase()); this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase()); - this.ignoreStartWithKeys = new HashSet(); - this.ignoreStartWithKeys.add(AT); - this.ignoreStartWithKeys.add(UNDERSCORE); - - this.relationClass = relationClass; - if (ConsistsOf.class.isAssignableFrom(relationClass)) { this.baseType = ConsistsOf.NAME; this.targetEntityClass = Facet.class; @@ -108,127 +82,14 @@ public abstract class RelationManagement { this.orientGraph = orientGraph; } - public void setEdge(Edge edge) { - this.edge = edge; - } - - public void setUUID(UUID uuid) throws ResourceRegistryException { - this.uuid = uuid; - if (jsonNode != null) { - checkUUIDMatch(); - } - } - - protected void checkJSON() throws ResourceRegistryException { - if (uuid == null) { - try { - uuid = org.gcube.informationsystem.impl.utils.Utility - .getUUIDFromJsonNode(jsonNode); - } catch (Exception e) { - - } - } else { - checkUUIDMatch(); - } - - if (this.relationType == null) { - this.relationType = ERManagement.getClassProperty(jsonNode); - } else { - checkEntityMatch(); - } - } - - public void setJSON(JsonNode jsonNode) throws ResourceRegistryException { - this.jsonNode = jsonNode; - checkJSON(); - } - - public void setJSON(String jsonRepresentation) - throws ResourceRegistryException { - ObjectMapper mapper = new ObjectMapper(); - try { - this.jsonNode = mapper.readTree(jsonRepresentation); - } catch (IOException e) { - throw new ResourceRegistryException(e); - } - - checkJSON(); - } - - public void setRelationType(String relationType) - throws ResourceRegistryException { - this.relationType = relationType; - if (relationType == null || relationType.compareTo("") == 0) { - if (ConsistsOf.class.isAssignableFrom(relationClass)) { - this.relationType = ConsistsOf.NAME; - } else if (IsRelatedTo.class.isAssignableFrom(relationClass)) { - this.relationType = IsRelatedTo.NAME; - } - } - if (jsonNode != null) { - checkEntityMatch(); - } - } - - protected void checkEntityMatch() throws ResourceRegistryException { - String type = ERManagement.getClassProperty(jsonNode); - if (type != null && type.compareTo(relationType) != 0) { - String error = String - .format("Declared resourceType does not match with json representation %s!=%s", - relationType, type); - logger.trace(error); - throw new ResourceRegistryException(error); - } - - try { - SchemaManagementImpl.getTypeSchema(relationType, baseType); - } catch (SchemaNotFoundException e) { - throw e; - } - } - - protected void checkUUIDMatch() throws ResourceRegistryException { - Header header = null; - try { - header = HeaderUtility.getHeader(jsonNode, false); - } catch (Exception e) { - throw new ResourceRegistryException(e); - } - - if (header != null) { - UUID resourceUUID = header.getUUID(); - if (resourceUUID.compareTo(uuid) != 0) { - String error = String - .format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance", - resourceUUID.toString(), uuid.toString(), - relationType); - throw new ResourceRegistryException(error); - - } - } - } - - public Edge getEdge() throws ResourceRegistryException { - try { - if (edge == null) { - edge = Utility.getElementByUUID(orientGraph, - relationType == null ? baseType : relationType, uuid, - Edge.class); - } - return edge; - } catch (ResourceRegistryException e) { - throw new RelationNotFoundException(e); - } - } - public String serialize() throws ResourceRegistryException { return serializeAsJson().toString(); } public JSONObject serializeAsJson() throws ResourceRegistryException { - JSONObject ret = Utility.toJsonObject((OrientEdge) getEdge(), false); + JSONObject ret = Utility.toJsonObject((OrientEdge) getElement(), false); - Vertex vertex = edge.getVertex(Direction.IN); + Vertex vertex = element.getVertex(Direction.IN); EntityManagement entityManagement = EntityManagement .getEntityManagement(orientGraph, vertex); @@ -246,11 +107,11 @@ public abstract class RelationManagement { throws ResourceRegistryException { ResourceManagement srmSource = new ResourceManagement(orientGraph); srmSource.setUUID(sourceUUID); - Vertex source = srmSource.getVertex(); + Vertex source = srmSource.getElement(); EntityManagement entityManagement = getEntityManagement(); entityManagement.setUUID(targetUUID); - Vertex target = entityManagement.getVertex(); + Vertex target = (Vertex) entityManagement.getElement(); return reallyCreate(source, target); @@ -268,7 +129,7 @@ public abstract class RelationManagement { "Any type of %s can have only a %s as %s. " + "Cannot instatiate %s beetween %s -> %s ", Relation.NAME, Resource.NAME, Relation.SOURCE_PROPERTY, - relationType, sourceEntityManagement.serialize(), + erType, sourceEntityManagement.serialize(), targetEntityManagement.serialize()); throw new ResourceRegistryException(error); } @@ -277,7 +138,7 @@ public abstract class RelationManagement { if (!(targetEntityManagement instanceof ResourceManagement)) { String error = String.format("A %s can have only a %s as %s. " + "Cannot instatiate %s beetween %s -> %s ", baseType, - Resource.NAME, Relation.TARGET_PROPERTY, relationType, + Resource.NAME, Relation.TARGET_PROPERTY, erType, sourceEntityManagement.serialize(), targetEntityManagement.serialize()); throw new ResourceRegistryException(error); @@ -286,7 +147,7 @@ public abstract class RelationManagement { if (!(targetEntityManagement instanceof FacetManagement)) { String error = String.format("A %s can have only a %s as %s. " + "Cannot instatiate %s beetween %s -> %s ", baseType, - Facet.NAME, Relation.TARGET_PROPERTY, relationType, + Facet.NAME, Relation.TARGET_PROPERTY, erType, sourceEntityManagement.serialize(), targetEntityManagement.serialize()); throw new ResourceRegistryException(error); @@ -300,23 +161,23 @@ public abstract class RelationManagement { throw new ResourceRegistryException(error); } - logger.trace("Creating {} beetween {} -> {}", relationType, + logger.trace("Creating {} beetween {} -> {}", erType, sourceEntityManagement.serialize(), targetEntityManagement.serialize()); - edge = orientGraph.addEdge(null, source, target, relationType); + element = orientGraph.addEdge(null, source, target, erType); - ERManagement.updateProperties(edge, jsonNode, ignoreKeys, + ERManagement.updateProperties(element, jsonNode, ignoreKeys, ignoreStartWithKeys); - HeaderUtility.addHeader(edge, null); - ContextUtility.addToActualContext(orientGraph, edge); + HeaderUtility.addHeader(element, null); + ContextUtility.addToActualContext(orientGraph, element); - ((OrientEdge) edge).save(); + ((OrientEdge) element).save(); - logger.info("{} successfully created", relationType); + logger.info("{} successfully created", erType); - return edge; + return element; } public Edge reallyCreate(Vertex source) throws ResourceRegistryException { @@ -329,7 +190,7 @@ public abstract class RelationManagement { } entityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY)); try { - target = entityManagement.getVertex(); + target = (Vertex) entityManagement.getElement(); } catch (Exception e) { target = entityManagement.reallyCreate(); } @@ -339,18 +200,18 @@ public abstract class RelationManagement { public Edge reallyCreate(UUID sourceUUID) throws ResourceRegistryException { ResourceManagement srmSource = new ResourceManagement(orientGraph); srmSource.setUUID(sourceUUID); - Vertex source = srmSource.getVertex(); + Vertex source = srmSource.getElement(); return reallyCreate(source); } public Edge reallyUpdate() throws ResourceRegistryException { - logger.debug("Trying to update {} : {}", relationType, jsonNode); + logger.debug("Trying to update {} : {}", erType, jsonNode); - Edge edge = getEdge(); + Edge edge = getElement(); ERManagement.updateProperties(edge, jsonNode, ignoreKeys, ignoreStartWithKeys); - if (ConsistsOf.class.isAssignableFrom(relationClass)) { + if (ConsistsOf.class.isAssignableFrom(erClass)) { JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); if (target != null) { FacetManagement fm = new FacetManagement(orientGraph); @@ -359,7 +220,7 @@ public abstract class RelationManagement { } } - logger.info("{} {} successfully updated", relationType, jsonNode); + logger.info("{} {} successfully updated", erType, jsonNode); return edge; @@ -367,13 +228,13 @@ public abstract class RelationManagement { public boolean reallyAddToContext() throws ContextException, ResourceRegistryException { - getEdge(); + getElement(); AddConstraint addConstraint = AddConstraint.unpropagate; try { PropagationConstraint propagationConstraint = Utility.getEmbedded( - PropagationConstraint.class, edge, + PropagationConstraint.class, element, Relation.PROPAGATION_CONSTRAINT); if (propagationConstraint.getAddConstraint() != null) { addConstraint = propagationConstraint.getAddConstraint(); @@ -383,10 +244,10 @@ public abstract class RelationManagement { + "This is really strange and should not occur. " + "Please Investigate it.", Relation.PROPAGATION_CONSTRAINT, - Utility.toJsonString(edge, true), addConstraint); + Utility.toJsonString(element, true), addConstraint); } - Vertex target = edge.getVertex(Direction.IN); + Vertex target = element.getVertex(Direction.IN); switch (addConstraint) { case propagate: @@ -395,7 +256,7 @@ public abstract class RelationManagement { * must be added. Otherwise we have a relation which point * to an entity outside of the context. */ - ContextUtility.addToActualContext(orientGraph, getEdge()); + ContextUtility.addToActualContext(orientGraph, getElement()); EntityManagement entityManagement = EntityManagement .getEntityManagement(orientGraph, target); entityManagement.reallyAddToContext(); @@ -425,13 +286,13 @@ public abstract class RelationManagement { public boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException { - getEdge(); + getElement(); RemoveConstraint removeConstraint = RemoveConstraint.keep; try { PropagationConstraint propagationConstraint = Utility.getEmbedded( - PropagationConstraint.class, edge, + PropagationConstraint.class, element, Relation.PROPAGATION_CONSTRAINT); if (propagationConstraint.getRemoveConstraint() != null) { removeConstraint = propagationConstraint.getRemoveConstraint(); @@ -441,16 +302,16 @@ public abstract class RelationManagement { + "This is really strange and should not occur. " + "Please Investigate it.", Relation.PROPAGATION_CONSTRAINT, - Utility.toJsonString(edge, true), removeConstraint); + Utility.toJsonString(element, true), removeConstraint); } - Vertex target = edge.getVertex(Direction.IN); + Vertex target = element.getVertex(Direction.IN); /* * In any removeConstraint value the relation MUSt be removed from * context to avoid to have edge having a source outside of the context. */ - ContextUtility.removeFromActualContext(orientGraph, edge); + ContextUtility.removeFromActualContext(orientGraph, element); switch (removeConstraint) { case cascade: @@ -463,7 +324,7 @@ public abstract class RelationManagement { if (iterator.hasNext()) { logger.trace( "{} point to {} which is not orphan. Giving {} directive, it will be not remove from current context.", - edge, target, removeConstraint); + element, target, removeConstraint); } else { removeFromContextTargetVertex(target); } @@ -482,20 +343,21 @@ public abstract class RelationManagement { protected EntityManagement getEntityManagement() throws ResourceRegistryException { EntityManagement entityManagement; - if (ConsistsOf.class.isAssignableFrom(relationClass)) { + if (ConsistsOf.class.isAssignableFrom(erClass)) { entityManagement = new FacetManagement(orientGraph); - } else if (IsRelatedTo.class.isAssignableFrom(relationClass)) { + } else if (IsRelatedTo.class.isAssignableFrom(erClass)) { entityManagement = new ResourceManagement(orientGraph); } else { String error = String.format("{%s is not a %s nor a %s. " + "This is really strange ad should not occur. " - + "Please Investigate it.", relationClass, ConsistsOf.NAME, + + "Please Investigate it.", erClass, ConsistsOf.NAME, IsRelatedTo.NAME); throw new ResourceRegistryException(error); } return entityManagement; } + @SuppressWarnings("unchecked") public static RelationManagement getRelationManagement( OrientGraph orientGraph, Edge edge) throws ResourceRegistryException { @@ -512,7 +374,7 @@ public abstract class RelationManagement { IsRelatedTo.NAME); throw new ResourceRegistryException(error); } - relationManagement.setEdge(edge); + relationManagement.setElement(edge); return relationManagement; } @@ -530,13 +392,17 @@ public abstract class RelationManagement { public boolean reallyDelete() throws RelationNotFoundException, ResourceRegistryException { - getEdge(); + logger.debug( + "Going to remove {} with UUID {}. Related {}s will be detached.", + baseType, uuid, targetEntityClass.getSimpleName()); + + getElement(); RemoveConstraint removeConstraint = RemoveConstraint.keep; try { PropagationConstraint propagationConstraint = Utility.getEmbedded( - PropagationConstraint.class, edge, + PropagationConstraint.class, element, Relation.PROPAGATION_CONSTRAINT); if (propagationConstraint.getRemoveConstraint() != null) { removeConstraint = propagationConstraint.getRemoveConstraint(); @@ -546,34 +412,34 @@ public abstract class RelationManagement { + "This is really strange and should not occur. " + "Please Investigate it.", Relation.PROPAGATION_CONSTRAINT, - Utility.toJsonString(edge, true), removeConstraint); + Utility.toJsonString(element, true), removeConstraint); } - Vertex target = edge.getVertex(Direction.IN); - edge.remove(); + Vertex target = element.getVertex(Direction.IN); + element.remove(); switch (removeConstraint) { - case cascade: - deleteTargetVertex(target); - break; - - case cascadeWhenOrphan: - Iterable iterable = target.getEdges(Direction.IN); - Iterator iterator = iterable.iterator(); - if (iterator.hasNext()) { - logger.trace( - "{} point to {} which is not orphan. Giving {} directive, it will be keep.", - edge, target, removeConstraint); - } else { + case cascade: deleteTargetVertex(target); - } - break; - - case keep: - break; - - default: - break; + break; + + case cascadeWhenOrphan: + Iterable iterable = target.getEdges(Direction.IN); + Iterator iterator = iterable.iterator(); + if (iterator.hasNext()) { + logger.trace( + "{} point to {} which is not orphan. Giving {} directive, it will be keep.", + element, target, removeConstraint); + } else { + deleteTargetVertex(target); + } + break; + + case keep: + break; + + default: + break; } return true; @@ -585,7 +451,7 @@ public abstract class RelationManagement { orientGraph = ContextUtility .getActualSecurityContextGraph(PermissionMode.WRITER); - edge = reallyCreate(sourceUUID, targetUUID); + element = reallyCreate(sourceUUID, targetUUID); orientGraph.commit(); @@ -608,160 +474,4 @@ public abstract class RelationManagement { } } - public String read() throws RelationNotFoundException, - ResourceRegistryException { - try { - - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.WRITER); - - return serialize(); - - } catch (ResourceRegistryException e) { - if (orientGraph != null) { - orientGraph.rollback(); - } - throw e; - } catch (Exception e) { - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ResourceRegistryException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - - public String update() throws RelationNotFoundException, - ResourceRegistryException { - try { - - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.WRITER); - - edge = reallyUpdate(); - - return serialize(); - - } catch (ResourceRegistryException e) { - if (orientGraph != null) { - orientGraph.rollback(); - } - throw e; - } catch (Exception e) { - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ResourceRegistryException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - - public boolean delete() throws RelationNotFoundException, - ResourceRegistryException { - - logger.debug( - "Going to remove {} with UUID {}. Related {}s will be detached.", - baseType, uuid, targetEntityClass.getSimpleName()); - - try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.WRITER); - - boolean deleted = reallyDelete(); - - orientGraph.commit(); - - logger.info("{} {} with UUID {} successfully removed.", baseType, - uuid); - - return deleted; - - } catch (ResourceRegistryException e) { - logger.error("Unable to remove {} with UUID.", baseType, uuid); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw e; - } catch (Exception e) { - logger.error("Unable to remove {} with UUID {}.", baseType, uuid); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ResourceRegistryException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - - } - - public boolean addToContext() throws ContextException { - logger.debug("Going to add {} with UUID {} to actual Context", - baseType, uuid); - - try { - orientGraph = SecurityContextMapper.getSecurityContextFactory( - SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, - PermissionMode.WRITER).getTx(); - - boolean added = reallyAddToContext(); - - orientGraph.commit(); - logger.info("{} with UUID {} successfully added to actual Context", - baseType, uuid); - - return added; - } catch (Exception e) { - logger.error("Unable to add {} with UUID {} to actual Context", - baseType, uuid, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ContextException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - - public boolean removeFromContext() throws ContextException { - logger.debug("Going to remove {} with UUID {} from actual Context", - baseType, uuid); - - try { - orientGraph = SecurityContextMapper.getSecurityContextFactory( - SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, - PermissionMode.WRITER).getTx(); - - boolean removed = reallyRemoveFromContext(); - - orientGraph.commit(); - logger.info( - "{} with UUID {} successfully removed from actual Context", - baseType, uuid); - - return removed; - } catch (Exception e) { - logger.error( - "Unable to remove {} with UUID {} from actual Context", - baseType, uuid, e); - if (orientGraph != null) { - orientGraph.rollback(); - } - throw new ContextException(e); - } finally { - if (orientGraph != null) { - orientGraph.shutdown(); - } - } - } - } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java index 586c28b..07e478a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java @@ -12,12 +12,14 @@ import javax.ws.rs.core.MediaType; import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException; 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.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; +import org.gcube.informationsystem.resourceregistry.er.ERManagement; 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.gcube.informationsystem.resourceregistry.query.Query; import org.gcube.informationsystem.resourceregistry.query.QueryImpl; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagement; @@ -36,27 +38,31 @@ public class Access { public static final String ID_PATH_PARAM = "id"; public static final String TYPE_PATH_PARAM = "type"; + /** - * It allows to query Entities and Relations in the current Context.
- * It accepts idempotent query only.. - *

- * For query syntax please refer to
+ * It includeSubtypesows to query Entities and Relations in the current Context.
+ * It accepts idempotent query only..
+ *
+ * For query syntax please refer to
* - * https://orientdb.com/docs/last/SQL-Syntax.html - * - *

+ * https://orientdb.com/docs/last/SQL-Syntax.html
+ *
* e.g. GET /resource-registry/access?query=SELECT FROM V - * @param query Defines the query to send to the backend. - * @param limit Defines the number of results you want returned, - * defaults to all results. - * @param fetchPlan Defines the fetching strategy you want to use. See - * - * https://orientdb.com/docs/last/Fetching-Strategies.html - * + * + * @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 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 no idempotent */ @GET @Produces(MediaType.APPLICATION_JSON) @@ -64,100 +70,254 @@ public class Access { @QueryParam(AccessPath.LIMIT_PARAM) int limit, @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) throws InvalidQueryException { - logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query); + logger.info("Requested query (fetch plan {}, limit : {}):\n{}", + fetchPlan, limit, query); Query queryManager = new QueryImpl(); return queryManager.query(query, limit, fetchPlan); } - /** - * e.g. GET /resource-registry/access/facet/instance/4d28077b-566d-4132-b073-f4edaf61dcb9 - * @param facetId - * @return - * @throws FacetNotFoundException - * @throws ResourceRegistryException + + @SuppressWarnings("rawtypes") + public static ERManagement getERManagement(AccessType querableType) throws ResourceRegistryException { + switch (querableType) { + case FACET: + return new FacetManagement(); + + case RESOURCE: + return new ResourceManagement(); + + case IS_RELATED_TO: + return new IsRelatedToManagement(); + + case CONSISTS_OF: + return new ConsistsOfManagement(); + + default: + throw new ResourceRegistryException(String.format("%s is not querable", querableType.toString())); + } + } + + + /* + * e.g. GET /resource-registry/access/instance/{E-R}/4d28077b-566d-4132-b073-f4edaf61dcb9 */ - @GET - @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @GET + @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM +"}" + + "/{" + ID_PATH_PARAM + "}") @Produces(MediaType.APPLICATION_JSON) - public String getFacet(@PathParam(ID_PATH_PARAM) String facetId) + public String getInstance( + @PathParam(ID_PATH_PARAM) String type, + @PathParam(ID_PATH_PARAM) String facetId) + throws ResourceRegistryException { + logger.info("Requested Facet with id {}", facetId); + + AccessType querableType = null; + try { + querableType = AccessType.valueOf(type); + }catch(Exception e){ + String error = String.format("%s is not querable", type); + throw new ResourceRegistryException(error); + } + + @SuppressWarnings("rawtypes") + ERManagement erManagement = getERManagement(querableType); + erManagement.setUUID(UUID.fromString(facetId)); + return erManagement.read(); + } + + /* + * e.g. GET /resource-registry/access/instances/{E-R}?polymorphic=true + */ + @GET + @Path(AccessPath.INSTANCE_PATH_PART + "s/" + "{" + TYPE_PATH_PARAM +"}" + + "/{" + ID_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) + public String getInstances( + @PathParam(ID_PATH_PARAM) String type, + @PathParam(ID_PATH_PARAM) String facetId) throws FacetNotFoundException, ResourceRegistryException { logger.info("Requested Facet with id {}", facetId); - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setUUID(UUID.fromString(facetId)); - return facetManagement.read(); - } - - /** - * e.g. GET /resource-registry/access/facet/schema/ContactFacet - * @param facetType - * @return - * @throws SchemaNotFoundException - */ - @GET - @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Produces(MediaType.APPLICATION_JSON) - public String getFacetSchema(@PathParam(TYPE_PATH_PARAM) String facetType) - throws SchemaNotFoundException { - logger.info("Requested Facet Schema for type {}", facetType); - SchemaManagement schemaManager = new SchemaManagementImpl(); - return schemaManager.getFacetSchema(facetType); + AccessType querableType = null; + try { + querableType = AccessType.valueOf(type); + }catch(Exception e){ + String error = String.format("%s is not querable", type); + throw new ResourceRegistryException(error); + } + + + // TODO + + return null; } - - /** - * e.g. GET /resource-registry/access/resource/instance/cc132a2c-d0b0-45a8-92fa-7451f6a44b6d - * @param resourceId - * @return - * @throws ResourceNotFoundException - * @throws ResourceRegistryException + /* + * e.g. GET /resource-registry/access/schema/Facet/ContactFacet? + * includeSubtypes=true& + * includeSchema=true */ @GET - @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(AccessPath.SCHEMA_PATH_PART + "/{" + + TYPE_PATH_PARAM + "}") @Produces(MediaType.APPLICATION_JSON) - public String getResource(@PathParam(ID_PATH_PARAM) String resourceId) - throws ResourceNotFoundException, ResourceRegistryException { - logger.info("Requested Resource with id {}", resourceId); - ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setUUID(UUID.fromString(resourceId)); - return resourceManagement.read(); + public String getSchema(@PathParam(TYPE_PATH_PARAM) String type, + @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes, + @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema) + throws SchemaNotFoundException, SchemaException { + logger.info("Requested Facet Schema for type {}", type); + SchemaManagement schemaManagement = new SchemaManagementImpl(); + + // TODO + + return schemaManagement.readFacetSchema(type, includeSubtypes, + includeSchema); } + + + + + + + +// /* +// * e.g. GET /resource-registry/access/facet/instance/ +// * 4d28077b-566d-4132-b073-f4edaf61dcb9 +// */ +// @GET +// @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART +// + "/{" + ID_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getFacet(@PathParam(ID_PATH_PARAM) String facetId) +// throws FacetNotFoundException, ResourceRegistryException { +// logger.info("Requested Facet with id {}", facetId); +// FacetManagement facetManagement = new FacetManagement(); +// facetManagement.setUUID(UUID.fromString(facetId)); +// return facetManagement.read(); +// } +// +// /* +// * e.g. GET /resource-registry/access/facet/schema/ContactFacet? +// * includeSubtypes=true& +// * includeSchema=true +// * +// */ +// @GET +// @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" +// + TYPE_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getFacetSchema(@PathParam(TYPE_PATH_PARAM) String facetType, +// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes, +// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema) +// throws SchemaNotFoundException, SchemaException { +// logger.info("Requested Facet Schema for type {}", facetType); +// SchemaManagement schemaManagement = new SchemaManagementImpl(); +// return schemaManagement.readFacetSchema(facetType, includeSubtypes, +// includeSchema); +// } +// +// /* +// * e.g. GET /resource-registry/access/resource/instance/ +// * cc132a2c-d0b0-45a8-92fa-7451f6a44b6d +// */ +// @GET +// @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART +// + "/{" + ID_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getResource(@PathParam(ID_PATH_PARAM) String resourceId) +// throws ResourceNotFoundException, ResourceRegistryException { +// logger.info("Requested Resource with id {}", resourceId); +// ResourceManagement resourceManagement = new ResourceManagement(); +// resourceManagement.setUUID(UUID.fromString(resourceId)); +// return resourceManagement.read(); +// } +// +// +// +// +// /* +// * e.g. GET /resource-registry/access/resource/schema/HostingNode? +// * includeSubtypes=true& +// * includeSchema=true +// */ +// @GET +// @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART +// + "/{" + TYPE_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getResourceSchema( +// @PathParam(TYPE_PATH_PARAM) String resourceType, +// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes, +// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema) +// throws SchemaNotFoundException, SchemaException { +// logger.info("Requested Resource Schema for type {}", resourceType); +// SchemaManagement schemaManagement = new SchemaManagementImpl(); +// return schemaManagement.getResourceSchema(resourceType, +// includeSubtypes, includeSchema); +// } +// +// /* +// * e.g. GET /resource-registry/access/embedded/schema/Embedded? +// * includeSubtypes=true& +// * includeSchema=true +// */ +// @GET +// @Path(AccessPath.EMBEDDED_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART +// + "/{" + TYPE_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getEmbeddedSchema( +// @PathParam(TYPE_PATH_PARAM) String embeddedType, +// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes, +// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema) +// throws SchemaNotFoundException, SchemaException { +// if (includeSchema == null) { +// includeSchema = false; +// } +// SchemaManagement schemaManagement = new SchemaManagementImpl(); +// return schemaManagement.getEmbeddedTypeSchema(embeddedType, +// includeSubtypes, includeSchema); +// } +// +// /* +// * e.g. GET /resource-registry/access/consistsOf/schema/HasContact? +// * includeSubtypes=true& +// * includeSchema=true +// */ +// @GET +// @Path(AccessPath.CONSISTS_OF_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART +// + "/{" + TYPE_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getConsistsOfSchema( +// @PathParam(TYPE_PATH_PARAM) String consistsOfType, +// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes, +// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema) +// throws SchemaNotFoundException, SchemaException { +// if (includeSchema == null) { +// includeSchema = false; +// } +// SchemaManagement schemaManagement = new SchemaManagementImpl(); +// return schemaManagement.getConsistsOfSchema(consistsOfType, +// includeSubtypes, includeSchema); +// } +// +// /* +// * e.g. GET /resource-registry/access/isRelatedTo/schema/HasContact? +// * includeSubtypes=true& +// * includeSchema=true +// */ +// @GET +// @Path(AccessPath.IS_RELATED_TO_PATH_PART + "/" +// + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") +// @Produces(MediaType.APPLICATION_JSON) +// public String getIsRelatedToSchema( +// @PathParam(TYPE_PATH_PARAM) String isRelatedToType, +// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes, +// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema) +// throws SchemaNotFoundException, SchemaException { +// if (includeSchema == null) { +// includeSchema = false; +// } +// SchemaManagement schemaManagement = new SchemaManagementImpl(); +// return schemaManagement.getIsRelatedToSchema(isRelatedToType, +// includeSubtypes, includeSchema); +// } - /** - * e.g. GET /resource-registry/access/resource/schema/HostingNode - * @param resourceType - * @return - * @throws SchemaNotFoundException - */ - @GET - @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Produces(MediaType.APPLICATION_JSON) - public String getResourceSchema(@PathParam(TYPE_PATH_PARAM) String resourceType) - throws SchemaNotFoundException { - logger.info("Requested Resource Schema for type {}", resourceType); - SchemaManagement schemaManager = new SchemaManagementImpl(); - return schemaManager.getResourceSchema(resourceType); - } - - - public String getResourceTypes(String resourceType, boolean includeSchema) throws SchemaNotFoundException, SchemaException { - throw new UnsupportedOperationException("Not Yet implemented"); - } - - public String getEmbeddedTypes(String embeddedType, boolean includeSchema) throws SchemaNotFoundException, SchemaException { - throw new UnsupportedOperationException("Not Yet implemented"); - } - - - public String getRelationTypes(String relationType, boolean includeSchema) throws SchemaNotFoundException, SchemaException { - throw new UnsupportedOperationException("Not Yet implemented"); - } - - public String getConsistsOfTypes(String consistsOfType, boolean includeSchema) throws SchemaNotFoundException, SchemaException { - throw new UnsupportedOperationException("Not Yet implemented"); - } - - public String getIsRelatedToTypes(String isRelatedToType, boolean includeSchema) throws SchemaNotFoundException, SchemaException { - throw new UnsupportedOperationException("Not Yet implemented"); - } - } \ No newline at end of file diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/AccessType.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/AccessType.java new file mode 100644 index 0000000..167923f --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/AccessType.java @@ -0,0 +1,45 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.rest; + +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.IsRelatedTo; +import org.gcube.informationsystem.model.relation.Relation; + +/** + * @author Luca Frosini (ISTI - CNR) + * + * Enumerates the basic type names. + */ +public enum AccessType { + + ENTITY(Entity.NAME), + RESOURCE(Resource.NAME), + FACET(Facet.NAME), + + RELATION(Relation.NAME), + IS_RELATED_TO(IsRelatedTo.NAME), + CONSISTS_OF(ConsistsOf.NAME); + + private final String name; + private final String lowerCaseFirstCharacter; + + AccessType(String name){ + this.name = name; + this.lowerCaseFirstCharacter = name.substring(0, 1).toLowerCase() + name.substring(1); + } + + public String lowerCaseFirstCharacter() { + return lowerCaseFirstCharacter; + } + + @Override + public String toString(){ + return name; + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java index e7bee5e..cba9bf1 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java @@ -20,7 +20,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; -import org.gcube.informationsystem.resourceregistry.api.rest.EntityPath; +import org.gcube.informationsystem.resourceregistry.api.rest.ERPath; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; @@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory; * @author Luca Frosini (ISTI - CNR) * @author Lucio Lelii (ISTI - CNR) */ -@Path(EntityPath.ENTITY_PATH_PART) +@Path(ERPath.ER_PATH_PART) public class ERManager { private static Logger logger = LoggerFactory.getLogger(SchemaManager.class); @@ -57,7 +57,7 @@ public class ERManager { * @throws ResourceRegistryException */ @PUT - @Path(EntityPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) public String createFacet(@PathParam(TYPE_PATH_PARAM) String type, @@ -65,7 +65,7 @@ public class ERManager { logger.info("requested facet creation for type {} defined by {} ", type, json); FacetManagement facetManagement = new FacetManagement(); - facetManagement.setEntityType(type); + facetManagement.setElementType(type); facetManagement.setJSON(json); return facetManagement.create(); } @@ -83,7 +83,7 @@ public class ERManager { * @throws ResourceRegistryException */ @POST - @Path(EntityPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json) @@ -105,7 +105,7 @@ public class ERManager { * @throws ResourceRegistryException */ @DELETE - @Path(EntityPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ResourceRegistryException { logger.info("Requested to delete Facet with id {}", uuid); @@ -128,7 +128,7 @@ public class ERManager { * @throws ResourceRegistryException */ @PUT - @Path(EntityPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) public String createResource(@PathParam(TYPE_PATH_PARAM) String type, @@ -137,13 +137,13 @@ public class ERManager { logger.info("requested resource creation for type {} with json {}", type, json); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(type); + resourceManagement.setElementType(type); resourceManagement.setJSON(json); return resourceManagement.create(); } @POST - @Path(EntityPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, @@ -166,7 +166,7 @@ public class ERManager { * @throws Exception */ @DELETE - @Path(EntityPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception { logger.info("requested resource deletion for id {}", uuid); @@ -194,8 +194,8 @@ public class ERManager { * @throws ResourceRegistryException */ @PUT - @Path(EntityPath.CONSISTS_OF_PATH_PART + "/" + EntityPath.SOURCE_PATH_PART - + "/{" + SOURCE_ID_PATH_PARAM + "}/" + EntityPath.TARGET_PATH_PART + @Path(ERPath.CONSISTS_OF_PATH_PART + "/" + ERPath.SOURCE_PATH_PART + + "/{" + SOURCE_ID_PATH_PARAM + "}/" + ERPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}/{" + TYPE_PATH_PARAM + "}") @Produces(MediaType.APPLICATION_JSON) public String attachFacet( @@ -209,7 +209,7 @@ public class ERManager { resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(), type, json); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setRelationType(type); + consistsOfManagement.setElementType(type); consistsOfManagement.setJSON(json); return consistsOfManagement.create(UUID.fromString(resourceUUID), UUID.fromString(facetUUID)); @@ -224,7 +224,7 @@ public class ERManager { * @throws ResourceRegistryException */ @DELETE - @Path(EntityPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException { logger.info("requested to detach {}", consistOfUUID); @@ -249,9 +249,9 @@ public class ERManager { * @throws ResourceRegistryException */ @PUT - @Path(EntityPath.IS_RELATED_TO_PATH_PART + "/" - + EntityPath.SOURCE_PATH_PART + "/{" + SOURCE_ID_PATH_PARAM + "}/" - + EntityPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}/{" + @Path(ERPath.IS_RELATED_TO_PATH_PART + "/" + + ERPath.SOURCE_PATH_PART + "/{" + SOURCE_ID_PATH_PARAM + "}/" + + ERPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}/{" + TYPE_PATH_PARAM + "}") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Produces(MediaType.APPLICATION_JSON) @@ -267,7 +267,7 @@ public class ERManager { json); IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); - isRelatedToManagement.setRelationType(type); + isRelatedToManagement.setElementType(type); isRelatedToManagement.setJSON(json); return isRelatedToManagement.create( @@ -284,7 +284,7 @@ public class ERManager { * @throws ResourceRegistryException */ @DELETE - @Path(EntityPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException { logger.info("requested to detach {}", relatedToUUID); @@ -304,7 +304,7 @@ public class ERManager { * @throws ResourceRegistryException */ @POST - @Path(EntityPath.ADD_PATH_PART + "/" + EntityPath.RESOURCE_PATH_PART + "/{" + @Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, ContextNotFoundException, @@ -327,7 +327,7 @@ public class ERManager { * @throws ResourceRegistryException */ @POST - @Path(EntityPath.ADD_PATH_PART + "/" + EntityPath.FACET_PATH_PART + "/{" + @Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ContextNotFoundException, @@ -350,7 +350,7 @@ public class ERManager { * @throws ResourceRegistryException */ @POST - @Path(EntityPath.REMOVE_PATH_PART + "/" + EntityPath.RESOURCE_PATH_PART + "/{" + @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, ContextNotFoundException, @@ -373,7 +373,7 @@ public class ERManager { * @throws ResourceRegistryException */ @POST - @Path(EntityPath.REMOVE_PATH_PART + "/" + EntityPath.FACET_PATH_PART + "/{" + @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ContextNotFoundException, diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java index 5396340..8957f5a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java @@ -28,8 +28,6 @@ public class SchemaManager { private static Logger logger = LoggerFactory.getLogger(SchemaManager.class); - protected SchemaManagement schemaManager = new SchemaManagementImpl(); - /** * e.g. PUT /resource-registry/schema/embedded * @@ -49,7 +47,8 @@ public class SchemaManager { throws SchemaException { logger.trace("Requested {} registration with schema {}", Embedded.NAME, jsonSchema); - return schemaManager.registerEmbeddedTypeSchema(jsonSchema); + SchemaManagement schemaManagement = new SchemaManagementImpl(); + return schemaManagement.registerEmbeddedTypeSchema(jsonSchema); } /** @@ -68,7 +67,8 @@ public class SchemaManager { public String registerFacetSchema(String jsonSchema) throws SchemaException { logger.trace("Requested {} registration with schema {}", Facet.NAME, jsonSchema); - return schemaManager.registerFacetSchema(jsonSchema); + SchemaManagement schemaManagement = new SchemaManagementImpl(); + return schemaManagement.createFacetSchema(jsonSchema); } /** @@ -89,7 +89,8 @@ public class SchemaManager { throws SchemaException { logger.trace("Requested {} registration with schema {}", Resource.NAME, jsonSchema); - return schemaManager.registerResourceSchema(jsonSchema); + SchemaManagement schemaManagement = new SchemaManagementImpl(); + return schemaManagement.registerResourceSchema(jsonSchema); } /** @@ -109,7 +110,8 @@ public class SchemaManager { throws SchemaException { logger.trace("Requested {} registration with schema {} ", ConsistsOf.NAME, jsonSchema); - return schemaManager.registerConsistsOfSchema(jsonSchema); + SchemaManagement schemaManagement = new SchemaManagementImpl(); + return schemaManagement.registerConsistsOfSchema(jsonSchema); } /** @@ -129,10 +131,8 @@ public class SchemaManager { throws SchemaException { logger.trace("Requested {} registration with schema {} ", IsRelatedTo.NAME, jsonSchema); - return schemaManager.registerIsRelatedToSchema(jsonSchema); + SchemaManagement schemaManagement = new SchemaManagementImpl(); + return schemaManagement.registerIsRelatedToSchema(jsonSchema); } - - - } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/EntitySchemaManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/EntitySchemaManagement.java new file mode 100644 index 0000000..cba0dae --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/EntitySchemaManagement.java @@ -0,0 +1,12 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.schema; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +public class EntitySchemaManagement { + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java index fe4bb80..f249ef4 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java @@ -12,85 +12,76 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema */ public interface SchemaManagement { - public String registerEntitySchema(String jsonSchema) throws SchemaException; + /* + public String create(String json) throws SchemaException; - public String getEntitySchema(String entityType) throws SchemaNotFoundException; + public String read(String type, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; + + public String update(String type, String json) throws SchemaNotFoundException, SchemaException; + + public String delete(String type) throws SchemaNotFoundException; + */ + + public String createEntitySchema(String jsonSchema) throws SchemaException; + + public String readEntitySchema(String entityType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateEntitySchema(String entityType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteEntitySchema(String entityType) throws SchemaNotFoundException; - public String getEntityTypes(String entityType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; + public String createFacetSchema(String jsonSchema) throws SchemaException; - public String registerFacetSchema(String jsonSchema) throws SchemaException; - - public String getFacetSchema(String facetType) throws SchemaNotFoundException; + public String readFacetSchema(String facetType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateFacetSchema(String facetType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteFacetSchema(String facetType) throws SchemaNotFoundException; - public String getFacetTypes(String facetType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; - - public String registerResourceSchema(String jsonSchema) throws SchemaException; - public String getResourceSchema(String resourceType) throws SchemaNotFoundException; + public String getResourceSchema(String resourceType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateResourceSchema(String resourceType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteResourceSchema(String resourceType) throws SchemaNotFoundException; - public String getResourceTypes(String resourceType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; - - public String registerEmbeddedTypeSchema(String jsonSchema) throws SchemaException; - public String getEmbeddedTypeSchema(String embeddedType) throws SchemaNotFoundException; + public String getEmbeddedTypeSchema(String embeddedType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateEmbeddedTypeSchema(String embeddedType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteEmbeddedTypeSchema(String embeddedType) throws SchemaNotFoundException; - public String getEmbeddedTypes(String embeddedType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; - - public String registerRelationSchema(String jsonSchema) throws SchemaException; - public String getRelationSchema(String relationType) throws SchemaNotFoundException; + public String getRelationSchema(String relationType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateRelationSchema(String relationType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteRelationSchema(String relationType) throws SchemaNotFoundException; - public String getRelationTypes(String relationType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; - - - + public String registerConsistsOfSchema(String jsonSchema) throws SchemaException; - public String getConsistsOfSchema(String consistsOfType) throws SchemaNotFoundException; + public String getConsistsOfSchema(String consistsOfType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateConsistsOfSchema(String consistsOfType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteConsistsOfSchema(String consistsOfType) throws SchemaException; - public String getConsistsOfTypes(String consistsOfType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; - - public String registerIsRelatedToSchema(String jsonSchema) throws SchemaException; - public String getIsRelatedToSchema(String isRelatedToType) throws SchemaNotFoundException; + public String getIsRelatedToSchema(String isRelatedToType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException; public String updateIsRelatedToSchema(String isRelatedToType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String deleteIsRelatedToSchema(String isRelatedToType) throws SchemaException; - - public String getIsRelatedToTypes(String isRelatedToType, boolean includeSchema) throws SchemaNotFoundException, SchemaException; - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java index 6ce6b8d..e17524a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java @@ -22,6 +22,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.types.TypeBinder; import org.gcube.informationsystem.types.TypeBinder.Property; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.slf4j.Logger; @@ -62,26 +63,34 @@ public class SchemaManagementImpl implements SchemaManagement { } public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, - String type, String baseType) throws SchemaNotFoundException { + String type, String baseType) throws SchemaException { + OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata(); + OSchema oSchema = oMetadata.getSchema(); + return getTypeSchema(oSchema, type, baseType); + } + + public static OClass getTypeSchema(OSchema oSchema, String type, + String baseType) throws SchemaException { try { - OClass oClass = getEntityOClass(orientBaseGraph, type); - if (baseType != null) { - if (baseType.compareTo(Embedded.NAME) != 0 - && !oClass.isSubClassOf(baseType)) { - throw new SchemaException("The requested type is not a " - + baseType); + OClass oClass = oSchema.getClass(type); + if (oClass == null) { + throw new SchemaNotFoundException(type + "was not registered"); + } + if (baseType != null && type.compareTo(baseType) != 0) { + if (!oClass.isSubClassOf(baseType)) { + throw new SchemaException(type + " is not a " + baseType); } } return oClass; } catch (SchemaNotFoundException snfe) { throw snfe; } catch (Exception e) { - throw new SchemaNotFoundException(e.getMessage()); + throw new SchemaException(e.getMessage()); } } public static OClass getTypeSchema(String type, String baseType) - throws SchemaNotFoundException { + throws SchemaException { OrientGraphFactory orientGraphFactory = SecurityContextMapper .getSecurityContextFactory( SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, @@ -103,11 +112,32 @@ public class SchemaManagementImpl implements SchemaManagement { } } + protected static TypeDefinition getTypeDefinition(OClass oClass) + throws SchemaException { + String json = serializeOClass(oClass); + try { + return TypeBinder.deserializeTypeDefinition(json); + } catch (Exception e) { + throw new SchemaException(e); + } + } + + protected static String getTypeDefinitionAsString(OClass oClass) + throws SchemaException { + + try { + TypeDefinition typeDefinition = getTypeDefinition(oClass); + return TypeBinder.serializeType(typeDefinition); + } catch (Exception e) { + throw new SchemaException(e); + } + } + protected static JSONObject serializeOClassAsJSON(OClass oClass) throws SchemaException { - String jsonString = serializeOClass(oClass); + String json = serializeOClass(oClass); try { - return new JSONObject(jsonString); + return new JSONObject(json); } catch (JSONException e) { throw new SchemaException(e); } @@ -205,14 +235,13 @@ public class SchemaManagementImpl implements SchemaManagement { typeDefinition.getName()); } - if(typeDefinition.getName().compareTo(Embedded.NAME)!=0){ + if (typeDefinition.getName().compareTo(Embedded.NAME) != 0) { List oSuperclasses = getSuperclassesAndCheckCompliancy( - orientGraphNoTx, - typeDefinition, + orientGraphNoTx, typeDefinition, baseType.getSimpleName()); oClass.setSuperClasses(oSuperclasses); } - + if (Resource.class.isAssignableFrom(baseType)) { Set properties = typeDefinition.getProperties(); if (properties != null && properties.size() > 0) { @@ -281,9 +310,9 @@ public class SchemaManagementImpl implements SchemaManagement { } } - protected String getListOfType(String type, String baseType, - boolean includeSchema) throws SchemaNotFoundException, - SchemaException { + protected String getSchema(String type, String baseType, + boolean includeSubtypes, boolean includeSchema) + throws SchemaNotFoundException, SchemaException { OrientGraphFactory orientGraphFactory = SecurityContextMapper .getSecurityContextFactory( SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, @@ -292,24 +321,34 @@ public class SchemaManagementImpl implements SchemaManagement { OrientGraphNoTx orientGraphNoTx = null; try { orientGraphNoTx = orientGraphFactory.getNoTx(); - JSONArray jsonArray = new JSONArray(); - OClass baseOClass = getTypeSchema(orientGraphNoTx, type, baseType); - OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); - Collection oClasses = oSchema.getClasses(); - for (OClass oClass : oClasses) { - if (oClass.isSubClassOf(baseOClass)) { - if (includeSchema) { - jsonArray.put(serializeOClassAsJSON(oClass)); - } else { - jsonArray.put(oClass.getName()); + OClass baseOClass = getTypeSchema(oSchema, type, baseType); + + String ret = null; + if (includeSubtypes) { + JSONArray jsonArray = new JSONArray(); + Collection oClasses = oSchema.getClasses(); + for (OClass oClass : oClasses) { + if (oClass.isSubClassOf(baseOClass)) { + if (includeSchema) { + jsonArray.put(getTypeDefinitionAsString(oClass)); + } else { + jsonArray.put(oClass.getName()); + } } } + ret = jsonArray.toString(); + } else { + if (includeSchema) { + ret = getTypeDefinitionAsString(baseOClass); + } else { + ret = baseOClass.getName(); + } } - return jsonArray.toString(); + return ret; } catch (SchemaException e) { throw e; } catch (Exception e) { @@ -323,15 +362,16 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String registerEntitySchema(String jsonSchema) - throws SchemaException { + public String createEntitySchema(String jsonSchema) throws SchemaException { return registerTypeSchema(jsonSchema, Entity.class); } @Override - public String getEntitySchema(String entityType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(entityType, Entity.NAME); + public String readEntitySchema(String entityType, boolean includeSubtypes, + boolean includeSchema) throws SchemaNotFoundException, + SchemaException { + return getSchema(entityType, Entity.NAME, includeSubtypes, + includeSchema); } @Override @@ -347,20 +387,15 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String getEntityTypes(String baseEntityType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(baseEntityType, Entity.NAME, includeSchema); - } - - @Override - public String registerFacetSchema(String jsonSchema) throws SchemaException { + public String createFacetSchema(String jsonSchema) throws SchemaException { return registerTypeSchema(jsonSchema, Facet.class); } @Override - public String getFacetSchema(String facetType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(facetType, Facet.NAME); + public String readFacetSchema(String facetType, boolean includeSubtypes, + boolean includeSchema) throws SchemaNotFoundException, + SchemaException { + return getSchema(facetType, Facet.NAME, includeSubtypes, includeSchema); } @Override @@ -375,12 +410,6 @@ public class SchemaManagementImpl implements SchemaManagement { throw new UnsupportedOperationException("Not Yet implemented"); } - @Override - public String getFacetTypes(String baseFacetType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(baseFacetType, Facet.NAME, includeSchema); - } - @Override public String registerResourceSchema(String jsonSchema) throws SchemaException { @@ -388,9 +417,11 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String getResourceSchema(String resourceType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(resourceType, Resource.NAME); + public String getResourceSchema(String resourceType, + boolean includeSubtypes, boolean includeSchema) + throws SchemaNotFoundException, SchemaException { + return getSchema(resourceType, Resource.NAME, includeSubtypes, + includeSchema); } @Override @@ -405,12 +436,6 @@ public class SchemaManagementImpl implements SchemaManagement { throw new UnsupportedOperationException("Not Yet implemented"); } - @Override - public String getResourceTypes(String baseResourceType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(baseResourceType, Resource.NAME, includeSchema); - } - @Override public String registerEmbeddedTypeSchema(String jsonSchema) throws SchemaException { @@ -418,9 +443,11 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String getEmbeddedTypeSchema(String embeddedType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(embeddedType, null); + public String getEmbeddedTypeSchema(String embeddedType, + boolean includeSubtypes, boolean includeSchema) + throws SchemaNotFoundException, SchemaException { + return getSchema(embeddedType, Embedded.NAME, includeSubtypes, + includeSchema); } @Override @@ -435,12 +462,6 @@ public class SchemaManagementImpl implements SchemaManagement { throw new UnsupportedOperationException("Not Yet implemented"); } - @Override - public String getEmbeddedTypes(String embeddedType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(embeddedType, Embedded.NAME, includeSchema); - } - @Override public String registerRelationSchema(String jsonSchema) throws SchemaException { @@ -448,9 +469,11 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String getRelationSchema(String relationType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(relationType, Relation.NAME); + public String getRelationSchema(String relationType, + boolean includeSubtypes, boolean includeSchema) + throws SchemaNotFoundException, SchemaException { + return getSchema(relationType, Relation.NAME, includeSubtypes, + includeSchema); } @Override @@ -465,12 +488,6 @@ public class SchemaManagementImpl implements SchemaManagement { throw new UnsupportedOperationException("Not Yet implemented"); } - @Override - public String getRelationTypes(String baseRelationType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(baseRelationType, Relation.NAME, includeSchema); - } - @Override public String registerConsistsOfSchema(String jsonSchema) throws SchemaException { @@ -478,14 +495,16 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String getConsistsOfSchema(String consistsOfType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(consistsOfType, ConsistsOf.NAME); + public String getConsistsOfSchema(String consistsOfType, + boolean includeSubtypes, boolean includeSchema) + throws SchemaNotFoundException, SchemaException { + return getSchema(consistsOfType, ConsistsOf.NAME, includeSubtypes, + includeSchema); } @Override - public String updateConsistsOfSchema(String consistsOfType, String jsonSchema) - throws SchemaNotFoundException, SchemaException { + public String updateConsistsOfSchema(String consistsOfType, + String jsonSchema) throws SchemaNotFoundException, SchemaException { throw new UnsupportedOperationException("Not Yet implemented"); } @@ -495,13 +514,6 @@ public class SchemaManagementImpl implements SchemaManagement { throw new UnsupportedOperationException("Not Yet implemented"); } - @Override - public String getConsistsOfTypes(String consistsOfType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(consistsOfType, ConsistsOf.NAME, includeSchema); - } - - @Override public String registerIsRelatedToSchema(String jsonSchema) throws SchemaException { @@ -509,9 +521,11 @@ public class SchemaManagementImpl implements SchemaManagement { } @Override - public String getIsRelatedToSchema(String isRelatedToType) - throws SchemaNotFoundException { - return getTypeSchemaAsString(isRelatedToType, IsRelatedTo.NAME); + public String getIsRelatedToSchema(String isRelatedToType, + boolean includeSubtypes, boolean includeSchema) + throws SchemaNotFoundException, SchemaException { + return getSchema(isRelatedToType, IsRelatedTo.NAME, includeSubtypes, + includeSchema); } @Override @@ -525,11 +539,5 @@ public class SchemaManagementImpl implements SchemaManagement { throws SchemaException { throw new UnsupportedOperationException("Not Yet implemented"); } - - @Override - public String getIsRelatedToTypes(String isRelatedToType, boolean includeSchema) - throws SchemaNotFoundException, SchemaException { - return getListOfType(isRelatedToType, IsRelatedTo.NAME, includeSchema); - } - + } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/context/MultiContextTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/context/MultiContextTest.java index 4d7c531..292e475 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/context/MultiContextTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/context/MultiContextTest.java @@ -72,7 +72,7 @@ public class MultiContextTest extends ScopedTest { FacetManagement facetManagement = new FacetManagement(); facetManagement.setJSON(Entities.marshal(cpuFacet)); - facetManagement.setEntityType(CPUFacet.NAME); + facetManagement.setElementType(CPUFacet.NAME); String json = facetManagement.create(); logger.debug("Created : {}", json); @@ -187,7 +187,7 @@ public class MultiContextTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(EService.NAME); + resourceManagement.setElementType(EService.NAME); resourceManagement.setJSON(Entities.marshal(eService)); String json = resourceManagement.create(); @@ -238,7 +238,7 @@ public class MultiContextTest extends ScopedTest { hostingNode.attachResource(hosts); resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setElementType(HostingNode.NAME); resourceManagement.setJSON(Entities.marshal(hostingNode)); String hnJson = resourceManagement.create(); 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 ee83dea..63704eb 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java @@ -94,7 +94,7 @@ public class ERManagementTest extends ScopedTest { eService.addFacet(licenseFacet); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(EService.NAME); + resourceManagement.setElementType(EService.NAME); resourceManagement.setJSON(Entities.marshal(eService)); String json = resourceManagement.create(); @@ -128,7 +128,7 @@ public class ERManagementTest extends ScopedTest { cpuFacet.setVendor("AMD"); FacetManagement facetManagement = new FacetManagement(); - facetManagement.setEntityType(CPUFacet.NAME); + facetManagement.setElementType(CPUFacet.NAME); facetManagement.setJSON(Entities.marshal(cpuFacet)); String cpuFacetJson = facetManagement.create(); @@ -235,7 +235,7 @@ public class ERManagementTest extends ScopedTest { eService.addFacet(isIdentifiedBy); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(EService.NAME); + resourceManagement.setElementType(EService.NAME); resourceManagement.setJSON(Entities.marshal(eService)); String json = resourceManagement.create(); @@ -253,7 +253,7 @@ public class ERManagementTest extends ScopedTest { FacetManagement facetManagement = new FacetManagement(); facetManagement.setJSON(Entities.marshal(networkingFacet)); - facetManagement.setEntityType(NetworkingFacet.NAME); + facetManagement.setElementType(NetworkingFacet.NAME); json = facetManagement.create(); logger.debug("Created : {}", json); @@ -282,7 +282,7 @@ public class ERManagementTest extends ScopedTest { hostingNode.attachResource(hosts); resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setElementType(HostingNode.NAME); resourceManagement.setJSON(Entities.marshal(hostingNode)); json = resourceManagement.create(); @@ -321,7 +321,7 @@ public class ERManagementTest extends ScopedTest { Facet shared = hostingNode.getConsistsOf().get(0).getTarget(); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setRelationType(ConsistsOf.NAME); + consistsOfManagement.setElementType(ConsistsOf.NAME); consistsOfManagement.setJSON("{}"); UUID eServiceUUID = eService.getHeader().getUUID(); @@ -354,7 +354,7 @@ public class ERManagementTest extends ScopedTest { @Test public void testCreateResourceAndFacet() throws Exception { ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setElementType(HostingNode.NAME); resourceManagement.setJSON("{}"); String json = resourceManagement.create(); @@ -367,14 +367,14 @@ public class ERManagementTest extends ScopedTest { FacetManagement facetManagement = new FacetManagement(); facetManagement.setJSON(Entities.marshal(cpuFacet)); - facetManagement.setEntityType(CPUFacet.NAME); + facetManagement.setElementType(CPUFacet.NAME); json = facetManagement.create(); logger.debug("Created : {}", json); UUID facetUUID = Utility.getUUIDFromJSONString(json); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setRelationType(ConsistsOf.NAME); + consistsOfManagement.setElementType(ConsistsOf.NAME); consistsOfManagement.setJSON("{}"); json = consistsOfManagement.create(resourceUUID, facetUUID); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java index 350b022..41f125e 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java @@ -85,7 +85,7 @@ public class SmartgearResourcesTest extends ScopedTest { logger.debug("{}", hostingNode); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setElementType(HostingNode.NAME); resourceManagement.setJSON(HOSTING_NODE); String hnJson = resourceManagement.create(); @@ -116,7 +116,7 @@ public class SmartgearResourcesTest extends ScopedTest { logger.debug("{}", eService); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(EService.NAME); + resourceManagement.setElementType(EService.NAME); resourceManagement.setJSON(ESERVICE); String json = resourceManagement.create(); @@ -219,7 +219,7 @@ public class SmartgearResourcesTest extends ScopedTest { hostingNode.addFacet(hasPersistentMemory); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setElementType(HostingNode.NAME); resourceManagement.setJSON(Entities.marshal(hostingNode)); String json = resourceManagement.create(); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java index 2776258..7d98649 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java @@ -45,7 +45,7 @@ public class SchemaManagementImplTest { @Test public void getEmbeddedTypeSchema() throws Exception{ - String json = new SchemaManagementImpl().getEmbeddedTypeSchema(AccessPolicy.NAME); + String json = new SchemaManagementImpl().getEmbeddedTypeSchema(AccessPolicy.NAME, false, true); logger.trace(json); } @@ -60,10 +60,10 @@ public class SchemaManagementImplTest { @Test public void getFacetSchema() throws Exception{ - String json = new SchemaManagementImpl().getFacetSchema(ContactFacet.NAME); - logger.trace(json); + String json = new SchemaManagementImpl().readFacetSchema(ContactFacet.NAME, false, true); + logger.info(json); TypeDefinition typeDefinition = TypeBinder.deserializeTypeDefinition(json); - logger.trace(typeDefinition.toString()); + logger.info(typeDefinition.toString()); } @Test @@ -84,7 +84,7 @@ public class SchemaManagementImplTest { @Test public void getResourceSchema() throws Exception{ - String json = new SchemaManagementImpl().getResourceSchema(Actor.NAME); + String json = new SchemaManagementImpl().getResourceSchema(Actor.NAME, false, true); logger.trace(json); } @@ -102,10 +102,12 @@ public class SchemaManagementImplTest { public void getList() throws Exception{ logger.debug("\n\n\n"); + boolean includeSubTypes = true; boolean includeSchema = true; + SchemaManagement schemaManagement = new SchemaManagementImpl(); - String list = schemaManagement.getEmbeddedTypes(Embedded.NAME, includeSchema); + String list = schemaManagement.getEmbeddedTypeSchema(Embedded.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", Embedded.NAME, list); ObjectMapper mapper = new ObjectMapper(); @@ -114,24 +116,24 @@ public class SchemaManagementImplTest { - list = schemaManagement.getEntityTypes(Entity.NAME, includeSchema); + list = schemaManagement.readEntitySchema(Entity.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", Entity.NAME, list); - list = schemaManagement.getResourceTypes(Resource.NAME, includeSchema); + list = schemaManagement.getResourceSchema(Resource.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", Resource.NAME, list); - list = schemaManagement.getFacetTypes(Facet.NAME, includeSchema); + list = schemaManagement.readFacetSchema(Facet.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", Facet.NAME, list); - list = schemaManagement.getRelationTypes(Relation.NAME, includeSchema); + list = schemaManagement.getRelationSchema(Relation.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", Relation.NAME, list); - list = schemaManagement.getConsistsOfTypes(ConsistsOf.NAME, includeSchema); + list = schemaManagement.getConsistsOfSchema(ConsistsOf.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", ConsistsOf.NAME, list); - list = schemaManagement.getIsRelatedToTypes(IsRelatedTo.NAME, includeSchema); + list = schemaManagement.getIsRelatedToSchema(IsRelatedTo.NAME, includeSubTypes, includeSchema); logger.debug("{} list : {}", IsRelatedTo.NAME, list); }