From b1112136fa344122ba1523e29baa7dbbf1f5f5b0 Mon Sep 17 00:00:00 2001 From: "luca.frosini" Date: Mon, 19 Dec 2016 13:59:27 +0000 Subject: [PATCH] Refactored EntityManagement git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@141249 82a268e6-3cf1-43bd-a215-b396298e98cf --- .../ermanagement/ERManagement.java | 211 ++++++ .../ermanagement/EmbeddedMangement.java | 78 +++ .../ermanagement/entity/EntityManagement.java | 537 +++++++++++++++ .../ermanagement/entity/FacetManagement.java | 60 ++ .../entity/ResourceManagement.java | 198 ++++++ .../relation/ConsistsOfManagement.java | 24 + .../relation/IsRelatedToManagement.java | 24 + .../relation/RelationManagement.java | 639 ++++++++++++++++++ .../resourceregistry/resources/Access.java | 19 +- .../resources/ContextManager.java | 4 +- .../resources/EntityManager.java | 71 +- .../ResourceRegistryExceptionMapper.java | 7 +- .../resources/impl/ContextManagementImpl.java | 5 +- .../resources/impl/SchemaManagementImpl.java | 4 +- .../resources/utils/ContextUtility.java | 11 +- .../resources/utils/HeaderUtility.java | 7 + .../resources/utils/Utility.java | 58 +- .../resourceregistry/ScopedTest.java | 90 +++ .../facet/FacetCreationTest.java | 49 -- .../impl/ContextManagementImplTest.java | 82 +-- .../resources/impl/ERManagementTest.java | 409 +++++++++++ .../resources/impl/MultiContextTest.java | 173 ++++- .../resources/impl/QueryImplTest.java | 5 +- .../impl/ReferentialIntegrityTest.java | 33 - .../impl/SchemaManagementImplTest.java | 2 +- .../impl/SmartgearResourcesTest.java | 52 +- .../resources/old}/EntityManagementImpl.java | 5 +- .../EntityManagementImplTest.java | 2 +- 28 files changed, 2604 insertions(+), 255 deletions(-) create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/ERManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/EmbeddedMangement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/EntityManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/FacetManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/ResourceManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/ConsistsOfManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/IsRelatedToManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/RelationManagement.java create mode 100644 src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java delete mode 100644 src/test/java/org/gcube/informationsystem/resourceregistry/facet/FacetCreationTest.java create mode 100644 src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ERManagementTest.java delete mode 100644 src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ReferentialIntegrityTest.java rename src/{main/java/org/gcube/informationsystem/resourceregistry/resources/impl => test/java/org/gcube/informationsystem/resourceregistry/resources/old}/EntityManagementImpl.java (99%) rename src/test/java/org/gcube/informationsystem/resourceregistry/resources/{impl => old}/EntityManagementImplTest.java (99%) diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/ERManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/ERManagement.java new file mode 100644 index 0000000..810905a --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/ERManagement.java @@ -0,0 +1,211 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.gcube.informationsystem.impl.utils.Entities; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +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.node.JsonNodeType; +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Element; +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.orient.OrientElement; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +public 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 static String getClassProperty(JsonNode jsonNode) { + if (jsonNode.has(Entities.CLASS_PROPERTY)) { + return jsonNode.get(Entities.CLASS_PROPERTY).asText(); + } + return null; + } + + + + public static Object getObjectFromElement(JsonNode value) + throws ResourceRegistryException { + JsonNodeType jsonNodeType = value.getNodeType(); + + switch (jsonNodeType) { + case OBJECT: + return EmbeddedMangement.getEmbeddedType(value); + + case ARRAY: + List array = new ArrayList<>(); + Iterator arrayElement = value.elements(); + while (arrayElement.hasNext()) { + JsonNode arrayNode = arrayElement.next(); + Object objectNode = getObjectFromElement(arrayNode); + if (objectNode != null) { + array.add(objectNode); + } + } + return array; + + case BINARY: + break; + + case BOOLEAN: + return value.asBoolean(); + + case NULL: + break; + + case NUMBER: + if (value.isDouble() || value.isFloat()) { + return value.asDouble(); + } + if (value.isBigInteger() || value.isShort() || value.isInt()) { + return value.asInt(); + } + + if (value.isLong()) { + return value.asLong(); + } + break; + + case STRING: + return value.asText(); + + case MISSING: + break; + + case POJO: + break; + + default: + break; + } + + return null; + } + + public static Map getPropertyMap(JsonNode jsonNode, + Set ignoreKeys, Set ignoreStartWith) + throws JsonProcessingException, IOException { + + Map map = new HashMap<>(); + + if (ignoreKeys == null) { + ignoreKeys = new HashSet<>(); + } + + if (ignoreStartWith == null) { + ignoreStartWith = new HashSet<>(); + } + + Iterator> fields = jsonNode.fields(); + + OUTER_WHILE: while (fields.hasNext()) { + Entry entry = fields.next(); + + String key = entry.getKey(); + + if (ignoreKeys.contains(key)) { + continue; + } + + for (String prefix : ignoreStartWith) { + if (key.startsWith(prefix)) { + continue OUTER_WHILE; + } + } + + JsonNode value = entry.getValue(); + Object object = null; + try { + object = getObjectFromElement(value); + if (object != null) { + map.put(key, object); + } + } catch (ResourceRegistryException e) { + logger.warn("An invalidy property has been provided. It will be ignored."); + } + + } + + return map; + } + + 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) { + throw new ResourceRegistryException(e); + } + } else { + String error = String.format("Error while updating {} properties", + element.toString()); + throw new ResourceRegistryException(error); + } + + oldKeys.removeAll(properties.keySet()); + + for (String key : properties.keySet()) { + try { + element.setProperty(key, properties.get(key)); + } catch (Exception e) { + String error = String.format( + "Error while setting property %s : %s", key, properties + .get(key).toString()); + logger.error(error); + throw new ResourceRegistryException(error, e); + } + } + + OUTER_FOR: for (String key : oldKeys) { + + if (ignoreKeys.contains(key)) { + continue; + } + + for (String prefix : ignoreStartWithKeys) { + if (key.startsWith(prefix)) { + continue OUTER_FOR; + } + } + + element.removeProperty(key); + } + + ((OrientElement) element).save(); + + return element; + } + + + + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/EmbeddedMangement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/EmbeddedMangement.java new file mode 100644 index 0000000..0f4f1e6 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/EmbeddedMangement.java @@ -0,0 +1,78 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement; + +import java.util.HashSet; +import java.util.Set; + +import org.gcube.informationsystem.impl.utils.Entities; +import org.gcube.informationsystem.model.embedded.Embedded; +import org.gcube.informationsystem.model.embedded.Header; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; +import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl; +import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.orientechnologies.orient.core.record.impl.ODocument; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +public class EmbeddedMangement { + + private static Logger logger = LoggerFactory + .getLogger(EmbeddedMangement.class); + + public static final Set EMBEDDED_IGNORE_KEYS; + public static final Set EMBEDDED_IGNORE_START_WITH_KEYS; + + public static final String AT = "@"; + public static final String UNDERSCORE = "_"; + + static { + EMBEDDED_IGNORE_KEYS = new HashSet(); + + EMBEDDED_IGNORE_START_WITH_KEYS = new HashSet(); + EMBEDDED_IGNORE_START_WITH_KEYS.add(AT); + EMBEDDED_IGNORE_START_WITH_KEYS.add(UNDERSCORE); + + } + + + public static ODocument getEmbeddedType(JsonNode jsonNode) + throws ResourceRegistryException { + if (jsonNode.has(Entities.CLASS_PROPERTY)) { + // Complex type + String type = ERManagement.getClassProperty(jsonNode); + + try { + SchemaManagementImpl.getTypeSchema(type, Embedded.NAME); + } catch (SchemaNotFoundException e) { + throw e; + } + + Header header = null; + try { + header = HeaderUtility.getHeader(jsonNode, false); + + } catch (Exception e) { + logger.warn("An invalid Header has been provided. Anyway embedded object cannot have an Header."); + throw new ResourceRegistryException("An embedded object cannot have an Header"); + } + + if (header != null) { + throw new ResourceRegistryException("An embedded object cannot have an Header"); + } + + ODocument oDocument = new ODocument(type); + return oDocument.fromJSON(jsonNode.toString()); + + } + return null; + } +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/EntityManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/EntityManagement.java new file mode 100644 index 0000000..903b1ed --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/EntityManagement.java @@ -0,0 +1,537 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement.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; +import org.gcube.informationsystem.model.entity.Resource; +import org.gcube.informationsystem.model.relation.ConsistsOf; +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.SecurityContextMapper; +import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.RelationManagement; +import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl; +import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility; +import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility; +import org.gcube.informationsystem.resourceregistry.resources.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; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; +import com.tinkerpop.blueprints.impls.orient.OrientVertex; +import com.tinkerpop.blueprints.impls.orient.OrientVertexType; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public abstract class EntityManagement { + + 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 EntityManagement(Class entityClass) { + this.ignoreKeys = new HashSet(); + 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 + .toLowerCase()); + this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX + .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)) { + this.baseType = Resource.NAME; + } else { + this.baseType = Entity.NAME; + } + } + + protected EntityManagement(Class entityClass, OrientGraph orientGraph) { + this(entityClass); + 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); + + try { + + vertex = orientGraph.addVertex("class:" + entityType); + + try { + + Vertex v = getVertex(); + if (v != null) { + String error = String.format( + "A %s with UUID %s already exist", entityType, + uuid.toString()); + throw new EntityAlreadyPresentException(error); + } + + } catch (EntityAlreadyPresentException e) { + throw e; + } catch (Exception e) { + // no header or no header with uuid is provided and it is fine + } + + Header entityHeader = HeaderUtility.getHeader(jsonNode, true); + if (entityHeader != null) { + vertex.setProperty(Entity.HEADER_PROPERTY, entityHeader); + } else { + entityHeader = HeaderUtility.addHeader(vertex, null); + } + + if (Resource.class.isAssignableFrom(entityClass)) { + // Facet and relation are created in calling method + } else { + ERManagement.updateProperties(vertex, jsonNode, ignoreKeys, + ignoreStartWithKeys); + } + + ContextUtility.addToActualContext(orientGraph, vertex); + + ((OrientVertex) vertex).save(); + + logger.info("Created {} is {}", Vertex.class.getSimpleName(), + Utility.toJsonString((OrientVertex) vertex, true)); + + return vertex; + } 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 + + " 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; + + + public boolean reallyAddToContext() throws ContextException, ResourceRegistryException { + getVertex(); + + ContextUtility.addToActualContext(orientGraph, vertex); + + Iterable edges = vertex.getEdges(Direction.OUT, ConsistsOf.NAME); + + /* + * Use this when the add integrity directive are inserted + * Iterable edges = vertex.getEdges(Direction.OUT); + * + */ + for (Edge edge : edges) { + @SuppressWarnings("rawtypes") + RelationManagement relationManagement = RelationManagement.getRelationManagement(orientGraph, edge); + relationManagement.reallyAddToContext(); + } + + return true; + } + + public boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException { + throw new UnsupportedOperationException(); + } + + @SuppressWarnings("rawtypes") + public static EntityManagement getEntityManagement(OrientGraph orientGraph, Vertex vertex) throws ResourceRegistryException{ + OrientVertexType orientVertexType = ((OrientVertex) vertex).getType(); + EntityManagement entityManagement = null; + if (orientVertexType.isSubClassOf(Resource.NAME)) { + entityManagement = new ResourceManagement(orientGraph); + } else if (orientVertexType.isSubClassOf(Facet.NAME)) { + entityManagement = new FacetManagement(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.", vertex, + Resource.NAME, Facet.NAME); + throw new ResourceRegistryException(error); + } + entityManagement.setVertex(vertex); + return entityManagement; + } + + + public String create() throws EntityAlreadyPresentException, + ResourceRegistryException { + + try { + if (orientGraph == null) { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.WRITER); + } + + reallyCreate(); + + 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 String read() throws EntityNotFoundException, + ResourceRegistryException { + try { + if (orientGraph == null) { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.READER); + } + + getVertex(); + + return serialize(); + } catch (ResourceRegistryException fnfe) { + throw fnfe; + } catch (Exception e) { + throw new ResourceRegistryException(e.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public String update() throws EntityNotFoundException, + ResourceRegistryException { + try { + if (orientGraph == null) { + 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("Error Updating " + baseType, + e.getCause()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + + } + + public boolean delete() throws FacetNotFoundException, + ResourceRegistryException { + logger.debug("Going to delete {} with UUID {}", baseType, uuid); + + try { + if (orientGraph == null) { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.WRITER); + } + + boolean deleted = reallyDelete(); + + orientGraph.commit(); + + logger.info("{} with UUID {} was successfully deleted.", baseType, + uuid); + + return deleted; + + } catch (FacetNotFoundException fnfe) { + logger.error("Unable to delete {} with UUID {}", baseType, uuid, + fnfe); + if (orientGraph != null) { + orientGraph.rollback(); + } + throw fnfe; + } 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 { + if (orientGraph == null) { + 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.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public boolean removeFromContext() throws ContextException { + logger.debug("Going to remove {} with UUID {} from actual Context", + baseType, uuid); + + try { + if (orientGraph == null) { + 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.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/FacetManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/FacetManagement.java new file mode 100644 index 0000000..dce6aaf --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/FacetManagement.java @@ -0,0 +1,60 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement.entity; + +import org.codehaus.jettison.json.JSONObject; +import org.gcube.informationsystem.model.entity.Facet; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; +import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement; +import org.gcube.informationsystem.resourceregistry.resources.utils.Utility; + +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; +import com.tinkerpop.blueprints.impls.orient.OrientVertex; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +public class FacetManagement extends EntityManagement { + + public FacetManagement() { + super(Facet.class); + } + + public FacetManagement(OrientGraph orientGraph) { + super(Facet.class, orientGraph); + } + + @Override + public String serialize() throws ResourceRegistryException { + return Utility.toJsonString((OrientVertex) vertex, true); + } + + @Override + public JSONObject serializeAsJson() throws ResourceRegistryException { + return Utility.toJsonObject((OrientVertex) vertex, true); + } + + public Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { + return createVertex(); + } + + @Override + public Vertex reallyUpdate() throws ResourceRegistryException { + Vertex facet = getVertex(); + facet = (Vertex) ERManagement.updateProperties(facet, jsonNode, ignoreKeys, ignoreStartWithKeys); + ((OrientVertex) facet).save(); + return facet; + } + + public boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException { + Vertex facet = getVertex(); + facet.remove(); + return true; + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/ResourceManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/ResourceManagement.java new file mode 100644 index 0000000..8d2d276 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/entity/ResourceManagement.java @@ -0,0 +1,198 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement.entity; + +import java.util.Iterator; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.gcube.informationsystem.model.entity.Resource; +import org.gcube.informationsystem.model.relation.ConsistsOf; +import org.gcube.informationsystem.model.relation.IsRelatedTo; +import org.gcube.informationsystem.resourceregistry.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.ermanagement.ERManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.ConsistsOfManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.IsRelatedToManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.RelationManagement; +import org.gcube.informationsystem.resourceregistry.resources.utils.Utility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.tinkerpop.blueprints.Direction; +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.orient.OrientEdge; +import com.tinkerpop.blueprints.impls.orient.OrientEdgeType; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; +import com.tinkerpop.blueprints.impls.orient.OrientVertex; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public class ResourceManagement extends EntityManagement { + + private static Logger logger = LoggerFactory + .getLogger(ResourceManagement.class); + + public ResourceManagement() { + super(Resource.class); + } + + public ResourceManagement(OrientGraph orientGraph) { + super(Resource.class, orientGraph); + } + + private static JSONObject marshallResource(OrientGraph orientGraph, + Vertex vertex) throws ResourceRegistryException { + JSONObject jsonObject = Utility.toJsonObject((OrientVertex) vertex, + true); + + JSONArray consistsOfArray = new JSONArray(); + /* + * JSONArray isRelatedToArray = new JSONArray(); + * Iterable edges = vertex.getEdges(Direction.OUT); + */ + + Iterable edges = vertex.getEdges(Direction.OUT, ConsistsOf.NAME); + + for (Edge edge : edges) { + + @SuppressWarnings("rawtypes") + RelationManagement relationManagement = RelationManagement.getRelationManagement(orientGraph, edge); + JSONObject relationJsonObject = relationManagement.serializeAsJson(); + consistsOfArray.put(relationJsonObject); + + /* + * else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ + * isRelatedToArray.put(jsonObjectEdge); } + */ + + } + + try { + jsonObject.put(ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME), + consistsOfArray); + } catch (JSONException e) { + throw new ResourceRegistryException(e); + } + /* + * jsonObject.put(lowerCaseFirstCharacter(IsRelatedTo.NAME), + * isRelatedToArray); + */ + + return jsonObject; + } + + @Override + public String serialize() throws ResourceRegistryException { + return marshallResource(orientGraph, getVertex()).toString(); + } + + @Override + public JSONObject serializeAsJson() throws ResourceRegistryException { + return marshallResource(orientGraph, getVertex()); + } + + @Override + public Vertex reallyCreate() throws EntityAlreadyPresentException, + ResourceRegistryException { + createVertex(); + + String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME); + if (jsonNode.has(property)) { + JsonNode jsonNodeArray = jsonNode.get(property); + for (JsonNode consistOfJsonNode : jsonNodeArray) { + ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); + com.setJSON(consistOfJsonNode); + com.reallyCreate(vertex); + } + } + + property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME); + if (jsonNode.has(property)) { + JsonNode jsonNodeArray = jsonNode.get(property); + for (JsonNode relationJsonNode : jsonNodeArray) { + IsRelatedToManagement irtm = new IsRelatedToManagement( + orientGraph); + irtm.setJSON(relationJsonNode); + irtm.reallyCreate(vertex); + } + } + + return vertex; + } + + @Override + public Vertex reallyUpdate() throws ResourceRegistryException { + + getVertex(); + + String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME); + if (jsonNode.has(property)) { + JsonNode jsonNodeArray = jsonNode.get(property); + for (JsonNode relationJsonNode : jsonNodeArray) { + ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); + com.setJSON(relationJsonNode); + com.reallyUpdate(); + } + } + + property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME); + if (jsonNode.has(property)) { + JsonNode jsonNodeArray = jsonNode.get(property); + for (JsonNode relationJsonNode : jsonNodeArray) { + IsRelatedToManagement irtm = new IsRelatedToManagement( + orientGraph); + irtm.setJSON(relationJsonNode); + irtm.reallyUpdate(); + } + } + + ((OrientVertex) vertex).save(); + + return vertex; + } + + @Override + public boolean reallyDelete() throws ResourceNotFoundException, + ResourceRegistryException { + //internalDeleteResource(orientGraph, uuid, null); + + getVertex(); + + Iterable iterable = vertex.getEdges(Direction.OUT); + Iterator iterator = iterable.iterator(); + while(iterator.hasNext()){ + Edge edge = iterator.next(); + OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); + @SuppressWarnings("rawtypes") + RelationManagement relationManagement = null; + if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ + relationManagement = new IsRelatedToManagement(orientGraph); + }else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)){ + relationManagement = new ConsistsOfManagement(orientGraph); + }else{ + logger.warn("{} is not a {} nor a {}. " + + "This is really strange ad should not occur. " + + "Please Investigate it.", + Utility.toJsonString(edge, true), + IsRelatedTo.NAME, ConsistsOf.NAME); + } + if(relationManagement!=null){ + relationManagement.setEdge(edge); + relationManagement.reallyDelete(); + } + + } + + ((OrientVertex) vertex).remove(); + + return true; + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/ConsistsOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/ConsistsOfManagement.java new file mode 100644 index 0000000..b4c86ec --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/ConsistsOfManagement.java @@ -0,0 +1,24 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement.relation; + +import org.gcube.informationsystem.model.relation.ConsistsOf; + +import com.tinkerpop.blueprints.impls.orient.OrientGraph; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +@SuppressWarnings("rawtypes") +public class ConsistsOfManagement extends RelationManagement { + + public ConsistsOfManagement() { + super(ConsistsOf.class); + } + + public ConsistsOfManagement(OrientGraph orientGraph) { + super(ConsistsOf.class, orientGraph); + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/IsRelatedToManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/IsRelatedToManagement.java new file mode 100644 index 0000000..b916c6d --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/IsRelatedToManagement.java @@ -0,0 +1,24 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement.relation; + +import org.gcube.informationsystem.model.relation.IsRelatedTo; + +import com.tinkerpop.blueprints.impls.orient.OrientGraph; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +@SuppressWarnings("rawtypes") +public class IsRelatedToManagement extends RelationManagement { + + public IsRelatedToManagement() { + super(IsRelatedTo.class); + } + + public IsRelatedToManagement(OrientGraph orientGraph) { + super(IsRelatedTo.class, orientGraph); + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/RelationManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/RelationManagement.java new file mode 100644 index 0000000..0dd1096 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ermanagement/relation/RelationManagement.java @@ -0,0 +1,639 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.ermanagement.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.JSONObject; +import org.gcube.informationsystem.model.embedded.Header; +import org.gcube.informationsystem.model.embedded.RelationProperty; +import org.gcube.informationsystem.model.embedded.RelationProperty.ReferentialIntegrity; +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; +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.SecurityContextMapper; +import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.EntityManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement; +import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl; +import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility; +import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility; +import org.gcube.informationsystem.resourceregistry.resources.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; +import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; +import com.tinkerpop.blueprints.impls.orient.OrientEdge; +import com.tinkerpop.blueprints.impls.orient.OrientEdgeType; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +@SuppressWarnings("rawtypes") +public abstract class RelationManagement { + + 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 RelationManagement(Class relationClass) { + this.ignoreKeys = new HashSet(); + this.ignoreKeys.add(Relation.HEADER_PROPERTY); + this.ignoreKeys.add(Relation.TARGET_PROPERTY); + this.ignoreKeys.add(Relation.SOURCE_PROPERTY); + this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toLowerCase()); + this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toLowerCase()); + 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; + } else if (IsRelatedTo.class.isAssignableFrom(relationClass)) { + this.baseType = IsRelatedTo.NAME; + this.targetEntityClass = Resource.class; + } else { + this.baseType = Relation.NAME; + this.targetEntityClass = Resource.class; + } + } + + protected RelationManagement(Class relationClass, OrientGraph orientGraph) { + this(relationClass); + 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 e; + } catch (Exception e) { + throw new ResourceRegistryException(e); + } + + } + + public String serialize() throws ResourceRegistryException { + return Utility.toJsonString((OrientEdge) getEdge(), false); + } + + public JSONObject serializeAsJson() throws ResourceRegistryException { + return Utility.toJsonObject((OrientEdge) getEdge(), false); + } + + public Edge reallyCreate(UUID sourceUUID, UUID targetUUID) + throws ResourceRegistryException { + ResourceManagement srmSource = new ResourceManagement(orientGraph); + srmSource.setUUID(sourceUUID); + Vertex source = srmSource.getVertex(); + + Vertex target = null; + if (ConsistsOf.class.isAssignableFrom(relationClass)) { + FacetManagement fmTarget = new FacetManagement(orientGraph); + fmTarget.setUUID(targetUUID); + target = fmTarget.getVertex(); + } else if (IsRelatedTo.class.isAssignableFrom(relationClass)) { + ResourceManagement srmTarget = new ResourceManagement(orientGraph); + srmTarget.setUUID(targetUUID); + target = srmTarget.getVertex(); + } + + return reallyCreate(source, target); + + } + + protected Edge reallyCreate(Vertex source, Vertex target) + throws ResourceRegistryException { + // TODO Check the relation compatibility between source and target + logger.trace("Creating {} ({}) beetween {} -> {}", + Relation.class.getSimpleName(), relationType, + Utility.toJsonString(source, true), + Utility.toJsonString(target, true)); + + edge = orientGraph.addEdge(null, source, target, relationType); + + ERManagement.updateProperties(edge, jsonNode, ignoreKeys, + ignoreStartWithKeys); + + HeaderUtility.addHeader(edge, null); + ContextUtility.addToActualContext(orientGraph, edge); + + ((OrientEdge) edge).save(); + + logger.info("{} successfully created", relationType); + + return edge; + } + + public Edge reallyCreate(Vertex source) throws ResourceRegistryException { + Vertex target = null; + EntityManagement entityManagement = getEntityManagement(); + + if (!jsonNode.has(Relation.TARGET_PROPERTY)) { + throw new ResourceRegistryException( + "Error while creating relation. No target definition found"); + } + entityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY)); + try { + target = entityManagement.getVertex(); + } catch (Exception e) { + target = entityManagement.reallyCreate(); + } + return reallyCreate(source, target); + } + + public Edge reallyCreate(UUID sourceUUID) throws ResourceRegistryException { + ResourceManagement srmSource = new ResourceManagement(orientGraph); + srmSource.setUUID(sourceUUID); + Vertex source = srmSource.getVertex(); + return reallyCreate(source); + } + + public Edge reallyUpdate() throws ResourceRegistryException { + + logger.debug("Trying to update {} : {}", relationClass.getSimpleName(), + jsonNode); + + Edge edge = getEdge(); + ERManagement.updateProperties(edge, jsonNode, ignoreKeys, + ignoreStartWithKeys); + + if (ConsistsOf.class.isAssignableFrom(relationClass)) { + JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); + if (target != null) { + FacetManagement fm = new FacetManagement(orientGraph); + fm.setJSON(target); + fm.reallyUpdate(); + } + } + + logger.info("{} {} successfully updated", relationType, jsonNode); + + return edge; + + } + + public boolean reallyAddToContext() throws ContextException, + ResourceRegistryException { + getEdge(); + + // TODO check add integrity directive + + ContextUtility.addToActualContext(orientGraph, edge); + + Vertex vertex = edge.getVertex(Direction.IN); + EntityManagement entityManagement = EntityManagement + .getEntityManagement(orientGraph, vertex); + entityManagement.reallyAddToContext(); + + return true; + } + + public boolean reallyRemoveFromContext() throws ContextException, + ResourceRegistryException { + throw new UnsupportedOperationException(); + } + + protected EntityManagement getEntityManagement() + throws ResourceRegistryException { + EntityManagement entityManagement; + if (ConsistsOf.class.isAssignableFrom(relationClass)) { + entityManagement = new FacetManagement(orientGraph); + } else if (IsRelatedTo.class.isAssignableFrom(relationClass)) { + 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, + IsRelatedTo.NAME); + throw new ResourceRegistryException(error); + } + return entityManagement; + } + + public static RelationManagement getRelationManagement( + OrientGraph orientGraph, Edge edge) + throws ResourceRegistryException { + OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); + RelationManagement relationManagement = null; + if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { + relationManagement = new ConsistsOfManagement(orientGraph); + } else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { + relationManagement = new IsRelatedToManagement(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.", edge, ConsistsOf.NAME, + IsRelatedTo.NAME); + throw new ResourceRegistryException(error); + } + relationManagement.setEdge(edge); + return relationManagement; + } + + protected boolean deleteTargetVertex(Vertex target) + throws ResourceRegistryException { + EntityManagement entityManagement = EntityManagement + .getEntityManagement(orientGraph, target); + if (entityManagement != null) { + entityManagement.reallyDelete(); + return true; + } else { + return false; + } + } + + public boolean reallyDelete() throws RelationNotFoundException, + ResourceRegistryException { + getEdge(); + + ReferentialIntegrity referentialIntegrity = ReferentialIntegrity.onDeleteKeep; + + try { + RelationProperty relationProperty = Utility.getEmbedded( + RelationProperty.class, edge, Relation.RELATION_PROPERTY); + referentialIntegrity = relationProperty.getReferentialIntegrity(); + } catch (Exception e) { + logger.warn("Error while getting {} from {}. Assuming {}. " + + "This is really strange ad should not occur. " + + "Please Investigate it.", + RelationProperty.REFERENTIAL_INTEGRITY, + Utility.toJsonString(edge, true), + ReferentialIntegrity.onDeleteKeep); + } + + Vertex target = edge.getVertex(Direction.IN); + edge.remove(); + + switch (referentialIntegrity) { + case onDeleteCascade: + deleteTargetVertex(target); + break; + + case onDeleteCascadeWhenOrphan: + 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, referentialIntegrity); + } else { + deleteTargetVertex(target); + } + break; + + case onDeleteKeep: + break; + + default: + break; + } + + return true; + } + + public String create(UUID sourceUUID, UUID targetUUID) + throws ResourceRegistryException { + try { + if (orientGraph == null) { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.WRITER); + } + + edge = reallyCreate(sourceUUID, targetUUID); + + 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 String read() throws RelationNotFoundException, + ResourceRegistryException { + try { + if (orientGraph == null) { + 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 { + if (orientGraph == null) { + 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 { + if (orientGraph == null) { + orientGraph = ContextUtility + .getActualSecurityContextGraph(PermissionMode.WRITER); + } + + boolean deleted = reallyDelete(); + + orientGraph.commit(); + + logger.info("{} {} with UUID {} successfully removed.", baseType, + uuid); + + return deleted; + + } catch (ResourceRegistryException rre) { + logger.error("Unable to remove {} with UUID.", baseType, uuid); + if (orientGraph != null) { + orientGraph.rollback(); + } + throw rre; + } 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 { + if (orientGraph == null) { + 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.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + + public boolean removeFromContext() throws ContextException { + logger.debug("Going to remove {} with UUID {} from actual Context", + baseType, uuid); + + try { + if (orientGraph == null) { + 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.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } + } + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java index e5cd142..cce49f9 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java @@ -9,7 +9,6 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import org.gcube.informationsystem.resourceregistry.api.EntityManagement; import org.gcube.informationsystem.resourceregistry.api.Query; import org.gcube.informationsystem.resourceregistry.api.SchemaManagement; import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException; @@ -18,7 +17,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet. import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; -import org.gcube.informationsystem.resourceregistry.resources.impl.EntityManagementImpl; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.resources.impl.QueryImpl; import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl; import org.slf4j.Logger; @@ -35,10 +35,6 @@ public class Access { public static final String ID_PATH_PARAM = "id"; public static final String TYPE_PATH_PARAM = "type"; - - protected Query queryManager = new QueryImpl(); - protected EntityManagement entityManager = new EntityManagementImpl(); - protected SchemaManagement schemaManager = new SchemaManagementImpl(); /** * It allows to query Entities and Relations in the current Context.
@@ -68,6 +64,7 @@ public class Access { @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) throws InvalidQueryException { logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query); + Query queryManager = new QueryImpl(); return queryManager.query(query, limit, fetchPlan); } @@ -84,7 +81,9 @@ public class Access { public String getFacet(@PathParam(ID_PATH_PARAM) String facetId) throws FacetNotFoundException, ResourceRegistryException { logger.info("Requested Facet with id {}", facetId); - return entityManager.readFacet(UUID.fromString(facetId)); + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setUUID(UUID.fromString(facetId)); + return facetManagement.read(); } /** @@ -99,6 +98,7 @@ public class Access { 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); } @@ -115,7 +115,9 @@ public class Access { public String getResource(@PathParam(ID_PATH_PARAM) String resourceId) throws ResourceNotFoundException, ResourceRegistryException { logger.info("Requested Resource with id {}", resourceId); - return entityManager.readResource(UUID.fromString(resourceId)); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(UUID.fromString(resourceId)); + return resourceManagement.read(); } /** @@ -130,6 +132,7 @@ public class Access { 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); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java index 69a3f93..78eaf9a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java @@ -15,7 +15,7 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.gcube.informationsystem.resourceregistry.api.ContextManagement; -import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; @@ -54,7 +54,7 @@ public class ContextManager { public String create( @QueryParam(ContextPath.PARENT_CONTEXT_ID_PARAM) String parentUUID, @QueryParam(ContextPath.NAME_PARAM) String name) - throws ContextCreationException, InternalException { + throws ContextCreationException, ResourceRegistryException { logger.trace("requested to create context with name : {} ", name); return contextManager.create(UUID.fromString(parentUUID), name); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java index 5ca23db..a62711f 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java @@ -15,14 +15,16 @@ import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.Resource; import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.IsRelatedTo; -import org.gcube.informationsystem.resourceregistry.api.EntityManagement; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; 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.resources.impl.EntityManagementImpl; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.ConsistsOfManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.IsRelatedToManagement; import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,8 +44,6 @@ public class EntityManager { public static final String SOURCE_ID_PATH_PARAM = "sourceId"; public static final String TARGET_ID_PATH_PARAM = "targetId"; - protected EntityManagement entityManager = new EntityManagementImpl(); - /* Facets Methods */ /** * e.g. PUT /resource-registry/entity/facet/ContactFacet @@ -64,7 +64,10 @@ public class EntityManager { String json) throws EntityException, ResourceRegistryException { logger.info("requested facet creation for type {} defined by {} ", type, json); - return entityManager.createFacet(type, json); + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setEntityType(type); + facetManagement.setJSON(json); + return facetManagement.create(); } /** @@ -86,7 +89,10 @@ public class EntityManager { public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json) throws FacetNotFoundException, ResourceRegistryException { logger.info("requested facet update for id {} with {}", uuid, json); - return entityManager.updateFacet(UUID.fromString(uuid), json); + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setUUID(UUID.fromString(uuid)); + facetManagement.setJSON(json); + return facetManagement.update(); } /** @@ -103,7 +109,9 @@ public class EntityManager { public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ResourceRegistryException { logger.info("Requested to delete Facet with id {}", uuid); - return entityManager.deleteFacet(UUID.fromString(uuid)); + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setUUID(UUID.fromString(uuid)); + return facetManagement.delete(); } /* Resources Methods */ @@ -128,7 +136,10 @@ public class EntityManager { ResourceRegistryException { logger.info("requested resource creation for type {} with json {}", type, json); - return entityManager.createResource(type, json); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(type); + resourceManagement.setJSON(json); + return resourceManagement.create(); } @POST @@ -139,10 +150,12 @@ public class EntityManager { String json) throws FacetNotFoundException, ResourceRegistryException { logger.info("requested resource update for id {} with {}", uuid, json); - return entityManager.updateResource(UUID.fromString(uuid), json); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(UUID.fromString(uuid)); + resourceManagement.setJSON(json); + return resourceManagement.update(); } - - + /** * e.g. DELETE * /resource-registry/entity/resource/67062c11-9c3a-4906-870d-7df6a43408b0 @@ -157,7 +170,9 @@ public class EntityManager { public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception { logger.info("requested resource deletion for id {}", uuid); - return entityManager.deleteResource(UUID.fromString(uuid)); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(UUID.fromString(uuid)); + return resourceManagement.delete(); } /* Relations Methods */ @@ -193,8 +208,11 @@ public class EntityManager { "requested to attach resource {} to facet {} ({} Type {}) with properties {}", resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(), type, json); - return entityManager.attachFacet(UUID.fromString(resourceUUID), - UUID.fromString(facetUUID), type, json); + ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); + consistsOfManagement.setRelationType(type); + consistsOfManagement.setJSON(json); + return consistsOfManagement.create(UUID.fromString(resourceUUID), + UUID.fromString(facetUUID)); } /** @@ -210,7 +228,9 @@ public class EntityManager { public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException { logger.info("requested to detach {}", consistOfUUID); - return entityManager.detachFacet(UUID.fromString(consistOfUUID)); + ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); + consistsOfManagement.setUUID(UUID.fromString(consistOfUUID)); + return consistsOfManagement.delete(); } /** @@ -245,9 +265,14 @@ public class EntityManager { Resource.NAME, sourceResourceUUID, Resource.NAME, targetResourceUUID, IsRelatedTo.class.getSimpleName(), type, json); - return entityManager.attachResource( + + IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); + isRelatedToManagement.setRelationType(type); + isRelatedToManagement.setJSON(json); + + return isRelatedToManagement.create( UUID.fromString(sourceResourceUUID), - UUID.fromString(targetResourceUUID), type, json); + UUID.fromString(targetResourceUUID)); } /** @@ -263,7 +288,9 @@ public class EntityManager { public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException { logger.info("requested to detach {}", relatedToUUID); - return entityManager.detachResource(UUID.fromString(relatedToUUID)); + IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); + isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID)); + return isRelatedToManagement.delete(); } /** @@ -284,7 +311,9 @@ public class EntityManager { ResourceRegistryException { logger.info("requested to add {} with UUID {} to current context {}", Resource.NAME, uuid, ContextUtility.getCurrentContext()); - return entityManager.addResourceToContext(UUID.fromString(uuid)); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(UUID.fromString(uuid)); + return resourceManagement.addToContext(); } /** @@ -305,7 +334,9 @@ public class EntityManager { ResourceRegistryException { logger.info("requested to add {} with UUID {} to current context {}", Facet.NAME, uuid, ContextUtility.getCurrentContext()); - return entityManager.addFacetToContext(UUID.fromString(uuid)); + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setUUID(UUID.fromString(uuid)); + return facetManagement.addToContext(); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java index 9200971..8670d77 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java @@ -6,8 +6,7 @@ import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; -import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.NotAllowedException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ElementAlreadyPresent; import org.gcube.informationsystem.resourceregistry.api.exceptions.ElementNotFound; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; @@ -25,9 +24,9 @@ public class ResourceRegistryExceptionMapper implements ExceptionMapper keys = new HashSet<>(element.getPropertyKeys()); for (String key : element.getPropertyKeys()) { if (key.startsWith("_")) { @@ -74,15 +82,16 @@ public class Utility { return String.valueOf(element); } } - - public static El getElementByUUID(OrientGraph orientGraph, - String elementType, UUID uuid, Class clz) throws ResourceRegistryException { - if (elementType == null || elementType.compareTo("")==0) { - if(Vertex.class.isAssignableFrom(clz)){ + public static El getElementByUUID( + OrientGraph orientGraph, String elementType, UUID uuid, + Class clz) throws ResourceRegistryException { + + if (elementType == null || elementType.compareTo("") == 0) { + if (Vertex.class.isAssignableFrom(clz)) { elementType = Entity.NAME; } - if(Edge.class.isAssignableFrom(clz)){ + if (Edge.class.isAssignableFrom(clz)) { elementType = Relation.NAME; } } @@ -116,5 +125,30 @@ public class Utility { return element; } + + public static T getEmbedded(Class clz, Element element, String property) + throws ResourceRegistryException { + try { + ODocument oDocument = element.getProperty(property); + T t = Entities.unmarshal(clz, oDocument.toJSON()); + return t; + } catch (Exception e) { + String error = String.format("Error while getting %s from %s", + property, toJsonString(element, true)); + throw new ResourceRegistryException(error, e); + } + } + + public static UUID getUUID(Element element) + throws ResourceRegistryException { + /* + * ODocument header = element.getProperty(Entity.HEADER_PROPERTY); + * String contextID = header.field(Header.UUID_PROPERTY); return + * UUID.fromString(contextID); + */ + Header header = HeaderUtility.getHeader(element); + return header.getUUID(); + } + } \ No newline at end of file diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java new file mode 100644 index 0000000..b90feae --- /dev/null +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java @@ -0,0 +1,90 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.gcube.common.authorization.client.Constants; +import org.gcube.common.authorization.client.exceptions.ObjectNotFound; +import org.gcube.common.authorization.library.AuthorizationEntry; +import org.gcube.common.authorization.library.provider.SecurityTokenProvider; +import org.gcube.common.scope.api.ScopeProvider; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +public class ScopedTest { + + private static final Logger logger = LoggerFactory.getLogger(ScopedTest.class); + + protected static final String PROPERTIES_FILENAME = "token.properties"; + + private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT"; + public static final String GCUBE_DEVNEXT; + + private static final String GCUBE_DEVNEXT_NEXTNEXT_VARNAME = "GCUBE_DEVNEXT_NEXTNEXT"; + public static final String GCUBE_DEVNEXT_NEXTNEXT; + + public static final String GCUBE_DEVSEC_VARNAME = "GCUBE_DEVSEC"; + public static final String GCUBE_DEVSEC; + + public static final String GCUBE_DEVSEC_DEVVRE_VARNAME = "GCUBE_DEVSEC_DEVVRE"; + public static final String GCUBE_DEVSEC_DEVVRE; + + public static final String DEFAULT_TEST_SCOPE; + public static final String ALTERNATIVE_TEST_SCOPE; + + static { + Properties properties = new Properties(); + InputStream input = ScopedTest.class.getClassLoader().getResourceAsStream(PROPERTIES_FILENAME); + + try { + // load the properties file + properties.load(input); + } catch (IOException e) { + throw new RuntimeException(e); + } + + GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME); + GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME); + + GCUBE_DEVSEC = properties.getProperty(GCUBE_DEVSEC_VARNAME); + GCUBE_DEVSEC_DEVVRE = properties.getProperty(GCUBE_DEVSEC_DEVVRE_VARNAME); + + DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT; + ALTERNATIVE_TEST_SCOPE = GCUBE_DEVSEC; + } + + public static String getCurrentScope(String token) throws ObjectNotFound, Exception{ + AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token); + String context = authorizationEntry.getContext(); + logger.info("Context of token {} is {}", token, context); + return context; + } + + + public static void setContext(String token) throws ObjectNotFound, Exception{ + SecurityTokenProvider.instance.set(token); + ScopeProvider.instance.set(getCurrentScope(token)); + } + + @BeforeClass + public static void beforeClass() throws Exception{ + setContext(DEFAULT_TEST_SCOPE); + } + + @AfterClass + public static void afterClass() throws Exception{ + SecurityTokenProvider.instance.reset(); + ScopeProvider.instance.reset(); + } + +} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/facet/FacetCreationTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/facet/FacetCreationTest.java deleted file mode 100644 index 9737176..0000000 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/facet/FacetCreationTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * - */ -package org.gcube.informationsystem.resourceregistry.facet; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl; -import org.gcube.informationsystem.impl.utils.Entities; -import org.gcube.informationsystem.model.entity.facet.AccessPointFacet; -import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; -import org.gcube.informationsystem.resourceregistry.resources.impl.EntityManagementImpl; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Luca Frosini (ISTI - CNR) - * - */ -public class FacetCreationTest { - - private static Logger logger = LoggerFactory - .getLogger(FacetCreationTest.class); - - protected EntityManagementImpl entityManagementImpl; - - public FacetCreationTest() { - entityManagementImpl = new EntityManagementImpl(); - } - - @Test - public void createAccessPointFacet() throws URISyntaxException, ResourceRegistryException, IOException{ - ScopeProvider.instance.set("/gcube/devNext"); - - AccessPointFacet accessPointFacet = new AccessPointFacetImpl(); - accessPointFacet.setEndpoint(new URI("http://localhost")); - accessPointFacet.setEntryName("port1"); - - String json = entityManagementImpl.createFacet(AccessPointFacet.NAME, Entities.marshal(accessPointFacet)); - logger.debug("Created : {}", json); - accessPointFacet = Entities.unmarshal(AccessPointFacet.class, json); - logger.debug("Unmarshalled {} {}", AccessPointFacet.NAME, accessPointFacet); - - } -} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java index 5c0c3bb..bad3271 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java @@ -3,12 +3,11 @@ */ package org.gcube.informationsystem.resourceregistry.resources.impl; -import java.io.IOException; import java.util.UUID; import org.gcube.informationsystem.impl.utils.Entities; import org.gcube.informationsystem.model.entity.Context; -import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; @@ -17,9 +16,6 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; - /** * @author Luca Frosini (ISTI - CNR) * @@ -31,17 +27,6 @@ public class ContextManagementImplTest { protected ContextManagementImpl contextManagementImpl; - /* - * private static final String VALID_CHARACTER = - * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private - * static final SecureRandom SECURE_RANDOM = new SecureRandom(); - * - * private String randomString(int lenght) { StringBuilder sb = new - * StringBuilder(lenght); for (int i = 0; i < lenght; i++) { - * sb.append(VALID_CHARACTER.charAt(SECURE_RANDOM - * .nextInt(VALID_CHARACTER.length()))); } return sb.toString(); } - */ - public ContextManagementImplTest() { contextManagementImpl = new ContextManagementImpl(); } @@ -51,7 +36,7 @@ public class ContextManagementImplTest { public static final String CTX_NAME_C = "C"; protected void invalidCreation(UUID parentUUID, String name) - throws InternalException { + throws ResourceRegistryException { try { contextManagementImpl.create(parentUUID, name); throw new RuntimeException("The context " + name + " with parent " @@ -115,9 +100,7 @@ public class ContextManagementImplTest { } @Test - public void simpleTest() throws ContextNotFoundException, ContextException, - InternalException, JsonParseException, JsonMappingException, - IOException { + public void simpleTest() throws Exception { String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A); Context createdContexA1 = Entities.unmarshal(Context.class, contextJsonA1); @@ -195,28 +178,24 @@ public class ContextManagementImplTest { logger.debug("The DB should be now clean"); } - + @Test - public void createContext() throws ContextNotFoundException, - ContextException, InternalException, JsonParseException, - JsonMappingException, IOException { + public void createContext() throws Exception { String name = "test"; - + String testJson = contextManagementImpl.create(null, name); Context testContext = Entities.unmarshal(Context.class, testJson); - Assert.assertTrue(testContext.getName().compareTo(name)==0); + Assert.assertTrue(testContext.getName().compareTo(name) == 0); UUID testUUID = testContext.getHeader().getUUID(); logger.trace("/test : {}", testUUID); - + boolean deleted = contextManagementImpl.delete(testUUID); Assert.assertTrue(deleted); logger.debug("The DB should be now clean"); } - - @Test - public void createDevContext() throws ContextNotFoundException, - ContextException, InternalException, JsonParseException, - JsonMappingException, IOException { + + // @Test + public void createDevContext() throws Exception { String gcubeJson = contextManagementImpl.create(null, "gcube"); Context gcubeContext = Entities.unmarshal(Context.class, gcubeJson); UUID gcube = gcubeContext.getHeader().getUUID(); @@ -239,7 +218,8 @@ public class ContextManagementImplTest { logger.trace("/gcube/devNext : {}", devNextJson); String NextNextJson = contextManagementImpl.create(devNext, "NextNext"); - Context NextNextContex = Entities.unmarshal(Context.class, NextNextJson); + Context NextNextContex = Entities + .unmarshal(Context.class, NextNextJson); @SuppressWarnings("unused") UUID NextNext = NextNextContex.getHeader().getUUID(); logger.trace("/gcube/devNext/NextNext : {}", NextNextJson); @@ -252,30 +232,22 @@ public class ContextManagementImplTest { * contextManagementImpl.delete(gcube); */ - //logger.debug("The DB should be now clean"); + // logger.debug("The DB should be now clean"); } - //@Test - public void removeContext() throws ContextNotFoundException, - ContextException, InternalException { + // @Test + public void removeContext() throws Exception { /* - contextManagementImpl.delete(UUID - .fromString("")); - contextManagementImpl.delete(UUID - .fromString("")); - contextManagementImpl.delete(UUID - .fromString("")); - contextManagementImpl.delete(UUID - .fromString("")); - contextManagementImpl.delete(UUID - .fromString("")); - */ + * contextManagementImpl.delete(UUID .fromString("")); + * contextManagementImpl.delete(UUID .fromString("")); + * contextManagementImpl.delete(UUID .fromString("")); + * contextManagementImpl.delete(UUID .fromString("")); + * contextManagementImpl.delete(UUID .fromString("")); + */ } @Test - public void readTest() throws ContextNotFoundException, ContextException, - InternalException, JsonParseException, JsonMappingException, - IOException { + public void readTest() throws Exception { String name = "LLL"; String contextJsonA1 = contextManagementImpl.create(null, name); Context createdContexA1 = Entities.unmarshal(Context.class, @@ -296,9 +268,7 @@ public class ContextManagementImplTest { } @Test - public void completeTest() throws ContextNotFoundException, - ContextException, InternalException, JsonParseException, - JsonMappingException, IOException { + public void completeTest() throws Exception { String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A); Context createdContexA1 = Entities.unmarshal(Context.class, contextJsonA1); @@ -458,9 +428,7 @@ public class ContextManagementImplTest { } @Test - public void moveToRootTest() throws ContextNotFoundException, - ContextException, InternalException, JsonParseException, - JsonMappingException, IOException { + public void moveToRootTest() throws Exception { String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A); Context createdContexA1 = Entities.unmarshal(Context.class, contextJsonA1); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ERManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ERManagementTest.java new file mode 100644 index 0000000..f96d899 --- /dev/null +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ERManagementTest.java @@ -0,0 +1,409 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.resources.impl; + +import java.net.URI; +import java.net.URL; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.gcube.informationsystem.impl.embedded.RelationPropertyImpl; +import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl; +import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl; +import org.gcube.informationsystem.impl.entity.facet.EventFacetImpl; +import org.gcube.informationsystem.impl.entity.facet.LicenseFacetImpl; +import org.gcube.informationsystem.impl.entity.facet.NetworkingFacetImpl; +import org.gcube.informationsystem.impl.entity.facet.ServiceStateFacetImpl; +import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl; +import org.gcube.informationsystem.impl.entity.resource.EServiceImpl; +import org.gcube.informationsystem.impl.entity.resource.HostingNodeImpl; +import org.gcube.informationsystem.impl.relation.IsIdentifiedByImpl; +import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl; +import org.gcube.informationsystem.impl.utils.Entities; +import org.gcube.informationsystem.impl.utils.Utility; +import org.gcube.informationsystem.model.embedded.RelationProperty; +import org.gcube.informationsystem.model.embedded.RelationProperty.ReferentialIntegrity; +import org.gcube.informationsystem.model.entity.Facet; +import org.gcube.informationsystem.model.entity.Resource; +import org.gcube.informationsystem.model.entity.facet.AccessPointFacet; +import org.gcube.informationsystem.model.entity.facet.CPUFacet; +import org.gcube.informationsystem.model.entity.facet.EventFacet; +import org.gcube.informationsystem.model.entity.facet.LicenseFacet; +import org.gcube.informationsystem.model.entity.facet.NetworkingFacet; +import org.gcube.informationsystem.model.entity.facet.ServiceStateFacet; +import org.gcube.informationsystem.model.entity.facet.SoftwareFacet; +import org.gcube.informationsystem.model.entity.resource.EService; +import org.gcube.informationsystem.model.entity.resource.HostingNode; +import org.gcube.informationsystem.model.relation.ConsistsOf; +import org.gcube.informationsystem.model.relation.IsIdentifiedBy; +import org.gcube.informationsystem.model.relation.Relation; +import org.gcube.informationsystem.model.relation.isrelatedto.Hosts; +import org.gcube.informationsystem.resourceregistry.ScopedTest; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.relation.ConsistsOfManagement; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Luca Frosini (ISTI - CNR) + * + */ +public class ERManagementTest extends ScopedTest { + + private static Logger logger = LoggerFactory + .getLogger(ERManagementTest.class); + + @Test + public void testCreateEService() throws Exception { + EService eService = new EServiceImpl(); + + SoftwareFacet softwareFacet = new SoftwareFacetImpl(); + softwareFacet.setGroup("InformationSystem"); + softwareFacet.setName("resource-registry"); + softwareFacet.setVersion("1.1.0"); + IsIdentifiedBy isIdentifiedBy = new IsIdentifiedByImpl( + eService, softwareFacet, null); + eService.addFacet(isIdentifiedBy); + + AccessPointFacet accessPointFacet = new AccessPointFacetImpl(); + accessPointFacet.setEndpoint(new URI("http://localhost")); + accessPointFacet.setEntryName("port1"); + eService.addFacet(accessPointFacet); + + EventFacet eventFacet = new EventFacetImpl(); + eventFacet.setDate(Calendar.getInstance().getTime()); + eventFacet.setValue("Created"); + eService.addFacet(eventFacet); + + ServiceStateFacet serviceStateFacet = new ServiceStateFacetImpl(); + serviceStateFacet.setValue("ready"); + eService.addFacet(serviceStateFacet); + + LicenseFacet licenseFacet = new LicenseFacetImpl(); + licenseFacet.setName("EUPL"); + licenseFacet + .setTextURL(new URL( + "https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11")); + eService.addFacet(licenseFacet); + + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(EService.NAME); + resourceManagement.setJSON(Entities.marshal(eService)); + + String json = resourceManagement.create(); + logger.debug("Created : {}", json); + eService = Entities.unmarshal(EService.class, json); + logger.debug("Unmarshalled {} {}", EService.NAME, eService); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(eService.getHeader().getUUID()); + + boolean deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + } + + //@Test + public void testDeleteResource() throws Exception { + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(UUID + .fromString("64635295-7ced-4931-a55f-40fc8199b280")); + + boolean deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + + } + + @Test + public void testCreateReadDeleteFacet() throws Exception { + CPUFacet cpuFacet = new CPUFacetImpl(); + cpuFacet.setClockSpeed("1 GHz"); + cpuFacet.setModel("Opteron"); + cpuFacet.setVendor("AMD"); + + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setEntityType(CPUFacet.NAME); + facetManagement.setJSON(Entities.marshal(cpuFacet)); + + String cpuFacetJson = facetManagement.create(); + CPUFacet createdCpuFacet = Entities.unmarshal(CPUFacet.class, + cpuFacetJson); + logger.debug("Created:\nRaw Json : {}\nUnmarshalled : {}", + cpuFacetJson, createdCpuFacet); + + Assert.assertTrue(cpuFacet.getClockSpeed().compareTo( + createdCpuFacet.getClockSpeed()) == 0); + Assert.assertTrue(cpuFacet.getModel().compareTo( + createdCpuFacet.getModel()) == 0); + Assert.assertTrue(cpuFacet.getVendor().compareTo( + createdCpuFacet.getVendor()) == 0); + + UUID uuid = createdCpuFacet.getHeader().getUUID(); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + + String readJson = facetManagement.read(); + CPUFacet readCpuFacet = Entities.unmarshal(CPUFacet.class, readJson); + logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, + readCpuFacet); + Assert.assertTrue(cpuFacet.getClockSpeed().compareTo( + readCpuFacet.getClockSpeed()) == 0); + Assert.assertTrue(cpuFacet.getModel() + .compareTo(readCpuFacet.getModel()) == 0); + Assert.assertTrue(cpuFacet.getVendor().compareTo( + readCpuFacet.getVendor()) == 0); + Assert.assertTrue(uuid.compareTo(readCpuFacet.getHeader().getUUID()) == 0); + + String newVendor = "Intel"; + String newClockSpeed = "2 GHz"; + readCpuFacet.setVendor(newVendor); + readCpuFacet.setClockSpeed(newClockSpeed); + + String additionPropertyKey = "My"; + String additionPropertyValue = "Test"; + readCpuFacet.setAdditionalProperty(additionPropertyKey, + additionPropertyValue); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + facetManagement.setJSON(Entities.marshal(readCpuFacet)); + + String updatedJson = facetManagement.update(); + CPUFacet updatedCpuFacet = Entities.unmarshal(CPUFacet.class, + updatedJson); + logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, + updatedCpuFacet); + Assert.assertTrue(readCpuFacet.getClockSpeed().compareTo( + updatedCpuFacet.getClockSpeed()) == 0); + Assert.assertTrue(readCpuFacet.getModel().compareTo( + updatedCpuFacet.getModel()) == 0); + Assert.assertTrue(readCpuFacet.getVendor().compareTo( + updatedCpuFacet.getVendor()) == 0); + Assert.assertTrue(((String) updatedCpuFacet + .getAdditionalProperty(additionPropertyKey)) + .compareTo((String) readCpuFacet + .getAdditionalProperty(additionPropertyKey)) == 0); + Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID()) == 0); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + + String readUpdatedJson = facetManagement.read(); + CPUFacet readUpdatedCpuFacet = Entities.unmarshal(CPUFacet.class, + readUpdatedJson); + logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", + readUpdatedJson, readUpdatedCpuFacet); + Assert.assertTrue(updatedCpuFacet.getClockSpeed().compareTo( + readUpdatedCpuFacet.getClockSpeed()) == 0); + Assert.assertTrue(updatedCpuFacet.getModel().compareTo( + readUpdatedCpuFacet.getModel()) == 0); + Assert.assertTrue(updatedCpuFacet.getVendor().compareTo( + readUpdatedCpuFacet.getVendor()) == 0); + Assert.assertTrue(((String) updatedCpuFacet + .getAdditionalProperty(additionPropertyKey)) + .compareTo((String) readUpdatedCpuFacet + .getAdditionalProperty(additionPropertyKey)) == 0); + Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID()) == 0); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + + boolean deleted = facetManagement.delete(); + Assert.assertTrue(deleted); + } + + + public Map createHostingNodeAndEService() throws Exception { + Map map = new HashMap<>(); + + EService eService = new EServiceImpl(); + + SoftwareFacet softwareFacet = new SoftwareFacetImpl(); + softwareFacet.setGroup("InformationSystem"); + softwareFacet.setName("resource-registry"); + softwareFacet.setVersion("1.1.0"); + + IsIdentifiedBy isIdentifiedBy = new IsIdentifiedByImpl( + eService, softwareFacet, null); + eService.addFacet(isIdentifiedBy); + + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(EService.NAME); + resourceManagement.setJSON(Entities.marshal(eService)); + + String json = resourceManagement.create(); + logger.debug("Created : {}", json); + eService = Entities.unmarshal(EService.class, json); + logger.debug("Unmarshalled {} {}", EService.NAME, eService); + map.put(EService.NAME, eService); + + NetworkingFacet networkingFacet = new NetworkingFacetImpl(); + networkingFacet.setIPAddress("146.48.87.183"); + networkingFacet.setHostName("pc-frosini.isti.cnr.it"); + networkingFacet.setDomainName("isti.cnr.it"); + networkingFacet.setMask("255.255.248.0"); + networkingFacet.setBroadcastAddress("146.48.87.255"); + + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setJSON(Entities.marshal(networkingFacet)); + facetManagement.setEntityType(NetworkingFacet.NAME); + + json = facetManagement.create(); + logger.debug("Created : {}", json); + networkingFacet = Entities.unmarshal(NetworkingFacet.class, json); + logger.debug("Unmarshalled {} {}", NetworkingFacet.NAME, + networkingFacet); + + HostingNode hostingNode = new HostingNodeImpl(); + + CPUFacet cpuFacet = new CPUFacetImpl(); + cpuFacet.setClockSpeed("1 GHz"); + cpuFacet.setModel("Opteron"); + cpuFacet.setVendor("AMD"); + hostingNode.addFacet(cpuFacet); + + isIdentifiedBy = new IsIdentifiedByImpl(hostingNode, + networkingFacet, null); + hostingNode.attachFacet(isIdentifiedBy); + + + RelationProperty relationProperty = new RelationPropertyImpl(); + relationProperty.setReferentialIntegrity(ReferentialIntegrity.onDeleteCascade); + Hosts hosts = new HostsImpl( + hostingNode, eService, relationProperty); + hostingNode.attachResource(hosts); + + resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setJSON(Entities.marshal(hostingNode)); + + json = resourceManagement.create(); + logger.debug("Created : {}", json); + hostingNode = Entities.unmarshal(HostingNode.class, json); + logger.debug("Unmarshalled {} {}", HostingNode.NAME, hostingNode); + map.put(HostingNode.NAME, hostingNode); + + return map; + } + + @Test + public void testCreateHostingNodeAndEService() throws Exception { + Map map = createHostingNodeAndEService(); + + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(map.get(EService.NAME).getHeader().getUUID()); + boolean deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(map.get(HostingNode.NAME).getHeader().getUUID()); + deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + } + + @Test + public void testCreateHostingNodeAndEServiceWithSharedFacet() throws Exception { + ScopedTest.setContext(ScopedTest.GCUBE_DEVNEXT); + + Map map = createHostingNodeAndEService(); + + EService eService = (EService) map.get(EService.NAME); + HostingNode hostingNode = (HostingNode) map.get(HostingNode.NAME); + + Facet shared = hostingNode.getConsistsOf().get(0).getTarget(); + + ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); + consistsOfManagement.setRelationType(ConsistsOf.NAME); + consistsOfManagement.setJSON("{}"); + + UUID eServiceUUID = eService.getHeader().getUUID(); + UUID sharedFacetUUID = shared.getHeader().getUUID(); + + String json = consistsOfManagement.create(eServiceUUID, sharedFacetUUID); + logger.debug("Created : {}", json); + + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(eService.getHeader().getUUID()); + boolean deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(hostingNode.getHeader().getUUID()); + deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setUUID(sharedFacetUUID); + + try { + facetManagement.read(); + throw new Exception(String.format("Shared Facet %s was not deleted", shared)); + }catch(ResourceRegistryException e){ + logger.debug("Shared Facet was not foud as expected"); + } + } + + @Test + public void testCreateResourceAndFacet() throws Exception { + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setJSON("{}"); + + String json = resourceManagement.create(); + UUID resourceUUID = Utility.getUUIDFromJSONString(json); + + CPUFacet cpuFacet = new CPUFacetImpl(); + cpuFacet.setClockSpeed("1 GHz"); + cpuFacet.setModel("Opteron"); + cpuFacet.setVendor("AMD"); + + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setJSON(Entities.marshal(cpuFacet)); + facetManagement.setEntityType(CPUFacet.NAME); + + json = facetManagement.create(); + logger.debug("Created : {}", json); + UUID facetUUID = Utility.getUUIDFromJSONString(json); + + ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); + consistsOfManagement.setRelationType(ConsistsOf.NAME); + consistsOfManagement.setJSON("{}"); + + json = consistsOfManagement.create(resourceUUID, facetUUID); + + logger.debug("Facet attached : {}", json); + + UUID consistOfUUID = Utility.getUUIDFromJSONString(json); + + consistsOfManagement = new ConsistsOfManagement(); + consistsOfManagement.setUUID(consistOfUUID); + + boolean detached = consistsOfManagement.delete(); + + if (detached) { + logger.trace("{} {} with uuid {} removed successfully", + ConsistsOf.NAME, Relation.NAME, consistOfUUID); + } else { + String error = String.format("Unable to remove %s %s with uuid %s", + ConsistsOf.NAME, Relation.NAME, consistOfUUID); + logger.error(error); + throw new Exception(error); + } + + facetManagement = new FacetManagement(); + facetManagement.setUUID(facetUUID); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(resourceUUID); + resourceManagement.delete(); + + } + +} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/MultiContextTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/MultiContextTest.java index 1ee6327..45b1947 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/MultiContextTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/MultiContextTest.java @@ -8,6 +8,7 @@ import java.net.URL; import java.util.Calendar; import java.util.UUID; +import org.codehaus.jettison.json.JSONObject; import org.gcube.common.scope.api.ScopeProvider; import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl; import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl; @@ -24,6 +25,8 @@ import org.gcube.informationsystem.impl.relation.consistsof.HasPersistentMemoryI import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl; import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl; import org.gcube.informationsystem.impl.utils.Entities; +import org.gcube.informationsystem.model.embedded.Header; +import org.gcube.informationsystem.model.entity.Entity; import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.facet.AccessPointFacet; import org.gcube.informationsystem.model.entity.facet.CPUFacet; @@ -40,9 +43,13 @@ import org.gcube.informationsystem.model.relation.IsIdentifiedBy; import org.gcube.informationsystem.model.relation.consistsof.HasPersistentMemory; import org.gcube.informationsystem.model.relation.consistsof.HasVolatileMemory; import org.gcube.informationsystem.model.relation.isrelatedto.Hosts; +import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement; +import org.gcube.informationsystem.resourceregistry.resources.old.EntityManagementImplTest; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -52,21 +59,102 @@ import org.slf4j.LoggerFactory; * @author Luca Frosini (ISTI - CNR) * */ -public class MultiContextTest { +public class MultiContextTest extends ScopedTest { private static Logger logger = LoggerFactory .getLogger(EntityManagementImplTest.class); - protected EntityManagementImpl entityManagementImpl; + @Test + public void testDifferentScopes() throws Exception { + CPUFacet cpuFacet = new CPUFacetImpl(); + cpuFacet.setClockSpeed("1 GHz"); + cpuFacet.setModel("Opteron"); + cpuFacet.setVendor("AMD"); - public MultiContextTest() { - entityManagementImpl = new EntityManagementImpl(); + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setJSON(Entities.marshal(cpuFacet)); + facetManagement.setEntityType(CPUFacet.NAME); + + String json = facetManagement.create(); + logger.debug("Created : {}", json); + + JSONObject jsonObject = new JSONObject(json); + JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY); + UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY)); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + + String readJson = facetManagement.read(); + logger.debug("Read : {}", readJson); + + /* ------------------------------------------------------------------ */ + + logger.debug("Switching to another scope"); + ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE); + try { + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + readJson = facetManagement.read(); + logger.debug("You should not be able to read Facet with UUID {}", + uuid); + throw new Exception( + "You should not be able to read Facet with UUID " + uuid); + } catch (ResourceRegistryException e) { + logger.debug("Good the facet created in /gcube/devsec is not visible in /gcube/devNext"); + } + + cpuFacet.setAdditionalProperty("My", "Test"); + + try { + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + facetManagement.setJSON(Entities.marshal(cpuFacet)); + readJson = facetManagement.update(); + logger.debug("You should not be able to update Facet with UUID {}", + uuid); + throw new Exception( + "You should not be able to read Facet with UUID " + uuid); + } catch (ResourceRegistryException e) { + logger.debug("Good the Facet created in /gcube/devsec cannot be updated in /gcube/devNext"); + } + + try { + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + facetManagement.delete(); + logger.debug("You should not be able to delete Facet with UUID {}", + uuid); + throw new Exception( + "You should not be able to delete Facet with UUID " + uuid); + } catch (ResourceRegistryException e) { + logger.debug("Good the Facet created in /gcube/devsec cannot be deleted in /gcube/devNext"); + } + + /* ------------------------------------------------------------------ */ + + logger.debug("Setting back default scope"); + ScopedTest.setContext(ScopedTest.DEFAULT_TEST_SCOPE); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + facetManagement.setJSON(Entities.marshal(cpuFacet)); + readJson = facetManagement.update(); + logger.debug("Updated : {}", readJson); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + readJson = facetManagement.read(); + logger.debug("Read Updated : {}", readJson); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + boolean deleted = facetManagement.delete(); + Assert.assertTrue(deleted); } - + @Test public void testCreateEServiceHostingNode() throws Exception { - ScopeProvider.instance.set("/gcube/devNext"); - EService eService = new EServiceImpl(); SoftwareFacet softwareFacet = new SoftwareFacetImpl(); @@ -97,14 +185,17 @@ public class MultiContextTest { .setTextURL(new URL( "https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11")); eService.addFacet(licenseFacet); + + + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(EService.NAME); + resourceManagement.setJSON(Entities.marshal(eService)); - String json = entityManagementImpl.createResource(EService.NAME, - Entities.marshal(eService)); + String json = resourceManagement.create(); logger.debug("Created : {}", json); eService = Entities.unmarshal(EService.class, json); logger.debug("Unmarshalled {} {}", EService.NAME, eService); - /* ----- */ HostingNode hostingNode = new HostingNodeImpl(); @@ -147,50 +238,76 @@ public class MultiContextTest { hostingNode, eService, null); hostingNode.attachResource(hosts); - String hnJson = entityManagementImpl.createResource(HostingNode.NAME, - Entities.marshal(hostingNode)); + resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setJSON(Entities.marshal(hostingNode)); + + String hnJson = resourceManagement.create(); logger.debug("Created : {}", hnJson); hostingNode = Entities.unmarshal(HostingNode.class, hnJson); logger.debug("Unmarshalled {} {}", HostingNode.NAME, hostingNode); - - ScopeProvider.instance.set("/gcube/devNext/NextNext"); UUID uuid = hostingNode.getHeader().getUUID(); - boolean addedToContext = entityManagementImpl - .addResourceToContext(uuid); + + /* ------------------------------------------------------------------ */ + + logger.debug("Switching to another scope"); + ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(uuid); + + boolean addedToContext = resourceManagement.addToContext(); Assert.assertTrue(addedToContext); - String hnString = entityManagementImpl.readResource(uuid); + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(uuid); + + String hnString = resourceManagement.read(); HostingNode readHN = Entities.unmarshal(HostingNode.class, hnString); Assert.assertTrue(readHN.getHeader().getUUID().compareTo(uuid) == 0); UUID eServiceUUID = eService.getHeader().getUUID(); try { - entityManagementImpl.readResource(eServiceUUID); + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(eServiceUUID); + resourceManagement.read(); } catch (ResourceNotFoundException e) { logger.debug("Resource with {} Not Found as Expected", - uuid.toString()); + eServiceUUID); } try { - entityManagementImpl.deleteResource(uuid); + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(eServiceUUID); + resourceManagement.delete(); } catch (ResourceNotFoundException e) { logger.debug("Resource with {} Not Found as Expected", - uuid.toString()); + eServiceUUID); } - try { - entityManagementImpl.deleteResource(eService.getHeader().getUUID()); - } catch (ResourceNotFoundException e) { - logger.debug("Resource with {} Not Found as Expected", - uuid.toString()); - } + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(uuid); + boolean deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + + /* ------------------------------------------------------------------ */ + logger.debug("Setting back default scope"); + ScopedTest.setContext(ScopedTest.DEFAULT_TEST_SCOPE); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(eServiceUUID); + deleted = resourceManagement.delete(); + Assert.assertTrue(deleted); + } // @Test public void addTest() throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { ScopeProvider.instance.set("/gcube/devNext/NextNext"); - entityManagementImpl.addResourceToContext(UUID.fromString("")); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(UUID.fromString("")); + resourceManagement.addToContext(); } } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/QueryImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/QueryImplTest.java index 582f7b0..ad080ed 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/QueryImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/QueryImplTest.java @@ -3,7 +3,7 @@ */ package org.gcube.informationsystem.resourceregistry.resources.impl; -import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException; import org.junit.Test; import org.slf4j.Logger; @@ -13,13 +13,12 @@ import org.slf4j.LoggerFactory; * @author Luca Frosini (ISTI - CNR) * */ -public class QueryImplTest { +public class QueryImplTest extends ScopedTest { private static Logger logger = LoggerFactory.getLogger(QueryImplTest.class); @Test public void testQuery() throws InvalidQueryException{ - ScopeProvider.instance.set("/gcube/devNext"); QueryImpl queryImpl = new QueryImpl(); String query = "select * from CPUFacet"; diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ReferentialIntegrityTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ReferentialIntegrityTest.java deleted file mode 100644 index 5be38d9..0000000 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ReferentialIntegrityTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * - */ -package org.gcube.informationsystem.resourceregistry.resources.impl; - -import org.gcube.common.scope.api.ScopeProvider; -import org.junit.Before; -import org.junit.Test; - -/** - * @author Luca Frosini (ISTI - CNR) - * - */ -public class ReferentialIntegrityTest { - - protected EntityManagementImpl entityManagementImpl; - - @Before - public void before(){ - ScopeProvider.instance.set("/gcube/devNext"); - } - - - public ReferentialIntegrityTest() { - entityManagementImpl = new EntityManagementImpl(); - } - - @Test - public void test() throws Exception{ - - } - -} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImplTest.java index fa44207..7c76b45 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImplTest.java @@ -26,7 +26,7 @@ public class SchemaManagementImplTest { Class clz = Header.class; String json = TypeBinder.serializeType(clz); logger.trace(json); - new SchemaManagementImpl().registerEmbeddedTypeSchema(json); + //new SchemaManagementImpl().registerEmbeddedTypeSchema(json); } @Test diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SmartgearResourcesTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SmartgearResourcesTest.java index c49f147..1909610 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SmartgearResourcesTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/SmartgearResourcesTest.java @@ -22,7 +22,6 @@ import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.gcube.common.scope.api.ScopeProvider; import org.gcube.informationsystem.impl.embedded.HeaderImpl; import org.gcube.informationsystem.impl.embedded.RelationPropertyImpl; import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl; @@ -54,7 +53,10 @@ import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.IsIdentifiedBy; import org.gcube.informationsystem.model.relation.consistsof.HasPersistentMemory; import org.gcube.informationsystem.model.relation.consistsof.HasVolatileMemory; +import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement; +import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,27 +68,23 @@ import com.fasterxml.jackson.databind.JsonMappingException; * @author Luca Frosini (ISTI - CNR) * */ -public class SmartgearResourcesTest { +public class SmartgearResourcesTest extends ScopedTest { private static Logger logger = LoggerFactory.getLogger(SmartgearResourcesTest.class); - - protected EntityManagementImpl entityManagementImpl; - - public SmartgearResourcesTest() { - entityManagementImpl = new EntityManagementImpl(); - } - public static final String HOSTING_NODE = "{\"@class\":\"HostingNode\",\"header\":{\"@class\":\"Header\",\"uuid\":\"f0460614-9ffb-4ecd-bf52-d91e8d81d604\",\"creator\":null,\"creationTime\":null,\"lastUpdateTime\":null},\"consistsOf\":[{\"@class\":\"IsIdentifiedBy\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"NetworkingFacet\",\"header\":null,\"hostName\":\"pc-frosini.isti.cnr.it\",\"domainName\":\"isti.cnr.it\",\"mask\":null,\"broadcastAddress\":null,\"ipaddress\":\"127.0.1.1\",\"Port\":8080}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"CPUFacet\",\"header\":null,\"model\":\"Intel(R) Core(TM) i5-3450 CPU @ 3.10GHz\",\"vendor\":\"GenuineIntel\",\"clockSpeed\":\"2872.828\",\"cache_size\":\"6144 KB\",\"flags\":\"fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts\",\"bogomips\":\"6199.91\",\"fpu\":\"yes\",\"stepping\":\"9\",\"address_sizes\":\"36 bits physical, 48 bits virtual\",\"wp\":\"yes\",\"clflush_size\":\"64\",\"siblings\":\"4\",\"microcode\":\"0x17\",\"cpu_family\":\"6\",\"cpu_cores\":\"4\",\"physical_id\":\"0\",\"cpuid_level\":\"13\",\"fpu_exception\":\"yes\",\"apicid\":\"0\",\"cache_alignment\":\"64\",\"processor\":\"0\",\"core_id\":\"0\",\"initial_apicid\":\"0\",\"modelNumber\":\"58\"}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"CPUFacet\",\"header\":null,\"model\":\"Intel(R) Core(TM) i5-3450 CPU @ 3.10GHz\",\"vendor\":\"GenuineIntel\",\"clockSpeed\":\"2617.199\",\"cache_size\":\"6144 KB\",\"flags\":\"fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts\",\"bogomips\":\"6199.91\",\"fpu\":\"yes\",\"stepping\":\"9\",\"address_sizes\":\"36 bits physical, 48 bits virtual\",\"wp\":\"yes\",\"clflush_size\":\"64\",\"siblings\":\"4\",\"microcode\":\"0x17\",\"cpu_family\":\"6\",\"cpu_cores\":\"4\",\"physical_id\":\"0\",\"cpuid_level\":\"13\",\"fpu_exception\":\"yes\",\"apicid\":\"2\",\"cache_alignment\":\"64\",\"processor\":\"1\",\"core_id\":\"1\",\"initial_apicid\":\"2\",\"modelNumber\":\"58\"}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"CPUFacet\",\"header\":null,\"model\":\"Intel(R) Core(TM) i5-3450 CPU @ 3.10GHz\",\"vendor\":\"GenuineIntel\",\"clockSpeed\":\"2610.660\",\"cache_size\":\"6144 KB\",\"flags\":\"fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts\",\"bogomips\":\"6199.91\",\"fpu\":\"yes\",\"stepping\":\"9\",\"address_sizes\":\"36 bits physical, 48 bits virtual\",\"wp\":\"yes\",\"clflush_size\":\"64\",\"siblings\":\"4\",\"microcode\":\"0x17\",\"cpu_family\":\"6\",\"cpu_cores\":\"4\",\"physical_id\":\"0\",\"cpuid_level\":\"13\",\"fpu_exception\":\"yes\",\"apicid\":\"4\",\"cache_alignment\":\"64\",\"processor\":\"2\",\"core_id\":\"2\",\"initial_apicid\":\"4\",\"modelNumber\":\"58\"}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"CPUFacet\",\"header\":null,\"model\":\"Intel(R) Core(TM) i5-3450 CPU @ 3.10GHz\",\"vendor\":\"GenuineIntel\",\"clockSpeed\":\"2712.257\",\"cache_size\":\"6144 KB\",\"flags\":\"fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts\",\"bogomips\":\"6199.91\",\"fpu\":\"yes\",\"stepping\":\"9\",\"address_sizes\":\"36 bits physical, 48 bits virtual\",\"wp\":\"yes\",\"clflush_size\":\"64\",\"siblings\":\"4\",\"microcode\":\"0x17\",\"cpu_family\":\"6\",\"cpu_cores\":\"4\",\"physical_id\":\"0\",\"cpuid_level\":\"13\",\"fpu_exception\":\"yes\",\"apicid\":\"6\",\"cache_alignment\":\"64\",\"processor\":\"3\",\"core_id\":\"3\",\"initial_apicid\":\"6\",\"modelNumber\":\"58\"}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"SoftwareFacet\",\"header\":null,\"name\":\"amd64\",\"group\":\"Linux\",\"version\":\"4.4.0-47-generic\",\"description\":null,\"qualifier\":null,\"optional\":false}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"SimplePropertyFacet\",\"header\":null,\"name\":\"ENVIRONMENT_VARIABLES\",\"value\":\"\",\"TERM\":\"xterm\",\"XDG_SESSION_PATH\":\"/org/freedesktop/DisplayManager/Session0\",\"JAVA_HOME\":\"/usr/lib/jvm/java-7-oracle\",\"J2REDIR\":\"/usr/lib/jvm/java-7-oracle/jre\",\"LESSCLOSE\":\"/usr/bin/lesspipe %s %s\",\"UPSTART_SESSION\":\"unix:abstract=/com/ubuntu/upstart-session/1000/1613\",\"J2SDKDIR\":\"/usr/lib/jvm/java-7-oracle\",\"SESSION_MANAGER\":\"local/pc-frosini.isti.cnr.it:@/tmp/.ICE-unix/1849,unix/pc-frosini.isti.cnr.it:/tmp/.ICE-unix/1849\",\"LC_NUMERIC\":\"it_IT.UTF-8\",\"GNOME_DESKTOP_SESSION_ID\":\"this-is-deprecated\",\"Java\":\"1.7.0_80\",\"COMPIZ_CONFIG_PROFILE\":\"ubuntu\",\"GDMSESSION\":\"ubuntu\",\"IM_CONFIG_PHASE\":\"1\",\"MANDATORY_PATH\":\"/usr/share/gconf/ubuntu.mandatory.path\",\"SmartGearsDistributionBundle\":\"2.0.1-SNAPSHOT\",\"PWD\":\"/home/lucafrosini/Desktop/SmartGears-Bundle\",\"SESSIONTYPE\":\"gnome-session\",\"GIO_LAUNCHED_DESKTOP_FILE_PID\":\"7474\",\"GTK_IM_MODULE\":\"ibus\",\"XDG_GREETER_DATA_DIR\":\"/var/lib/lightdm-data/lucafrosini\",\"XDG_SESSION_TYPE\":\"x11\",\"NLSPATH\":\"/usr/dt/lib/nls/msg/%L/%N.cat\",\"TERMINATOR_UUID\":\"urn:uuid:7e1ff3e9-f2ca-4c64-b5db-922901ce32dc\",\"XDG_MENU_PREFIX\":\"gnome-\",\"LC_ADDRESS\":\"it_IT.UTF-8\",\"ghn-update-interval-in-secs\":\"60\",\"XDG_CONFIG_DIRS\":\"/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg\",\"XDG_CURRENT_DESKTOP\":\"Unity\",\"QT_LINUX_ACCESSIBILITY_ALWAYS_ON\":\"1\",\"GHN_HOME\":\"/home/lucafrosini/Desktop/SmartGears-Bundle/SmartGears\",\"XAUTHORITY\":\"/home/lucafrosini/.Xauthority\",\"GDM_LANG\":\"en_US\",\"XDG_SEAT\":\"seat0\",\"SmartGears\":\"2.2.0-SNAPSHOT\",\"CATALINA_PID\":\"/home/lucafrosini/Desktop/SmartGears-Bundle/tomcat.pid\",\"XDG_SESSION_ID\":\"c2\",\"XDG_SEAT_PATH\":\"/org/freedesktop/DisplayManager/Seat0\",\"XDG_VTNR\":\"7\",\"LC_TIME\":\"it_IT.UTF-8\",\"GNOME_KEYRING_CONTROL\":\"\",\"GTK_MODULES\":\"gail:atk-bridge:unity-gtk-module\",\"LC_TELEPHONE\":\"it_IT.UTF-8\",\"SHLVL\":\"2\",\"XFILESEARCHPATH\":\"/usr/dt/app-defaults/%L/Dt\",\"GTK2_MODULES\":\"overlay-scrollbar\",\"COMPIZ_BIN_PATH\":\"/usr/bin/\",\"COLORTERM\":\"gnome-terminal\",\"JOB\":\"unity-settings-daemon\",\"UPSTART_JOB\":\"unity7\",\"LC_NAME\":\"it_IT.UTF-8\",\"IBUS_DISABLE_SNOOPER\":\"1\",\"XDG_DATA_DIRS\":\"/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop\",\"QT_QPA_PLATFORMTHEME\":\"appmenu-qt5\",\"QT_IM_MODULE\":\"ibus\",\"GIO_LAUNCHED_DESKTOP_FILE\":\"/usr/share/applications/terminator.desktop\",\"UPSTART_INSTANCE\":\"\",\"LOGNAME\":\"lucafrosini\",\"WINDOWID\":\"81788932\",\"LC_PAPER\":\"it_IT.UTF-8\",\"SmartGearsDistribution\":\"2.0.0-SNAPSHOT\",\"SESSION\":\"ubuntu\",\"GPG_AGENT_INFO\":\"/home/lucafrosini/.gnupg/S.gpg-agent:0:1\",\"LC_IDENTIFICATION\":\"it_IT.UTF-8\",\"DERBY_HOME\":\"/usr/lib/jvm/java-7-oracle/db\",\"XMODIFIERS\":\"@im=ibus\",\"LD_LIBRARY_PATH\":\"/home/lucafrosini/MATLAB/MATLAB_Runtime/v90/runtime/glnxa64\",\"UPSTART_EVENTS\":\"xsession started\",\"OLDPWD\":\"/home/lucafrosini/Desktop/SmartGears-Bundle\",\"DBUS_SESSION_BUS_ADDRESS\":\"unix:abstract=/tmp/dbus-mf1KaSOYwP\",\"SHELL\":\"/bin/bash\",\"GNOME_KEYRING_PID\":\"\",\"LANGUAGE\":\"en_US\",\"QT_ACCESSIBILITY\":\"1\",\"DESKTOP_SESSION\":\"ubuntu\",\"INSTANCE\":\"\",\"DISPLAY\":\":0\",\"CLUTTER_IM_MODULE\":\"xim\",\"LC_MONETARY\":\"it_IT.UTF-8\",\"USER\":\"lucafrosini\",\"CATALINA_HOME\":\"/home/lucafrosini/Desktop/SmartGears-Bundle/tomcat\",\"HOME\":\"/home/lucafrosini\",\"LESSOPEN\":\"| /usr/bin/lesspipe %s\",\"QT4_IM_MODULE\":\"xim\",\"CATALINA_OPTS\":\"-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n -Xmx2000m -Xms2000m\",\"DEFAULTS_PATH\":\"/usr/share/gconf/ubuntu.default.path\",\"ORBIT_SOCKETDIR\":\"/tmp/orbit-lucafrosini\",\"XDG_SESSION_DESKTOP\":\"ubuntu\",\"LC_MEASUREMENT\":\"it_IT.UTF-8\",\"BUNDLE_HOME\":\"/home/lucafrosini/Desktop/SmartGears-Bundle\",\"XDG_RUNTIME_DIR\":\"/run/user/1000\",\"LANG\":\"en_US.UTF-8\"}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"ContainerStateFacet\",\"header\":null,\"value\":\"started\"}},{\"@class\":\"HasVolatileMemory\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"MemoryFacet\",\"header\":null,\"size\":15736,\"used\":9042,\"unit\":\"MB\"},\"memoryType\":\"RAM\"},{\"@class\":\"HasVolatileMemory\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"MemoryFacet\",\"header\":null,\"size\":1917,\"used\":374,\"unit\":\"MB\",\"jvmMaxMemory\":1917},\"memoryType\":\"JVM\"},{\"@class\":\"HasPersistentMemory\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"MemoryFacet\",\"header\":null,\"size\":273894,\"used\":101270,\"unit\":\"MB\"}}],\"isRelatedTo\":[]}"; public static final String ESERVICE = "{\"@class\":\"EService\",\"header\":{\"@class\":\"Header\",\"uuid\":\"3ace4bd0-e5cd-49a3-97a8-a0a9468ce6d4\",\"creator\":null, \"creationTime\":null, \"lastUpdateTime\":null},\"consistsOf\":[{\"@class\":\"IsIdentifiedBy\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"SoftwareFacet\",\"header\":null,\"name\":\"WhnManager\",\"group\":\"VREManagement\",\"version\":\"2.0.0-SNAPSHOT\",\"description\":\"Web Hosting Node Service\",\"qualifier\":null,\"optional\":false}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"AccessPointFacet\",\"header\":null,\"entryName\":\"whnmanager\",\"endpoint\":\"http://pc-frosini.isti.cnr.it:8080/whn-manager/gcube/vremanagement/ws/whnmanager\",\"protocol\":null,\"description\":null,\"authorization\": {\"@class\":\"ValueSchema\",\"value\":\"gcube-token\",\"schema\":null},\"properties\":null}},{\"@class\":\"ConsistsOf\",\"header\":null,\"relationProperty\":null,\"target\":{\"@class\":\"AccessPointFacet\",\"header\":null,\"entryName\":\"WhnManager-remote-management\",\"endpoint\":\"http://pc-frosini.isti.cnr.it:8080/whn-manager/gcube/resource\",\"protocol\":null,\"description\":null,\"authorization\":{\"@class\":\"ValueSchema\",\"value\":\"gcube-token\",\"schema\":null},\"properties\":null}}],\"isRelatedTo\":[]}"; @Test public void testHostingNode() throws JsonParseException, JsonMappingException, IOException, ResourceRegistryException{ - ScopeProvider.instance.set("/gcube/devNext"); HostingNode hostingNode = Entities.unmarshal(HostingNode.class, HOSTING_NODE); logger.debug("{}", hostingNode); - String hnJson = entityManagementImpl.createResource(HostingNode.NAME, Entities.marshal(hostingNode)); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setJSON(HOSTING_NODE); + + String hnJson = resourceManagement.create(); logger.debug("Created : {}", hnJson); hostingNode = Entities.unmarshal(HostingNode.class, hnJson); logger.debug("Unmarshalled {} {}", HostingNode.NAME, hostingNode); @@ -95,11 +93,14 @@ public class SmartgearResourcesTest { @Test public void testEService() throws JsonParseException, JsonMappingException, IOException, ResourceRegistryException{ - ScopeProvider.instance.set("/gcube/devNext"); EService eService = Entities.unmarshal(EService.class, ESERVICE); logger.debug("{}", eService); - String json = entityManagementImpl.createResource(EService.NAME, Entities.marshal(eService)); + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(EService.NAME); + resourceManagement.setJSON(ESERVICE); + + String json = resourceManagement.create(); logger.debug("Created : {}", json); eService = Entities.unmarshal(EService.class, json); logger.debug("Unmarshalled {} {}", EService.NAME, eService); @@ -113,8 +114,6 @@ public class SmartgearResourcesTest { @Test public void testHostingNodeOperations() throws ResourceRegistryException, IOException{ - ScopeProvider.instance.set("/gcube/devNext"); - UUID uuid = UUID.randomUUID(); HostingNode hostingNode = new HostingNodeImpl(); @@ -181,7 +180,12 @@ public class SmartgearResourcesTest { new HasPersistentMemoryImpl(hostingNode, disk, relationProperty); hostingNode.addFacet(hasPersistentMemory); - String json = entityManagementImpl.createResource(HostingNode.NAME, Entities.marshal(hostingNode)); + + ResourceManagement resourceManagement = new ResourceManagement(); + resourceManagement.setEntityType(HostingNode.NAME); + resourceManagement.setJSON(Entities.marshal(hostingNode)); + + String json = resourceManagement.create(); HostingNode hostingNodeToUpdate = Entities.unmarshal(HostingNode.class, json); @@ -226,13 +230,21 @@ public class SmartgearResourcesTest { consistsOfList.removeAll(consistsOfToRemove); - String updatedHN = entityManagementImpl.updateResource(uuid, Entities.marshal(hostingNodeToUpdate)); + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(uuid); + resourceManagement.setJSON(Entities.marshal(hostingNodeToUpdate)); + + String updatedHN = resourceManagement.update(); logger.debug("Updated {}", updatedHN); - HostingNode hostingNodeToUpdated = Entities.unmarshal(HostingNode.class, updatedHN); - logger.debug("Upodate Hosting Node {}", hostingNodeToUpdated); + HostingNode updatedHostingNode = Entities.unmarshal(HostingNode.class, updatedHN); + logger.debug("Updated Hosting Node {}", updatedHostingNode); - entityManagementImpl.deleteResource(uuid); + + resourceManagement = new ResourceManagement(); + resourceManagement.setUUID(uuid); + boolean deleted= resourceManagement.delete(); + Assert.assertTrue(deleted); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/old/EntityManagementImpl.java similarity index 99% rename from src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java rename to src/test/java/org/gcube/informationsystem/resourceregistry/resources/old/EntityManagementImpl.java index 8ce078f..6a1b472 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/old/EntityManagementImpl.java @@ -1,7 +1,7 @@ /** * */ -package org.gcube.informationsystem.resourceregistry.resources.impl; +package org.gcube.informationsystem.resourceregistry.resources.old; import java.io.IOException; import java.util.ArrayList; @@ -41,6 +41,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour 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.resourceregistry.resources.impl.SchemaManagementImpl; import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility; import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.resources.utils.Utility; @@ -1175,7 +1176,7 @@ public class EntityManagementImpl implements EntityManagement { } private static String marshallResource(OrientGraph orientGraph, - Vertex vertex) throws JSONException { + Vertex vertex) throws JSONException, ResourceRegistryException { JSONObject jsonObject = Utility.toJsonObject((OrientVertex) vertex, true); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/old/EntityManagementImplTest.java similarity index 99% rename from src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java rename to src/test/java/org/gcube/informationsystem/resourceregistry/resources/old/EntityManagementImplTest.java index 0d6f7c3..3034280 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/old/EntityManagementImplTest.java @@ -1,7 +1,7 @@ /** * */ -package org.gcube.informationsystem.resourceregistry.resources.impl; +package org.gcube.informationsystem.resourceregistry.resources.old; import java.io.StringWriter; import java.net.URI;