Reorganizing code

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@141436 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2016-12-30 16:31:12 +00:00
parent 0bcdd8a260
commit 1078b43fcf
17 changed files with 1002 additions and 1035 deletions

View File

@ -57,11 +57,11 @@ public class SchemaActionImpl implements SchemaAction {
String json = TypeBinder.serializeType(e); String json = TypeBinder.serializeType(e);
logger.trace(json); logger.trace(json);
if (Facet.class.isAssignableFrom(e)) { if (Facet.class.isAssignableFrom(e)) {
schemaManagement.registerFacetSchema(json); schemaManagement.createFacetSchema(json);
} else if(Resource.class.isAssignableFrom(e)){ } else if(Resource.class.isAssignableFrom(e)){
schemaManagement.registerResourceSchema(json); schemaManagement.registerResourceSchema(json);
} else { } else {
schemaManagement.registerEntitySchema(json); schemaManagement.createEntitySchema(json);
} }
} catch(Exception ex){ } catch(Exception ex){
logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage()); logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage());

View File

@ -12,30 +12,388 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.impl.utils.Entities; import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType; import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
* *
*/ */
public class ERManagement { public abstract class ERManagement<ER, El extends Element> {
private static Logger logger = LoggerFactory.getLogger(ERManagement.class); private static Logger logger = LoggerFactory.getLogger(ERManagement.class);
public static String lowerCaseFirstCharacter(String string) { public final String AT = "@";
return string.substring(0, 1).toLowerCase() + string.substring(1); public final String UNDERSCORE = "_";
protected final Set<String> ignoreKeys;
protected final Set<String> ignoreStartWithKeys;
protected Class<ER> erClass;
protected String baseType;
protected OrientGraph orientGraph;
protected UUID uuid;
protected JsonNode jsonNode;
protected String erType;
protected Class<El> elementClass;
protected El element;
protected ERManagement(Class<ER> erClass) {
this.erClass = erClass;
this.ignoreKeys = new HashSet<String>();
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(AT);
this.ignoreStartWithKeys.add(UNDERSCORE);
}
protected ERManagement(Class<ER> erClass, OrientGraph orientGraph) {
this(erClass);
this.orientGraph = orientGraph;
}
public void setUUID(UUID uuid) throws ResourceRegistryException {
this.uuid = uuid;
if (jsonNode != null) {
checkUUIDMatch();
}
}
public void setJSON(JsonNode jsonNode) throws ResourceRegistryException {
this.jsonNode = jsonNode;
checkJSON();
}
public void setJSON(String jsonRepresentation)
throws ResourceRegistryException {
ObjectMapper mapper = new ObjectMapper();
try {
this.jsonNode = mapper.readTree(jsonRepresentation);
} catch (IOException e) {
throw new ResourceRegistryException(e);
}
checkJSON();
}
public void setElementType(String erType) throws ResourceRegistryException {
this.erType = erType;
if (erType == null || erType.compareTo("") == 0) {
if (Facet.class.isAssignableFrom(erClass)) {
this.erType = Facet.NAME;
}
if (Resource.class.isAssignableFrom(erClass)) {
this.erType = Resource.NAME;
}
if (ConsistsOf.class.isAssignableFrom(erClass)) {
this.erType = ConsistsOf.NAME;
}
if (IsRelatedTo.class.isAssignableFrom(erClass)) {
this.erType = IsRelatedTo.NAME;
}
throw new ResourceRegistryException("Invalid type " + erType
+ " provided");
}
if (jsonNode != null) {
checkERMatch();
}
}
protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) {
try {
uuid = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {
}
} else {
checkUUIDMatch();
}
if (this.erType == null) {
this.erType = getClassProperty(jsonNode);
} else {
checkERMatch();
}
}
protected void checkERMatch() throws ResourceRegistryException {
String type = getClassProperty(jsonNode);
if (type != null && type.compareTo(erType) != 0) {
String error = String
.format("Declared resourceType does not match with json representation %s!=%s",
erType, type);
logger.trace(error);
throw new ResourceRegistryException(error);
}
try {
SchemaManagementImpl.getTypeSchema(erType, baseType);
} catch (SchemaNotFoundException e) {
throw e;
}
}
protected void checkUUIDMatch() throws ResourceRegistryException {
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) {
throw new ResourceRegistryException(e);
}
if (header != null) {
UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) {
String error = String
.format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(),
erType);
throw new ResourceRegistryException(error);
}
}
}
public abstract String serialize() throws ResourceRegistryException;
public abstract JSONObject serializeAsJson()
throws ResourceRegistryException;
public abstract El reallyUpdate() throws EntityNotFoundException,
ResourceRegistryException;
public abstract boolean reallyDelete() throws EntityNotFoundException,
ResourceRegistryException;
public abstract boolean reallyAddToContext() throws ContextException,
ResourceRegistryException;
public abstract boolean reallyRemoveFromContext() throws ContextException,
ResourceRegistryException;
public void setElement(El element) throws ResourceRegistryException {
if (element == null) {
throw new ResourceRegistryException("Trying to set null "
+ elementClass.getSimpleName() + " in " + this);
}
this.element = element;
this.uuid = HeaderUtility.getHeader(element).getUUID();
}
protected void throwElementNotFoundException(ResourceRegistryException e)
throws EntityNotFoundException, RelationNotFoundException,
ResourceRegistryException {
if (Resource.class.isAssignableFrom(erClass)) {
throw new ResourceNotFoundException(e);
} else if (Facet.class.isAssignableFrom(erClass)) {
throw new FacetNotFoundException(e);
} else if (Relation.class.isAssignableFrom(erClass)) {
throw new RelationNotFoundException(e);
}
throw e;
}
public El getElement() throws ResourceRegistryException {
try {
if (element == null) {
element = Utility.getElementByUUID(orientGraph,
erType == null ? baseType : erType, uuid, elementClass);
}
} catch (ResourceRegistryException e) {
throwElementNotFoundException(e);
}
return element;
}
public String read() throws EntityNotFoundException,
ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER);
getElement();
return serialize();
} catch (ResourceRegistryException e) {
throw e;
} catch (Exception e) {
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String update() throws RelationNotFoundException,
ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
element = reallyUpdate();
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean delete() throws FacetNotFoundException,
ResourceRegistryException {
logger.debug("Going to delete {} with UUID {}", baseType, uuid);
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
boolean deleted = reallyDelete();
orientGraph.commit();
logger.info("{} with UUID {} was successfully deleted.", baseType,
uuid);
return deleted;
} catch (ResourceRegistryException e) {
logger.error("Unable to delete {} with UUID {}", baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
logger.error("Unable to delete {} with UUID {}", baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean addToContext() throws ContextException {
logger.debug("Going to add {} with UUID {} to actual Context",
baseType, uuid);
try {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
boolean added = reallyAddToContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context",
baseType, uuid);
return added;
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean removeFromContext() throws ContextException {
logger.debug("Going to remove {} with UUID {} from actual Context",
baseType, uuid);
try {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
boolean removed = reallyRemoveFromContext();
orientGraph.commit();
logger.info(
"{} with UUID {} successfully removed from actual Context",
baseType, uuid);
return removed;
} catch (Exception e) {
logger.error(
"Unable to remove {} with UUID {} from actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
} }
public static String getClassProperty(JsonNode jsonNode) { public static String getClassProperty(JsonNode jsonNode) {
@ -45,8 +403,6 @@ public class ERManagement {
return null; return null;
} }
public static Object getObjectFromElement(JsonNode value) public static Object getObjectFromElement(JsonNode value)
throws ResourceRegistryException { throws ResourceRegistryException {
JsonNodeType jsonNodeType = value.getNodeType(); JsonNodeType jsonNodeType = value.getNodeType();
@ -152,17 +508,18 @@ public class ERManagement {
return map; return map;
} }
public static Element updateProperties(Element element, JsonNode jsonNode, Set<String> ignoreKeys, Set<String> ignoreStartWithKeys) public static Element updateProperties(Element element, JsonNode jsonNode,
Set<String> ignoreKeys, Set<String> ignoreStartWithKeys)
throws ResourceRegistryException { throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyKeys(); Set<String> oldKeys = element.getPropertyKeys();
Map<String, Object> properties; Map<String, Object> properties;
if (element instanceof Vertex || element instanceof Edge) { if (element instanceof Vertex || element instanceof Edge) {
try { try {
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys); properties = getPropertyMap(jsonNode, ignoreKeys,
} catch ( IOException e) { ignoreStartWithKeys);
} catch (IOException e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} else { } else {
@ -201,11 +558,8 @@ public class ERManagement {
} }
((OrientElement) element).save(); ((OrientElement) element).save();
return element; return element;
} }
} }

View File

@ -3,12 +3,6 @@
*/ */
package org.gcube.informationsystem.resourceregistry.er.entity; package org.gcube.informationsystem.resourceregistry.er.entity;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.embedded.Header; import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Entity; import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.Facet;
@ -16,23 +10,15 @@ import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; 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.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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.Direction;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
@ -43,32 +29,19 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class EntityManagement<E extends Entity> { public abstract class EntityManagement<E extends Entity> extends
ERManagement<E, Vertex> {
private static Logger logger = LoggerFactory private static Logger logger = LoggerFactory
.getLogger(EntityManagement.class); .getLogger(EntityManagement.class);
public final String AT = "@"; protected Vertex element;
public final String UNDERSCORE = "_";
protected final Set<String> ignoreKeys;
protected final Set<String> ignoreStartWithKeys;
protected final Class<E> entityClass;
protected final String baseType;
protected OrientGraph orientGraph;
protected UUID uuid;
protected JsonNode jsonNode;
protected String entityType;
protected Vertex vertex;
protected EntityManagement(Class<E> entityClass) { protected EntityManagement(Class<E> entityClass) {
this.ignoreKeys = new HashSet<String>(); super(entityClass);
this.ignoreKeys.add(Entity.HEADER_PROPERTY); this.ignoreKeys.add(Entity.HEADER_PROPERTY);
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX
.toLowerCase()); .toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
@ -77,10 +50,7 @@ public abstract class EntityManagement<E extends Entity> {
.toUpperCase()); .toUpperCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
.toUpperCase()); .toUpperCase());
this.ignoreStartWithKeys.add(AT);
this.ignoreStartWithKeys.add(UNDERSCORE);
this.entityClass = entityClass;
if (Facet.class.isAssignableFrom(entityClass)) { if (Facet.class.isAssignableFrom(entityClass)) {
this.baseType = Facet.NAME; this.baseType = Facet.NAME;
} else if (Resource.class.isAssignableFrom(entityClass)) { } else if (Resource.class.isAssignableFrom(entityClass)) {
@ -95,150 +65,22 @@ public abstract class EntityManagement<E extends Entity> {
this.orientGraph = orientGraph; 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, protected Vertex createVertex() throws EntityAlreadyPresentException,
ResourceRegistryException { ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", logger.trace("Going to create {} for {} ({}) using {}",
Vertex.class.getSimpleName(), baseType, entityType, jsonNode); Vertex.class.getSimpleName(), baseType, erType, jsonNode);
try { try {
Vertex vertexEntity = orientGraph.addVertex("class:" + entityType); Vertex vertexEntity = orientGraph.addVertex("class:" + erType);
try { try {
Vertex v = getVertex(); Vertex v = getElement();
if (v != null) { if (v != null) {
String error = String.format( String error = String.format(
"A %s with UUID %s already exist", entityType, "A %s with UUID %s already exist", erType,
uuid.toString()); uuid.toString());
throw new EntityAlreadyPresentException(error); throw new EntityAlreadyPresentException(error);
} }
@ -249,61 +91,47 @@ public abstract class EntityManagement<E extends Entity> {
// no header or no header with uuid is provided and it is fine // no header or no header with uuid is provided and it is fine
} }
this.vertex = vertexEntity; this.element = vertexEntity;
Header entityHeader = HeaderUtility.getHeader(jsonNode, true); Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
if (entityHeader != null) { if (entityHeader != null) {
vertex.setProperty(Entity.HEADER_PROPERTY, entityHeader); element.setProperty(Entity.HEADER_PROPERTY, entityHeader);
} else { } else {
entityHeader = HeaderUtility.addHeader(vertex, null); entityHeader = HeaderUtility.addHeader(element, null);
} }
if (Resource.class.isAssignableFrom(entityClass)) { if (Resource.class.isAssignableFrom(erClass)) {
// Facet and relation are created in calling method // Facet and relation are created in calling method
} else { } else {
ERManagement.updateProperties(vertex, jsonNode, ignoreKeys, ERManagement.updateProperties(element, jsonNode, ignoreKeys,
ignoreStartWithKeys); ignoreStartWithKeys);
} }
ContextUtility.addToActualContext(orientGraph, vertex); ContextUtility.addToActualContext(orientGraph, element);
((OrientVertex) vertex).save(); ((OrientVertex) element).save();
logger.info("Created {} is {}", Vertex.class.getSimpleName(), logger.info("Created {} is {}", Vertex.class.getSimpleName(),
Utility.toJsonString((OrientVertex) vertex, true)); Utility.toJsonString((OrientVertex) element, true));
return vertex; return element;
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", logger.trace("Error while creating {} for {} ({}) using {}",
Vertex.class.getSimpleName(), baseType, entityType, Vertex.class.getSimpleName(), baseType, erType, jsonNode, e);
jsonNode, e); throw new ResourceRegistryException("Error Creating " + erType
throw new ResourceRegistryException("Error Creating " + entityType
+ " with " + jsonNode, e.getCause()); + " with " + jsonNode, e.getCause());
} }
} }
public abstract String serialize() throws ResourceRegistryException; @Override
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, public boolean reallyAddToContext() throws ContextException,
ResourceRegistryException { ResourceRegistryException {
ContextUtility.addToActualContext(orientGraph, getVertex()); ContextUtility.addToActualContext(orientGraph, getElement());
Iterable<Edge> edges = vertex.getEdges(Direction.OUT); Iterable<Edge> edges = element.getEdges(Direction.OUT);
for (Edge edge : edges) { for (Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -315,12 +143,13 @@ public abstract class EntityManagement<E extends Entity> {
return true; return true;
} }
@Override
public boolean reallyRemoveFromContext() throws ContextException, public boolean reallyRemoveFromContext() throws ContextException,
ResourceRegistryException { ResourceRegistryException {
ContextUtility.removeFromActualContext(orientGraph, getVertex());
Iterable<Edge> edges = vertex.getEdges(Direction.OUT); ContextUtility.removeFromActualContext(orientGraph, getElement());
Iterable<Edge> edges = element.getEdges(Direction.OUT);
for (Edge edge : edges) { for (Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -332,7 +161,7 @@ public abstract class EntityManagement<E extends Entity> {
return true; return true;
} }
@SuppressWarnings("rawtypes") @SuppressWarnings({ "rawtypes", "unchecked" })
public static EntityManagement getEntityManagement(OrientGraph orientGraph, public static EntityManagement getEntityManagement(OrientGraph orientGraph,
Vertex vertex) throws ResourceRegistryException { Vertex vertex) throws ResourceRegistryException {
OrientVertexType orientVertexType = ((OrientVertex) vertex).getType(); OrientVertexType orientVertexType = ((OrientVertex) vertex).getType();
@ -348,10 +177,13 @@ public abstract class EntityManagement<E extends Entity> {
Facet.NAME); Facet.NAME);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
entityManagement.setVertex(vertex); entityManagement.setElement(vertex);
return entityManagement; return entityManagement;
} }
public abstract Vertex reallyCreate() throws EntityAlreadyPresentException,
ResourceRegistryException;
public String create() throws EntityAlreadyPresentException, public String create() throws EntityAlreadyPresentException,
ResourceRegistryException { ResourceRegistryException {
@ -359,7 +191,7 @@ public abstract class EntityManagement<E extends Entity> {
orientGraph = ContextUtility orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER); .getActualSecurityContextGraph(PermissionMode.WRITER);
reallyCreate(); element = reallyCreate();
orientGraph.commit(); orientGraph.commit();
@ -382,154 +214,6 @@ public abstract class EntityManagement<E extends Entity> {
} }
} }
public String read() throws EntityNotFoundException,
ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER);
getVertex();
return serialize();
} catch (ResourceRegistryException e) {
throw e;
} catch (Exception e) {
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String update() throws EntityNotFoundException,
ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
reallyUpdate();
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
logger.debug("Unable to update {} with UUID {} usign {}", baseType,
uuid, jsonNode, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean delete() throws FacetNotFoundException,
ResourceRegistryException {
logger.debug("Going to delete {} with UUID {}", baseType, uuid);
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
boolean deleted = reallyDelete();
orientGraph.commit();
logger.info("{} with UUID {} was successfully deleted.", baseType,
uuid);
return deleted;
} catch (ResourceRegistryException e) {
logger.error("Unable to delete {} with UUID {}", baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
logger.error("Unable to delete {} with UUID {}", baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean addToContext() throws ContextException {
logger.debug("Going to add {} with UUID {} to actual Context",
baseType, uuid);
try {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
boolean added = reallyAddToContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context",
baseType, uuid);
return added;
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean removeFromContext() throws ContextException {
logger.debug("Going to remove {} with UUID {} from actual Context",
baseType, uuid);
try {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
boolean removed = reallyRemoveFromContext();
orientGraph.commit();
logger.info(
"{} with UUID {} successfully removed from actual Context",
baseType, uuid);
return removed;
} catch (Exception e) {
logger.error(
"Unable to remove {} with UUID {} from actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
} }

View File

@ -31,12 +31,12 @@ public class FacetManagement extends EntityManagement<Facet> {
@Override @Override
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return Utility.toJsonString((OrientVertex) vertex, true); return Utility.toJsonString((OrientVertex) element, true);
} }
@Override @Override
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
return Utility.toJsonObject((OrientVertex) vertex, true); return Utility.toJsonObject((OrientVertex) element, true);
} }
public Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { public Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
@ -45,14 +45,14 @@ public class FacetManagement extends EntityManagement<Facet> {
@Override @Override
public Vertex reallyUpdate() throws ResourceRegistryException { public Vertex reallyUpdate() throws ResourceRegistryException {
Vertex facet = getVertex(); Vertex facet = getElement();
facet = (Vertex) ERManagement.updateProperties(facet, jsonNode, ignoreKeys, ignoreStartWithKeys); facet = (Vertex) ERManagement.updateProperties(facet, jsonNode, ignoreKeys, ignoreStartWithKeys);
((OrientVertex) facet).save(); ((OrientVertex) facet).save();
return facet; return facet;
} }
public boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException { public boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException {
getVertex().remove(); getElement().remove();
return true; return true;
} }

View File

@ -14,10 +14,10 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.rest.AccessType;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -78,7 +78,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
try { try {
jsonObject.put(ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME), jsonObject.put(AccessType.CONSISTS_OF.lowerCaseFirstCharacter(),
consistsOfArray); consistsOfArray);
} catch (JSONException e) { } catch (JSONException e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
@ -93,12 +93,12 @@ public class ResourceManagement extends EntityManagement<Resource> {
@Override @Override
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return marshallResource(orientGraph, getVertex()).toString(); return marshallResource(orientGraph, getElement()).toString();
} }
@Override @Override
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
return marshallResource(orientGraph, getVertex()); return marshallResource(orientGraph, getElement());
} }
@Override @Override
@ -106,36 +106,36 @@ public class ResourceManagement extends EntityManagement<Resource> {
ResourceRegistryException { ResourceRegistryException {
createVertex(); createVertex();
String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME); String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode consistOfJsonNode : jsonNodeArray) { for (JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(orientGraph);
com.setJSON(consistOfJsonNode); com.setJSON(consistOfJsonNode);
com.reallyCreate(vertex); com.reallyCreate(element);
} }
} }
property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME); property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement( IsRelatedToManagement irtm = new IsRelatedToManagement(
orientGraph); orientGraph);
irtm.setJSON(relationJsonNode); irtm.setJSON(relationJsonNode);
irtm.reallyCreate(vertex); irtm.reallyCreate(element);
} }
} }
return vertex; return element;
} }
@Override @Override
public Vertex reallyUpdate() throws ResourceRegistryException { public Vertex reallyUpdate() throws ResourceRegistryException {
getVertex(); getElement();
String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME); String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for (JsonNode relationJsonNode : jsonNodeArray) {
@ -145,7 +145,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
} }
property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME); property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for (JsonNode relationJsonNode : jsonNodeArray) {
@ -156,19 +156,20 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
} }
((OrientVertex) vertex).save(); ((OrientVertex) element).save();
return vertex; return element;
} }
@SuppressWarnings("unchecked")
@Override @Override
public boolean reallyDelete() throws ResourceNotFoundException, public boolean reallyDelete() throws ResourceNotFoundException,
ResourceRegistryException { ResourceRegistryException {
//internalDeleteResource(orientGraph, uuid, null); //internalDeleteResource(orientGraph, uuid, null);
getVertex(); getElement();
Iterable<Edge> iterable = vertex.getEdges(Direction.OUT); Iterable<Edge> iterable = element.getEdges(Direction.OUT);
Iterator<Edge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
while(iterator.hasNext()){ while(iterator.hasNext()){
Edge edge = iterator.next(); Edge edge = iterator.next();
@ -187,13 +188,13 @@ public class ResourceManagement extends EntityManagement<Resource> {
IsRelatedTo.NAME, ConsistsOf.NAME); IsRelatedTo.NAME, ConsistsOf.NAME);
} }
if(relationManagement!=null){ if(relationManagement!=null){
relationManagement.setEdge(edge); relationManagement.setElement(edge);
relationManagement.reallyDelete(); relationManagement.reallyDelete();
} }
} }
vertex.remove(); element.remove();
return true; return true;
} }

