Refs #10238: Refactor Context Port Type

Task-Url: https://support.d4science.org/issues/10238

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@158614 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2017-11-17 14:59:25 +00:00
parent bcf1621866
commit 6edb78bdfd
11 changed files with 450 additions and 424 deletions

View File

@ -1,11 +1,14 @@
package org.gcube.informationsystem.resourceregistry.context; package org.gcube.informationsystem.resourceregistry.context;
import java.io.StringWriter;
import java.util.Iterator; import java.util.Iterator;
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.AccessType; import org.gcube.informationsystem.model.AccessType;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Context; import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.model.relation.Relation; 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.ContextAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException;
@ -20,6 +23,7 @@ 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.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
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;
@ -46,6 +50,10 @@ public class ContextManagement extends EntityManagement<Context> {
init(); init();
} }
public String getName() {
return jsonNode.get(Context.NAME_PROPERTY).asText();
}
@Override @Override
protected ContextNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { protected ContextNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) {
return new ContextNotFoundException(e.getMessage(), e.getCause()); return new ContextNotFoundException(e.getMessage(), e.getCause());
@ -61,6 +69,61 @@ public class ContextManagement extends EntityManagement<Context> {
return new ContextAlreadyPresentException(message); return new ContextAlreadyPresentException(message);
} }
protected void checkContext(ContextManagement parentContext, ContextManagement childContext) throws ContextNotFoundException,
ContextAlreadyPresentException, ResourceRegistryException {
if (parentContext != null) {
String parentId = parentContext.getElement().getId().toString();
// TODO Rewrite using Gremlin
String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME
+ ") FROM " + parentId + " MAXDEPTH 1) WHERE "
+ Context.NAME_PROPERTY + "=\"" + childContext.getName() + "\" AND "
+ Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ "<>\"" + parentContext.toString() + "\"";
logger.trace(select);
StringWriter message = new StringWriter();
message.append("A context with the same name (");
message.append(childContext.getName());
message.append(") has been already created as child of ");
message.append(parentContext.serializeSelfOnly().toString());
logger.trace("Checking if {} -> {}", message, select);
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(
select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery)
.execute();
if (vertexes != null && vertexes.iterator().hasNext()) {
throw new ContextAlreadyPresentException(message.toString());
}
} else {
// TODO Rewrite using Gremlin
String select = "SELECT FROM "
+ org.gcube.informationsystem.model.entity.Context.NAME
+ " WHERE " + Context.NAME_PROPERTY + " = \"" + childContext.getName()
+ "\"" + " AND in(\"" + IsParentOf.NAME + "\").size() = 0";
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(
select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery)
.execute();
if (vertexes != null && vertexes.iterator().hasNext()) {
throw new ContextAlreadyPresentException(
"A root context with the same name (" + childContext.getName()
+ ") already exist");
}
}
}
@Override @Override
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString(); return serializeAsJson().toString();
@ -111,6 +174,9 @@ public class ContextManagement extends EntityManagement<Context> {
@Override @Override
protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException {
createVertex(); createVertex();
String propertyName = Context.PARENT_PROPERTY; String propertyName = Context.PARENT_PROPERTY;
@ -139,6 +205,7 @@ public class ContextManagement extends EntityManagement<Context> {
// TODO check if parent changed // TODO check if parent changed
// TODO check if name changes and check the feasibility
context = (Vertex) ERManagement.updateProperties(oClass, context, jsonNode, ignoreKeys, ignoreStartWithKeys); context = (Vertex) ERManagement.updateProperties(oClass, context, jsonNode, ignoreKeys, ignoreStartWithKeys);
return context; return context;

View File

@ -199,7 +199,7 @@ public class ContextUtility {
ScopeBean scopeBean = new ScopeBean(fullName); ScopeBean scopeBean = new ScopeBean(fullName);
String name = scopeBean.name(); String name = scopeBean.name();
// TODO Rewrite the previous query using Gremlin // TODO Rewrite the query using Gremlin
// Please note that this query works because all the scope parts has a // Please note that this query works because all the scope parts has a
// different name // different name
String select = "SELECT FROM " + Context.class.getSimpleName() String select = "SELECT FROM " + Context.class.getSimpleName()

View File

@ -3,8 +3,6 @@
*/ */
package org.gcube.informationsystem.resourceregistry.context; package org.gcube.informationsystem.resourceregistry.context;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.AccessType;
import org.gcube.informationsystem.model.relation.IsParentOf; import org.gcube.informationsystem.model.relation.IsParentOf;
@ -96,17 +94,13 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
} }
@Override @Override
protected ContextManagement getSourceEntityManagement(UUID sourceUUID) throws ResourceRegistryException { protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement(orientGraph); return new ContextManagement(orientGraph);
contextManagement.setUUID(sourceUUID);
return contextManagement;
} }
@Override @Override
protected ContextManagement getTargetEntityManagement(UUID targetUUID) throws ResourceRegistryException { protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement(orientGraph); return new ContextManagement(orientGraph);
contextManagement.setUUID(targetUUID);
return contextManagement;
} }
} }

View File

@ -270,7 +270,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public El internalUpdate() throws ERNotFoundException, ResourceRegistryException { public El internalUpdate() throws ERNotFoundException, ResourceRegistryException {
try { try {
reallyUpdate(); reallyUpdate();
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientVertex) element).save(); ((OrientVertex) element).save();
@ -490,6 +492,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
try { try {
orientGraph = ContextUtility orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin); .getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
element = internalUpdate(); element = internalUpdate();
orientGraph.commit(); orientGraph.commit();

View File

@ -18,15 +18,22 @@ import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManag
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.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass;
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.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
public class ERManagementUtility { public class ERManagementUtility {
private static Logger logger = LoggerFactory.getLogger(EntityManagement.class);
/* /*
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static ERManagement getERManagement(AccessType querableType) public static ERManagement getERManagement(AccessType querableType)
@ -81,10 +88,10 @@ public class ERManagementUtility {
private static ERManagement getERManagement(OrientGraph orientGraph, private static ERManagement getERManagement(OrientGraph orientGraph,
Element element) throws ResourceRegistryException { Element element) throws ResourceRegistryException {
if (element instanceof Vertex) { if (element instanceof Vertex) {
return EntityManagement.getEntityManagement(orientGraph, return getEntityManagement(orientGraph,
(Vertex) element); (Vertex) element);
} else if (element instanceof Edge) { } else if (element instanceof Edge) {
return RelationManagement.getRelationManagement(orientGraph, return getRelationManagement(orientGraph,
(Edge) element); (Edge) element);
} }
throw new ResourceRegistryException(String.format( throw new ResourceRegistryException(String.format(
@ -131,4 +138,71 @@ public class ERManagementUtility {
} }
} }
@SuppressWarnings({ "rawtypes", "unchecked" })
public static EntityManagement getEntityManagement(OrientGraph orientGraph,
Vertex vertex) throws ResourceRegistryException {
if(orientGraph==null){
throw new ResourceRegistryException(OrientGraph.class.getSimpleName() + "instance is null. This is really strage please contact the administrator.");
}
if(vertex==null){
throw new ResourceRegistryException(Vertex.class.getSimpleName() + "instance is null. This is really strage please contact the administrator.");
}
OrientVertexType orientVertexType = null;
try {
orientVertexType = ((OrientVertex) vertex).getType();
}catch (Exception e) {
String error = String.format("Unable to detect type of %s. This is really strage please contact the administrator.", vertex.toString());
logger.error(error, e);
throw new ResourceRegistryException(error);
}
EntityManagement entityManagement = null;
if (orientVertexType.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(orientGraph);
} else if (orientVertexType.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange and should not occur. "
+ "Please Investigate it.", vertex, Resource.NAME,
Facet.NAME);
throw new ResourceRegistryException(error);
}
entityManagement.setElement(vertex);
return entityManagement;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static RelationManagement getRelationManagement(OrientGraph orientGraph, Edge edge)
throws ResourceRegistryException {
if (orientGraph == null) {
throw new ResourceRegistryException(OrientGraph.class.getSimpleName()
+ "instance is null. This is really strage please contact the administrator.");
}
if (edge == null) {
throw new ResourceRegistryException(Edge.class.getSimpleName()
+ "instance is null. This is really strage please contact the administrator.");
}
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(orientGraph);
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. " + "This is really strange ad should not occur. "
+ "Please Investigate it.", edge, ConsistsOf.NAME, IsRelatedTo.NAME);
throw new ResourceRegistryException(error);
}
relationManagement.setElement(edge);
return relationManagement;
}
} }

View File

@ -3,12 +3,13 @@
*/ */
package org.gcube.informationsystem.resourceregistry.er.entity; package org.gcube.informationsystem.resourceregistry.er.entity;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.AccessType;
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.Resource;
import org.gcube.informationsystem.model.relation.Relation; 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;
@ -20,8 +21,6 @@ import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
@ -29,7 +28,6 @@ import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex; import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -37,8 +35,13 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
public abstract class EntityManagement<E extends Entity> extends public abstract class EntityManagement<E extends Entity> extends
ERManagement<E, Vertex> { ERManagement<E, Vertex> {
private static Logger staticLogger = LoggerFactory /**
.getLogger(EntityManagement.class); * Provide a cache edge-internal-id -> RelationManagement
* this avoid to recreate the relationManagement of already visited
* edges
*/
@SuppressWarnings("rawtypes")
protected Map<String, RelationManagement> relationManagements;
protected EntityManagement(AccessType accessType) { protected EntityManagement(AccessType accessType) {
super(accessType); super(accessType);
@ -54,6 +57,18 @@ public abstract class EntityManagement<E extends Entity> extends
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
.toUpperCase()); .toUpperCase());
this.relationManagements = new HashMap<>();
}
@SuppressWarnings("rawtypes")
protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException {
String id = edge.getId().toString();
RelationManagement relationManagement = relationManagements.get(id);
if(relationManagement==null) {
relationManagement = RelationManagement.getRelationManagement(orientGraph, edge);
}
return relationManagement;
} }
protected EntityManagement(AccessType accessType, OrientGraph orientGraph) { protected EntityManagement(AccessType accessType, OrientGraph orientGraph) {
@ -167,8 +182,7 @@ public abstract class EntityManagement<E extends Entity> extends
for (Edge edge : edges) { for (Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = RelationManagement RelationManagement relationManagement = getRelationManagement(edge);
.getRelationManagement(orientGraph, edge);
relationManagement.internalAddToContext(); relationManagement.internalAddToContext();
} }
@ -185,50 +199,14 @@ public abstract class EntityManagement<E extends Entity> extends
for (Edge edge : edges) { for (Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = RelationManagement RelationManagement relationManagement = getRelationManagement(edge);
.getRelationManagement(orientGraph, edge);
relationManagement.internalRemoveFromContext(); relationManagement.internalRemoveFromContext();
} }
return true; return true;
} }
@SuppressWarnings({ "rawtypes", "unchecked" })
public static EntityManagement getEntityManagement(OrientGraph orientGraph,
Vertex vertex) throws ResourceRegistryException {
if(orientGraph==null){
throw new ResourceRegistryException(OrientGraph.class.getSimpleName() + "instance is null. This is really strage please contact the administrator.");
}
if(vertex==null){
throw new ResourceRegistryException(Vertex.class.getSimpleName() + "instance is null. This is really strage please contact the administrator.");
}
OrientVertexType orientVertexType = null;
try {
orientVertexType = ((OrientVertex) vertex).getType();
}catch (Exception e) {
String error = String.format("Unable to detect type of %s. This is really strage please contact the administrator.", vertex.toString());
staticLogger.error(error, e);
throw new ResourceRegistryException(error);
}
EntityManagement entityManagement = null;
if (orientVertexType.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(orientGraph);
} else if (orientVertexType.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange and should not occur. "
+ "Please Investigate it.", vertex, Resource.NAME,
Facet.NAME);
throw new ResourceRegistryException(error);
}
entityManagement.setElement(vertex);
return entityManagement;
}
@Override @Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
@ -236,7 +214,7 @@ public abstract class EntityManagement<E extends Entity> extends
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic); Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
for(Vertex vertex : iterable){ for(Vertex vertex : iterable){
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = getEntityManagement(orientGraph, vertex); EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex);
try { try {
JSONObject jsonObject = entityManagement.serializeAsJson(); JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);

View File

@ -20,6 +20,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
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;
@ -330,7 +331,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
Vertex vertex = (Vertex) element; Vertex vertex = (Vertex) element;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = EntityManagement.getEntityManagement(orientGraph, vertex); EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex);
try { try {
JSONObject jsonObject = entityManagement.serializeAsJson(); JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);

View File

@ -3,8 +3,6 @@
*/ */
package org.gcube.informationsystem.resourceregistry.er.relation; package org.gcube.informationsystem.resourceregistry.er.relation;
import java.util.UUID;
import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.AccessType;
import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
@ -48,17 +46,13 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf, Resourc
} }
@Override @Override
protected ResourceManagement getSourceEntityManagement(UUID sourceUUID) throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement(orientGraph); return new ResourceManagement(orientGraph);
resourceManagement.setUUID(sourceUUID);
return resourceManagement;
} }
@Override @Override
protected FacetManagement getTargetEntityManagement(UUID targetUUID) throws ResourceRegistryException { protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
FacetManagement facetManagement = new FacetManagement(orientGraph); return new FacetManagement(orientGraph);
facetManagement.setUUID(targetUUID);
return facetManagement;
} }
} }