View File

@ -3,15 +3,11 @@
*/ */
package org.gcube.informationsystem.resourceregistry.er.relation; package org.gcube.informationsystem.resourceregistry.er.relation;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.embedded.PropagationConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint;
import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint;
@ -24,22 +20,18 @@ import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; 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.relation.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
@ -53,30 +45,18 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* *
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public abstract class RelationManagement<R extends Relation> { public abstract class RelationManagement<R extends Relation> extends ERManagement<R, Edge> {
private static Logger logger = LoggerFactory private static Logger logger = LoggerFactory
.getLogger(RelationManagement.class); .getLogger(RelationManagement.class);
public final Set<String> ignoreKeys;
public final Set<String> ignoreStartWithKeys;
public static final String AT = "@";
public static final String UNDERSCORE = "_";
protected final Class<R> relationClass;
protected final String baseType;
protected final Class<? extends Entity> targetEntityClass; protected final Class<? extends Entity> targetEntityClass;
protected OrientGraph orientGraph; protected Edge element;
protected UUID uuid;
protected JsonNode jsonNode;
protected String relationType;
protected Edge edge;
protected RelationManagement(Class<R> relationClass) { protected RelationManagement(Class<R> relationClass) {
this.ignoreKeys = new HashSet<String>(); super(relationClass);
this.ignoreKeys.add(Relation.HEADER_PROPERTY); this.ignoreKeys.add(Relation.HEADER_PROPERTY);
this.ignoreKeys.add(Relation.TARGET_PROPERTY); this.ignoreKeys.add(Relation.TARGET_PROPERTY);
this.ignoreKeys.add(Relation.SOURCE_PROPERTY); this.ignoreKeys.add(Relation.SOURCE_PROPERTY);
@ -85,12 +65,6 @@ public abstract class RelationManagement<R extends Relation> {
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase()); this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase()); this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase());
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(AT);
this.ignoreStartWithKeys.add(UNDERSCORE);
this.relationClass = relationClass;
if (ConsistsOf.class.isAssignableFrom(relationClass)) { if (ConsistsOf.class.isAssignableFrom(relationClass)) {
this.baseType = ConsistsOf.NAME; this.baseType = ConsistsOf.NAME;
this.targetEntityClass = Facet.class; this.targetEntityClass = Facet.class;
@ -108,127 +82,14 @@ public abstract class RelationManagement<R extends Relation> {
this.orientGraph = orientGraph; this.orientGraph = orientGraph;
} }
public void setEdge(Edge edge) {
this.edge = edge;
}
public void setUUID(UUID uuid) throws ResourceRegistryException {
this.uuid = uuid;
if (jsonNode != null) {
checkUUIDMatch();
}
}
protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) {
try {
uuid = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {
}
} else {
checkUUIDMatch();
}
if (this.relationType == null) {
this.relationType = ERManagement.getClassProperty(jsonNode);
} else {
checkEntityMatch();
}
}
public void setJSON(JsonNode jsonNode) throws ResourceRegistryException {
this.jsonNode = jsonNode;
checkJSON();
}
public void setJSON(String jsonRepresentation)
throws ResourceRegistryException {
ObjectMapper mapper = new ObjectMapper();
try {
this.jsonNode = mapper.readTree(jsonRepresentation);
} catch (IOException e) {
throw new ResourceRegistryException(e);
}
checkJSON();
}
public void setRelationType(String relationType)
throws ResourceRegistryException {
this.relationType = relationType;
if (relationType == null || relationType.compareTo("") == 0) {
if (ConsistsOf.class.isAssignableFrom(relationClass)) {
this.relationType = ConsistsOf.NAME;
} else if (IsRelatedTo.class.isAssignableFrom(relationClass)) {
this.relationType = IsRelatedTo.NAME;
}
}
if (jsonNode != null) {
checkEntityMatch();
}
}
protected void checkEntityMatch() throws ResourceRegistryException {
String type = ERManagement.getClassProperty(jsonNode);
if (type != null && type.compareTo(relationType) != 0) {
String error = String
.format("Declared resourceType does not match with json representation %s!=%s",
relationType, type);
logger.trace(error);
throw new ResourceRegistryException(error);
}
try {
SchemaManagementImpl.getTypeSchema(relationType, baseType);
} catch (SchemaNotFoundException e) {
throw e;
}
}
protected void checkUUIDMatch() throws ResourceRegistryException {
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) {
throw new ResourceRegistryException(e);
}
if (header != null) {
UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) {
String error = String
.format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(),
relationType);
throw new ResourceRegistryException(error);
}
}
}
public Edge getEdge() throws ResourceRegistryException {
try {
if (edge == null) {
edge = Utility.getElementByUUID(orientGraph,
relationType == null ? baseType : relationType, uuid,
Edge.class);
}
return edge;
} catch (ResourceRegistryException e) {
throw new RelationNotFoundException(e);
}
}
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString(); return serializeAsJson().toString();
} }
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
JSONObject ret = Utility.toJsonObject((OrientEdge) getEdge(), false); JSONObject ret = Utility.toJsonObject((OrientEdge) getElement(), false);
Vertex vertex = edge.getVertex(Direction.IN); Vertex vertex = element.getVertex(Direction.IN);
EntityManagement entityManagement = EntityManagement EntityManagement entityManagement = EntityManagement
.getEntityManagement(orientGraph, vertex); .getEntityManagement(orientGraph, vertex);
@ -246,11 +107,11 @@ public abstract class RelationManagement<R extends Relation> {
throws ResourceRegistryException { throws ResourceRegistryException {
ResourceManagement srmSource = new ResourceManagement(orientGraph); ResourceManagement srmSource = new ResourceManagement(orientGraph);
srmSource.setUUID(sourceUUID); srmSource.setUUID(sourceUUID);
Vertex source = srmSource.getVertex(); Vertex source = srmSource.getElement();
EntityManagement entityManagement = getEntityManagement(); EntityManagement entityManagement = getEntityManagement();
entityManagement.setUUID(targetUUID); entityManagement.setUUID(targetUUID);
Vertex target = entityManagement.getVertex(); Vertex target = (Vertex) entityManagement.getElement();
return reallyCreate(source, target); return reallyCreate(source, target);
@ -268,7 +129,7 @@ public abstract class RelationManagement<R extends Relation> {
"Any type of %s can have only a %s as %s. " "Any type of %s can have only a %s as %s. "
+ "Cannot instatiate %s beetween %s -> %s ", + "Cannot instatiate %s beetween %s -> %s ",
Relation.NAME, Resource.NAME, Relation.SOURCE_PROPERTY, Relation.NAME, Resource.NAME, Relation.SOURCE_PROPERTY,
relationType, sourceEntityManagement.serialize(), erType, sourceEntityManagement.serialize(),
targetEntityManagement.serialize()); targetEntityManagement.serialize());
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
@ -277,7 +138,7 @@ public abstract class RelationManagement<R extends Relation> {
if (!(targetEntityManagement instanceof ResourceManagement)) { if (!(targetEntityManagement instanceof ResourceManagement)) {
String error = String.format("A %s can have only a %s as %s. " String error = String.format("A %s can have only a %s as %s. "
+ "Cannot instatiate %s beetween %s -> %s ", baseType, + "Cannot instatiate %s beetween %s -> %s ", baseType,
Resource.NAME, Relation.TARGET_PROPERTY, relationType, Resource.NAME, Relation.TARGET_PROPERTY, erType,
sourceEntityManagement.serialize(), sourceEntityManagement.serialize(),
targetEntityManagement.serialize()); targetEntityManagement.serialize());
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
@ -286,7 +147,7 @@ public abstract class RelationManagement<R extends Relation> {
if (!(targetEntityManagement instanceof FacetManagement)) { if (!(targetEntityManagement instanceof FacetManagement)) {
String error = String.format("A %s can have only a %s as %s. " String error = String.format("A %s can have only a %s as %s. "
+ "Cannot instatiate %s beetween %s -> %s ", baseType, + "Cannot instatiate %s beetween %s -> %s ", baseType,
Facet.NAME, Relation.TARGET_PROPERTY, relationType, Facet.NAME, Relation.TARGET_PROPERTY, erType,
sourceEntityManagement.serialize(), sourceEntityManagement.serialize(),
targetEntityManagement.serialize()); targetEntityManagement.serialize());
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
@ -300,23 +161,23 @@ public abstract class RelationManagement<R extends Relation> {
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
logger.trace("Creating {} beetween {} -> {}", relationType, logger.trace("Creating {} beetween {} -> {}", erType,
sourceEntityManagement.serialize(), sourceEntityManagement.serialize(),
targetEntityManagement.serialize()); targetEntityManagement.serialize());
edge = orientGraph.addEdge(null, source, target, relationType); element = orientGraph.addEdge(null, source, target, erType);
ERManagement.updateProperties(edge, jsonNode, ignoreKeys, ERManagement.updateProperties(element, jsonNode, ignoreKeys,
ignoreStartWithKeys); ignoreStartWithKeys);
HeaderUtility.addHeader(edge, null); HeaderUtility.addHeader(element, null);
ContextUtility.addToActualContext(orientGraph, edge); ContextUtility.addToActualContext(orientGraph, element);
((OrientEdge) edge).save(); ((OrientEdge) element).save();
logger.info("{} successfully created", relationType); logger.info("{} successfully created", erType);
return edge; return element;
} }
public Edge reallyCreate(Vertex source) throws ResourceRegistryException { public Edge reallyCreate(Vertex source) throws ResourceRegistryException {
@ -329,7 +190,7 @@ public abstract class RelationManagement<R extends Relation> {
} }
entityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY)); entityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
try { try {
target = entityManagement.getVertex(); target = (Vertex) entityManagement.getElement();
} catch (Exception e) { } catch (Exception e) {
target = entityManagement.reallyCreate(); target = entityManagement.reallyCreate();
} }
@ -339,18 +200,18 @@ public abstract class RelationManagement<R extends Relation> {
public Edge reallyCreate(UUID sourceUUID) throws ResourceRegistryException { public Edge reallyCreate(UUID sourceUUID) throws ResourceRegistryException {
ResourceManagement srmSource = new ResourceManagement(orientGraph); ResourceManagement srmSource = new ResourceManagement(orientGraph);
srmSource.setUUID(sourceUUID); srmSource.setUUID(sourceUUID);
Vertex source = srmSource.getVertex(); Vertex source = srmSource.getElement();
return reallyCreate(source); return reallyCreate(source);
} }
public Edge reallyUpdate() throws ResourceRegistryException { public Edge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", relationType, jsonNode); logger.debug("Trying to update {} : {}", erType, jsonNode);
Edge edge = getEdge(); Edge edge = getElement();
ERManagement.updateProperties(edge, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
if (ConsistsOf.class.isAssignableFrom(relationClass)) { if (ConsistsOf.class.isAssignableFrom(erClass)) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if (target != null) { if (target != null) {
FacetManagement fm = new FacetManagement(orientGraph); FacetManagement fm = new FacetManagement(orientGraph);
@ -359,7 +220,7 @@ public abstract class RelationManagement<R extends Relation> {
} }
} }
logger.info("{} {} successfully updated", relationType, jsonNode); logger.info("{} {} successfully updated", erType, jsonNode);
return edge; return edge;
@ -367,13 +228,13 @@ public abstract class RelationManagement<R extends Relation> {
public boolean reallyAddToContext() throws ContextException, public boolean reallyAddToContext() throws ContextException,
ResourceRegistryException { ResourceRegistryException {
getEdge(); getElement();
AddConstraint addConstraint = AddConstraint.unpropagate; AddConstraint addConstraint = AddConstraint.unpropagate;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded( PropagationConstraint propagationConstraint = Utility.getEmbedded(
PropagationConstraint.class, edge, PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getAddConstraint() != null) { if (propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint(); addConstraint = propagationConstraint.getAddConstraint();
@ -383,10 +244,10 @@ public abstract class RelationManagement<R extends Relation> {
+ "This is really strange and should not occur. " + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT,
Utility.toJsonString(edge, true), addConstraint); Utility.toJsonString(element, true), addConstraint);
} }
Vertex target = edge.getVertex(Direction.IN); Vertex target = element.getVertex(Direction.IN);
switch (addConstraint) { switch (addConstraint) {
case propagate: case propagate:
@ -395,7 +256,7 @@ public abstract class RelationManagement<R extends Relation> {
* must be added. Otherwise we have a relation which point * must be added. Otherwise we have a relation which point
* to an entity outside of the context. * to an entity outside of the context.
*/ */
ContextUtility.addToActualContext(orientGraph, getEdge()); ContextUtility.addToActualContext(orientGraph, getElement());
EntityManagement entityManagement = EntityManagement EntityManagement entityManagement = EntityManagement
.getEntityManagement(orientGraph, target); .getEntityManagement(orientGraph, target);
entityManagement.reallyAddToContext(); entityManagement.reallyAddToContext();
@ -425,13 +286,13 @@ public abstract class RelationManagement<R extends Relation> {
public boolean reallyRemoveFromContext() throws ContextException, public boolean reallyRemoveFromContext() throws ContextException,
ResourceRegistryException { ResourceRegistryException {
getEdge(); getElement();
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded( PropagationConstraint propagationConstraint = Utility.getEmbedded(
PropagationConstraint.class, edge, PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) { if (propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
@ -441,16 +302,16 @@ public abstract class RelationManagement<R extends Relation> {
+ "This is really strange and should not occur. " + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT,
Utility.toJsonString(edge, true), removeConstraint); Utility.toJsonString(element, true), removeConstraint);
} }
Vertex target = edge.getVertex(Direction.IN); Vertex target = element.getVertex(Direction.IN);
/* /*
* In any removeConstraint value the relation MUSt be removed from * In any removeConstraint value the relation MUSt be removed from
* context to avoid to have edge having a source outside of the context. * context to avoid to have edge having a source outside of the context.
*/ */
ContextUtility.removeFromActualContext(orientGraph, edge); ContextUtility.removeFromActualContext(orientGraph, element);
switch (removeConstraint) { switch (removeConstraint) {
case cascade: case cascade:
@ -463,7 +324,7 @@ public abstract class RelationManagement<R extends Relation> {
if (iterator.hasNext()) { if (iterator.hasNext()) {
logger.trace( logger.trace(
"{} point to {} which is not orphan. Giving {} directive, it will be not remove from current context.", "{} point to {} which is not orphan. Giving {} directive, it will be not remove from current context.",
edge, target, removeConstraint); element, target, removeConstraint);
} else { } else {
removeFromContextTargetVertex(target); removeFromContextTargetVertex(target);
} }
@ -482,20 +343,21 @@ public abstract class RelationManagement<R extends Relation> {
protected EntityManagement getEntityManagement() protected EntityManagement getEntityManagement()
throws ResourceRegistryException { throws ResourceRegistryException {
EntityManagement entityManagement; EntityManagement entityManagement;
if (ConsistsOf.class.isAssignableFrom(relationClass)) { if (ConsistsOf.class.isAssignableFrom(erClass)) {
entityManagement = new FacetManagement(orientGraph); entityManagement = new FacetManagement(orientGraph);
} else if (IsRelatedTo.class.isAssignableFrom(relationClass)) { } else if (IsRelatedTo.class.isAssignableFrom(erClass)) {
entityManagement = new ResourceManagement(orientGraph); entityManagement = new ResourceManagement(orientGraph);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. " String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange ad should not occur. " + "This is really strange ad should not occur. "
+ "Please Investigate it.", relationClass, ConsistsOf.NAME, + "Please Investigate it.", erClass, ConsistsOf.NAME,
IsRelatedTo.NAME); IsRelatedTo.NAME);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
return entityManagement; return entityManagement;
} }
@SuppressWarnings("unchecked")
public static RelationManagement getRelationManagement( public static RelationManagement getRelationManagement(
OrientGraph orientGraph, Edge edge) OrientGraph orientGraph, Edge edge)
throws ResourceRegistryException { throws ResourceRegistryException {
@ -512,7 +374,7 @@ public abstract class RelationManagement<R extends Relation> {
IsRelatedTo.NAME); IsRelatedTo.NAME);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
relationManagement.setEdge(edge); relationManagement.setElement(edge);
return relationManagement; return relationManagement;
} }
@ -530,13 +392,17 @@ public abstract class RelationManagement<R extends Relation> {
public boolean reallyDelete() throws RelationNotFoundException, public boolean reallyDelete() throws RelationNotFoundException,
ResourceRegistryException { ResourceRegistryException {
getEdge(); logger.debug(
"Going to remove {} with UUID {}. Related {}s will be detached.",
baseType, uuid, targetEntityClass.getSimpleName());
getElement();
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded( PropagationConstraint propagationConstraint = Utility.getEmbedded(
PropagationConstraint.class, edge, PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) { if (propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
@ -546,34 +412,34 @@ public abstract class RelationManagement<R extends Relation> {
+ "This is really strange and should not occur. " + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT,
Utility.toJsonString(edge, true), removeConstraint); Utility.toJsonString(element, true), removeConstraint);
} }
Vertex target = edge.getVertex(Direction.IN); Vertex target = element.getVertex(Direction.IN);
edge.remove(); element.remove();
switch (removeConstraint) { switch (removeConstraint) {
case cascade: case cascade:
deleteTargetVertex(target);
break;
case cascadeWhenOrphan:
Iterable<Edge> iterable = target.getEdges(Direction.IN);
Iterator<Edge> iterator = iterable.iterator();
if (iterator.hasNext()) {
logger.trace(
"{} point to {} which is not orphan. Giving {} directive, it will be keep.",
edge, target, removeConstraint);
} else {
deleteTargetVertex(target); deleteTargetVertex(target);
} break;
break;
case cascadeWhenOrphan:
case keep: Iterable<Edge> iterable = target.getEdges(Direction.IN);
break; Iterator<Edge> iterator = iterable.iterator();
if (iterator.hasNext()) {
default: logger.trace(
break; "{} point to {} which is not orphan. Giving {} directive, it will be keep.",
element, target, removeConstraint);
} else {
deleteTargetVertex(target);
}
break;
case keep:
break;
default:
break;
} }
return true; return true;
@ -585,7 +451,7 @@ public abstract class RelationManagement<R extends Relation> {
orientGraph = ContextUtility orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER); .getActualSecurityContextGraph(PermissionMode.WRITER);
edge = reallyCreate(sourceUUID, targetUUID); element = reallyCreate(sourceUUID, targetUUID);
orientGraph.commit(); orientGraph.commit();
@ -608,160 +474,4 @@ public abstract class RelationManagement<R extends Relation> {
} }
} }
public String read() throws RelationNotFoundException,
ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String update() throws RelationNotFoundException,
ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
edge = reallyUpdate();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean delete() throws RelationNotFoundException,
ResourceRegistryException {
logger.debug(
"Going to remove {} with UUID {}. Related {}s will be detached.",
baseType, uuid, targetEntityClass.getSimpleName());
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
boolean deleted = reallyDelete();
orientGraph.commit();
logger.info("{} {} with UUID {} successfully removed.", baseType,
uuid);
return deleted;
} catch (ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID.", baseType, uuid);
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
logger.error("Unable to remove {} with UUID {}.", baseType, uuid);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean addToContext() throws ContextException {
logger.debug("Going to add {} with UUID {} to actual Context",
baseType, uuid);
try {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
boolean added = reallyAddToContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context",
baseType, uuid);
return added;
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean removeFromContext() throws ContextException {
logger.debug("Going to remove {} with UUID {} from actual Context",
baseType, uuid);
try {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
boolean removed = reallyRemoveFromContext();
orientGraph.commit();
logger.info(
"{} with UUID {} successfully removed from actual Context",
baseType, uuid);
return removed;
} catch (Exception e) {
logger.error(
"Unable to remove {} with UUID {} from actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
} }

View File

@ -12,12 +12,14 @@ import javax.ws.rs.core.MediaType;
import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.query.Query; import org.gcube.informationsystem.resourceregistry.query.Query;
import org.gcube.informationsystem.resourceregistry.query.QueryImpl; import org.gcube.informationsystem.resourceregistry.query.QueryImpl;
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagement; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagement;
@ -36,27 +38,31 @@ public class Access {
public static final String ID_PATH_PARAM = "id"; public static final String ID_PATH_PARAM = "id";
public static final String TYPE_PATH_PARAM = "type"; public static final String TYPE_PATH_PARAM = "type";
/** /**
* It allows to query Entities and Relations in the current Context.<br /> * It includeSubtypesows to query Entities and Relations in the current Context.<br />
* It accepts idempotent query only.. * It accepts idempotent query only.. <br />
* <br /><br /> * <br />
* For query syntax please refer to<br /> * For query syntax please refer to<br />
* <a href="https://orientdb.com/docs/last/SQL-Syntax.html" target="_blank"> * <a href="https://orientdb.com/docs/last/SQL-Syntax.html" target="_blank">
* https://orientdb.com/docs/last/SQL-Syntax.html * https://orientdb.com/docs/last/SQL-Syntax.html </a> <br />
* </a> * <br />
* <br /><br />
* e.g. GET /resource-registry/access?query=SELECT FROM V * e.g. GET /resource-registry/access?query=SELECT FROM V
* @param query Defines the query to send to the backend. *
* @param limit Defines the number of results you want returned, * @param query
* defaults to all results. * Defines the query to send to the backend.
* @param fetchPlan Defines the fetching strategy you want to use. See * @param limit
* <a href="https://orientdb.com/docs/last/Fetching-Strategies.html" * Defines the number of results you want returned, defaults to
* target="_blank"> * includeSubtypes results.
* https://orientdb.com/docs/last/Fetching-Strategies.html * @param fetchPlan
* </a> * Defines the fetching strategy you want to use. See <a
* href="https://orientdb.com/docs/last/Fetching-Strategies.html"
* target="_blank">
* https://orientdb.com/docs/last/Fetching-Strategies.html </a>
* @return The JSON representation of the result * @return The JSON representation of the result
* @throws InvalidQueryException if the query is invalid or no idempotent * @throws InvalidQueryException
* if the query is invalid or no idempotent
*/ */
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -64,100 +70,254 @@ public class Access {
@QueryParam(AccessPath.LIMIT_PARAM) int limit, @QueryParam(AccessPath.LIMIT_PARAM) int limit,
@QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan)
throws InvalidQueryException { throws InvalidQueryException {
logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query); logger.info("Requested query (fetch plan {}, limit : {}):\n{}",
fetchPlan, limit, query);
Query queryManager = new QueryImpl(); Query queryManager = new QueryImpl();
return queryManager.query(query, limit, fetchPlan); return queryManager.query(query, limit, fetchPlan);
} }
/**
* e.g. GET /resource-registry/access/facet/instance/4d28077b-566d-4132-b073-f4edaf61dcb9 @SuppressWarnings("rawtypes")
* @param facetId public static ERManagement getERManagement(AccessType querableType) throws ResourceRegistryException {
* @return switch (querableType) {
* @throws FacetNotFoundException case FACET:
* @throws ResourceRegistryException return new FacetManagement();
case RESOURCE:
return new ResourceManagement();
case IS_RELATED_TO:
return new IsRelatedToManagement();
case CONSISTS_OF:
return new ConsistsOfManagement();
default:
throw new ResourceRegistryException(String.format("%s is not querable", querableType.toString()));
}
}
/*
* e.g. GET /resource-registry/access/instance/{E-R}/4d28077b-566d-4132-b073-f4edaf61dcb9
*/ */
@GET @GET
@Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM +"}"
+ "/{" + ID_PATH_PARAM + "}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String getFacet(@PathParam(ID_PATH_PARAM) String facetId) public String getInstance(
@PathParam(ID_PATH_PARAM) String type,
@PathParam(ID_PATH_PARAM) String facetId)
throws ResourceRegistryException {
logger.info("Requested Facet with id {}", facetId);
AccessType querableType = null;
try {
querableType = AccessType.valueOf(type);
}catch(Exception e){
String error = String.format("%s is not querable", type);
throw new ResourceRegistryException(error);
}
@SuppressWarnings("rawtypes")
ERManagement erManagement = getERManagement(querableType);
erManagement.setUUID(UUID.fromString(facetId));
return erManagement.read();
}
/*
* e.g. GET /resource-registry/access/instances/{E-R}?polymorphic=true
*/
@GET
@Path(AccessPath.INSTANCE_PATH_PART + "s/" + "{" + TYPE_PATH_PARAM +"}"
+ "/{" + ID_PATH_PARAM + "}")
@Produces(MediaType.APPLICATION_JSON)
public String getInstances(
@PathParam(ID_PATH_PARAM) String type,
@PathParam(ID_PATH_PARAM) String facetId)
throws FacetNotFoundException, ResourceRegistryException { throws FacetNotFoundException, ResourceRegistryException {
logger.info("Requested Facet with id {}", facetId); logger.info("Requested Facet with id {}", facetId);
FacetManagement facetManagement = new FacetManagement(); AccessType querableType = null;
facetManagement.setUUID(UUID.fromString(facetId)); try {
return facetManagement.read(); querableType = AccessType.valueOf(type);
} }catch(Exception e){
String error = String.format("%s is not querable", type);
/** throw new ResourceRegistryException(error);
* e.g. GET /resource-registry/access/facet/schema/ContactFacet }
* @param facetType
* @return
* @throws SchemaNotFoundException // TODO
*/
@GET return null;
@Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Produces(MediaType.APPLICATION_JSON)
public String getFacetSchema(@PathParam(TYPE_PATH_PARAM) String facetType)
throws SchemaNotFoundException {
logger.info("Requested Facet Schema for type {}", facetType);
SchemaManagement schemaManager = new SchemaManagementImpl();
return schemaManager.getFacetSchema(facetType);
} }
/*
/** * e.g. GET /resource-registry/access/schema/Facet/ContactFacet?
* e.g. GET /resource-registry/access/resource/instance/cc132a2c-d0b0-45a8-92fa-7451f6a44b6d * includeSubtypes=true&
* @param resourceId * includeSchema=true
* @return
* @throws ResourceNotFoundException
* @throws ResourceRegistryException
*/ */
@GET @GET
@Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(AccessPath.SCHEMA_PATH_PART + "/{"
+ TYPE_PATH_PARAM + "}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String getResource(@PathParam(ID_PATH_PARAM) String resourceId) public String getSchema(@PathParam(TYPE_PATH_PARAM) String type,
throws ResourceNotFoundException, ResourceRegistryException { @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes,
logger.info("Requested Resource with id {}", resourceId); @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema)
ResourceManagement resourceManagement = new ResourceManagement(); throws SchemaNotFoundException, SchemaException {
resourceManagement.setUUID(UUID.fromString(resourceId)); logger.info("Requested Facet Schema for type {}", type);
return resourceManagement.read(); SchemaManagement schemaManagement = new SchemaManagementImpl();
// TODO
return schemaManagement.readFacetSchema(type, includeSubtypes,
includeSchema);
} }
// /*
// * e.g. GET /resource-registry/access/facet/instance/
// * 4d28077b-566d-4132-b073-f4edaf61dcb9
// */
// @GET
// @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART
// + "/{" + ID_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getFacet(@PathParam(ID_PATH_PARAM) String facetId)
// throws FacetNotFoundException, ResourceRegistryException {
// logger.info("Requested Facet with id {}", facetId);
// FacetManagement facetManagement = new FacetManagement();
// facetManagement.setUUID(UUID.fromString(facetId));
// return facetManagement.read();
// }
//
// /*
// * e.g. GET /resource-registry/access/facet/schema/ContactFacet?
// * includeSubtypes=true&
// * includeSchema=true
// *
// */
// @GET
// @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{"
// + TYPE_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getFacetSchema(@PathParam(TYPE_PATH_PARAM) String facetType,
// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes,
// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema)
// throws SchemaNotFoundException, SchemaException {
// logger.info("Requested Facet Schema for type {}", facetType);
// SchemaManagement schemaManagement = new SchemaManagementImpl();
// return schemaManagement.readFacetSchema(facetType, includeSubtypes,
// includeSchema);
// }
//
// /*
// * e.g. GET /resource-registry/access/resource/instance/
// * cc132a2c-d0b0-45a8-92fa-7451f6a44b6d
// */
// @GET
// @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART
// + "/{" + ID_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getResource(@PathParam(ID_PATH_PARAM) String resourceId)
// throws ResourceNotFoundException, ResourceRegistryException {
// logger.info("Requested Resource with id {}", resourceId);
// ResourceManagement resourceManagement = new ResourceManagement();
// resourceManagement.setUUID(UUID.fromString(resourceId));
// return resourceManagement.read();
// }
//
//
//
//
// /*
// * e.g. GET /resource-registry/access/resource/schema/HostingNode?
// * includeSubtypes=true&
// * includeSchema=true
// */
// @GET
// @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART
// + "/{" + TYPE_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getResourceSchema(
// @PathParam(TYPE_PATH_PARAM) String resourceType,
// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes,
// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema)
// throws SchemaNotFoundException, SchemaException {
// logger.info("Requested Resource Schema for type {}", resourceType);
// SchemaManagement schemaManagement = new SchemaManagementImpl();
// return schemaManagement.getResourceSchema(resourceType,
// includeSubtypes, includeSchema);
// }
//
// /*
// * e.g. GET /resource-registry/access/embedded/schema/Embedded?
// * includeSubtypes=true&
// * includeSchema=true
// */
// @GET
// @Path(AccessPath.EMBEDDED_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART
// + "/{" + TYPE_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getEmbeddedSchema(
// @PathParam(TYPE_PATH_PARAM) String embeddedType,
// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes,
// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema)
// throws SchemaNotFoundException, SchemaException {
// if (includeSchema == null) {
// includeSchema = false;
// }
// SchemaManagement schemaManagement = new SchemaManagementImpl();
// return schemaManagement.getEmbeddedTypeSchema(embeddedType,
// includeSubtypes, includeSchema);
// }
//
// /*
// * e.g. GET /resource-registry/access/consistsOf/schema/HasContact?
// * includeSubtypes=true&
// * includeSchema=true
// */
// @GET
// @Path(AccessPath.CONSISTS_OF_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART
// + "/{" + TYPE_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getConsistsOfSchema(
// @PathParam(TYPE_PATH_PARAM) String consistsOfType,
// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes,
// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema)
// throws SchemaNotFoundException, SchemaException {
// if (includeSchema == null) {
// includeSchema = false;
// }
// SchemaManagement schemaManagement = new SchemaManagementImpl();
// return schemaManagement.getConsistsOfSchema(consistsOfType,
// includeSubtypes, includeSchema);
// }
//
// /*
// * e.g. GET /resource-registry/access/isRelatedTo/schema/HasContact?
// * includeSubtypes=true&
// * includeSchema=true
// */
// @GET
// @Path(AccessPath.IS_RELATED_TO_PATH_PART + "/"
// + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
// @Produces(MediaType.APPLICATION_JSON)
// public String getIsRelatedToSchema(
// @PathParam(TYPE_PATH_PARAM) String isRelatedToType,
// @QueryParam(AccessPath.INCLUDE_SUBTYPES_PARAM) Boolean includeSubtypes,
// @QueryParam(AccessPath.INCLUDE_SCHEMA_PARAM) Boolean includeSchema)
// throws SchemaNotFoundException, SchemaException {
// if (includeSchema == null) {
// includeSchema = false;
// }
// SchemaManagement schemaManagement = new SchemaManagementImpl();
// return schemaManagement.getIsRelatedToSchema(isRelatedToType,
// includeSubtypes, includeSchema);
// }
/**
* e.g. GET /resource-registry/access/resource/schema/HostingNode
* @param resourceType
* @return
* @throws SchemaNotFoundException
*/
@GET
@Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Produces(MediaType.APPLICATION_JSON)
public String getResourceSchema(@PathParam(TYPE_PATH_PARAM) String resourceType)
throws SchemaNotFoundException {
logger.info("Requested Resource Schema for type {}", resourceType);
SchemaManagement schemaManager = new SchemaManagementImpl();
return schemaManager.getResourceSchema(resourceType);
}
public String getResourceTypes(String resourceType, boolean includeSchema) throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
}
public String getEmbeddedTypes(String embeddedType, boolean includeSchema) throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
}
public String getRelationTypes(String relationType, boolean includeSchema) throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
}
public String getConsistsOfTypes(String consistsOfType, boolean includeSchema) throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
}
public String getIsRelatedToTypes(String isRelatedToType, boolean includeSchema) throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
}
} }

View File

@ -0,0 +1,45 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.rest;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.model.relation.Relation;
/**
* @author Luca Frosini (ISTI - CNR)
*
* Enumerates the basic type names.
*/
public enum AccessType {
ENTITY(Entity.NAME),
RESOURCE(Resource.NAME),
FACET(Facet.NAME),
RELATION(Relation.NAME),
IS_RELATED_TO(IsRelatedTo.NAME),
CONSISTS_OF(ConsistsOf.NAME);
private final String name;
private final String lowerCaseFirstCharacter;
AccessType(String name){
this.name = name;
this.lowerCaseFirstCharacter = name.substring(0, 1).toLowerCase() + name.substring(1);
}
public String lowerCaseFirstCharacter() {
return lowerCaseFirstCharacter;
}
@Override
public String toString(){
return name;
}
}

View File

@ -20,7 +20,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; 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.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.EntityPath; import org.gcube.informationsystem.resourceregistry.api.rest.ERPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
* @author Lucio Lelii (ISTI - CNR) * @author Lucio Lelii (ISTI - CNR)
*/ */
@Path(EntityPath.ENTITY_PATH_PART) @Path(ERPath.ER_PATH_PART)
public class ERManager { public class ERManager {
private static Logger logger = LoggerFactory.getLogger(SchemaManager.class); private static Logger logger = LoggerFactory.getLogger(SchemaManager.class);
@ -57,7 +57,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@PUT @PUT
@Path(EntityPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String createFacet(@PathParam(TYPE_PATH_PARAM) String type, public String createFacet(@PathParam(TYPE_PATH_PARAM) String type,
@ -65,7 +65,7 @@ public class ERManager {
logger.info("requested facet creation for type {} defined by {} ", logger.info("requested facet creation for type {} defined by {} ",
type, json); type, json);
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setEntityType(type); facetManagement.setElementType(type);
facetManagement.setJSON(json); facetManagement.setJSON(json);
return facetManagement.create(); return facetManagement.create();
} }
@ -83,7 +83,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@POST @POST
@Path(EntityPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json) public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json)
@ -105,7 +105,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@DELETE @DELETE
@Path(EntityPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ResourceRegistryException { throws FacetNotFoundException, ResourceRegistryException {
logger.info("Requested to delete Facet with id {}", uuid); logger.info("Requested to delete Facet with id {}", uuid);
@ -128,7 +128,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@PUT @PUT
@Path(EntityPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String createResource(@PathParam(TYPE_PATH_PARAM) String type, public String createResource(@PathParam(TYPE_PATH_PARAM) String type,
@ -137,13 +137,13 @@ public class ERManager {
logger.info("requested resource creation for type {} with json {}", logger.info("requested resource creation for type {} with json {}",
type, json); type, json);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(type); resourceManagement.setElementType(type);
resourceManagement.setJSON(json); resourceManagement.setJSON(json);
return resourceManagement.create(); return resourceManagement.create();
} }
@POST @POST
@Path(EntityPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, public String updateResource(@PathParam(ID_PATH_PARAM) String uuid,
@ -166,7 +166,7 @@ public class ERManager {
* @throws Exception * @throws Exception
*/ */
@DELETE @DELETE
@Path(EntityPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, Exception { throws ResourceNotFoundException, Exception {
logger.info("requested resource deletion for id {}", uuid); logger.info("requested resource deletion for id {}", uuid);
@ -194,8 +194,8 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@PUT @PUT
@Path(EntityPath.CONSISTS_OF_PATH_PART + "/" + EntityPath.SOURCE_PATH_PART @Path(ERPath.CONSISTS_OF_PATH_PART + "/" + ERPath.SOURCE_PATH_PART
+ "/{" + SOURCE_ID_PATH_PARAM + "}/" + EntityPath.TARGET_PATH_PART + "/{" + SOURCE_ID_PATH_PARAM + "}/" + ERPath.TARGET_PATH_PART
+ "/{" + TARGET_ID_PATH_PARAM + "}/{" + TYPE_PATH_PARAM + "}") + "/{" + TARGET_ID_PATH_PARAM + "}/{" + TYPE_PATH_PARAM + "}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public String attachFacet( public String attachFacet(
@ -209,7 +209,7 @@ public class ERManager {
resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(), resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(),
type, json); type, json);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setRelationType(type); consistsOfManagement.setElementType(type);
consistsOfManagement.setJSON(json); consistsOfManagement.setJSON(json);
return consistsOfManagement.create(UUID.fromString(resourceUUID), return consistsOfManagement.create(UUID.fromString(resourceUUID),
UUID.fromString(facetUUID)); UUID.fromString(facetUUID));
@ -224,7 +224,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@DELETE @DELETE
@Path(EntityPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID)
throws ResourceRegistryException { throws ResourceRegistryException {
logger.info("requested to detach {}", consistOfUUID); logger.info("requested to detach {}", consistOfUUID);
@ -249,9 +249,9 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@PUT @PUT
@Path(EntityPath.IS_RELATED_TO_PATH_PART + "/" @Path(ERPath.IS_RELATED_TO_PATH_PART + "/"
+ EntityPath.SOURCE_PATH_PART + "/{" + SOURCE_ID_PATH_PARAM + "}/" + ERPath.SOURCE_PATH_PART + "/{" + SOURCE_ID_PATH_PARAM + "}/"
+ EntityPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}/{" + ERPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}/{"
+ TYPE_PATH_PARAM + "}") + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -267,7 +267,7 @@ public class ERManager {
json); json);
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setRelationType(type); isRelatedToManagement.setElementType(type);
isRelatedToManagement.setJSON(json); isRelatedToManagement.setJSON(json);
return isRelatedToManagement.create( return isRelatedToManagement.create(
@ -284,7 +284,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@DELETE @DELETE
@Path(EntityPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID)
throws ResourceRegistryException { throws ResourceRegistryException {
logger.info("requested to detach {}", relatedToUUID); logger.info("requested to detach {}", relatedToUUID);
@ -304,7 +304,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@POST @POST
@Path(EntityPath.ADD_PATH_PART + "/" + EntityPath.RESOURCE_PATH_PART + "/{" @Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{"
+ ID_PATH_PARAM + "}") + ID_PATH_PARAM + "}")
public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, ContextNotFoundException, throws ResourceNotFoundException, ContextNotFoundException,
@ -327,7 +327,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@POST @POST
@Path(EntityPath.ADD_PATH_PART + "/" + EntityPath.FACET_PATH_PART + "/{" @Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{"
+ ID_PATH_PARAM + "}") + ID_PATH_PARAM + "}")
public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ContextNotFoundException, throws FacetNotFoundException, ContextNotFoundException,
@ -350,7 +350,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@POST @POST
@Path(EntityPath.REMOVE_PATH_PART + "/" + EntityPath.RESOURCE_PATH_PART + "/{" @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{"
+ ID_PATH_PARAM + "}") + ID_PATH_PARAM + "}")
public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, ContextNotFoundException, throws ResourceNotFoundException, ContextNotFoundException,
@ -373,7 +373,7 @@ public class ERManager {
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
@POST @POST
@Path(EntityPath.REMOVE_PATH_PART + "/" + EntityPath.FACET_PATH_PART + "/{" @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{"
+ ID_PATH_PARAM + "}") + ID_PATH_PARAM + "}")
public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ContextNotFoundException, throws FacetNotFoundException, ContextNotFoundException,

View File

@ -28,8 +28,6 @@ public class SchemaManager {
private static Logger logger = LoggerFactory.getLogger(SchemaManager.class); private static Logger logger = LoggerFactory.getLogger(SchemaManager.class);
protected SchemaManagement schemaManager = new SchemaManagementImpl();
/** /**
* e.g. PUT /resource-registry/schema/embedded * e.g. PUT /resource-registry/schema/embedded
* *
@ -49,7 +47,8 @@ public class SchemaManager {
throws SchemaException { throws SchemaException {
logger.trace("Requested {} registration with schema {}", Embedded.NAME, logger.trace("Requested {} registration with schema {}", Embedded.NAME,
jsonSchema); jsonSchema);
return schemaManager.registerEmbeddedTypeSchema(jsonSchema); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.registerEmbeddedTypeSchema(jsonSchema);
} }
/** /**
@ -68,7 +67,8 @@ public class SchemaManager {
public String registerFacetSchema(String jsonSchema) throws SchemaException { public String registerFacetSchema(String jsonSchema) throws SchemaException {
logger.trace("Requested {} registration with schema {}", Facet.NAME, logger.trace("Requested {} registration with schema {}", Facet.NAME,
jsonSchema); jsonSchema);
return schemaManager.registerFacetSchema(jsonSchema); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.createFacetSchema(jsonSchema);
} }
/** /**
@ -89,7 +89,8 @@ public class SchemaManager {
throws SchemaException { throws SchemaException {
logger.trace("Requested {} registration with schema {}", Resource.NAME, logger.trace("Requested {} registration with schema {}", Resource.NAME,
jsonSchema); jsonSchema);
return schemaManager.registerResourceSchema(jsonSchema); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.registerResourceSchema(jsonSchema);
} }
/** /**
@ -109,7 +110,8 @@ public class SchemaManager {
throws SchemaException { throws SchemaException {
logger.trace("Requested {} registration with schema {} ", logger.trace("Requested {} registration with schema {} ",
ConsistsOf.NAME, jsonSchema); ConsistsOf.NAME, jsonSchema);
return schemaManager.registerConsistsOfSchema(jsonSchema); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.registerConsistsOfSchema(jsonSchema);
} }
/** /**
@ -129,10 +131,8 @@ public class SchemaManager {
throws SchemaException { throws SchemaException {
logger.trace("Requested {} registration with schema {} ", logger.trace("Requested {} registration with schema {} ",
IsRelatedTo.NAME, jsonSchema); IsRelatedTo.NAME, jsonSchema);
return schemaManager.registerIsRelatedToSchema(jsonSchema); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.registerIsRelatedToSchema(jsonSchema);
} }
} }

View File

@ -0,0 +1,12 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.schema;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class EntitySchemaManagement {
}

View File

@ -12,85 +12,76 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
*/ */
public interface SchemaManagement { public interface SchemaManagement {
public String registerEntitySchema(String jsonSchema) throws SchemaException; /*
public String create(String json) throws SchemaException;
public String getEntitySchema(String entityType) throws SchemaNotFoundException; public String read(String type, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String update(String type, String json) throws SchemaNotFoundException, SchemaException;
public String delete(String type) throws SchemaNotFoundException;
*/
public String createEntitySchema(String jsonSchema) throws SchemaException;
public String readEntitySchema(String entityType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String updateEntitySchema(String entityType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateEntitySchema(String entityType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteEntitySchema(String entityType) throws SchemaNotFoundException; public String deleteEntitySchema(String entityType) throws SchemaNotFoundException;
public String getEntityTypes(String entityType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String createFacetSchema(String jsonSchema) throws SchemaException;
public String registerFacetSchema(String jsonSchema) throws SchemaException; public String readFacetSchema(String facetType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String getFacetSchema(String facetType) throws SchemaNotFoundException;
public String updateFacetSchema(String facetType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateFacetSchema(String facetType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteFacetSchema(String facetType) throws SchemaNotFoundException; public String deleteFacetSchema(String facetType) throws SchemaNotFoundException;
public String getFacetTypes(String facetType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String registerResourceSchema(String jsonSchema) throws SchemaException; public String registerResourceSchema(String jsonSchema) throws SchemaException;
public String getResourceSchema(String resourceType) throws SchemaNotFoundException; public String getResourceSchema(String resourceType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String updateResourceSchema(String resourceType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateResourceSchema(String resourceType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteResourceSchema(String resourceType) throws SchemaNotFoundException; public String deleteResourceSchema(String resourceType) throws SchemaNotFoundException;
public String getResourceTypes(String resourceType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String registerEmbeddedTypeSchema(String jsonSchema) throws SchemaException; public String registerEmbeddedTypeSchema(String jsonSchema) throws SchemaException;
public String getEmbeddedTypeSchema(String embeddedType) throws SchemaNotFoundException; public String getEmbeddedTypeSchema(String embeddedType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String updateEmbeddedTypeSchema(String embeddedType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateEmbeddedTypeSchema(String embeddedType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteEmbeddedTypeSchema(String embeddedType) throws SchemaNotFoundException; public String deleteEmbeddedTypeSchema(String embeddedType) throws SchemaNotFoundException;
public String getEmbeddedTypes(String embeddedType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String registerRelationSchema(String jsonSchema) throws SchemaException; public String registerRelationSchema(String jsonSchema) throws SchemaException;
public String getRelationSchema(String relationType) throws SchemaNotFoundException; public String getRelationSchema(String relationType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String updateRelationSchema(String relationType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateRelationSchema(String relationType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteRelationSchema(String relationType) throws SchemaNotFoundException; public String deleteRelationSchema(String relationType) throws SchemaNotFoundException;
public String getRelationTypes(String relationType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String registerConsistsOfSchema(String jsonSchema) throws SchemaException; public String registerConsistsOfSchema(String jsonSchema) throws SchemaException;
public String getConsistsOfSchema(String consistsOfType) throws SchemaNotFoundException; public String getConsistsOfSchema(String consistsOfType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String updateConsistsOfSchema(String consistsOfType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateConsistsOfSchema(String consistsOfType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteConsistsOfSchema(String consistsOfType) throws SchemaException; public String deleteConsistsOfSchema(String consistsOfType) throws SchemaException;
public String getConsistsOfTypes(String consistsOfType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String registerIsRelatedToSchema(String jsonSchema) throws SchemaException; public String registerIsRelatedToSchema(String jsonSchema) throws SchemaException;
public String getIsRelatedToSchema(String isRelatedToType) throws SchemaNotFoundException; public String getIsRelatedToSchema(String isRelatedToType, boolean includeSubtypes, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
public String updateIsRelatedToSchema(String isRelatedToType, String jsonSchema) throws SchemaNotFoundException, SchemaException; public String updateIsRelatedToSchema(String isRelatedToType, String jsonSchema) throws SchemaNotFoundException, SchemaException;
public String deleteIsRelatedToSchema(String isRelatedToType) throws SchemaException; public String deleteIsRelatedToSchema(String isRelatedToType) throws SchemaException;
public String getIsRelatedToTypes(String isRelatedToType, boolean includeSchema) throws SchemaNotFoundException, SchemaException;
} }

View File

@ -22,6 +22,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder;
import org.gcube.informationsystem.types.TypeBinder.Property; import org.gcube.informationsystem.types.TypeBinder.Property;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -62,26 +63,34 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph,
String type, String baseType) throws SchemaNotFoundException { String type, String baseType) throws SchemaException {
OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema();
return getTypeSchema(oSchema, type, baseType);
}
public static OClass getTypeSchema(OSchema oSchema, String type,
String baseType) throws SchemaException {
try { try {
OClass oClass = getEntityOClass(orientBaseGraph, type); OClass oClass = oSchema.getClass(type);
if (baseType != null) { if (oClass == null) {
if (baseType.compareTo(Embedded.NAME) != 0 throw new SchemaNotFoundException(type + "was not registered");
&& !oClass.isSubClassOf(baseType)) { }
throw new SchemaException("The requested type is not a " if (baseType != null && type.compareTo(baseType) != 0) {
+ baseType); if (!oClass.isSubClassOf(baseType)) {
throw new SchemaException(type + " is not a " + baseType);
} }
} }
return oClass; return oClass;
} catch (SchemaNotFoundException snfe) { } catch (SchemaNotFoundException snfe) {
throw snfe; throw snfe;
} catch (Exception e) { } catch (Exception e) {
throw new SchemaNotFoundException(e.getMessage()); throw new SchemaException(e.getMessage());
} }
} }
public static OClass getTypeSchema(String type, String baseType) public static OClass getTypeSchema(String type, String baseType)
throws SchemaNotFoundException { throws SchemaException {
OrientGraphFactory orientGraphFactory = SecurityContextMapper OrientGraphFactory orientGraphFactory = SecurityContextMapper
.getSecurityContextFactory( .getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
@ -103,11 +112,32 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
} }
protected static TypeDefinition getTypeDefinition(OClass oClass)
throws SchemaException {
String json = serializeOClass(oClass);
try {
return TypeBinder.deserializeTypeDefinition(json);
} catch (Exception e) {
throw new SchemaException(e);
}
}
protected static String getTypeDefinitionAsString(OClass oClass)
throws SchemaException {
try {
TypeDefinition typeDefinition = getTypeDefinition(oClass);
return TypeBinder.serializeType(typeDefinition);
} catch (Exception e) {
throw new SchemaException(e);
}
}
protected static JSONObject serializeOClassAsJSON(OClass oClass) protected static JSONObject serializeOClassAsJSON(OClass oClass)
throws SchemaException { throws SchemaException {
String jsonString = serializeOClass(oClass); String json = serializeOClass(oClass);
try { try {
return new JSONObject(jsonString); return new JSONObject(json);
} catch (JSONException e) { } catch (JSONException e) {
throw new SchemaException(e); throw new SchemaException(e);
} }
@ -205,14 +235,13 @@ public class SchemaManagementImpl implements SchemaManagement {
typeDefinition.getName()); typeDefinition.getName());
} }
if(typeDefinition.getName().compareTo(Embedded.NAME)!=0){ if (typeDefinition.getName().compareTo(Embedded.NAME) != 0) {
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy( List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(
orientGraphNoTx, orientGraphNoTx, typeDefinition,
typeDefinition,
baseType.getSimpleName()); baseType.getSimpleName());
oClass.setSuperClasses(oSuperclasses); oClass.setSuperClasses(oSuperclasses);
} }
if (Resource.class.isAssignableFrom(baseType)) { if (Resource.class.isAssignableFrom(baseType)) {
Set<Property> properties = typeDefinition.getProperties(); Set<Property> properties = typeDefinition.getProperties();
if (properties != null && properties.size() > 0) { if (properties != null && properties.size() > 0) {
@ -281,9 +310,9 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
} }
protected String getListOfType(String type, String baseType, protected String getSchema(String type, String baseType,
boolean includeSchema) throws SchemaNotFoundException, boolean includeSubtypes, boolean includeSchema)
SchemaException { throws SchemaNotFoundException, SchemaException {
OrientGraphFactory orientGraphFactory = SecurityContextMapper OrientGraphFactory orientGraphFactory = SecurityContextMapper
.getSecurityContextFactory( .getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
@ -292,24 +321,34 @@ public class SchemaManagementImpl implements SchemaManagement {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
orientGraphNoTx = orientGraphFactory.getNoTx(); orientGraphNoTx = orientGraphFactory.getNoTx();
JSONArray jsonArray = new JSONArray();
OClass baseOClass = getTypeSchema(orientGraphNoTx, type, baseType);
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
Collection<OClass> oClasses = oSchema.getClasses(); OClass baseOClass = getTypeSchema(oSchema, type, baseType);
for (OClass oClass : oClasses) {
if (oClass.isSubClassOf(baseOClass)) { String ret = null;
if (includeSchema) { if (includeSubtypes) {
jsonArray.put(serializeOClassAsJSON(oClass)); JSONArray jsonArray = new JSONArray();
} else { Collection<OClass> oClasses = oSchema.getClasses();
jsonArray.put(oClass.getName()); for (OClass oClass : oClasses) {
if (oClass.isSubClassOf(baseOClass)) {
if (includeSchema) {
jsonArray.put(getTypeDefinitionAsString(oClass));
} else {
jsonArray.put(oClass.getName());
}
} }
} }
ret = jsonArray.toString();
} else {
if (includeSchema) {
ret = getTypeDefinitionAsString(baseOClass);
} else {
ret = baseOClass.getName();
}
} }
return jsonArray.toString(); return ret;
} catch (SchemaException e) { } catch (SchemaException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
@ -323,15 +362,16 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String registerEntitySchema(String jsonSchema) public String createEntitySchema(String jsonSchema) throws SchemaException {
throws SchemaException {
return registerTypeSchema(jsonSchema, Entity.class); return registerTypeSchema(jsonSchema, Entity.class);
} }
@Override @Override
public String getEntitySchema(String entityType) public String readEntitySchema(String entityType, boolean includeSubtypes,
throws SchemaNotFoundException { boolean includeSchema) throws SchemaNotFoundException,
return getTypeSchemaAsString(entityType, Entity.NAME); SchemaException {
return getSchema(entityType, Entity.NAME, includeSubtypes,
includeSchema);
} }
@Override @Override
@ -347,20 +387,15 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String getEntityTypes(String baseEntityType, boolean includeSchema) public String createFacetSchema(String jsonSchema) throws SchemaException {
throws SchemaNotFoundException, SchemaException {
return getListOfType(baseEntityType, Entity.NAME, includeSchema);
}
@Override
public String registerFacetSchema(String jsonSchema) throws SchemaException {
return registerTypeSchema(jsonSchema, Facet.class); return registerTypeSchema(jsonSchema, Facet.class);
} }
@Override @Override
public String getFacetSchema(String facetType) public String readFacetSchema(String facetType, boolean includeSubtypes,
throws SchemaNotFoundException { boolean includeSchema) throws SchemaNotFoundException,
return getTypeSchemaAsString(facetType, Facet.NAME); SchemaException {
return getSchema(facetType, Facet.NAME, includeSubtypes, includeSchema);
} }
@Override @Override
@ -375,12 +410,6 @@ public class SchemaManagementImpl implements SchemaManagement {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override
public String getFacetTypes(String baseFacetType, boolean includeSchema)
throws SchemaNotFoundException, SchemaException {
return getListOfType(baseFacetType, Facet.NAME, includeSchema);
}
@Override @Override
public String registerResourceSchema(String jsonSchema) public String registerResourceSchema(String jsonSchema)
throws SchemaException { throws SchemaException {
@ -388,9 +417,11 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String getResourceSchema(String resourceType) public String getResourceSchema(String resourceType,
throws SchemaNotFoundException { boolean includeSubtypes, boolean includeSchema)
return getTypeSchemaAsString(resourceType, Resource.NAME); throws SchemaNotFoundException, SchemaException {
return getSchema(resourceType, Resource.NAME, includeSubtypes,
includeSchema);
} }
@Override @Override
@ -405,12 +436,6 @@ public class SchemaManagementImpl implements SchemaManagement {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override
public String getResourceTypes(String baseResourceType, boolean includeSchema)
throws SchemaNotFoundException, SchemaException {
return getListOfType(baseResourceType, Resource.NAME, includeSchema);
}
@Override @Override
public String registerEmbeddedTypeSchema(String jsonSchema) public String registerEmbeddedTypeSchema(String jsonSchema)
throws SchemaException { throws SchemaException {
@ -418,9 +443,11 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String getEmbeddedTypeSchema(String embeddedType) public String getEmbeddedTypeSchema(String embeddedType,
throws SchemaNotFoundException { boolean includeSubtypes, boolean includeSchema)
return getTypeSchemaAsString(embeddedType, null); throws SchemaNotFoundException, SchemaException {
return getSchema(embeddedType, Embedded.NAME, includeSubtypes,
includeSchema);
} }
@Override @Override
@ -435,12 +462,6 @@ public class SchemaManagementImpl implements SchemaManagement {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override
public String getEmbeddedTypes(String embeddedType, boolean includeSchema)
throws SchemaNotFoundException, SchemaException {
return getListOfType(embeddedType, Embedded.NAME, includeSchema);
}
@Override @Override
public String registerRelationSchema(String jsonSchema) public String registerRelationSchema(String jsonSchema)
throws SchemaException { throws SchemaException {
@ -448,9 +469,11 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String getRelationSchema(String relationType) public String getRelationSchema(String relationType,
throws SchemaNotFoundException { boolean includeSubtypes, boolean includeSchema)
return getTypeSchemaAsString(relationType, Relation.NAME); throws SchemaNotFoundException, SchemaException {
return getSchema(relationType, Relation.NAME, includeSubtypes,
includeSchema);
} }
@Override @Override
@ -465,12 +488,6 @@ public class SchemaManagementImpl implements SchemaManagement {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override
public String getRelationTypes(String baseRelationType, boolean includeSchema)
throws SchemaNotFoundException, SchemaException {
return getListOfType(baseRelationType, Relation.NAME, includeSchema);
}
@Override @Override
public String registerConsistsOfSchema(String jsonSchema) public String registerConsistsOfSchema(String jsonSchema)
throws SchemaException { throws SchemaException {
@ -478,14 +495,16 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String getConsistsOfSchema(String consistsOfType) public String getConsistsOfSchema(String consistsOfType,
throws SchemaNotFoundException { boolean includeSubtypes, boolean includeSchema)
return getTypeSchemaAsString(consistsOfType, ConsistsOf.NAME); throws SchemaNotFoundException, SchemaException {
return getSchema(consistsOfType, ConsistsOf.NAME, includeSubtypes,
includeSchema);
} }
@Override @Override
public String updateConsistsOfSchema(String consistsOfType, String jsonSchema) public String updateConsistsOfSchema(String consistsOfType,
throws SchemaNotFoundException, SchemaException { String jsonSchema) throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@ -495,13 +514,6 @@ public class SchemaManagementImpl implements SchemaManagement {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override
public String getConsistsOfTypes(String consistsOfType, boolean includeSchema)
throws SchemaNotFoundException, SchemaException {
return getListOfType(consistsOfType, ConsistsOf.NAME, includeSchema);
}
@Override @Override
public String registerIsRelatedToSchema(String jsonSchema) public String registerIsRelatedToSchema(String jsonSchema)
throws SchemaException { throws SchemaException {
@ -509,9 +521,11 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
@Override @Override
public String getIsRelatedToSchema(String isRelatedToType) public String getIsRelatedToSchema(String isRelatedToType,
throws SchemaNotFoundException { boolean includeSubtypes, boolean includeSchema)
return getTypeSchemaAsString(isRelatedToType, IsRelatedTo.NAME); throws SchemaNotFoundException, SchemaException {
return getSchema(isRelatedToType, IsRelatedTo.NAME, includeSubtypes,
includeSchema);
} }
@Override @Override
@ -525,11 +539,5 @@ public class SchemaManagementImpl implements SchemaManagement {
throws SchemaException { throws SchemaException {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override
public String getIsRelatedToTypes(String isRelatedToType, boolean includeSchema)
throws SchemaNotFoundException, SchemaException {
return getListOfType(isRelatedToType, IsRelatedTo.NAME, includeSchema);
}
} }

View File

@ -72,7 +72,7 @@ public class MultiContextTest extends ScopedTest {
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setJSON(Entities.marshal(cpuFacet)); facetManagement.setJSON(Entities.marshal(cpuFacet));
facetManagement.setEntityType(CPUFacet.NAME); facetManagement.setElementType(CPUFacet.NAME);
String json = facetManagement.create(); String json = facetManagement.create();
logger.debug("Created : {}", json); logger.debug("Created : {}", json);
@ -187,7 +187,7 @@ public class MultiContextTest extends ScopedTest {
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME); resourceManagement.setElementType(EService.NAME);
resourceManagement.setJSON(Entities.marshal(eService)); resourceManagement.setJSON(Entities.marshal(eService));
String json = resourceManagement.create(); String json = resourceManagement.create();
@ -238,7 +238,7 @@ public class MultiContextTest extends ScopedTest {
hostingNode.attachResource(hosts); hostingNode.attachResource(hosts);
resourceManagement = new ResourceManagement(); resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME); resourceManagement.setElementType(HostingNode.NAME);
resourceManagement.setJSON(Entities.marshal(hostingNode)); resourceManagement.setJSON(Entities.marshal(hostingNode));
String hnJson = resourceManagement.create(); String hnJson = resourceManagement.create();

View File

@ -94,7 +94,7 @@ public class ERManagementTest extends ScopedTest {
eService.addFacet(licenseFacet); eService.addFacet(licenseFacet);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME); resourceManagement.setElementType(EService.NAME);
resourceManagement.setJSON(Entities.marshal(eService)); resourceManagement.setJSON(Entities.marshal(eService));
String json = resourceManagement.create(); String json = resourceManagement.create();
@ -128,7 +128,7 @@ public class ERManagementTest extends ScopedTest {
cpuFacet.setVendor("AMD"); cpuFacet.setVendor("AMD");
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setEntityType(CPUFacet.NAME); facetManagement.setElementType(CPUFacet.NAME);
facetManagement.setJSON(Entities.marshal(cpuFacet)); facetManagement.setJSON(Entities.marshal(cpuFacet));
String cpuFacetJson = facetManagement.create(); String cpuFacetJson = facetManagement.create();
@ -235,7 +235,7 @@ public class ERManagementTest extends ScopedTest {
eService.addFacet(isIdentifiedBy); eService.addFacet(isIdentifiedBy);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME); resourceManagement.setElementType(EService.NAME);
resourceManagement.setJSON(Entities.marshal(eService)); resourceManagement.setJSON(Entities.marshal(eService));
String json = resourceManagement.create(); String json = resourceManagement.create();
@ -253,7 +253,7 @@ public class ERManagementTest extends ScopedTest {
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setJSON(Entities.marshal(networkingFacet)); facetManagement.setJSON(Entities.marshal(networkingFacet));
facetManagement.setEntityType(NetworkingFacet.NAME); facetManagement.setElementType(NetworkingFacet.NAME);
json = facetManagement.create(); json = facetManagement.create();
logger.debug("Created : {}", json); logger.debug("Created : {}", json);
@ -282,7 +282,7 @@ public class ERManagementTest extends ScopedTest {
hostingNode.attachResource(hosts); hostingNode.attachResource(hosts);
resourceManagement = new ResourceManagement(); resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME); resourceManagement.setElementType(HostingNode.NAME);
resourceManagement.setJSON(Entities.marshal(hostingNode)); resourceManagement.setJSON(Entities.marshal(hostingNode));
json = resourceManagement.create(); json = resourceManagement.create();
@ -321,7 +321,7 @@ public class ERManagementTest extends ScopedTest {
Facet shared = hostingNode.getConsistsOf().get(0).getTarget(); Facet shared = hostingNode.getConsistsOf().get(0).getTarget();
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setRelationType(ConsistsOf.NAME); consistsOfManagement.setElementType(ConsistsOf.NAME);
consistsOfManagement.setJSON("{}"); consistsOfManagement.setJSON("{}");
UUID eServiceUUID = eService.getHeader().getUUID(); UUID eServiceUUID = eService.getHeader().getUUID();
@ -354,7 +354,7 @@ public class ERManagementTest extends ScopedTest {
@Test @Test
public void testCreateResourceAndFacet() throws Exception { public void testCreateResourceAndFacet() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME); resourceManagement.setElementType(HostingNode.NAME);
resourceManagement.setJSON("{}"); resourceManagement.setJSON("{}");
String json = resourceManagement.create(); String json = resourceManagement.create();
@ -367,14 +367,14 @@ public class ERManagementTest extends ScopedTest {
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setJSON(Entities.marshal(cpuFacet)); facetManagement.setJSON(Entities.marshal(cpuFacet));
facetManagement.setEntityType(CPUFacet.NAME); facetManagement.setElementType(CPUFacet.NAME);
json = facetManagement.create(); json = facetManagement.create();
logger.debug("Created : {}", json); logger.debug("Created : {}", json);
UUID facetUUID = Utility.getUUIDFromJSONString(json); UUID facetUUID = Utility.getUUIDFromJSONString(json);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setRelationType(ConsistsOf.NAME); consistsOfManagement.setElementType(ConsistsOf.NAME);
consistsOfManagement.setJSON("{}"); consistsOfManagement.setJSON("{}");
json = consistsOfManagement.create(resourceUUID, facetUUID); json = consistsOfManagement.create(resourceUUID, facetUUID);

View File

@ -85,7 +85,7 @@ public class SmartgearResourcesTest extends ScopedTest {
logger.debug("{}", hostingNode); logger.debug("{}", hostingNode);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME); resourceManagement.setElementType(HostingNode.NAME);
resourceManagement.setJSON(HOSTING_NODE); resourceManagement.setJSON(HOSTING_NODE);
String hnJson = resourceManagement.create(); String hnJson = resourceManagement.create();
@ -116,7 +116,7 @@ public class SmartgearResourcesTest extends ScopedTest {
logger.debug("{}", eService); logger.debug("{}", eService);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME); resourceManagement.setElementType(EService.NAME);
resourceManagement.setJSON(ESERVICE); resourceManagement.setJSON(ESERVICE);
String json = resourceManagement.create(); String json = resourceManagement.create();
@ -219,7 +219,7 @@ public class SmartgearResourcesTest extends ScopedTest {
hostingNode.addFacet(hasPersistentMemory); hostingNode.addFacet(hasPersistentMemory);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME); resourceManagement.setElementType(HostingNode.NAME);
resourceManagement.setJSON(Entities.marshal(hostingNode)); resourceManagement.setJSON(Entities.marshal(hostingNode));
String json = resourceManagement.create(); String json = resourceManagement.create();

View File

@ -45,7 +45,7 @@ public class SchemaManagementImplTest {
@Test @Test
public void getEmbeddedTypeSchema() throws Exception{ public void getEmbeddedTypeSchema() throws Exception{
String json = new SchemaManagementImpl().getEmbeddedTypeSchema(AccessPolicy.NAME); String json = new SchemaManagementImpl().getEmbeddedTypeSchema(AccessPolicy.NAME, false, true);
logger.trace(json); logger.trace(json);
} }
@ -60,10 +60,10 @@ public class SchemaManagementImplTest {
@Test @Test
public void getFacetSchema() throws Exception{ public void getFacetSchema() throws Exception{
String json = new SchemaManagementImpl().getFacetSchema(ContactFacet.NAME); String json = new SchemaManagementImpl().readFacetSchema(ContactFacet.NAME, false, true);
logger.trace(json); logger.info(json);
TypeDefinition typeDefinition = TypeBinder.deserializeTypeDefinition(json); TypeDefinition typeDefinition = TypeBinder.deserializeTypeDefinition(json);
logger.trace(typeDefinition.toString()); logger.info(typeDefinition.toString());
} }
@Test @Test
@ -84,7 +84,7 @@ public class SchemaManagementImplTest {
@Test @Test
public void getResourceSchema() throws Exception{ public void getResourceSchema() throws Exception{
String json = new SchemaManagementImpl().getResourceSchema(Actor.NAME); String json = new SchemaManagementImpl().getResourceSchema(Actor.NAME, false, true);
logger.trace(json); logger.trace(json);
} }
@ -102,10 +102,12 @@ public class SchemaManagementImplTest {
public void getList() throws Exception{ public void getList() throws Exception{
logger.debug("\n\n\n"); logger.debug("\n\n\n");
boolean includeSubTypes = true;
boolean includeSchema = true; boolean includeSchema = true;
SchemaManagement schemaManagement = new SchemaManagementImpl(); SchemaManagement schemaManagement = new SchemaManagementImpl();
String list = schemaManagement.getEmbeddedTypes(Embedded.NAME, includeSchema); String list = schemaManagement.getEmbeddedTypeSchema(Embedded.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", Embedded.NAME, list); logger.debug("{} list : {}", Embedded.NAME, list);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@ -114,24 +116,24 @@ public class SchemaManagementImplTest {
list = schemaManagement.getEntityTypes(Entity.NAME, includeSchema); list = schemaManagement.readEntitySchema(Entity.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", Entity.NAME, list); logger.debug("{} list : {}", Entity.NAME, list);
list = schemaManagement.getResourceTypes(Resource.NAME, includeSchema); list = schemaManagement.getResourceSchema(Resource.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", Resource.NAME, list); logger.debug("{} list : {}", Resource.NAME, list);
list = schemaManagement.getFacetTypes(Facet.NAME, includeSchema); list = schemaManagement.readFacetSchema(Facet.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", Facet.NAME, list); logger.debug("{} list : {}", Facet.NAME, list);
list = schemaManagement.getRelationTypes(Relation.NAME, includeSchema); list = schemaManagement.getRelationSchema(Relation.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", Relation.NAME, list); logger.debug("{} list : {}", Relation.NAME, list);
list = schemaManagement.getConsistsOfTypes(ConsistsOf.NAME, includeSchema); list = schemaManagement.getConsistsOfSchema(ConsistsOf.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", ConsistsOf.NAME, list); logger.debug("{} list : {}", ConsistsOf.NAME, list);
list = schemaManagement.getIsRelatedToTypes(IsRelatedTo.NAME, includeSchema); list = schemaManagement.getIsRelatedToSchema(IsRelatedTo.NAME, includeSubTypes, includeSchema);
logger.debug("{} list : {}", IsRelatedTo.NAME, list); logger.debug("{} list : {}", IsRelatedTo.NAME, list);
} }