View File

@ -3,8 +3,6 @@
*/ */
package org.gcube.informationsystem.resourceregistry.er.relation; package org.gcube.informationsystem.resourceregistry.er.relation;
import java.util.UUID;
import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.AccessType;
import org.gcube.informationsystem.model.relation.IsRelatedTo; import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
@ -47,17 +45,13 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, Resou
} }
@Override @Override
protected ResourceManagement getSourceEntityManagement(UUID sourceUUID) throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement(orientGraph); return new ResourceManagement(orientGraph);
resourceManagement.setUUID(sourceUUID);
return resourceManagement;
} }
@Override @Override
protected ResourceManagement getTargetEntityManagement(UUID targetUUID) throws ResourceRegistryException { protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement(orientGraph); return new ResourceManagement(orientGraph);
resourceManagement.setUUID(targetUUID);
return resourceManagement;
} }
} }

View File

@ -51,13 +51,13 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public abstract class RelationManagement<R extends Relation, S extends EntityManagement, T extends EntityManagement> extends public abstract class RelationManagement<R extends Relation, S extends EntityManagement, T extends EntityManagement>
ERManagement<R, Edge> { extends ERManagement<R, Edge> {
protected final Class<? extends Entity> targetEntityClass; protected final Class<? extends Entity> targetEntityClass;
protected S sourceEntityManagement; private S sourceEntityManagemen;
protected T targetEntityManagement; private T targetEntityManagemen;
protected RelationManagement(AccessType accessType) { protected RelationManagement(AccessType accessType) {
super(accessType); super(accessType);
@ -84,8 +84,8 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
break; break;
} }
sourceEntityManagement = null; sourceEntityManagemen = null;
targetEntityManagement = null; targetEntityManagemen = null;
} }
@ -94,6 +94,34 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
this.orientGraph = orientGraph; this.orientGraph = orientGraph;
} }
@SuppressWarnings("unchecked")
protected S getSourceEntityManagemen() throws ResourceRegistryException {
if (sourceEntityManagemen == null) {
Vertex source = getElement().getVertex(Direction.OUT);
sourceEntityManagemen = newSourceEntityManagement();
sourceEntityManagemen.setElement(source);
}
return sourceEntityManagemen;
}
@SuppressWarnings("unchecked")
public T getTargetEntityManagemen() throws ResourceRegistryException {
if (targetEntityManagemen == null) {
Vertex target = getElement().getVertex(Direction.IN);
targetEntityManagemen = newTargetEntityManagement();
targetEntityManagemen.setElement(target);
}
return targetEntityManagemen;
}
public void setSourceEntityManagement(S sourceEntityManagement) {
this.sourceEntityManagemen = sourceEntityManagement;
}
public void setTargetEntityManagement(T targetEntityManagement) {
this.targetEntityManagemen = targetEntityManagement;
}
@Override @Override
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString(); return serializeAsJson().toString();
@ -104,26 +132,16 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return serializeAsJson(true, true); return serializeAsJson(true, true);
} }
@SuppressWarnings("unchecked")
public JSONObject serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException { public JSONObject serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException {
JSONObject relation = serializeSelfOnly(); JSONObject relation = serializeSelfOnly();
try { try {
if (includeSource) { if (includeSource) {
if(sourceEntityManagement == null) { relation.put(Relation.SOURCE_PROPERTY, getSourceEntityManagemen().serializeSelfOnly());
Vertex source = element.getVertex(Direction.OUT);
sourceEntityManagement = (S) EntityManagement.getEntityManagement(orientGraph, source);
}
relation.put(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly());
} }
if (includeTarget) { if (includeTarget) {
if(targetEntityManagement == null) { relation.put(Relation.TARGET_PROPERTY, getTargetEntityManagemen().serializeAsJson());
Vertex target = element.getVertex(Direction.IN);
targetEntityManagement = (T) EntityManagement
.getEntityManagement(orientGraph, target);
}
relation.put(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson());
} }
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -137,8 +155,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return relation; return relation;
} }
protected Map<String, JSONObject> fullSerialize( protected Map<String, JSONObject> fullSerialize(Map<String, JSONObject> visitedSourceResources)
Map<String, JSONObject> visitedSourceResources)
throws ResourceRegistryException { throws ResourceRegistryException {
Vertex source = element.getVertex(Direction.OUT); Vertex source = element.getVertex(Direction.OUT);
@ -146,34 +163,30 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
JSONObject sourceResource = visitedSourceResources.get(id); JSONObject sourceResource = visitedSourceResources.get(id);
if (sourceResource == null) { if (sourceResource == null) {
ResourceManagement resourceManagement = (ResourceManagement) EntityManagement ResourceManagement resourceManagement = (ResourceManagement) ERManagementUtility
.getEntityManagement(orientGraph, source); .getEntityManagement(orientGraph, source);
if (this instanceof IsRelatedToManagement) { if (this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.serializeAsJson(); sourceResource = resourceManagement.serializeAsJson();
} else if (this instanceof ConsistsOfManagement) { } else if (this instanceof ConsistsOfManagement) {
sourceResource = resourceManagement.serializeSelfOnly(); sourceResource = resourceManagement.serializeSelfOnly();
} else { } else {
String error = String.format("{%s is not a %s nor a %s. " String error = String.format(
+ "This is really strange and should not occur. " "{%s is not a %s nor a %s. " + "This is really strange and should not occur. "
+ "Please Investigate it.", this, + "Please Investigate it.",
IsRelatedToManagement.class.getSimpleName(), this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName());
ConsistsOfManagement.class.getSimpleName());
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} }
if (this instanceof IsRelatedToManagement) { if (this instanceof IsRelatedToManagement) {
sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson());
serializeAsJson());
} else if (this instanceof ConsistsOfManagement) { } else if (this instanceof ConsistsOfManagement) {
sourceResource = ResourceManagement.addConsistsOf(sourceResource, sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson());
serializeAsJson());
} else { } else {
String error = String.format("{%s is not a %s nor a %s. " String error = String.format(
+ "This is really strange and should not occur. " "{%s is not a %s nor a %s. " + "This is really strange and should not occur. "
+ "Please Investigate it.", this, + "Please Investigate it.",
IsRelatedToManagement.class.getSimpleName(), this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName());
ConsistsOfManagement.class.getSimpleName());
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
@ -185,118 +198,103 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@Override @Override
protected Edge reallyCreate() throws ResourceRegistryException { protected Edge reallyCreate() throws ResourceRegistryException {
if(sourceEntityManagement==null) { if (sourceEntityManagemen == null) {
if (!jsonNode.has(Relation.SOURCE_PROPERTY)) { if (!jsonNode.has(Relation.SOURCE_PROPERTY)) {
throw new ResourceRegistryException( throw new ResourceRegistryException("Error while creating relation. No source definition found");
"Error while creating relation. No source definition found");
} }
UUID sourceUUID = org.gcube.informationsystem.impl.utils.Utility UUID sourceUUID = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY)); .getUUIDFromJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY));
setSourceUUID(sourceUUID); sourceEntityManagemen = newSourceEntityManagement();
sourceEntityManagemen.setUUID(sourceUUID);
} }
if(targetEntityManagement == null) { if (targetEntityManagemen == null) {
targetEntityManagement = getTargetEntityManagement(); targetEntityManagemen = newTargetEntityManagement();
if (!jsonNode.has(Relation.TARGET_PROPERTY)) { if (!jsonNode.has(Relation.TARGET_PROPERTY)) {
throw new ResourceRegistryException( throw new ResourceRegistryException("Error while creating " + erType + ". No target definition found");
"Error while creating " + erType + ". No target definition found");
} }
try { try {
targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY)); targetEntityManagemen.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
} catch (SchemaException e) { } catch (SchemaException e) {
StringWriter errorMessage = new StringWriter(); StringWriter errorMessage = new StringWriter();
errorMessage.append("A "); errorMessage.append("A ");
errorMessage.append(erType); errorMessage.append(erType);
errorMessage.append(" can be only created beetween "); errorMessage.append(" can be only created beetween ");
errorMessage.append(sourceEntityManagement.getAccessType().getName()); errorMessage.append(sourceEntityManagemen.getAccessType().getName());
errorMessage.append(" and "); errorMessage.append(" and ");
errorMessage.append(targetEntityManagement.getAccessType().getName()); errorMessage.append(targetEntityManagemen.getAccessType().getName());
throw new ResourceRegistryException(errorMessage.toString(), e); throw new ResourceRegistryException(errorMessage.toString(), e);
} }
try { try {
targetEntityManagement.getElement(); targetEntityManagemen.getElement();
} catch (Exception e) { } catch (Exception e) {
targetEntityManagement.internalCreate(); targetEntityManagemen.internalCreate();
} }
} }
// Revisit this if-else because should be not needed anymore. // Revisit this if-else because should be not needed anymore.
/* /*
if(this instanceof IsParentOfManagement) { * if(this instanceof IsParentOfManagement) { if (!(sourceEntityManagement
if (!(sourceEntityManagement instanceof ContextManagement && targetEntityManagement instanceof ContextManagement)) { * instanceof ContextManagement && targetEntityManagement instanceof
String error = String.format( * ContextManagement)) { String error = String.format(
"A %s can be only created beetween two %s. " * "A %s can be only created beetween two %s. " +
+ "Cannot instatiate %s beetween %s -> %s ", * "Cannot instatiate %s beetween %s -> %s ", IsParentOf.NAME, Context.NAME,
IsParentOf.NAME, Context.NAME, erType, * erType, sourceEntityManagement.serialize(),
sourceEntityManagement.serialize(), * targetEntityManagement.serialize()); throw new
targetEntityManagement.serialize()); * ResourceRegistryException(error); } } else { if (!(sourceEntityManagement
throw new ResourceRegistryException(error); * instanceof ResourceManagement)) { String error = String.format(
} * "Any type of %s can have only a %s as %s. " +
} else { * "Cannot instatiate %s beetween %s -> %s ", Relation.NAME, Resource.NAME,
if (!(sourceEntityManagement instanceof ResourceManagement)) { * Relation.SOURCE_PROPERTY, erType, sourceEntityManagement.serialize(),
String error = String.format( * targetEntityManagement.serialize()); throw new
"Any type of %s can have only a %s as %s. " * ResourceRegistryException(error); }
+ "Cannot instatiate %s beetween %s -> %s ", *
Relation.NAME, Resource.NAME, Relation.SOURCE_PROPERTY, * if (this instanceof IsRelatedToManagement) { if (!(targetEntityManagement
erType, sourceEntityManagement.serialize(), * instanceof ResourceManagement)) { String error =
targetEntityManagement.serialize()); * String.format("A %s can have only a %s as %s. " +
throw new ResourceRegistryException(error); * "Cannot instatiate %s beetween %s -> %s ", accessType.getName(),
} * Resource.NAME, Relation.TARGET_PROPERTY, erType,
* sourceEntityManagement.serialize(), targetEntityManagement.serialize());
if (this instanceof IsRelatedToManagement) { * throw new ResourceRegistryException(error); } } else if (this instanceof
if (!(targetEntityManagement instanceof ResourceManagement)) { * ConsistsOfManagement) { if (!(targetEntityManagement instanceof
String error = String.format("A %s can have only a %s as %s. " * FacetManagement)) { String error =
+ "Cannot instatiate %s beetween %s -> %s ", accessType.getName(), * String.format("A %s can have only a %s as %s. " +
Resource.NAME, Relation.TARGET_PROPERTY, erType, * "Cannot instatiate %s beetween %s -> %s ", accessType.getName(), Facet.NAME,
sourceEntityManagement.serialize(), * Relation.TARGET_PROPERTY, erType, sourceEntityManagement.serialize(),
targetEntityManagement.serialize()); * targetEntityManagement.serialize()); throw new
throw new ResourceRegistryException(error); * ResourceRegistryException(error); } } else { String error =
} * String.format("{%s is not a %s nor a %s. " +
} else if (this instanceof ConsistsOfManagement) { * "This is really strange and should not occur. " + "Please Investigate it.",
if (!(targetEntityManagement instanceof FacetManagement)) { * this, IsRelatedToManagement.class.getSimpleName(),
String error = String.format("A %s can have only a %s as %s. " * ConsistsOfManagement.class.getSimpleName()); throw new
+ "Cannot instatiate %s beetween %s -> %s ", accessType.getName(), * ResourceRegistryException(error); }
Facet.NAME, Relation.TARGET_PROPERTY, erType, *
sourceEntityManagement.serialize(), * }
targetEntityManagement.serialize());
throw new ResourceRegistryException(error);
}
} else {
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange and should not occur. "
+ "Please Investigate it.", this,
IsRelatedToManagement.class.getSimpleName(),
ConsistsOfManagement.class.getSimpleName());
throw new ResourceRegistryException(error);
}
}
*/ */
// end of if-else to be revisited // end of if-else to be revisited
logger.trace("Creating {} beetween {} -> {}", erType, logger.trace("Creating {} beetween {} -> {}", erType, getSourceEntityManagemen().serialize(),
sourceEntityManagement.serialize(), getTargetEntityManagemen().serialize());
targetEntityManagement.serialize());
Vertex source = (Vertex) sourceEntityManagement.getElement(); Vertex source = (Vertex) getSourceEntityManagemen().getElement();
Vertex target = (Vertex) targetEntityManagement.getElement(); Vertex target = (Vertex) getTargetEntityManagemen().getElement();
element = orientGraph.addEdge(null, source, target, erType); element = orientGraph.addEdge(null, source, target, erType);
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
ignoreStartWithKeys);
/* This code has been moved in ERManagement.internalCreate() /*
HeaderUtility.addHeader(element, null); * This code has been moved in ERManagement.internalCreate()
ContextUtility.addToActualContext(orientGraph, element); * HeaderUtility.addHeader(element, null);
* ContextUtility.addToActualContext(orientGraph, element);
((OrientEdge) element).save(); *
* ((OrientEdge) element).save();
*/ */
logger.info("{} successfully created", erType); logger.info("{} successfully created", erType);
@ -304,26 +302,22 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return element; return element;
} }
protected abstract S getSourceEntityManagement(UUID sourceUUID) throws ResourceRegistryException; protected abstract S newSourceEntityManagement() throws ResourceRegistryException;
protected abstract T getTargetEntityManagement(UUID targetUUID) throws ResourceRegistryException; protected abstract T newTargetEntityManagement() throws ResourceRegistryException;
public void setSourceEntityManagement(S sourceEntityManagement) {
this.sourceEntityManagement = sourceEntityManagement;
}
public void setTargetEntityManagement(T targetEntityManagement) {
this.targetEntityManagement = targetEntityManagement;
}
/*
public void setSourceUUID(UUID sourceUUID) throws ResourceRegistryException { public void setSourceUUID(UUID sourceUUID) throws ResourceRegistryException {
this.sourceEntityManagement = getSourceEntityManagement(sourceUUID); this.sourceEntityManagemen = newSourceEntityManagement();
this.sourceEntityManagemen.setUUID(sourceUUID);
} }
public void setTargetUUID(UUID targetUUID) throws ResourceRegistryException { public void setTargetUUID(UUID targetUUID) throws ResourceRegistryException {
this.targetEntityManagement = getTargetEntityManagement(targetUUID); this.targetEntityManagemen = newTargetEntityManagement();
this.targetEntityManagemen.setUUID(targetUUID);
} }
*/
@Override @Override
protected Edge reallyUpdate() throws ResourceRegistryException { protected Edge reallyUpdate() throws ResourceRegistryException {
@ -331,8 +325,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
logger.debug("Trying to update {} : {}", erType, jsonNode); logger.debug("Trying to update {} : {}", erType, jsonNode);
Edge edge = getElement(); Edge edge = getElement();
ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
ignoreStartWithKeys);
if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) { if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
@ -350,50 +343,42 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
@Override @Override
protected boolean reallyAddToContext() throws ContextException, protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException {
ResourceRegistryException {
getElement(); getElement();
AddConstraint addConstraint = AddConstraint.unpropagate; AddConstraint addConstraint = AddConstraint.unpropagate;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded( PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getAddConstraint() != null) { if (propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint(); addConstraint = propagationConstraint.getAddConstraint();
} else { } else {
String error = String.format("%s.%s in %s is null" String error = String.format(
+ "This is really strange and should not occur. " "%s.%s in %s is null" + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.ADD_PROPERTY,
PropagationConstraint.ADD_PROPERTY,
Utility.toJsonString(element, true)); Utility.toJsonString(element, true));
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch (Exception e) { } catch (Exception e) {
String error = String.format("Error while getting %s from %s while performing AddToContext." String error = String.format(
+ "This is really strange and should not occur. " "Error while getting %s from %s while performing AddToContext."
+ "Please Investigate it.", + "This is really strange and should not occur. " + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true));
Utility.toJsonString(element, true));
logger.warn(error); logger.warn(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
} }
Vertex target = element.getVertex(Direction.IN);
switch (addConstraint) { switch (addConstraint) {
case propagate: case propagate:
/* /*
* The relation must be added only in the case the target vertex * The relation must be added only in the case the target vertex must be added.
* must be added. Otherwise we have a relation which point to an * Otherwise we have a relation which point to an entity outside of the context.
* entity outside of the context.
*/ */
EntityManagement entityManagement = EntityManagement getTargetEntityManagemen().internalAddToContext();
.getEntityManagement(orientGraph, target);
entityManagement.internalAddToContext();
ContextUtility.addToActualContext(orientGraph, getElement()); ContextUtility.addToActualContext(orientGraph, getElement());
break; break;
@ -408,32 +393,24 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return true; return true;
} }
public boolean forcedAddToContext() throws ContextException, public boolean forcedAddToContext() throws ContextException, ResourceRegistryException {
ResourceRegistryException {
getElement(); getElement();
/* Adding source to Context */ /* Adding source to Context */
Vertex source = element.getVertex(Direction.OUT); getSourceEntityManagemen().internalAddToContext();
EntityManagement entityManagement = EntityManagement
.getEntityManagement(orientGraph, source);
entityManagement.internalAddToContext();
/* Adding target to Context */ /* Adding target to Context */
Vertex target = element.getVertex(Direction.IN); getTargetEntityManagemen().internalAddToContext();
entityManagement = EntityManagement
.getEntityManagement(orientGraph, target);
entityManagement.internalAddToContext();
ContextUtility.addToActualContext(orientGraph, getElement()); ContextUtility.addToActualContext(orientGraph, getElement());
return true; return true;
} }
protected boolean removeFromContextTargetVertex(Vertex target) /*
throws ResourceRegistryException { protected boolean removeFromContextTargetVertex(Vertex target) throws ResourceRegistryException {
EntityManagement entityManagement = EntityManagement EntityManagement entityManagement = EntityManagement.getEntityManagement(orientGraph, target);
.getEntityManagement(orientGraph, target);
if (entityManagement != null) { if (entityManagement != null) {
entityManagement.internalRemoveFromContext(); entityManagement.internalRemoveFromContext();
return true; return true;
@ -441,71 +418,67 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return false; return false;
} }
} }
*/
@Override @Override
protected boolean reallyRemoveFromContext() throws ContextException, protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException {
ResourceRegistryException {
getElement(); getElement();
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded( PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) { if (propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
} else { } else {
String error = String.format("%s.%s in %s is null" String error = String.format(
+ "This is really strange and should not occur. " "%s.%s in %s is null" + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY,
PropagationConstraint.REMOVE_PROPERTY,
Utility.toJsonString(element, true)); Utility.toJsonString(element, true));
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch (Exception e) { } catch (Exception e) {
String error = String.format("Error while getting %s from %s while performing RemoveFromContext." String error = String.format(
+ "This is really strange and should not occur. " "Error while getting %s from %s while performing RemoveFromContext."
+ "Please Investigate it.", + "This is really strange and should not occur. " + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true));
Utility.toJsonString(element, true));
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
} }
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
* context to avoid to have edge having a source outside of the context. * avoid to have edge having a source outside of the context.
*/ */
ContextUtility.removeFromActualContext(orientGraph, element); ContextUtility.removeFromActualContext(orientGraph, element);
switch (removeConstraint) { switch (removeConstraint) {
case cascade: case cascade:
removeFromContextTargetVertex(target); getTargetEntityManagemen().internalRemoveFromContext();
break; break;
case cascadeWhenOrphan: case cascadeWhenOrphan:
Vertex target = (Vertex) getTargetEntityManagemen().getElement();
Iterable<Edge> iterable = target.getEdges(Direction.IN); Iterable<Edge> iterable = target.getEdges(Direction.IN);
Iterator<Edge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
int count = 0; int count = 0;
OrientEdge edge = null; OrientEdge edge = null;
while (iterator.hasNext()) { while (iterator.hasNext()) {
edge = (OrientEdge) iterator.next(); edge = (OrientEdge) iterator.next();
OrientEdge thisOrientEdge = (OrientEdge) element; OrientEdge thisOrientEdge = (OrientEdge) getElement();
if (edge.compareTo(thisOrientEdge) != 0) { if (edge.compareTo(thisOrientEdge) != 0) {
if (thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) { if (thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
count++; count++;
break; break;
} }
/* /*
else{ * else{ ContextUtility.removeFromActualContext(orientGraph, edge); }
ContextUtility.removeFromActualContext(orientGraph, edge);
}
*/ */
} }
} }
@ -515,7 +488,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.", "{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.",
element, target, edge, removeConstraint); element, target, edge, removeConstraint);
} else { } else {
removeFromContextTargetVertex(target); getTargetEntityManagemen().internalRemoveFromContext();
} }
break; break;
@ -530,41 +503,19 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
@SuppressWarnings("unchecked")
protected T getTargetEntityManagement()
throws ResourceRegistryException {
T entityManagement;
switch (accessType) {
case CONSISTS_OF:
entityManagement = (T) new FacetManagement(orientGraph);
break;
case IS_RELATED_TO:
entityManagement = (T) new ResourceManagement(orientGraph);
break;
default:
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange ad should not occur. "
+ "Please Investigate it.", accessType.getName(), ConsistsOf.NAME,
IsRelatedTo.NAME);
throw new ResourceRegistryException(error);
}
return entityManagement;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static RelationManagement getRelationManagement( public static RelationManagement getRelationManagement(OrientGraph orientGraph, Edge edge)
OrientGraph orientGraph, Edge edge)
throws ResourceRegistryException { throws ResourceRegistryException {
if (orientGraph == null) { if (orientGraph == null) {
throw new ResourceRegistryException(OrientGraph.class.getSimpleName() + "instance is null. This is really strage please contact the administrator."); throw new ResourceRegistryException(OrientGraph.class.getSimpleName()
+ "instance is null. This is really strage please contact the administrator.");
} }
if (edge == null) { if (edge == null) {
throw new ResourceRegistryException(Edge.class.getSimpleName() + "instance is null. This is really strage please contact the administrator."); throw new ResourceRegistryException(Edge.class.getSimpleName()
+ "instance is null. This is really strage please contact the administrator.");
} }
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
@ -574,78 +525,60 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { } else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph); relationManagement = new IsRelatedToManagement(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.", edge, ConsistsOf.NAME, IsRelatedTo.NAME);
+ "Please Investigate it.", edge, ConsistsOf.NAME,
IsRelatedTo.NAME);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
relationManagement.setElement(edge); relationManagement.setElement(edge);
return relationManagement; return relationManagement;
} }
protected boolean deleteTargetVertex(Vertex target)
throws ResourceRegistryException {
EntityManagement entityManagement = EntityManagement.getEntityManagement(orientGraph, target);
if (entityManagement != null) {
return entityManagement.internalDelete();
} else {
return false;
}
}
@Override @Override
protected boolean reallyDelete() throws RelationNotFoundException, protected boolean reallyDelete() throws RelationNotFoundException, ResourceRegistryException {
ResourceRegistryException { logger.debug("Going to remove {} with UUID {}. Related {}s will be detached.", accessType.getName(), uuid,
logger.debug( targetEntityClass.getSimpleName());
"Going to remove {} with UUID {}. Related {}s will be detached.",
accessType.getName(), uuid, targetEntityClass.getSimpleName());
getElement(); getElement();
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded( PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) { if (propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
} else { } else {
String error = String.format("%s.%s in %s is null" String error = String.format(
+ "This is really strange and should not occur. " "%s.%s in %s is null" + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY,
PropagationConstraint.REMOVE_PROPERTY,
Utility.toJsonString(element, true)); Utility.toJsonString(element, true));
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch (Exception e) { } catch (Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. " logger.warn(
+ "This is really strange and should not occur. " "Error while getting {} from {}. Assuming {}. " + "This is really strange and should not occur. "
+ "Please Investigate it.", + "Please Investigate it.",
Relation.PROPAGATION_CONSTRAINT, Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), removeConstraint);
Utility.toJsonString(element, true), removeConstraint);
} }
Vertex target = element.getVertex(Direction.IN); Vertex target = (Vertex) getTargetEntityManagemen().getElement();
element.remove(); element.remove();
switch (removeConstraint) { switch (removeConstraint) {
case cascade: case cascade:
deleteTargetVertex(target); getTargetEntityManagemen().internalDelete();
break; break;
case cascadeWhenOrphan: case cascadeWhenOrphan:
Iterable<Edge> iterable = target.getEdges(Direction.IN); Iterable<Edge> iterable = target.getEdges(Direction.IN);
Iterator<Edge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
if (iterator.hasNext()) { if (iterator.hasNext()) {
logger.trace( logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
"{} point to {} which is not orphan. Giving {} directive, it will be keep.", target, removeConstraint);
element, target, removeConstraint);
} else { } else {
deleteTargetVertex(target); getTargetEntityManagemen().internalDelete();
} }
break; break;
@ -660,14 +593,12 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private String create(UUID sourceUUID, UUID targetUUID) private String create(UUID sourceUUID, UUID targetUUID) throws ResourceRegistryException {
throws ResourceRegistryException {
try { try {
orientGraph = ContextUtility orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
setSourceUUID(sourceUUID); getSourceEntityManagemen().setUUID(sourceUUID);
setTargetUUID(targetUUID); getTargetEntityManagemen().setUUID(targetUUID);
element = reallyCreate(); element = reallyCreate();
@ -693,17 +624,15 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
boolean postFilterPolymorphic) throws ResourceRegistryException { throws ResourceRegistryException {
Map<String, JSONObject> visitedSourceResources = new HashMap<>(); Map<String, JSONObject> visitedSourceResources = new HashMap<>();
for (Edge edge : edges) { for (Edge edge : edges) {
if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) { if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
continue; continue;
} }
RelationManagement relationManagement = getRelationManagement( RelationManagement relationManagement = getRelationManagement(orientGraph, edge);
orientGraph, edge); visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
visitedSourceResources = relationManagement
.fullSerialize(visitedSourceResources);
} }
return visitedSourceResources.values(); return visitedSourceResources.values();
} }
@ -714,24 +643,22 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
@Override @Override
public String reallyGetAll(boolean polymorphic) public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
throws ResourceRegistryException {
Iterable<Edge> edges = orientGraph.getEdgesOfClass(erType, polymorphic); Iterable<Edge> edges = orientGraph.getEdgesOfClass(erType, polymorphic);
Collection<JSONObject> collection = serializeEdges(edges, false); Collection<JSONObject> collection = serializeEdges(edges, false);
return serializeJSONObjectList(collection); return serializeJSONObjectList(collection);
} }
public String reallyGetAllFrom(UUID uuid, Direction direction, public String reallyGetAllFrom(UUID uuid, Direction direction, boolean polymorphic)
boolean polymorphic) throws ResourceRegistryException { throws ResourceRegistryException {
EntityManagement entityManagement = null; EntityManagement entityManagement = null;
try { try {
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(orientGraph, uuid); entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(orientGraph, uuid);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException(String.format( throw new ResourceRegistryException(
"Provided UUID %s does not belogn to any %s", String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME));
uuid.toString(), Entity.NAME));
} }
Vertex vertex = (Vertex) entityManagement.getElement(); Vertex vertex = (Vertex) entityManagement.getElement();
@ -744,11 +671,9 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
public String allFrom(UUID uuid, Direction direction, boolean polymorphic) public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException {
throws ResourceRegistryException {
try { try {
orientGraph = ContextUtility orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
return reallyGetAllFrom(uuid, direction, polymorphic); return reallyGetAllFrom(uuid, direction, polymorphic);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -764,23 +689,19 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@Override @Override
public boolean addToContext() throws ERNotFoundException, ContextException { public boolean addToContext() throws ERNotFoundException, ContextException {
logger.debug("Going to add {} with UUID {} to actual Context", logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid);
accessType.getName(), uuid);
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph( orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, true);
PermissionMode.WRITER, true);
boolean added = forcedAddToContext(); boolean added = forcedAddToContext();
orientGraph.commit(); orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context", logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
accessType.getName(), uuid);
return added; return added;
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context", logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
accessType.getName(), uuid, e);
if (orientGraph != null) { if (orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }