Switched from OrientGraph to oDatabaseDocument to have one interface for

managing vertexes, edges and properties.
Moreover, switched from Element to OElement, Vertex to OVertex, Edge to
OEdge to have the same APIs to manage instances, and to be able to
directly use oDatabaseDocument instead of frequent casts to
OrientElement to perform operations not supported by thinkerpop standard
interface.
This commit is contained in:
Luca Frosini 2019-11-05 18:36:44 +01:00
parent f14061774d
commit f683681a8a
27 changed files with 657 additions and 749 deletions

View File

@ -36,14 +36,13 @@ import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.ODatabaseType; import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.db.OrientDB; import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig; import com.orientechnologies.orient.core.db.OrientDBConfig;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.ORole; import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity; import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.core.metadata.security.OUser;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -197,13 +196,12 @@ public class DatabaseEnvironment {
contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext); contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext);
if(created) { if(created) {
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME, ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD);
CHANGED_ADMIN_PASSWORD).setupPool(1, 10); ODatabaseDocument oDatabaseDocument = pool.acquire();
OrientGraph orientGraph = factory.getTx(); adminSecurityContext.create(oDatabaseDocument);
adminSecurityContext.create(orientGraph); oDatabaseDocument.commit();
orientGraph.commit(); oDatabaseDocument.close();
orientGraph.shutdown(); pool.close();
factory.close();
contextSecurityContext.create(); contextSecurityContext.create();
@ -261,8 +259,8 @@ public class DatabaseEnvironment {
} }
} }
protected static void setDateTimeFormat(ODatabaseSession oDatabaseSession) { protected static void setDateTimeFormat(ODatabaseDocument oDatabaseDocument) {
oDatabaseSession.set(ATTRIBUTES.DATETIMEFORMAT, ISConstants.DATETIME_PATTERN); oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, ISConstants.DATETIME_PATTERN);
} }

View File

@ -11,6 +11,7 @@ import java.util.Iterator;
import java.util.List; 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.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -46,24 +47,21 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeType; import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.node.TextNode;
import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.util.ODateHelper; import com.orientechnologies.orient.core.util.ODateHelper;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.util.StringFactory; import com.tinkerpop.blueprints.util.StringFactory;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class ERManagement<El extends Element> { public abstract class ERManagement<El extends OElement> {
protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Logger logger = LoggerFactory.getLogger(this.getClass());
@ -80,7 +78,7 @@ public abstract class ERManagement<El extends Element> {
protected Class<El> elementClass; protected Class<El> elementClass;
protected final AccessType accessType; protected final AccessType accessType;
protected OrientGraph orientGraph; protected ODatabaseDocument oDatabaseDocument;
protected UUID uuid; protected UUID uuid;
protected JsonNode jsonNode; protected JsonNode jsonNode;
@ -155,14 +153,19 @@ public abstract class ERManagement<El extends Element> {
checkJsonNode(); checkJsonNode();
} }
public static OClass getOClass(OElement oElement) throws SchemaException, ResourceRegistryException {
Optional<OClass> optional = oElement.getSchemaType();
if(optional.isPresent()) {
return optional.get();
}else {
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
}
}
protected OClass getOClass() throws SchemaException, ResourceRegistryException { protected OClass getOClass() throws SchemaException, ResourceRegistryException {
if(oClass == null) { if(oClass == null) {
if(element != null) { if(element != null) {
OrientElement orientElement = (OrientElement) element; oClass = getOClass(element);
OMetadata oMetadata = orientElement.getRecord().getDatabase().getMetadata();
OSchema oSchema = oMetadata.getSchema();
String type = orientElement.getRecord().getClassName();
oClass = oSchema.getClass(type);
} else { } else {
oClass = SchemaManagementImpl.getTypeSchema(elementType, accessType); oClass = SchemaManagementImpl.getTypeSchema(elementType, accessType);
} }
@ -268,9 +271,9 @@ public abstract class ERManagement<El extends Element> {
entityHeader = HeaderUtility.addHeader(element, null); entityHeader = HeaderUtility.addHeader(element, null);
} }
getWorkingContext().addElement(element, orientGraph); getWorkingContext().addElement(element, oDatabaseDocument);
((OrientElement) element).save(); element.save();
return element; return element;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
@ -288,7 +291,7 @@ public abstract class ERManagement<El extends Element> {
reallyUpdate(); reallyUpdate();
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save(); element.save();
return element; return element;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
@ -321,7 +324,7 @@ public abstract class ERManagement<El extends Element> {
try { try {
boolean ret = reallyAddToContext(targetSecurityContext); boolean ret = reallyAddToContext(targetSecurityContext);
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save(); element.save();
return ret && true; return ret && true;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
@ -339,7 +342,7 @@ public abstract class ERManagement<El extends Element> {
try { try {
boolean ret = reallyRemoveFromContext(targetSecurityContext); boolean ret = reallyRemoveFromContext(targetSecurityContext);
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save(); element.save();
return ret && true; return ret && true;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
@ -355,7 +358,8 @@ public abstract class ERManagement<El extends Element> {
} }
this.element = element; this.element = element;
this.uuid = HeaderUtility.getHeader(element).getUUID(); this.uuid = HeaderUtility.getHeader(element).getUUID();
this.elementType = ((OrientElement) element).getLabel(); OClass oClass = getOClass();
this.elementType = oClass.getName();
} }
protected abstract NotFoundException getSpecificElementNotFoundException(NotFoundException e); protected abstract NotFoundException getSpecificElementNotFoundException(NotFoundException e);
@ -388,7 +392,7 @@ public abstract class ERManagement<El extends Element> {
} else { } else {
if(reload) { if(reload) {
((OrientElement) element).reload(); element.reload();
} }
} }
return element; return element;
@ -399,7 +403,7 @@ public abstract class ERManagement<El extends Element> {
if(uuid == null) { if(uuid == null) {
throw new NotFoundException("null UUID does not allow to retrieve the Element"); throw new NotFoundException("null UUID does not allow to retrieve the Element");
} }
return Utility.getElementByUUID(orientGraph, elementType == null ? accessType.getName() : elementType, uuid, return Utility.getElementByUUID(oDatabaseDocument, elementType == null ? accessType.getName() : elementType, uuid,
elementClass); elementClass);
} catch(NotFoundException e) { } catch(NotFoundException e) {
throw getSpecificElementNotFoundException(e); throw getSpecificElementNotFoundException(e);
@ -428,7 +432,7 @@ public abstract class ERManagement<El extends Element> {
public String all(boolean polymorphic) throws ResourceRegistryException { public String all(boolean polymorphic) throws ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
return reallyGetAll(polymorphic); return reallyGetAll(polymorphic);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
@ -436,15 +440,15 @@ public abstract class ERManagement<El extends Element> {
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
getElement(); getElement();
@ -456,8 +460,8 @@ public abstract class ERManagement<El extends Element> {
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e); logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
@ -465,9 +469,8 @@ public abstract class ERManagement<El extends Element> {
public String createOrUpdate() public String createOrUpdate()
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
orientGraph.setAutoStartTx(false); oDatabaseDocument.begin();
orientGraph.begin();
boolean update = false; boolean update = false;
try { try {
@ -478,7 +481,7 @@ public abstract class ERManagement<El extends Element> {
element = internalCreate(); element = internalCreate();
} }
orientGraph.commit(); oDatabaseDocument.commit();
if(update) { if(update) {
setReload(true); setReload(true);
@ -490,19 +493,19 @@ public abstract class ERManagement<El extends Element> {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e); logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
@ -510,13 +513,12 @@ public abstract class ERManagement<El extends Element> {
public String create() throws AlreadyPresentException, ResourceRegistryException { public String create() throws AlreadyPresentException, ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
orientGraph.setAutoStartTx(false); oDatabaseDocument.begin();
orientGraph.begin();
element = internalCreate(); element = internalCreate();
orientGraph.commit(); oDatabaseDocument.commit();
// TODO Notify to subscriptionNotification // TODO Notify to subscriptionNotification
@ -524,26 +526,26 @@ public abstract class ERManagement<El extends Element> {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to create {}", accessType.getName()); logger.error("Unable to create {}", accessType.getName());
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to create {}", accessType.getName(), e); logger.error("Unable to create {}", accessType.getName(), e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
public String read() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public String read() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
getElement(); getElement();
@ -555,21 +557,20 @@ public abstract class ERManagement<El extends Element> {
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e); logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
orientGraph.setAutoStartTx(false); oDatabaseDocument.begin();
orientGraph.begin();
element = internalUpdate(); element = internalUpdate();
orientGraph.commit(); oDatabaseDocument.commit();
setReload(true); setReload(true);
@ -579,19 +580,19 @@ public abstract class ERManagement<El extends Element> {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e); logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
@ -600,15 +601,13 @@ public abstract class ERManagement<El extends Element> {
logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid); logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid);
try { try {
oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); oDatabaseDocument.begin();
orientGraph.setAutoStartTx(false);
orientGraph.begin();
boolean deleted = reallyDelete(); boolean deleted = reallyDelete();
if(deleted) { if(deleted) {
orientGraph.commit(); oDatabaseDocument.commit();
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid); logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
} else { } else {
throw new ResourceRegistryException("Error while deleting " + accessType.getName() + " with UUID " + uuid); throw new ResourceRegistryException("Error while deleting " + accessType.getName() + " with UUID " + uuid);
@ -619,19 +618,19 @@ public abstract class ERManagement<El extends Element> {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid); logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e); logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
@ -641,33 +640,32 @@ public abstract class ERManagement<El extends Element> {
logger.info("Going to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid, contextUUID); logger.info("Going to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid, contextUUID);
try { try {
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
orientGraph.setAutoStartTx(false); oDatabaseDocument.begin();
orientGraph.begin();
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
boolean added = internalAddToContext(targetSecurityContext); boolean added = internalAddToContext(targetSecurityContext);
orientGraph.commit(); oDatabaseDocument.commit();
logger.info("{} with UUID {} successfully added to Context with UUID {}", elementType, uuid, contextUUID); logger.info("{} with UUID {} successfully added to Context with UUID {}", elementType, uuid, contextUUID);
return added; return added;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {}", elementType, uuid, contextUUID); logger.error("Unable to add {} with UUID {} to Context with UUID {}", elementType, uuid, contextUUID);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {}", elementType, uuid, contextUUID, e); logger.error("Unable to add {} with UUID {} to Context with UUID {}", elementType, uuid, contextUUID, e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
@ -677,36 +675,34 @@ public abstract class ERManagement<El extends Element> {
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", elementType, uuid, contextUUID); logger.debug("Going to remove {} with UUID {} from Context with UUID {}", elementType, uuid, contextUUID);
try { try {
oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); oDatabaseDocument.begin();
orientGraph.setAutoStartTx(false);
orientGraph.begin();
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
boolean removed = internalRemoveFromContext(targetSecurityContext); boolean removed = internalRemoveFromContext(targetSecurityContext);
orientGraph.commit(); oDatabaseDocument.commit();
logger.info("{} with UUID {} successfully removed from Context with UUID {}", elementType, uuid, logger.info("{} with UUID {} successfully removed from Context with UUID {}", elementType, uuid,
contextUUID); contextUUID);
return removed; return removed;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", elementType, uuid, contextUUID); logger.error("Unable to remove {} with UUID {} from Context with UUID {}", elementType, uuid, contextUUID);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", elementType, uuid, contextUUID, logger.error("Unable to remove {} with UUID {} from Context with UUID {}", elementType, uuid, contextUUID,
e); e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }
@ -837,13 +833,13 @@ public abstract class ERManagement<El extends Element> {
* @return * @return
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, Set<String> ignoreKeys, public static OElement updateProperties(OClass oClass, OElement element, JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreStartWithKeys) throws ResourceRegistryException { Set<String> ignoreStartWithKeys) throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyKeys(); Set<String> oldKeys = element.getPropertyNames();
Map<String,Object> properties; Map<String,Object> properties;
if(element instanceof Vertex || element instanceof Edge) { if(element instanceof OVertex || element instanceof OEdge) {
try { try {
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys); properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
} catch(IOException e) { } catch(IOException e) {
@ -865,7 +861,7 @@ public abstract class ERManagement<El extends Element> {
if(object instanceof ODocument) { if(object instanceof ODocument) {
ODocument oDocument = (ODocument) object; ODocument oDocument = (ODocument) object;
((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED); element.setProperty(key, oDocument, OType.EMBEDDED);
set = true; set = true;
} }
@ -873,11 +869,11 @@ public abstract class ERManagement<El extends Element> {
* List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354 * List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354
*/ */
if(object instanceof Set) { if(object instanceof Set) {
((OrientElement) element).setProperty(key, object, OType.EMBEDDEDSET); element.setProperty(key, object, OType.EMBEDDEDSET);
set = true; set = true;
} }
if(object instanceof List) { if(object instanceof List) {
((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); element.setProperty(key, object, OType.EMBEDDEDLIST);
set = true; set = true;
} }
@ -908,7 +904,7 @@ public abstract class ERManagement<El extends Element> {
element.removeProperty(key); element.removeProperty(key);
} }
((OrientElement) element).save(); element.save();
return element; return element;
} }
@ -1001,20 +997,21 @@ public abstract class ERManagement<El extends Element> {
public JsonNode toJsonNode() throws ResourceRegistryException { public JsonNode toJsonNode() throws ResourceRegistryException {
try { try {
OrientElement orientElement = (OrientElement) getElement();
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode(); ObjectNode objectNode = objectMapper.createObjectNode();
OElement element = getElement();
Map<String,Object> properties = orientElement.getProperties(); Set<String> keys = element.getPropertyNames();
for(String key : orientElement.getPropertyKeys()) { for(String key : keys) {
Object object = properties.get(key); Object object = element.getProperty(key);
JsonNode jsonNode = getPropertyForJson(key, object); JsonNode jsonNode = getPropertyForJson(key, object);
if(jsonNode != null) { if(jsonNode != null) {
objectNode.replace(key, jsonNode); objectNode.replace(key, jsonNode);
} }
} }
String type = orientElement.getRecord().getClassName(); OClass oClass = getOClass();
String type = oClass.getName();
objectNode.put(ISManageable.CLASS_PROPERTY, type); objectNode.put(ISManageable.CLASS_PROPERTY, type);
Collection<String> superClasses = getSuperclasses(); Collection<String> superClasses = getSuperclasses();

View File

@ -24,15 +24,11 @@ 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.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.tinkerpop.blueprints.Edge; import com.orientechnologies.orient.core.record.OEdge;
import com.tinkerpop.blueprints.Element; import com.orientechnologies.orient.core.record.OElement;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.record.OVertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -86,23 +82,22 @@ public class ERManagementUtility {
return erManagement; return erManagement;
} }
@SuppressWarnings("rawtypes") public static ERManagement<?> getERManagement(SecurityContext workingContext, ODatabaseDocument orientGraph,
public static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, OElement element) throws ResourceRegistryException {
Element element) throws ResourceRegistryException { if(element instanceof OVertex) {
if(element instanceof Vertex) { return getEntityManagement(workingContext, orientGraph, (OVertex) element);
return getEntityManagement(workingContext, orientGraph, (Vertex) element); } else if(element instanceof OEdge) {
} else if(element instanceof Edge) { return getRelationManagement(workingContext, orientGraph, (OEdge) element);
return getRelationManagement(workingContext, orientGraph, (Edge) element);
} }
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(), throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
Entity.NAME, Relation.NAME)); Entity.NAME, Relation.NAME));
} }
public static Element getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException { public static OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
try { try {
return Utility.getElementByUUIDAsAdmin(null, uuid, Vertex.class); return Utility.getElementByUUIDAsAdmin(null, uuid, OVertex.class);
} catch(NotFoundException e) { } catch(NotFoundException e) {
return Utility.getElementByUUIDAsAdmin(null, uuid, Edge.class); return Utility.getElementByUUIDAsAdmin(null, uuid, OEdge.class);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
@ -110,12 +105,12 @@ public class ERManagementUtility {
} }
} }
private static Element getAnyElementByUUID(OrientGraph orientGraph, UUID uuid) private static OElement getAnyElementByUUID(ODatabaseDocument orientGraph, UUID uuid)
throws NotFoundException, ResourceRegistryException { throws NotFoundException, ResourceRegistryException {
try { try {
return Utility.getElementByUUID(orientGraph, null, uuid, Vertex.class); return Utility.getElementByUUID(orientGraph, null, uuid, OVertex.class);
} catch(NotFoundException e) { } catch(NotFoundException e) {
return Utility.getElementByUUID(orientGraph, null, uuid, Edge.class); return Utility.getElementByUUID(orientGraph, null, uuid, OEdge.class);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
@ -124,9 +119,9 @@ public class ERManagementUtility {
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, public static ERManagement getERManagementFromUUID(SecurityContext workingContext, ODatabaseDocument orientGraph,
UUID uuid) throws ResourceRegistryException { UUID uuid) throws ResourceRegistryException {
Element element; OElement element;
try { try {
element = getAnyElementByUUID(orientGraph, uuid); element = getAnyElementByUUID(orientGraph, uuid);
return getERManagement(workingContext, orientGraph, element); return getERManagement(workingContext, orientGraph, element);
@ -137,22 +132,22 @@ public class ERManagementUtility {
} }
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, public static EntityManagement getEntityManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument,
Vertex vertex) throws ResourceRegistryException { OVertex vertex) throws ResourceRegistryException {
if(orientGraph == null) { if(oDatabaseDocument == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); ODatabaseDocument.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if(vertex == null) { if(vertex == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
Vertex.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); OVertex.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
OrientVertexType orientVertexType = null; OClass oClass = null;
try { try {
orientVertexType = ((OrientVertex) vertex).getType(); oClass = ERManagement.getOClass(vertex);
} catch(Exception e) { } catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", vertex.toString(), String error = String.format("Unable to detect type of %s. %s", vertex.toString(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -161,10 +156,10 @@ public class ERManagementUtility {
} }
EntityManagement entityManagement = null; EntityManagement entityManagement = null;
if(orientVertexType.isSubClassOf(Resource.NAME)) { if(oClass.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(workingContext, orientGraph); entityManagement = new ResourceManagement(workingContext, oDatabaseDocument);
} else if(orientVertexType.isSubClassOf(Facet.NAME)) { } else if(oClass.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(workingContext, orientGraph); entityManagement = new FacetManagement(workingContext, oDatabaseDocument);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME, String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -175,25 +170,26 @@ public class ERManagementUtility {
} }
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, public static RelationManagement getRelationManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument,
Edge edge) throws ResourceRegistryException { OEdge edge) throws ResourceRegistryException {
if(orientGraph == null) { if(oDatabaseDocument == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); ODatabaseDocument.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if(edge == null) { if(edge == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
Edge.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); OEdge.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); OClass oClass = ERManagement.getOClass(edge);
RelationManagement relationManagement = null; RelationManagement relationManagement = null;
if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { if(oClass.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(workingContext, orientGraph); relationManagement = new ConsistsOfManagement(workingContext, oDatabaseDocument);
} else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { } else if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(workingContext, orientGraph); relationManagement = new IsRelatedToManagement(workingContext, oDatabaseDocument);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME, String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);

View File

@ -19,16 +19,15 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tinkerpop.blueprints.Edge; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.Element; import com.orientechnologies.orient.core.record.OEdge;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.record.OElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.record.OVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManagement<Vertex> { public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManagement<OVertex> {
/** /**
* Provide a cache edge-internal-id -> RelationManagement * Provide a cache edge-internal-id -> RelationManagement
@ -42,18 +41,18 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
this.ignoreKeys.add(BaseEntity.HEADER_PROPERTY); this.ignoreKeys.add(BaseEntity.HEADER_PROPERTY);
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toLowerCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_IN_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toUpperCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_IN_PREFIX.toUpperCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase());
this.relationManagements = new HashMap<>(); this.relationManagements = new HashMap<>();
} }
protected BaseEntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) { protected BaseEntityManagement(AccessType accessType, SecurityContext workingContext, ODatabaseDocument orientGraph) {
this(accessType); this(accessType);
this.orientGraph = orientGraph; this.oDatabaseDocument = orientGraph;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
@ -64,11 +63,11 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
* fake id starting with - (minus) sign. This not imply any collateral effect * fake id starting with - (minus) sign. This not imply any collateral effect
* but a better solution is a desiderata. * but a better solution is a desiderata.
*/ */
protected BaseRelationManagement getBaseRelationManagement(Edge edge) throws ResourceRegistryException { protected BaseRelationManagement getBaseRelationManagement(OEdge edge) throws ResourceRegistryException {
String id = edge.getId().toString(); String id = edge.getIdentity().toString();
BaseRelationManagement relationManagement = relationManagements.get(id); BaseRelationManagement relationManagement = relationManagements.get(id);
if(relationManagement == null) { if(relationManagement == null) {
relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
return relationManagement; return relationManagement;
@ -76,8 +75,8 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
protected void addToRelationManagement(@SuppressWarnings("rawtypes") BaseRelationManagement baseRelationManagement) protected void addToRelationManagement(@SuppressWarnings("rawtypes") BaseRelationManagement baseRelationManagement)
throws ResourceRegistryException { throws ResourceRegistryException {
Element elem = baseRelationManagement.getElement(); OElement elem = baseRelationManagement.getElement();
String id = elem.getId().toString(); String id = elem.getIdentity().toString();
if(relationManagements.get(id) != null && relationManagements.get(id) != baseRelationManagement) { if(relationManagements.get(id) != null && relationManagements.get(id) != baseRelationManagement) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Two different instance of "); errorMessage.append("Two different instance of ");
@ -108,9 +107,9 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
return sourceResource; return sourceResource;
} }
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(), logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
elementType, jsonNode); elementType, jsonNode);
try { try {
@ -122,11 +121,11 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
Vertex vertexEntity = orientGraph.addVertex("class:" + elementType); OVertex vertexEntity = oDatabaseDocument.newVertex(elementType);
try { try {
if(uuid != null) { if(uuid != null) {
Vertex v = getElement(); OVertex v = getElement();
if(v != null) { if(v != null) {
String error = String.format("A %s with UUID %s already exist", elementType, uuid.toString()); String error = String.format("A %s with UUID %s already exist", elementType, uuid.toString());
throw getSpecificERAlreadyPresentException(error); throw getSpecificERAlreadyPresentException(error);
@ -135,10 +134,10 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
} catch(NotFoundException e) { } catch(NotFoundException e) {
try { try {
Element el = ERManagementUtility.getAnyElementByUUID(uuid); OElement el = ERManagementUtility.getAnyElementByUUID(uuid);
String error = String.format("UUID %s is already used by another %s. This is not allowed.", String error = String.format("UUID %s is already used by another %s. This is not allowed.",
uuid.toString(), uuid.toString(),
(el instanceof Vertex) ? org.gcube.informationsystem.model.reference.entities.Entity.NAME : (el instanceof OVertex) ? org.gcube.informationsystem.model.reference.entities.Entity.NAME :
org.gcube.informationsystem.model.reference.relations.Relation.NAME); org.gcube.informationsystem.model.reference.relations.Relation.NAME);
throw getSpecificERAvailableInAnotherContextException(error); throw getSpecificERAvailableInAnotherContextException(error);
@ -157,14 +156,14 @@ public abstract class BaseEntityManagement<E extends BaseEntity> extends ERManag
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
} }
logger.info("Created {} is {}", Vertex.class.getSimpleName(), logger.info("Created {} is {}", OVertex.class.getSimpleName(),
Utility.toJsonString((OrientVertex) element, true)); Utility.toJsonString(element, true));
return element; 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 {}", Vertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), elementType, jsonNode, e); accessType.getName(), elementType, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + elementType + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + elementType + " with " + jsonNode, e.getCause());
} }

View File

@ -17,17 +17,16 @@ import org.gcube.informationsystem.resourceregistry.utils.Utility;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tinkerpop.blueprints.Direction; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.Edge; import com.orientechnologies.orient.core.record.ODirection;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.record.OEdge;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.orientechnologies.orient.core.record.OVertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM extends BaseEntityManagement<S>, TEM extends BaseEntityManagement<T>, S extends BaseEntity, T extends BaseEntity> public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM extends BaseEntityManagement<S>, TEM extends BaseEntityManagement<T>, S extends BaseEntity, T extends BaseEntity>
extends ERManagement<Edge> { extends ERManagement<OEdge> {
protected final Class<S> sourceEntityClass; protected final Class<S> sourceEntityClass;
protected final Class<T> targetEntityClass; protected final Class<T> targetEntityClass;
@ -41,10 +40,10 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
this.ignoreKeys.add(Relation.HEADER_PROPERTY); this.ignoreKeys.add(Relation.HEADER_PROPERTY);
this.ignoreKeys.add(Relation.SOURCE_PROPERTY); this.ignoreKeys.add(Relation.SOURCE_PROPERTY);
this.ignoreKeys.add(Relation.TARGET_PROPERTY); this.ignoreKeys.add(Relation.TARGET_PROPERTY);
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toLowerCase()); this.ignoreKeys.add(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.CONNECTION_OUT.toLowerCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toLowerCase()); this.ignoreKeys.add(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.CONNECTION_IN.toLowerCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase()); this.ignoreKeys.add(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.CONNECTION_OUT.toUpperCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase()); this.ignoreKeys.add(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.CONNECTION_IN.toUpperCase());
this.sourceEntityClass = sourceEntityClass; this.sourceEntityClass = sourceEntityClass;
this.targetEntityClass = targetEntityClass; this.targetEntityClass = targetEntityClass;
@ -53,15 +52,15 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
this.targetEntityManagement = null; this.targetEntityManagement = null;
} }
protected BaseRelationManagement(AccessType accessType, Class<S> sourceEntityClass, Class<T> targetEntityClass, SecurityContext workingContext, OrientGraph orientGraph) { protected BaseRelationManagement(AccessType accessType, Class<S> sourceEntityClass, Class<T> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) {
this(accessType, sourceEntityClass, targetEntityClass); this(accessType, sourceEntityClass, targetEntityClass);
this.orientGraph = orientGraph; this.oDatabaseDocument = orientGraph;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
public SEM getSourceEntityManagement() throws ResourceRegistryException { public SEM getSourceEntityManagement() throws ResourceRegistryException {
if(sourceEntityManagement == null) { if(sourceEntityManagement == null) {
Vertex source = getElement().getVertex(Direction.OUT); OVertex source = getElement().getVertex(ODirection.OUT);
sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElement(source); sourceEntityManagement.setElement(source);
} }
@ -71,7 +70,7 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
public TEM getTargetEntityManagement() throws ResourceRegistryException { public TEM getTargetEntityManagement() throws ResourceRegistryException {
if(targetEntityManagement == null) { if(targetEntityManagement == null) {
Vertex target = getElement().getVertex(Direction.IN); OVertex target = getElement().getVertex(ODirection.IN);
targetEntityManagement = newTargetEntityManagement(); targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElement(target); targetEntityManagement.setElement(target);
} }
@ -123,7 +122,7 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
} }
@Override @Override
protected Edge reallyCreate() throws ResourceRegistryException { protected OEdge reallyCreate() throws ResourceRegistryException {
if(sourceEntityManagement == null) { if(sourceEntityManagement == null) {
@ -169,10 +168,10 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
logger.trace("Creating {} beetween {} -> {}", elementType, getSourceEntityManagement().serialize(), logger.trace("Creating {} beetween {} -> {}", elementType, getSourceEntityManagement().serialize(),
getTargetEntityManagement().serialize()); getTargetEntityManagement().serialize());
Vertex source = (Vertex) getSourceEntityManagement().getElement(); OVertex source = (OVertex) getSourceEntityManagement().getElement();
Vertex target = (Vertex) getTargetEntityManagement().getElement(); OVertex target = (OVertex) getTargetEntityManagement().getElement();
element = orientGraph.addEdge(null, source, target, elementType); element = oDatabaseDocument.newEdge(source, target, elementType);
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
@ -184,17 +183,17 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
protected abstract TEM newTargetEntityManagement() throws ResourceRegistryException; protected abstract TEM newTargetEntityManagement() throws ResourceRegistryException;
@Override @Override
protected Edge reallyUpdate() throws ResourceRegistryException { protected OEdge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", elementType, jsonNode); logger.debug("Trying to update {} : {}", elementType, jsonNode);
Edge edge = getElement(); OEdge edge = getElement();
ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, 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);
if(target != null) { if(target != null) {
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph); FacetManagement fm = new FacetManagement(getWorkingContext(), oDatabaseDocument);
fm.setJsonNode(target); fm.setJsonNode(target);
fm.internalUpdate(); fm.internalUpdate();
} }
@ -211,7 +210,7 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
logger.debug("Going to remove {} with UUID {}. Related {}s will be detached.", accessType.getName(), uuid, logger.debug("Going to remove {} with UUID {}. Related {}s will be detached.", accessType.getName(), uuid,
targetEntityClass.getSimpleName()); targetEntityClass.getSimpleName());
getElement().remove(); getElement().delete();
return true; return true;
} }

View File

@ -24,9 +24,11 @@ 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.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Vertex;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -123,7 +125,7 @@ public class ContextUtility {
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(), logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
fullName); fullName);
Vertex contextVertex = getContextVertexByFullName(fullName); OVertex contextVertex = getContextVertexByFullName(fullName);
uuid = Utility.getUUID(contextVertex); uuid = Utility.getUUID(contextVertex);
@ -147,12 +149,27 @@ public class ContextUtility {
return getSecurityContextByUUID(uuid, null); return getSecurityContextByUUID(uuid, null);
} }
private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException { public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() {
return Utility.getElementByUUID(getAdminSecurityContext().getGraph(PermissionMode.READER), Context.NAME, uuid, ODatabaseDocument current = null;
Vertex.class); try {
current = (ODatabaseDocument) ODatabaseRecordThreadLocal.instance().get();
}catch (Exception e) {
// It is possible that there is non current ODatabaseDocument
}
return current;
} }
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException { private OVertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
OVertex oVertex = Utility.getElementByUUID(getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER), Context.NAME, uuid,
OVertex.class);
if(current!=null) {
current.activateOnCurrentThread();
}
return oVertex;
}
private SecurityContext getSecurityContextByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid); SecurityContext securityContext = contexts.get(uuid);
if(securityContext == null) { if(securityContext == null) {
@ -162,7 +179,7 @@ public class ContextUtility {
if(contextVertex == null) { if(contextVertex == null) {
contextVertex = getContextVertexByUUID(uuid); contextVertex = getContextVertexByUUID(uuid);
} }
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next(); OVertex parentVertex = contextVertex.getVertices(ODirection.IN, IsParentOf.NAME).iterator().next();
if(parentVertex != null) { if(parentVertex != null) {
UUID parentUUID = Utility.getUUID(parentVertex); UUID parentUUID = Utility.getUUID(parentVertex);
@ -180,14 +197,14 @@ public class ContextUtility {
} }
protected UUID getContextUUIDFromFullName(String fullName) throws ResourceRegistryException { protected UUID getContextUUIDFromFullName(String fullName) throws ResourceRegistryException {
Vertex contextVertex = getContextVertexByFullName(fullName); OVertex contextVertex = getContextVertexByFullName(fullName);
return Utility.getUUID(contextVertex); return Utility.getUUID(contextVertex);
} }
private Vertex getContextVertexByFullName(String fullName) throws ResourceRegistryException { private OVertex getContextVertexByFullName(String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} with full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName); logger.trace("Going to get {} {} with full name '{}'", Context.NAME, OVertex.class.getSimpleName(), fullName);
ScopeBean scopeBean = new ScopeBean(fullName); ScopeBean scopeBean = new ScopeBean(fullName);
String name = scopeBean.name(); String name = scopeBean.name();
@ -198,17 +215,20 @@ public class ContextUtility {
String select = "SELECT FROM " + Context.class.getSimpleName() + " WHERE " + Context.NAME_PROPERTY + " = \"" String select = "SELECT FROM " + Context.class.getSimpleName() + " WHERE " + Context.NAME_PROPERTY + " = \""
+ name + "\""; + name + "\"";
; ;
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select); OSQLSynchQuery<OVertex> osqlSynchQuery = new OSQLSynchQuery<OVertex>(select);
Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
Iterable<OVertex> vertexes = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER).command(osqlSynchQuery)
.execute(); .execute();
if(vertexes == null || !vertexes.iterator().hasNext()) { if(vertexes == null || !vertexes.iterator().hasNext()) {
throw new ContextNotFoundException("Error retrieving context with name " + fullName); throw new ContextNotFoundException("Error retrieving context with name " + fullName);
} }
Iterator<Vertex> iterator = vertexes.iterator(); Iterator<OVertex> iterator = vertexes.iterator();
Vertex context = iterator.next(); OVertex context = iterator.next();
logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true)); logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
@ -217,6 +237,10 @@ public class ContextUtility {
+ "but required the one with path" + fullName + ". Please Reimplement the query"); + "but required the one with path" + fullName + ". Please Reimplement the query");
} }
if(current!=null) {
current.activateOnCurrentThread();
}
return context; return context;
} }

View File

@ -31,11 +31,12 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -57,9 +58,9 @@ public class ContextManagement extends BaseEntityManagement<Context> {
init(); init();
} }
public ContextManagement(OrientGraph orientGraph) throws ResourceRegistryException { public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this(); this();
this.orientGraph = orientGraph; this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext(); getWorkingContext();
} }
@ -104,7 +105,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException { throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException {
if(parentContext != null) { if(parentContext != null) {
String parentId = parentContext.getElement().getId().toString(); String parentId = parentContext.getElement().getIdentity().toString();
// TODO Rewrite using Gremlin // TODO Rewrite using Gremlin
String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME + ") FROM " + parentId String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME + ") FROM " + parentId
@ -121,8 +122,8 @@ public class ContextManagement extends BaseEntityManagement<Context> {
logger.trace("Checking if {} -> {}", message, select); logger.trace("Checking if {} -> {}", message, select);
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select); OSQLSynchQuery<OVertex> osqlSynchQuery = new OSQLSynchQuery<OVertex>(select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery).execute(); Iterable<OVertex> vertexes = oDatabaseDocument.command(osqlSynchQuery).execute();
if(vertexes != null && vertexes.iterator().hasNext()) { if(vertexes != null && vertexes.iterator().hasNext()) {
throw new ContextAlreadyPresentException(message.toString()); throw new ContextAlreadyPresentException(message.toString());
@ -134,8 +135,8 @@ public class ContextManagement extends BaseEntityManagement<Context> {
+ Context.NAME_PROPERTY + " = \"" + getName() + "\"" + " AND in(\"" + IsParentOf.NAME + Context.NAME_PROPERTY + " = \"" + getName() + "\"" + " AND in(\"" + IsParentOf.NAME
+ "\").size() = 0"; + "\").size() = 0";
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select); OSQLSynchQuery<OVertex> osqlSynchQuery = new OSQLSynchQuery<OVertex>(select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery).execute(); Iterable<OVertex> vertexes = oDatabaseDocument.command(osqlSynchQuery).execute();
if(vertexes != null && vertexes.iterator().hasNext()) { if(vertexes != null && vertexes.iterator().hasNext()) {
throw new ContextAlreadyPresentException( throw new ContextAlreadyPresentException(
@ -157,13 +158,13 @@ public class ContextManagement extends BaseEntityManagement<Context> {
JsonNode context = serializeSelfOnly(); JsonNode context = serializeSelfOnly();
int count = 0; int count = 0;
Iterable<Edge> parents = getElement().getEdges(Direction.IN); Iterable<OEdge> parents = getElement().getEdges(ODirection.IN);
for(Edge edge : parents) { for(OEdge edge : parents) {
if(++count > 1) { if(++count > 1) {
throw new ContextException("A " + Context.NAME + " can not have more than one parent"); throw new ContextException("A " + Context.NAME + " can not have more than one parent");
} }
try { try {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
JsonNode isParentOf = isParentOfManagement.serializeAsJson(true, false); JsonNode isParentOf = isParentOfManagement.serializeAsJson(true, false);
if(isParentOf!=null) { if(isParentOf!=null) {
@ -175,10 +176,10 @@ public class ContextManagement extends BaseEntityManagement<Context> {
} }
} }
Iterable<Edge> childrenEdges = getElement().getEdges(Direction.OUT); Iterable<OEdge> childrenEdges = getElement().getEdges(ODirection.OUT);
for(Edge edge : childrenEdges) { for(OEdge edge : childrenEdges) {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
try { try {
JsonNode isParentOf = isParentOfManagement.serializeAsJson(); JsonNode isParentOf = isParentOfManagement.serializeAsJson();
@ -196,7 +197,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
} }
@Override @Override
protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException { protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null; SecurityContext securityContext = null;
SecurityContext parentSecurityContext = null; SecurityContext parentSecurityContext = null;
@ -206,7 +207,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) { if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY); JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
ContextManagement parentContextManagement = new ContextManagement(orientGraph); ContextManagement parentContextManagement = new ContextManagement(oDatabaseDocument);
parentContextManagement.setJsonNode(parentJsonNode); parentContextManagement.setJsonNode(parentJsonNode);
UUID parentUUID = parentContextManagement.uuid; UUID parentUUID = parentContextManagement.uuid;
parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID); parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID);
@ -219,7 +220,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
createVertex(); createVertex();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(parentContextManagement); isParentOfManagement.setSourceEntityManagement(parentContextManagement);
isParentOfManagement.setTargetEntityManagement(this); isParentOfManagement.setTargetEntityManagement(this);
@ -233,15 +234,15 @@ public class ContextManagement extends BaseEntityManagement<Context> {
securityContext = new SecurityContext(uuid); securityContext = new SecurityContext(uuid);
securityContext.setParentSecurityContext(parentSecurityContext); securityContext.setParentSecurityContext(parentSecurityContext);
securityContext.create(orientGraph); securityContext.create(oDatabaseDocument);
ContextUtility.getInstance().addSecurityContext(securityContext); ContextUtility.getInstance().addSecurityContext(securityContext);
return getElement(); return getElement();
} catch(Exception e) { } catch(Exception e) {
orientGraph.rollback(); oDatabaseDocument.rollback();
if(securityContext != null) { if(securityContext != null) {
securityContext.delete(orientGraph); securityContext.delete(oDatabaseDocument);
if(parentSecurityContext!=null && securityContext!=null) { if(parentSecurityContext!=null && securityContext!=null) {
parentSecurityContext.getChildren().remove(securityContext); parentSecurityContext.getChildren().remove(securityContext);
} }
@ -252,16 +253,16 @@ public class ContextManagement extends BaseEntityManagement<Context> {
} }
@Override @Override
protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException { protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
boolean parentChanged = false; boolean parentChanged = false;
boolean nameChanged = false; boolean nameChanged = false;
Vertex parent = null; OVertex parent = null;
boolean found = false; boolean found = false;
Iterable<Vertex> iterable = getElement().getVertices(Direction.IN, IsParentOf.NAME); Iterable<OVertex> iterable = getElement().getVertices(ODirection.IN, IsParentOf.NAME);
for(Vertex p : iterable) { for(OVertex p : iterable) {
if(found) { if(found) {
String message = String.format("{} has more than one parent. {}", Context.NAME, String message = String.format("{} has more than one parent. {}", Context.NAME,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -273,7 +274,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
ContextManagement actualParentContextManagement = null; ContextManagement actualParentContextManagement = null;
if(parent != null) { if(parent != null) {
actualParentContextManagement = new ContextManagement(orientGraph); actualParentContextManagement = new ContextManagement(oDatabaseDocument);
actualParentContextManagement.setElement(parent); actualParentContextManagement.setElement(parent);
} }
@ -296,7 +297,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
} }
if(parentChanged) { if(parentChanged) {
newParentContextManagement = new ContextManagement(orientGraph); newParentContextManagement = new ContextManagement(oDatabaseDocument);
newParentContextManagement.setJsonNode(parentContextJsonNode); newParentContextManagement.setJsonNode(parentContextJsonNode);
} }
} else { } else {
@ -322,7 +323,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
move(newParentContextManagement, false); move(newParentContextManagement, false);
} }
element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, element = (OVertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys,
ignoreStartWithKeys); ignoreStartWithKeys);
ContextUtility.getInstance().removeFromCache(uuid, (nameChanged && !parentChanged)); ContextUtility.getInstance().removeFromCache(uuid, (nameChanged && !parentChanged));
@ -339,10 +340,10 @@ public class ContextManagement extends BaseEntityManagement<Context> {
SecurityContext newParentSecurityContext = null; SecurityContext newParentSecurityContext = null;
// Removing the old parent relationship if any // Removing the old parent relationship if any
Iterable<Edge> edges = getElement().getEdges(Direction.IN, IsParentOf.NAME); Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME);
if(edges != null && edges.iterator().hasNext()) { if(edges != null && edges.iterator().hasNext()) {
Iterator<Edge> edgeIterator = edges.iterator(); Iterator<OEdge> edgeIterator = edges.iterator();
Edge edge = edgeIterator.next(); OEdge edge = edgeIterator.next();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(); IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
isParentOfManagement.internalDelete(); isParentOfManagement.internalDelete();
@ -355,7 +356,7 @@ public class ContextManagement extends BaseEntityManagement<Context> {
if(newParentContextManagement != null) { if(newParentContextManagement != null) {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(newParentContextManagement); isParentOfManagement.setSourceEntityManagement(newParentContextManagement);
isParentOfManagement.setTargetEntityManagement(this); isParentOfManagement.setTargetEntityManagement(this);
@ -364,22 +365,22 @@ public class ContextManagement extends BaseEntityManagement<Context> {
} }
SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid); SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, orientGraph); thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, oDatabaseDocument);
} }
@Override @Override
protected boolean reallyDelete() throws NotFoundException, ResourceRegistryException { protected boolean reallyDelete() throws NotFoundException, ResourceRegistryException {
Iterable<Edge> iterable = getElement().getEdges(Direction.OUT); Iterable<OEdge> iterable = getElement().getEdges(ODirection.OUT);
Iterator<Edge> iterator = iterable.iterator(); Iterator<OEdge> iterator = iterable.iterator();
while(iterator.hasNext()) { while(iterator.hasNext()) {
throw new ContextException("Cannot remove a " + Context.NAME + " having children"); throw new ContextException("Cannot remove a " + Context.NAME + " having children");
} }
element.remove(); element.delete();
ContextUtility contextUtility = ContextUtility.getInstance(); ContextUtility contextUtility = ContextUtility.getInstance();
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid); SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(orientGraph); securityContext.delete(oDatabaseDocument);
contextUtility.removeFromCache(uuid, false); contextUtility.removeFromCache(uuid, false);
@ -391,10 +392,10 @@ public class ContextManagement extends BaseEntityManagement<Context> {
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(elementType, polymorphic); Iterable<ODocument> iterable = oDatabaseDocument.browseClass(elementType, polymorphic);
for(Vertex vertex : iterable) { for(ODocument vertex : iterable) {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
contextManagement.setElement(vertex); contextManagement.setElement((OVertex) vertex);
try { try {
JsonNode jsonObject = contextManagement.serializeAsJson(); JsonNode jsonObject = contextManagement.serializeAsJson();
arrayNode.add(jsonObject); arrayNode.add(jsonObject);

View File

@ -19,9 +19,9 @@ import org.gcube.informationsystem.resourceregistry.utils.Utility;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tinkerpop.blueprints.Direction; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.record.ODirection;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.record.OVertex;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -32,9 +32,9 @@ public class IsParentOfManagement extends BaseRelationManagement<IsParentOf,Cont
super(AccessType.IS_PARENT_OF, Context.class, Context.class); super(AccessType.IS_PARENT_OF, Context.class, Context.class);
} }
public IsParentOfManagement(OrientGraph orientGraph) throws ResourceRegistryException { public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this(); this();
this.orientGraph = orientGraph; this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext(); getWorkingContext();
} }
@ -66,15 +66,15 @@ public class IsParentOfManagement extends BaseRelationManagement<IsParentOf,Cont
JsonNode relation = serializeSelfOnly(); JsonNode relation = serializeSelfOnly();
try { try {
Vertex source = element.getVertex(Direction.OUT); OVertex source = element.getVertex(ODirection.OUT);
ContextManagement sourceContextManagement = new ContextManagement(orientGraph); ContextManagement sourceContextManagement = new ContextManagement(oDatabaseDocument);
sourceContextManagement.setElement(source); sourceContextManagement.setElement(source);
if(includeSource) { if(includeSource) {
((ObjectNode)relation).replace(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly()); ((ObjectNode)relation).replace(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
} }
Vertex target = element.getVertex(Direction.IN); OVertex target = element.getVertex(ODirection.IN);
ContextManagement targetContextManagement = new ContextManagement(orientGraph); ContextManagement targetContextManagement = new ContextManagement(oDatabaseDocument);
targetContextManagement.setElement(target); targetContextManagement.setElement(target);
if(includeTarget) { if(includeTarget) {
((ObjectNode)relation).replace(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly()); ((ObjectNode)relation).replace(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly());
@ -93,12 +93,12 @@ public class IsParentOfManagement extends BaseRelationManagement<IsParentOf,Cont
@Override @Override
protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException { protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ContextManagement(orientGraph); return new ContextManagement(oDatabaseDocument);
} }
@Override @Override
protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException { protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ContextManagement(orientGraph); return new ContextManagement(oDatabaseDocument);
} }
@Override @Override

View File

@ -33,16 +33,14 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -61,18 +59,18 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
this.ignoreKeys.add(Entity.HEADER_PROPERTY); this.ignoreKeys.add(Entity.HEADER_PROPERTY);
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toLowerCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_IN_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toUpperCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_IN_PREFIX.toUpperCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase()); this.ignoreStartWithKeys.add(com.tinkerpop.blueprints.impls.orient.OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase());
this.relationManagements = new HashMap<>(); this.relationManagements = new HashMap<>();
} }
protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) { protected EntityManagement(AccessType accessType, SecurityContext workingContext, ODatabaseDocument orientGraph) {
this(accessType); this(accessType);
this.orientGraph = orientGraph; this.oDatabaseDocument = orientGraph;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
@ -83,11 +81,11 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
* fake id starting with - (minus) sign. This not imply any collateral effect * fake id starting with - (minus) sign. This not imply any collateral effect
* but a better solution is a desiderata. * but a better solution is a desiderata.
*/ */
protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException { protected RelationManagement getRelationManagement(OEdge edge) throws ResourceRegistryException {
String id = edge.getId().toString(); String id = edge.getIdentity().toString();
RelationManagement relationManagement = relationManagements.get(id); RelationManagement relationManagement = relationManagements.get(id);
if(relationManagement == null) { if(relationManagement == null) {
relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
return relationManagement; return relationManagement;
@ -95,8 +93,8 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement) protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement)
throws ResourceRegistryException { throws ResourceRegistryException {
Element elem = relationManagement.getElement(); OElement elem = relationManagement.getElement();
String id = elem.getId().toString(); String id = elem.getIdentity().toString();
if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) { if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Two different instance of "); errorMessage.append("Two different instance of ");
@ -127,9 +125,9 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
return sourceResource; return sourceResource;
} }
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(), logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
elementType, jsonNode); elementType, jsonNode);
try { try {
@ -141,11 +139,11 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
Vertex vertexEntity = orientGraph.addVertex("class:" + elementType); OVertex vertexEntity = oDatabaseDocument.newVertex(elementType);
try { try {
if(uuid != null) { if(uuid != null) {
Vertex v = getElement(); OVertex v = getElement();
if(v != null) { if(v != null) {
String error = String.format("A %s with UUID %s already exist", elementType, uuid.toString()); String error = String.format("A %s with UUID %s already exist", elementType, uuid.toString());
throw getSpecificERAlreadyPresentException(error); throw getSpecificERAlreadyPresentException(error);
@ -154,9 +152,9 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} catch(NotFoundException e) { } catch(NotFoundException e) {
try { try {
Element el = ERManagementUtility.getAnyElementByUUID(uuid); OElement el = ERManagementUtility.getAnyElementByUUID(uuid);
String error = String.format("UUID %s is already used by another %s. This is not allowed.", String error = String.format("UUID %s is already used by another %s. This is not allowed.",
uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME); uuid.toString(), (el instanceof OVertex) ? Entity.NAME : Relation.NAME);
throw getSpecificERAvailableInAnotherContextException(error); throw getSpecificERAvailableInAnotherContextException(error);
} catch(NotFoundException e1) { } catch(NotFoundException e1) {
@ -174,14 +172,14 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
} }
logger.info("Created {} is {}", Vertex.class.getSimpleName(), logger.info("Created {} is {}", OVertex.class.getSimpleName(),
Utility.toJsonString((OrientVertex) element, true)); Utility.toJsonString((OVertex) element, true));
return element; 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 {}", Vertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), elementType, jsonNode, e); accessType.getName(), elementType, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + elementType + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + elementType + " with " + jsonNode, e.getCause());
} }
@ -191,11 +189,11 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
protected boolean reallyAddToContext(SecurityContext targetSecurityContext) protected boolean reallyAddToContext(SecurityContext targetSecurityContext)
throws ContextException, ResourceRegistryException { throws ContextException, ResourceRegistryException {
targetSecurityContext.addElement(getElement(), orientGraph); targetSecurityContext.addElement(getElement(), oDatabaseDocument);
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(Edge edge : edges) { for(OEdge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge); RelationManagement relationManagement = getRelationManagement(edge);
relationManagement.internalAddToContext(targetSecurityContext); relationManagement.internalAddToContext(targetSecurityContext);
@ -208,15 +206,15 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
protected boolean reallyRemoveFromContext(SecurityContext targetSecurityContext) protected boolean reallyRemoveFromContext(SecurityContext targetSecurityContext)
throws ContextException, ResourceRegistryException { throws ContextException, ResourceRegistryException {
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(Edge edge : edges) { for(OEdge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge); RelationManagement relationManagement = getRelationManagement(edge);
relationManagement.internalRemoveFromContext(targetSecurityContext); relationManagement.internalRemoveFromContext(targetSecurityContext);
} }
targetSecurityContext.removeElement(getElement(), orientGraph); targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
return true; return true;
} }
@ -226,11 +224,10 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(elementType, polymorphic); Iterable<ODocument> iterable = oDatabaseDocument.browseClass(elementType, polymorphic);
for(Vertex vertex : iterable) { for(ODocument vertex : iterable) {
@SuppressWarnings("rawtypes") EntityManagement<?> entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), oDatabaseDocument, (OVertex) vertex);
orientGraph, vertex);
try { try {
JsonNode jsonNode = entityManagement.serializeAsJson(); JsonNode jsonNode = entityManagement.serializeAsJson();
arrayNode.add(jsonNode); arrayNode.add(jsonNode);
@ -246,25 +243,23 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} }
} }
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, Direction direction, public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException { boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<Vertex> references = null; Iterable<?> references = null;
if(referenceUUID != null) { if(referenceUUID != null) {
Element element = ERManagementUtility.getAnyElementByUUID(referenceUUID); OElement element = ERManagementUtility.getAnyElementByUUID(referenceUUID);
if(element instanceof Vertex) { if(element instanceof OVertex) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
EntityManagement<Entity> entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement<Entity> entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, (Vertex) element); oDatabaseDocument, (OVertex) element);
OrientVertexType orientVertexType = ((OrientVertex) element).getType();
String elementType = entityManagement.getElementType(); String elementType = entityManagement.getElementType();
if(elementType.compareTo(referenceType) != 0) { if(elementType.compareTo(referenceType) != 0) {
if(polymorphic && orientVertexType.isSubClassOf(referenceType)) { if(polymorphic && getOClass().isSubClassOf(referenceType)) {
// OK // OK
} else { } else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID,
@ -273,8 +268,8 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} }
} }
List<Vertex> vertexes = new ArrayList<>(); List<OVertex> vertexes = new ArrayList<>();
vertexes.add((Vertex) element); vertexes.add((OVertex) element);
references = vertexes; references = vertexes;
} else { } else {
@ -283,45 +278,42 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} }
} else { } else {
references = orientGraph.getVerticesOfClass(referenceType, polymorphic); references = oDatabaseDocument.browseClass(referenceType, polymorphic);
} }
for(Vertex v : references) { for(Object r : references) {
List<Direction> directions = new ArrayList<>(); OVertex v = (OVertex) r;
if(direction==Direction.BOTH) { List<ODirection> directions = new ArrayList<>();
directions.add(Direction.IN); if(direction==ODirection.BOTH) {
directions.add(Direction.OUT); directions.add(ODirection.IN);
directions.add(ODirection.OUT);
}else { }else {
directions.add(direction); directions.add(direction);
} }
for(Direction d : directions) { for(ODirection d : directions) {
Iterable<Edge> edges = v.getEdges(d.opposite(), relationType); Iterable<OEdge> edges = v.getEdges(d.opposite(), relationType);
for(Edge edge : edges) { for(OEdge edge : edges) {
Vertex vertex = ((OrientEdge) edge).getVertex(d); OVertex vertex = edge.getVertex(d);
OrientVertex orientVertex = (OrientVertex) vertex;
if(((OrientVertex) v).getIdentity().compareTo(orientVertex.getIdentity()) == 0) { if(v.getIdentity().compareTo(vertex.getIdentity()) == 0) {
continue; continue;
} }
if(elementType.compareTo(orientVertex.getLabel()) != 0) { OClass oClass = ERManagement.getOClass(vertex);
OrientVertexType orientVertexType = orientVertex.getType(); if(polymorphic && oClass.isSubClassOf(elementType)) {
// OK
if(polymorphic && orientVertexType.isSubClassOf(elementType)) { } else {
// OK // excluding from results
} else { continue;
// excluding from results
continue;
}
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, vertex); oDatabaseDocument, vertex);
try { try {
if(entityManagement.getUUID().compareTo(referenceUUID) == 0) { if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
continue; continue;
} }
JsonNode jsonNode = entityManagement.serializeAsJson(); JsonNode jsonNode = entityManagement.serializeAsJson();
@ -342,7 +334,7 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} }
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID, public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
Direction direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException { ODirection direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
@ -395,19 +387,18 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
String select = selectStringBuilder.toString(); String select = selectStringBuilder.toString();
logger.trace(select); logger.trace(select);
OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>(select); OSQLSynchQuery<OElement> osqlSynchQuery = new OSQLSynchQuery<OElement>(select);
Iterable<Element> elements = orientGraph.command(osqlSynchQuery).execute(); Iterable<OElement> elements = oDatabaseDocument.command(osqlSynchQuery).execute();
for(Element element : elements) { for(OElement element : elements) {
if(polymorphic) { if(polymorphic) {
OrientVertexType orientVertexType = null; OClass oClass = null;
try { try {
OrientElement orientElement = ((OrientElement) element); if(element instanceof OEdge) {
if(orientElement instanceof OrientEdge) {
continue; continue;
} }
orientVertexType = ((OrientVertex) orientElement).getType(); oClass = ERManagement.getOClass(element);
} catch(Exception e) { } catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", element.toString(), String error = String.format("Unable to detect type of %s. %s", element.toString(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -415,19 +406,17 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
if(orientVertexType.getName().compareTo(elementType) != 0) { if(oClass.isSubClassOf(elementType)) {
if(!orientVertexType.isSubClassOf(elementType)) { continue;
continue;
}
} }
} }
Vertex vertex = (Vertex) element; OVertex vertex = (OVertex) element;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, vertex); oDatabaseDocument, vertex);
try { try {
if(constraint.containsKey(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY)) { if(constraint.containsKey(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY)) {
String uuid = constraint.get(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY); String uuid = constraint.get(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY);
@ -450,10 +439,10 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} }
} }
public String query(String relationType, String referenceType, UUID referenceUUID, Direction direction, public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException { boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
AccessType relationAccessType = ERManagementUtility.getBaseAccessType(relationType); AccessType relationAccessType = ERManagementUtility.getBaseAccessType(relationType);
if(relationAccessType != AccessType.IS_RELATED_TO && relationAccessType != AccessType.CONSISTS_OF) { if(relationAccessType != AccessType.IS_RELATED_TO && relationAccessType != AccessType.CONSISTS_OF) {
@ -476,9 +465,9 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
if(relationAccessType == AccessType.CONSISTS_OF) { if(relationAccessType == AccessType.CONSISTS_OF) {
if(direction != Direction.OUT) { if(direction != ODirection.OUT) {
String error = String.format("%s can only goes %s from %s.", relationType, String error = String.format("%s can only goes %s from %s.", relationType,
Direction.OUT.name(), elementType); ODirection.OUT.name(), elementType);
throw new InvalidQueryException(error); throw new InvalidQueryException(error);
} else { } else {
if(referenceAccessType != AccessType.FACET) { if(referenceAccessType != AccessType.FACET) {
@ -492,10 +481,10 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
break; break;
case FACET: case FACET:
if(relationAccessType != AccessType.CONSISTS_OF || direction != Direction.IN if(relationAccessType != AccessType.CONSISTS_OF || direction != ODirection.IN
|| referenceAccessType != AccessType.RESOURCE) { || referenceAccessType != AccessType.RESOURCE) {
String error = String.format("%s can only has %s %s from a %s.", elementType, String error = String.format("%s can only has %s %s from a %s.", elementType,
Direction.IN.name(), ConsistsOf.NAME, Resource.NAME); ODirection.IN.name(), ConsistsOf.NAME, Resource.NAME);
throw new InvalidQueryException(error); throw new InvalidQueryException(error);
} }
@ -512,8 +501,8 @@ public abstract class EntityManagement<E extends BaseEntity> extends BaseEntityM
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }

View File

@ -11,8 +11,8 @@ import org.gcube.informationsystem.resourceregistry.instances.base.ERManagement;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.security.SecurityContext;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.record.OVertex;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -23,7 +23,7 @@ public class FacetManagement extends EntityManagement<Facet> {
super(AccessType.FACET); super(AccessType.FACET);
} }
public FacetManagement(SecurityContext workingContext, OrientGraph orientGraph) { public FacetManagement(SecurityContext workingContext, ODatabaseDocument orientGraph) {
super(AccessType.FACET, workingContext, orientGraph); super(AccessType.FACET, workingContext, orientGraph);
} }
@ -53,20 +53,20 @@ public class FacetManagement extends EntityManagement<Facet> {
} }
@Override @Override
protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { protected OVertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
return createVertex(); return createVertex();
} }
@Override @Override
protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException { protected OVertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException {
Vertex facet = getElement(); OVertex facet = getElement();
facet = (Vertex) ERManagement.updateProperties(oClass, facet, jsonNode, ignoreKeys, ignoreStartWithKeys); facet = (OVertex) ERManagement.updateProperties(oClass, facet, jsonNode, ignoreKeys, ignoreStartWithKeys);
return facet; return facet;
} }
@Override @Override
protected boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException { protected boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException {
getElement().remove(); getElement().delete();
return true; return true;
} }

View File

@ -19,12 +19,11 @@ import org.gcube.informationsystem.resourceregistry.security.SecurityContext.Per
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.tinkerpop.blueprints.Direction; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.Edge; import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.record.ODirection;
import com.tinkerpop.blueprints.impls.orient.OrientEdge; import com.orientechnologies.orient.core.record.OEdge;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType; import com.orientechnologies.orient.core.record.OVertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -35,8 +34,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
super(AccessType.RESOURCE); super(AccessType.RESOURCE);
} }
public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) { public ResourceManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument) {
super(AccessType.RESOURCE, workingContext, orientGraph); super(AccessType.RESOURCE, workingContext, oDatabaseDocument);
} }
@Override @Override
@ -71,8 +70,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
* ConsistsOf.NAME); TODO Looks for a different query * ConsistsOf.NAME); TODO Looks for a different query
*/ */
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(Edge edge : edges) { for(OEdge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge); RelationManagement relationManagement = getRelationManagement(edge);
@ -128,7 +127,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
@Override @Override
protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException { protected OVertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
createVertex(); createVertex();
@ -136,7 +135,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
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(getWorkingContext(), orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), oDatabaseDocument);
com.setJsonNode(consistOfJsonNode); com.setJsonNode(consistOfJsonNode);
com.setSourceEntityManagement(this); com.setSourceEntityManagement(this);
com.internalCreate(); com.internalCreate();
@ -148,7 +147,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
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(getWorkingContext(), orientGraph); IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), oDatabaseDocument);
irtm.setJsonNode(relationJsonNode); irtm.setJsonNode(relationJsonNode);
irtm.setSourceEntityManagement(this); irtm.setSourceEntityManagement(this);
irtm.internalCreate(); irtm.internalCreate();
@ -160,7 +159,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
@Override @Override
protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException { protected OVertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
getElement(); getElement();
@ -168,7 +167,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
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) {
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), oDatabaseDocument);
com.setJsonNode(relationJsonNode); com.setJsonNode(relationJsonNode);
com.internalCreateOrUdate(); com.internalCreateOrUdate();
addToRelationManagement(com); addToRelationManagement(com);
@ -179,7 +178,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
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(getWorkingContext(), orientGraph); IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), oDatabaseDocument);
irtm.setJsonNode(relationJsonNode); irtm.setJsonNode(relationJsonNode);
irtm.internalUpdate(); irtm.internalUpdate();
addToRelationManagement(irtm); addToRelationManagement(irtm);
@ -196,18 +195,19 @@ public class ResourceManagement extends EntityManagement<Resource> {
getElement(); getElement();
Iterable<Edge> iterable = element.getEdges(Direction.OUT); Iterable<OEdge> iterable = element.getEdges(ODirection.OUT);
Iterator<Edge> iterator = iterable.iterator(); Iterator<OEdge> iterator = iterable.iterator();
while(iterator.hasNext()) { while(iterator.hasNext()) {
Edge edge = iterator.next(); OEdge edge = iterator.next();
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); OClass oClass = getOClass(edge);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = null; RelationManagement relationManagement = null;
if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph); relationManagement = new IsRelatedToManagement(getWorkingContext(), oDatabaseDocument);
} else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { } else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph); relationManagement = new ConsistsOfManagement(getWorkingContext(), oDatabaseDocument);
} else { } else {
logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME, logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME,
ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -219,14 +219,14 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
element.remove(); element.delete();
return true; return true;
} }
public String all(boolean polymorphic) throws ResourceRegistryException { public String all(boolean polymorphic) throws ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
return reallyGetAll(polymorphic); return reallyGetAll(polymorphic);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
@ -234,8 +234,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }

View File

@ -16,7 +16,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.cons
import org.gcube.informationsystem.resourceregistry.instances.model.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.instances.model.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.security.SecurityContext;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -35,7 +35,7 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf<Resource
super(AccessType.CONSISTS_OF, Facet.class, DEFAULT_CONSISTS_OF_PC); super(AccessType.CONSISTS_OF, Facet.class, DEFAULT_CONSISTS_OF_PC);
} }
public ConsistsOfManagement(SecurityContext workingContext, OrientGraph orientGraph) { public ConsistsOfManagement(SecurityContext workingContext, ODatabaseDocument orientGraph) {
super(AccessType.CONSISTS_OF, Facet.class, workingContext, orientGraph, DEFAULT_CONSISTS_OF_PC); super(AccessType.CONSISTS_OF, Facet.class, workingContext, orientGraph, DEFAULT_CONSISTS_OF_PC);
} }
@ -57,7 +57,7 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf<Resource
@Override @Override
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException { protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
return new FacetManagement(getWorkingContext(), orientGraph); return new FacetManagement(getWorkingContext(), oDatabaseDocument);
} }
} }

View File

@ -15,7 +15,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isre
import org.gcube.informationsystem.resourceregistry.instances.model.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.instances.model.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.security.SecurityContext;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -34,7 +34,7 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo<Resour
super(AccessType.IS_RELATED_TO, Resource.class, DEFAULT_IS_RELATED_TO_PC); super(AccessType.IS_RELATED_TO, Resource.class, DEFAULT_IS_RELATED_TO_PC);
} }
public IsRelatedToManagement(SecurityContext workingContext, OrientGraph orientGraph) { public IsRelatedToManagement(SecurityContext workingContext, ODatabaseDocument orientGraph) {
super(AccessType.IS_RELATED_TO, Resource.class, workingContext, orientGraph, DEFAULT_IS_RELATED_TO_PC); super(AccessType.IS_RELATED_TO, Resource.class, workingContext, orientGraph, DEFAULT_IS_RELATED_TO_PC);
} }
@ -56,7 +56,7 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo<Resour
@Override @Override
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException { protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(getWorkingContext(), orientGraph); return new ResourceManagement(getWorkingContext(), oDatabaseDocument);
} }
} }

View File

@ -34,14 +34,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -56,10 +55,10 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
this.defaultPropagationConstraint = defaultPropagationConstraint; this.defaultPropagationConstraint = defaultPropagationConstraint;
} }
protected RelationManagement(AccessType accessType, Class<TE> targetEntityClass, SecurityContext workingContext, OrientGraph orientGraph, protected RelationManagement(AccessType accessType, Class<TE> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph,
PropagationConstraint defaultPropagationConstraint) { PropagationConstraint defaultPropagationConstraint) {
this(accessType, targetEntityClass, defaultPropagationConstraint); this(accessType, targetEntityClass, defaultPropagationConstraint);
this.orientGraph = orientGraph; this.oDatabaseDocument = orientGraph;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
@ -74,7 +73,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
public ResourceManagement getSourceEntityManagement() throws ResourceRegistryException { public ResourceManagement getSourceEntityManagement() throws ResourceRegistryException {
if(sourceEntityManagement == null) { if(sourceEntityManagement == null) {
Vertex source = getElement().getVertex(Direction.OUT); OVertex source = getElement().getVertex(ODirection.OUT);
sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElement(source); sourceEntityManagement.setElement(source);
} }
@ -84,7 +83,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
public T getTargetEntityManagement() throws ResourceRegistryException { public T getTargetEntityManagement() throws ResourceRegistryException {
if(targetEntityManagement == null) { if(targetEntityManagement == null) {
Vertex target = getElement().getVertex(Direction.IN); OVertex target = getElement().getVertex(ODirection.IN);
targetEntityManagement = newTargetEntityManagement(); targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElement(target); targetEntityManagement.setElement(target);
} }
@ -138,16 +137,16 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
protected Map<String,JsonNode> fullSerialize(Map<String,JsonNode> visitedSourceResources) protected Map<String,JsonNode> fullSerialize(Map<String,JsonNode> visitedSourceResources)
throws ResourceRegistryException { throws ResourceRegistryException {
Vertex source = getElement().getVertex(Direction.OUT); OVertex source = getElement().getVertex(ODirection.OUT);
String id = source.getId().toString(); String id = source.getIdentity().toString();
JsonNode sourceResource = visitedSourceResources.get(id); JsonNode sourceResource = visitedSourceResources.get(id);
ResourceManagement resourceManagement = null; ResourceManagement resourceManagement = null;
if(sourceResource == null) { if(sourceResource == null) {
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, source); oDatabaseDocument, 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) {
@ -216,14 +215,13 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
} }
protected void checkPropagationConstraint() throws ResourceRegistryException { protected void checkPropagationConstraint() throws ResourceRegistryException {
OrientElement orientElement = (OrientElement) element; Object object = getElement().getProperty(Relation.PROPAGATION_CONSTRAINT);
Object object = orientElement.getProperty(Relation.PROPAGATION_CONSTRAINT);
PropagationConstraintOrient pc = getPropagationConstraint((ODocument) object); PropagationConstraintOrient pc = getPropagationConstraint((ODocument) object);
orientElement.setProperty(Relation.PROPAGATION_CONSTRAINT, pc, OType.EMBEDDED); getElement().setProperty(Relation.PROPAGATION_CONSTRAINT, pc, OType.EMBEDDED);
} }
@Override @Override
protected Edge reallyCreate() throws ResourceRegistryException { protected OEdge reallyCreate() throws ResourceRegistryException {
element = super.reallyCreate(); element = super.reallyCreate();
checkPropagationConstraint(); checkPropagationConstraint();
@ -234,23 +232,23 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
} }
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(getWorkingContext(), orientGraph); return new ResourceManagement(getWorkingContext(), oDatabaseDocument);
} }
protected abstract T newTargetEntityManagement() throws ResourceRegistryException; protected abstract T newTargetEntityManagement() throws ResourceRegistryException;
@Override @Override
protected Edge reallyUpdate() throws ResourceRegistryException { protected OEdge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", elementType, jsonNode); logger.debug("Trying to update {} : {}", elementType, jsonNode);
Edge edge = getElement(); OEdge edge = getElement();
ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, 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);
if(target != null) { if(target != null) {
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph); FacetManagement fm = new FacetManagement(getWorkingContext(), oDatabaseDocument);
fm.setJsonNode(target); fm.setJsonNode(target);
fm.internalUpdate(); fm.internalUpdate();
} }
@ -297,7 +295,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
*/ */
getTargetEntityManagement().internalAddToContext(targetSecurityContext); getTargetEntityManagement().internalAddToContext(targetSecurityContext);
targetSecurityContext.addElement(getElement(), orientGraph); targetSecurityContext.addElement(getElement(), oDatabaseDocument);
break; break;
@ -322,7 +320,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
/* Adding target to Context */ /* Adding target to Context */
getTargetEntityManagement().internalAddToContext(targetSecurityContext); getTargetEntityManagement().internalAddToContext(targetSecurityContext);
targetSecurityContext.addElement(getElement(), orientGraph); targetSecurityContext.addElement(getElement(), oDatabaseDocument);
return true; return true;
} }
@ -359,7 +357,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
* In any removeConstraint value the relation MUST be removed from context to * In any removeConstraint value the relation MUST be removed from context to
* avoid to have edge having a source outside of the context. * avoid to have edge having a source outside of the context.
*/ */
targetSecurityContext.removeElement(getElement(), orientGraph); targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
switch(removeConstraint) { switch(removeConstraint) {
case cascade: case cascade:
@ -367,17 +365,17 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
break; break;
case cascadeWhenOrphan: case cascadeWhenOrphan:
Vertex target = (Vertex) getTargetEntityManagement().getElement(); OVertex target = (OVertex) getTargetEntityManagement().getElement();
Iterable<Edge> iterable = target.getEdges(Direction.IN); Iterable<OEdge> iterable = target.getEdges(ODirection.IN);
Iterator<Edge> iterator = iterable.iterator(); Iterator<OEdge> iterator = iterable.iterator();
int count = 0; int count = 0;
OrientEdge edge = null; OEdge edge = null;
while(iterator.hasNext()) { while(iterator.hasNext()) {
edge = (OrientEdge) iterator.next(); edge = (OEdge) iterator.next();
OrientEdge thisOrientEdge = (OrientEdge) getElement(); OEdge thisOEdge = (OEdge) getElement();
if(edge.compareTo(thisOrientEdge) != 0) { if(edge.compareTo(thisOEdge) != 0) {
if(thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) { if(thisOEdge.getVertex(ODirection.OUT).compareTo(edge.getVertex(ODirection.OUT)) != 0) {
count++; count++;
break; break;
} }
@ -432,8 +430,8 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
Vertex target = (Vertex) getTargetEntityManagement().getElement(); OVertex target = getTargetEntityManagement().getElement();
element.remove(); element.delete();
switch(removeConstraint) { switch(removeConstraint) {
case cascade: case cascade:
@ -441,8 +439,8 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
break; break;
case cascadeWhenOrphan: case cascadeWhenOrphan:
Iterable<Edge> iterable = target.getEdges(Direction.IN); Iterable<OEdge> iterable = target.getEdges(ODirection.IN);
Iterator<Edge> iterator = iterable.iterator(); Iterator<OEdge> iterator = iterable.iterator();
if(iterator.hasNext()) { if(iterator.hasNext()) {
logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element, logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
target, removeConstraint); target, removeConstraint);
@ -462,16 +460,19 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Collection<JsonNode> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic) protected Collection<JsonNode> serializeEdges(Iterable<ODocument> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException { throws ResourceRegistryException {
Map<String,JsonNode> visitedSourceResources = new HashMap<>(); Map<String,JsonNode> visitedSourceResources = new HashMap<>();
for(Edge edge : edges) { for(ODocument d : edges) {
if(postFilterPolymorphic && edge.getLabel().compareTo(elementType) != 0) { OEdge edge = (OEdge) d;
// TODO check because it was using compare
if(postFilterPolymorphic && getOClass().isSubClassOf(elementType)) {
continue; continue;
} }
RelationManagement<R, T, TE> relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), RelationManagement<R, T, TE> relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(),
orientGraph, edge); oDatabaseDocument, edge);
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
} }
return visitedSourceResources.values(); return visitedSourceResources.values();
@ -489,7 +490,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
@Override @Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
Iterable<Edge> edges = orientGraph.getEdgesOfClass(elementType, polymorphic); Iterable<ODocument> edges = oDatabaseDocument.browseClass(elementType, polymorphic);
Collection<JsonNode> collection = serializeEdges(edges, false); Collection<JsonNode> collection = serializeEdges(edges, false);
return serializeJsonNodeCollectionAsString(collection); return serializeJsonNodeCollectionAsString(collection);
} }
@ -499,13 +500,13 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
logger.debug("Going to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid, contextUUID); logger.debug("Going to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid, contextUUID);
try { try {
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
boolean added = forcedAddToContext(targetSecurityContext); boolean added = forcedAddToContext(targetSecurityContext);
orientGraph.commit(); oDatabaseDocument.commit();
logger.info("{} with UUID {} successfully added to Context with UUID {}", accessType.getName(), uuid, logger.info("{} with UUID {} successfully added to Context with UUID {}", accessType.getName(), uuid,
contextUUID); contextUUID);
@ -513,13 +514,13 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid, logger.error("Unable to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid,
contextUUID, e); contextUUID, e);
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.rollback(); oDatabaseDocument.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(orientGraph != null) { if(oDatabaseDocument != null) {
orientGraph.shutdown(); oDatabaseDocument.close();
} }
} }
} }

View File

@ -17,11 +17,10 @@ import org.gcube.informationsystem.types.reference.relations.RelationTypeDefinit
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class SchemaContextManagementOld implements SchemaManagement { public class SchemaContextManagementOld implements SchemaManagement {
@ -29,13 +28,13 @@ public class SchemaContextManagementOld implements SchemaManagement {
public static final String SCHEMA = "__SCHEMA"; public static final String SCHEMA = "__SCHEMA";
protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception { protected OVertex getVertex(ODatabaseDocument oDatabaseDocument, String vertexType) throws Exception {
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(vertexType, false); Iterable<ODocument> iterable = oDatabaseDocument.browseClass(vertexType, false);
Iterator<Vertex> iterator = iterable.iterator(); Iterator<ODocument> iterator = iterable.iterator();
Vertex vertex = null; OVertex vertex = null;
if(iterator.hasNext()) { if(iterator.hasNext()) {
vertex = iterator.next(); vertex = (OVertex) iterator.next();
} else { } else {
String error = String.format("%s is not a registered type", vertexType); String error = String.format("%s is not a registered type", vertexType);
logger.trace(error); logger.trace(error);
@ -56,30 +55,30 @@ public class SchemaContextManagementOld implements SchemaManagement {
@Override @Override
public String create(String json, AccessType baseType) throws SchemaException { public String create(String json, AccessType baseType) throws SchemaException {
OrientGraph orientGraph = null; ODatabaseDocument orientGraph = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraph = adminSecurityContext.getGraph(PermissionMode.WRITER); orientGraph = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
TypeDefinition typeDefinition = TypeBinder.deserializeTypeDefinition(json); TypeDefinition typeDefinition = TypeBinder.deserializeTypeDefinition(json);
if(BaseEntity.class.isAssignableFrom(baseType.getTypeClass())) { if(BaseEntity.class.isAssignableFrom(baseType.getTypeClass())) {
OrientVertex orientVertex = orientGraph.addVertex("class:" + typeDefinition.getName()); OVertex oVertex = orientGraph.newVertex(typeDefinition.getName());
orientVertex.setProperty(SCHEMA, json); oVertex.setProperty(SCHEMA, json);
orientVertex.save(); oVertex.save();
} else if(BaseRelation.class.isAssignableFrom(baseType.getTypeClass())) { } else if(BaseRelation.class.isAssignableFrom(baseType.getTypeClass())) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
String sourceClass = ((RelationTypeDefinition) typeDefinition).getSourceType(); String sourceClass = ((RelationTypeDefinition) typeDefinition).getSourceType();
Vertex source = getVertex(orientGraph, sourceClass); OVertex source = getVertex(orientGraph, sourceClass);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
String targetClass = ((RelationTypeDefinition) typeDefinition).getTargetType(); String targetClass = ((RelationTypeDefinition) typeDefinition).getTargetType();
Vertex target = getVertex(orientGraph, targetClass); OVertex target = getVertex(orientGraph, targetClass);
OrientEdge orientEdge = orientGraph.addEdge(null, source, target, typeDefinition.getName()); OEdge oEdge = orientGraph.newEdge(source, target, typeDefinition.getName());
orientEdge.setProperty(SCHEMA, json); oEdge.setProperty(SCHEMA, json);
orientEdge.save(); oEdge.save();
} else if(BaseProperty.class.isAssignableFrom(baseType.getTypeClass())) { } else if(BaseProperty.class.isAssignableFrom(baseType.getTypeClass())) {
ODocument doc = new ODocument(typeDefinition.getName()); ODocument doc = new ODocument(typeDefinition.getName());
@ -97,7 +96,7 @@ public class SchemaContextManagementOld implements SchemaManagement {
throw new SchemaException(e); throw new SchemaException(e);
} finally { } finally {
if(orientGraph != null) { if(orientGraph != null) {
orientGraph.shutdown(); orientGraph.close();
} }
} }

View File

@ -46,7 +46,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.exception.OSchemaException; import com.orientechnologies.orient.core.exception.OSchemaException;
import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass;
@ -78,9 +78,9 @@ public class SchemaManagementImpl implements SchemaManagement {
this.typeName = typeName; this.typeName = typeName;
} }
public static OClass getTypeSchema(ODatabaseSession oDatabaseSession, String type, AccessType accessType) public static OClass getTypeSchema(ODatabaseDocument oDatabaseDocument, String type, AccessType accessType)
throws SchemaException, SchemaNotFoundException { throws SchemaException, SchemaNotFoundException {
OMetadata oMetadata = oDatabaseSession.getMetadata(); OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
return getTypeSchema(oSchema, type, accessType); return getTypeSchema(oSchema, type, accessType);
} }
@ -114,21 +114,21 @@ public class SchemaManagementImpl implements SchemaManagement {
ExecutorService es = Executors.newSingleThreadExecutor(); ExecutorService es = Executors.newSingleThreadExecutor();
Future<OClass> result = es.submit(new Callable<OClass>() { Future<OClass> result = es.submit(new Callable<OClass>() {
public OClass call() throws Exception { public OClass call() throws Exception {
ODatabaseSession oDatabaseSession = null; ODatabaseDocument oDatabaseDocument = null;
try { try {
logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type); logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseSession = adminSecurityContext.getDatabaseSession(PermissionMode.READER); oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.activateOnCurrentThread();
return getTypeSchema(oDatabaseSession, type, accessType); return getTypeSchema(oDatabaseDocument, type, accessType);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
}catch(Exception e) { }catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseSession != null) { if(oDatabaseDocument != null) {
oDatabaseSession.close(); oDatabaseDocument.close();
} }
} }
} }
@ -179,7 +179,7 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
} }
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseSession oDatabaseSession, protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
TypeDefinition typeDefinition, String baseType) throws SchemaException, SchemaNotFoundException { TypeDefinition typeDefinition, String baseType) throws SchemaException, SchemaNotFoundException {
Set<String> superClasses = typeDefinition.getSuperClasses(); Set<String> superClasses = typeDefinition.getSuperClasses();
@ -191,7 +191,7 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
} }
OMetadata oMetadata = oDatabaseSession.getMetadata(); OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
List<OClass> oSuperclasses = new ArrayList<>(); List<OClass> oSuperclasses = new ArrayList<>();
@ -231,7 +231,7 @@ public class SchemaManagementImpl implements SchemaManagement {
protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException { protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException {
ODatabaseSession oDatabaseSession = null; ODatabaseDocument oDatabaseDocument = null;
try { try {
TypeDefinition typeDefinition = null; TypeDefinition typeDefinition = null;
try { try {
@ -250,17 +250,17 @@ public class SchemaManagementImpl implements SchemaManagement {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseSession = adminSecurityContext.getDatabaseSession(PermissionMode.WRITER); oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
OMetadata oMetadata = oDatabaseSession.getMetadata(); OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass oClass = null; OClass oClass = null;
if(BaseEntity.class.isAssignableFrom(baseType.getTypeClass())) { if(BaseEntity.class.isAssignableFrom(baseType.getTypeClass())) {
oClass = oDatabaseSession.createVertexClass(typeDefinition.getName()); oClass = oDatabaseDocument.createVertexClass(typeDefinition.getName());
} else if(BaseRelation.class.isAssignableFrom(baseType.getTypeClass())) { } else if(BaseRelation.class.isAssignableFrom(baseType.getTypeClass())) {
oClass = oDatabaseSession.createEdgeClass(typeDefinition.getName()); oClass = oDatabaseDocument.createEdgeClass(typeDefinition.getName());
/* /*
* This information are persisted in Management Context String outBaseType = * This information are persisted in Management Context String outBaseType =
@ -299,7 +299,7 @@ public class SchemaManagementImpl implements SchemaManagement {
} }
if(! baseTypes.contains(typeDefinition.getName())) { if(! baseTypes.contains(typeDefinition.getName())) {
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseSession, typeDefinition, List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseDocument, typeDefinition,
baseType.getName()); baseType.getName());
oClass.setSuperClasses(oSuperclasses); oClass.setSuperClasses(oSuperclasses);
} }
@ -396,19 +396,19 @@ public class SchemaManagementImpl implements SchemaManagement {
} catch(Exception ex) { } catch(Exception ex) {
throw new SchemaCreationException(ex); throw new SchemaCreationException(ex);
} finally { } finally {
if(oDatabaseSession != null) { if(oDatabaseDocument != null) {
oDatabaseSession.close(); oDatabaseDocument.close();
} }
} }
} }
protected String getSchema(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { protected String getSchema(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
ODatabaseSession oDatabaseSession = null; ODatabaseDocument oDatabaseDocument = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseSession = adminSecurityContext.getDatabaseSession(PermissionMode.WRITER); oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
OMetadata oMetadata = oDatabaseSession.getMetadata(); OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass baseOClass = getTypeSchema(oSchema, type, null); OClass baseOClass = getTypeSchema(oSchema, type, null);
@ -428,8 +428,8 @@ public class SchemaManagementImpl implements SchemaManagement {
} catch(Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} finally { } finally {
if(oDatabaseSession != null) { if(oDatabaseDocument != null) {
oDatabaseSession.close(); oDatabaseDocument.close();
} }
} }

View File

@ -21,8 +21,8 @@ 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.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.record.OVertex;
public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? extends BaseEntity>> extends BaseEntityManagement<ETD> { public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? extends BaseEntity>> extends BaseEntityManagement<ETD> {
@ -39,9 +39,9 @@ public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? e
init(); init();
} }
public EntityTypeDefinitionManagement(OrientGraph orientGraph) throws ResourceRegistryException { public EntityTypeDefinitionManagement(ODatabaseDocument orientGraph) throws ResourceRegistryException {
this(); this();
this.orientGraph = orientGraph; this.oDatabaseDocument = orientGraph;
getWorkingContext(); getWorkingContext();
} }
@ -94,23 +94,23 @@ public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? e
} }
@Override @Override
protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException { protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", EntityTypeDefinition.NAME, getName()); logger.debug("Going to create {} for {}", EntityTypeDefinition.NAME, getName());
return createVertex(); return createVertex();
} }
@Override @Override
protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException { protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", EntityTypeDefinition.NAME, getName()); logger.debug("Going to update {} for {}", EntityTypeDefinition.NAME, getName());
Vertex entityTypeDefinition = getElement(); OVertex entityTypeDefinition = getElement();
entityTypeDefinition = (Vertex) ERManagement.updateProperties(oClass, entityTypeDefinition, jsonNode, ignoreKeys, ignoreStartWithKeys); entityTypeDefinition = (OVertex) ERManagement.updateProperties(oClass, entityTypeDefinition, jsonNode, ignoreKeys, ignoreStartWithKeys);
return entityTypeDefinition; return entityTypeDefinition;
} }
@Override @Override
protected boolean reallyDelete() throws NotFoundException, ResourceRegistryException { protected boolean reallyDelete() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to remove {} for {}", EntityTypeDefinition.NAME, getName()); logger.debug("Going to remove {} for {}", EntityTypeDefinition.NAME, getName());
getElement().remove(); getElement().delete();
return true; return true;
} }

View File

@ -21,9 +21,9 @@ import org.gcube.informationsystem.types.reference.relations.RelationTypeDefinit
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tinkerpop.blueprints.Direction; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.tinkerpop.blueprints.Vertex; import com.orientechnologies.orient.core.record.ODirection;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.orientechnologies.orient.core.record.OVertex;
public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<SETD, TETD, S, T>, public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<SETD, TETD, S, T>,
SEM extends EntityTypeDefinitionManagement<SETD>, TEM extends EntityTypeDefinitionManagement<TETD>, SEM extends EntityTypeDefinitionManagement<SETD>, TEM extends EntityTypeDefinitionManagement<TETD>,
@ -37,9 +37,9 @@ public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<S
super(AccessType.RELATION_TYPE_DEFINITION, (Class<SETD>) EntityTypeDefinition.class, (Class<TETD>) EntityTypeDefinition.class); super(AccessType.RELATION_TYPE_DEFINITION, (Class<SETD>) EntityTypeDefinition.class, (Class<TETD>) EntityTypeDefinition.class);
} }
public RelationTypeDefinitionManagement(OrientGraph orientGraph) throws ResourceRegistryException { public RelationTypeDefinitionManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this(); this();
this.orientGraph = orientGraph; this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext(); getWorkingContext();
} }
@ -71,15 +71,15 @@ public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<S
JsonNode relation = serializeSelfOnly(); JsonNode relation = serializeSelfOnly();
try { try {
Vertex source = element.getVertex(Direction.OUT); OVertex source = element.getVertex(ODirection.OUT);
ContextManagement sourceContextManagement = new ContextManagement(orientGraph); ContextManagement sourceContextManagement = new ContextManagement(oDatabaseDocument);
sourceContextManagement.setElement(source); sourceContextManagement.setElement(source);
if(includeSource) { if(includeSource) {
((ObjectNode)relation).replace(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly()); ((ObjectNode)relation).replace(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
} }
Vertex target = element.getVertex(Direction.IN); OVertex target = element.getVertex(ODirection.IN);
ContextManagement targetContextManagement = new ContextManagement(orientGraph); ContextManagement targetContextManagement = new ContextManagement(oDatabaseDocument);
targetContextManagement.setElement(target); targetContextManagement.setElement(target);
if(includeTarget) { if(includeTarget) {
((ObjectNode)relation).replace(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly()); ((ObjectNode)relation).replace(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly());
@ -99,14 +99,14 @@ public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<S
@Override @Override
protected SEM newSourceEntityManagement() throws ResourceRegistryException { protected SEM newSourceEntityManagement() throws ResourceRegistryException {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
SEM sem = (SEM) new EntityTypeDefinitionManagement<SETD>(orientGraph); SEM sem = (SEM) new EntityTypeDefinitionManagement<SETD>(oDatabaseDocument);
return sem; return sem;
} }
@Override @Override
protected TEM newTargetEntityManagement() throws ResourceRegistryException { protected TEM newTargetEntityManagement() throws ResourceRegistryException {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
TEM tem = (TEM) new EntityTypeDefinitionManagement<TETD>(orientGraph); TEM tem = (TEM) new EntityTypeDefinitionManagement<TETD>(oDatabaseDocument);
return tem; return tem;
} }

View File

@ -15,10 +15,10 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -34,13 +34,12 @@ public class QueryImpl implements Query {
} }
limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit; limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit;
OrientGraph orientGraph = null; ODatabaseDocument orientGraph = null;
try { try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
orientGraph = securityContext.getGraph(PermissionMode.READER); orientGraph = securityContext.getDatabaseDocument(PermissionMode.READER);
orientGraph.setAutoStartTx(false);
orientGraph.begin(); orientGraph.begin();
OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit); OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit);
@ -50,13 +49,13 @@ public class QueryImpl implements Query {
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(), logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(),
osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit()); osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit());
Iterable<Element> elements = orientGraph.command(osqlSynchQuery).execute(); Iterable<OElement> elements = orientGraph.command(osqlSynchQuery).execute();
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
for(Element element : elements) { for(OElement element : elements) {
try { try {
JsonNode jsonNode = null; JsonNode jsonNode = null;
if(raw) { if(raw) {
@ -81,7 +80,7 @@ public class QueryImpl implements Query {
throw new InvalidQueryException(e.getMessage()); throw new InvalidQueryException(e.getMessage());
} finally { } finally {
if(orientGraph != null) { if(orientGraph != null) {
orientGraph.shutdown(); orientGraph.close();
} }
} }

View File

@ -45,6 +45,7 @@ import org.gcube.informationsystem.resourceregistry.query.QueryImpl;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.ODirection;
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Direction;
/** /**
@ -341,7 +342,7 @@ public class Access {
if(erManagement instanceof ResourceManagement) { if(erManagement instanceof ResourceManagement) {
UUID refereceUUID = null; UUID refereceUUID = null;
Direction directionEnum = Direction.OUT; ODirection directionEnum = ODirection.OUT;
Map<String,String> constraint = new HashMap<>(); Map<String,String> constraint = new HashMap<>();
@ -368,7 +369,7 @@ public class Access {
} }
} }
try { try {
directionEnum = Direction.valueOf(direction.toUpperCase()); directionEnum = ODirection.valueOf(direction.toUpperCase());
} catch(Exception e) { } catch(Exception e) {
String error = String.format("%s is not a valid. Allowed values are %s", direction, Direction.values()); String error = String.format("%s is not a valid. Allowed values are %s", direction, Direction.values());
throw new InvalidQueryException(error); throw new InvalidQueryException(error);

View File

@ -25,17 +25,15 @@ import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.ODatabasePool; import com.orientechnologies.orient.core.db.ODatabasePool;
import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation; import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
import com.orientechnologies.orient.core.metadata.security.ORole; import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity; import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES; import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -81,7 +79,6 @@ public class SecurityContext {
protected final UUID context; protected final UUID context;
protected final Map<Boolean,Map<PermissionMode,OrientGraphFactory>> factoryMap;
protected final Map<Boolean,Map<PermissionMode,ODatabasePool>> poolMap; protected final Map<Boolean,Map<PermissionMode,ODatabasePool>> poolMap;
protected SecurityContext parentSecurityContext; protected SecurityContext parentSecurityContext;
@ -115,12 +112,8 @@ public class SecurityContext {
return this.children; return this.children;
} }
protected OrientGraph getAdminOrientGraph() throws ResourceRegistryException { protected ODatabaseDocument getAdminDatabaseDocument() throws ResourceRegistryException {
return ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); return ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
}
protected ODatabaseSession getAdminDatabaseSession() throws ResourceRegistryException {
return ContextUtility.getAdminSecurityContext().getDatabaseSession(PermissionMode.WRITER);
} }
/** /**
@ -157,7 +150,7 @@ public class SecurityContext {
* @param orientGraph * @param orientGraph
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
public void changeParentSecurityContext(SecurityContext newParentSecurityContext, OrientGraph orientGraph) throws ResourceRegistryException { public void changeParentSecurityContext(SecurityContext newParentSecurityContext, ODatabaseDocument orientGraph) throws ResourceRegistryException {
if(!hierarchic) { if(!hierarchic) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Cannot change parent "); errorMessage.append("Cannot change parent ");
@ -210,7 +203,6 @@ public class SecurityContext {
protected SecurityContext(UUID context, boolean hierarchic) throws ResourceRegistryException { protected SecurityContext(UUID context, boolean hierarchic) throws ResourceRegistryException {
this.context = context; this.context = context;
this.factoryMap = new HashMap<>();
this.poolMap = new HashMap<>(); this.poolMap = new HashMap<>();
this.hierarchic = hierarchic; this.hierarchic = hierarchic;
this.children = new HashSet<>(); this.children = new HashSet<>();
@ -247,7 +239,6 @@ public class SecurityContext {
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode); String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password); pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password);
//pool.setConnectionStrategy(DatabaseEnvironment.CONNECTION_STRATEGY_PARAMETER.toString());
pools.put(permissionMode, pool); pools.put(permissionMode, pool);
} }
@ -255,41 +246,6 @@ public class SecurityContext {
return pool; return pool;
} }
private synchronized OrientGraphFactory getFactory(PermissionMode permissionMode, boolean recreate) {
OrientGraphFactory factory = null;
Boolean h = isHierarchicMode();
Map<PermissionMode,OrientGraphFactory> factories = factoryMap.get(h);
if(factories == null) {
factories = new HashMap<>();
factoryMap.put(h, factories);
} else {
if(recreate) {
factory = factories.get(permissionMode);
if(factory!=null) {
factory.close();
factories.remove(permissionMode);
}
}
}
factory = factories.get(permissionMode);
if(factory == null) {
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI, username, password).setupPool(1, 10);
factory.setConnectionStrategy(DatabaseEnvironment.CONNECTION_STRATEGY_PARAMETER.toString());
factories.put(permissionMode, factory);
}
return factory;
}
public UUID getUUID() { public UUID getUUID() {
return context; return context;
} }
@ -307,17 +263,18 @@ public class SecurityContext {
return stringBuilder.toString(); return stringBuilder.toString();
} }
@Deprecated private OSecurity getOSecurity(ODatabaseDocument oDatabaseDocument) {
private OSecurity getOSecurity(OrientGraph orientGraph) { return oDatabaseDocument.getMetadata().getSecurity();
return orientGraph.getRawGraph().getMetadata().getSecurity();
} }
private OSecurity getOSecurity(ODatabaseSession oDatabaseSession) { public void addElement(OElement element) throws ResourceRegistryException {
return oDatabaseSession.getMetadata().getSecurity(); ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
} ODatabaseDocument adminDatabaseDocument = getAdminDatabaseDocument();
adminDatabaseDocument.activateOnCurrentThread();
public void addElement(Element element) throws ResourceRegistryException { addElement(element, adminDatabaseDocument);
addElement(element, getAdminOrientGraph()); if(current!=null) {
current.activateOnCurrentThread();
}
} }
protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) { protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) {
@ -327,20 +284,25 @@ public class SecurityContext {
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
} }
public void addElement(Element element, OrientGraph orientGraph) { public void addElement(OElement element, ODatabaseDocument oDatabaseDocument) {
OrientElement orientElement = (OrientElement) element; ODocument oDocument = element.getRecord();
ODocument oDocument = orientElement.getRecord(); OSecurity oSecurity = getOSecurity(oDatabaseDocument);
OSecurity oSecurity = getOSecurity(orientGraph);
allow(oSecurity, oDocument, false); allow(oSecurity, oDocument, false);
if(hierarchic) { if(hierarchic) {
allow(oSecurity, oDocument, true); allow(oSecurity, oDocument, true);
} }
oDocument.save(); oDocument.save();
orientElement.save(); element.save();
} }
public void removeElement(Element element) throws ResourceRegistryException { public void removeElement(OElement element) throws ResourceRegistryException {
removeElement(element, getAdminOrientGraph()); ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument adminDatabaseDocument = getAdminDatabaseDocument();
adminDatabaseDocument.activateOnCurrentThread();
removeElement(element, adminDatabaseDocument);
if(current!=null) {
current.activateOnCurrentThread();
}
} }
protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) { protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) {
@ -358,16 +320,15 @@ public class SecurityContext {
} }
public void removeElement(Element element, OrientGraph orientGraph) { public void removeElement(OElement element, ODatabaseDocument oDatabaseDocument) {
OrientElement orientElement = (OrientElement) element; ODocument oDocument = element.getRecord();
ODocument oDocument = orientElement.getRecord(); OSecurity oSecurity = getOSecurity(oDatabaseDocument);
OSecurity oSecurity = getOSecurity(orientGraph);
deny(oSecurity, oDocument, false); deny(oSecurity, oDocument, false);
if(hierarchic) { if(hierarchic) {
deny(oSecurity, oDocument, true); deny(oSecurity, oDocument, true);
} }
oDocument.save(); oDocument.save();
orientElement.save(); element.save();
} }
protected boolean allowed(final ORole role, final ODocument oDocument) { protected boolean allowed(final ORole role, final ODocument oDocument) {
@ -379,9 +340,10 @@ public class SecurityContext {
@Override @Override
public Boolean call() throws Exception { public Boolean call() throws Exception {
ContextUtility.getHierarchicMode().set(false); ContextUtility.getHierarchicMode().set(false);
ODatabaseSession oDatabaseSession = getDatabaseSession(PermissionMode.READER); ODatabaseDocument oDatabaseDocument = getDatabaseDocument(PermissionMode.READER);
try { try {
OrientElement element = oDatabaseSession.getRecord(oDocument.getIdentity()); oDatabaseDocument.activateOnCurrentThread();
ORecord element = oDatabaseDocument.getRecord(oDocument.getIdentity());
if(element == null) { if(element == null) {
return false; return false;
} }
@ -389,7 +351,7 @@ public class SecurityContext {
} catch(Exception e) { } catch(Exception e) {
return false; return false;
} finally { } finally {
oDatabaseSession.close(); oDatabaseDocument.close();
} }
} }
@ -404,16 +366,17 @@ public class SecurityContext {
} }
public void create() throws ResourceRegistryException { public void create() throws ResourceRegistryException {
/* ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
OrientGraph orientGraph = getAdminOrientGraph(); ODatabaseDocument adminDatabaseDocument = getAdminDatabaseDocument();
create(orientGraph); adminDatabaseDocument.activateOnCurrentThread();
orientGraph.commit();
orientGraph.shutdown(); create(adminDatabaseDocument);
*/ adminDatabaseDocument.commit();
ODatabaseSession oDatabaseSession = getAdminDatabaseSession(); adminDatabaseDocument.close();
create(oDatabaseSession);
oDatabaseSession.commit(); if(current!=null) {
oDatabaseSession.close(); current.activateOnCurrentThread();
}
} }
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
@ -476,7 +439,7 @@ public class SecurityContext {
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
} }
public void create(OrientGraph orientGraph) { public void create(ODatabaseDocument orientGraph) {
OSecurity oSecurity = getOSecurity(orientGraph); OSecurity oSecurity = getOSecurity(orientGraph);
createRolesAndUsers(oSecurity); createRolesAndUsers(oSecurity);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
@ -504,16 +467,17 @@ public class SecurityContext {
} }
public void delete() throws ResourceRegistryException { public void delete() throws ResourceRegistryException {
/* ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
OrientGraph orientGraph = getAdminOrientGraph(); ODatabaseDocument adminDatabaseDocument = getAdminDatabaseDocument();
delete(orientGraph); adminDatabaseDocument.activateOnCurrentThread();
orientGraph.commit();
orientGraph.shutdown(); delete(adminDatabaseDocument);
*/ adminDatabaseDocument.commit();
ODatabaseSession oDatabaseSession = getAdminDatabaseSession(); adminDatabaseDocument.close();
create(oDatabaseSession);
oDatabaseSession.commit(); if(current!=null) {
oDatabaseSession.close(); current.activateOnCurrentThread();
}
} }
protected void removeChildrenHRolesFromParents(OSecurity oSecurity) { protected void removeChildrenHRolesFromParents(OSecurity oSecurity) {
@ -572,64 +536,18 @@ public class SecurityContext {
} }
} }
public void delete(OrientGraph orientGraph) { public void delete(ODatabaseDocument orientGraph) {
OSecurity oSecurity = getOSecurity(orientGraph); OSecurity oSecurity = getOSecurity(orientGraph);
delete(oSecurity); delete(oSecurity);
} }
public void delete(ODatabaseSession oDatabaseSession) {
OSecurity oSecurity = getOSecurity(oDatabaseSession);
delete(oSecurity);
}
private void delete(OSecurity oSecurity) { private void delete(OSecurity oSecurity) {
logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString()); logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString());
deleteRolesAndUsers(oSecurity); deleteRolesAndUsers(oSecurity);
logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString()); logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString());
} }
public OrientGraph getGraph(PermissionMode permissionMode) throws ResourceRegistryException { public ODatabaseDocument getDatabaseDocument(PermissionMode permissionMode) throws ResourceRegistryException {
try {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraph orientGraph = null;
try {
orientGraph = factory.getTx();
if(orientGraph.isClosed()) {
// Enforcing factory recreation
throw new Exception();
}
}catch (Exception e) {
factory = getFactory(permissionMode, true);
orientGraph = factory.getTx();
}
return orientGraph;
}catch (Exception e) {
throw new ResourceRegistryException(e);
}
}
public OrientGraphNoTx getGraphNoTx(PermissionMode permissionMode) throws ResourceRegistryException {
try {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraphNoTx orientGraphNoTx = null;
try {
orientGraphNoTx = factory.getNoTx();
if(orientGraphNoTx.isClosed()) {
// Enforcing factory recreation
throw new Exception();
}
}catch (Exception e) {
factory = getFactory(permissionMode, true);
orientGraphNoTx = factory.getNoTx();
}
return orientGraphNoTx;
}catch (Exception e) {
throw new ResourceRegistryException(e);
}
}
public ODatabaseSession getDatabaseSession(PermissionMode permissionMode) throws ResourceRegistryException {
try { try {
ODatabasePool oDatabasePool = getPool(permissionMode, false); ODatabasePool oDatabasePool = getPool(permissionMode, false);
ODatabaseSession oDatabaseSession = null; ODatabaseSession oDatabaseSession = null;
@ -643,28 +561,13 @@ public class SecurityContext {
oDatabasePool = getPool(permissionMode, true); oDatabasePool = getPool(permissionMode, true);
oDatabaseSession = oDatabasePool.acquire(); oDatabaseSession = oDatabasePool.acquire();
} }
oDatabaseSession.activateOnCurrentThread();
return oDatabaseSession; return oDatabaseSession;
}catch (Exception e) { }catch (Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
/* *
* Use {@link #getDatabaseSession(PermissionMode)} instead
* /
@Deprecated
private ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if(databaseDocumentTx.isClosed()) {
factory.close();
factory = getFactory(permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
*/
@Override @Override
public String toString() { public String toString() {
return String.format("%s %s", Context.NAME, getUUID().toString()); return String.format("%s %s", Context.NAME, getUUID().toString());

View File

@ -19,9 +19,9 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -114,7 +114,7 @@ public class HeaderUtility {
} }
} }
public static Header addHeader(Element element, UUID uuid) { public static Header addHeader(OElement element, UUID uuid) {
Header header = createHeader(uuid); Header header = createHeader(uuid);
element.setProperty(ER.HEADER_PROPERTY, header); element.setProperty(ER.HEADER_PROPERTY, header);
return header; return header;
@ -126,11 +126,11 @@ public class HeaderUtility {
return header; return header;
} }
public static Header getHeader(Element element) throws ResourceRegistryException { public static Header getHeader(OElement element) throws ResourceRegistryException {
return Utility.getPropertyDocument(Header.class, element, ER.HEADER_PROPERTY); return Utility.getPropertyDocument(Header.class, element, ER.HEADER_PROPERTY);
} }
public static void updateModifiedByAndLastUpdate(Element element) throws ResourceRegistryException { public static void updateModifiedByAndLastUpdate(OElement element) throws ResourceRegistryException {
ODocument oDocument = element.getProperty(ER.HEADER_PROPERTY); ODocument oDocument = element.getProperty(ER.HEADER_PROPERTY);
String modifiedBy = getUser(); String modifiedBy = getUser();
oDocument.field(Header.MODIFIED_BY_PROPERTY, modifiedBy); oDocument.field(Header.MODIFIED_BY_PROPERTY, modifiedBy);

View File

@ -18,16 +18,13 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -38,8 +35,8 @@ public class Utility {
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator."; public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JsonNode toJsonNode(Element element, boolean raw) throws ResourceRegistryException { public static JsonNode toJsonNode(OElement element, boolean raw) throws ResourceRegistryException {
ORecord oRecord = ((OrientElement) element).getRecord(); ORecord oRecord = element.getRecord();
return Utility.toJsonNode(oRecord, raw); return Utility.toJsonNode(oRecord, raw);
} }
@ -52,8 +49,8 @@ public class Utility {
} }
} }
public static String toJsonString(Element element, boolean raw) { public static String toJsonString(OElement element, boolean raw) {
ORecord oRecord = ((OrientElement) element).getRecord(); ORecord oRecord = element.getRecord();
return Utility.toJsonString(oRecord, raw); return Utility.toJsonString(oRecord, raw);
} }
@ -65,28 +62,33 @@ public class Utility {
return oRecord.toJSON("class"); return oRecord.toJSON("class");
} }
public static <El extends Element> El getElementByUUIDAsAdmin(String elementType, UUID uuid, public static <El extends OElement> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException { Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
OrientGraphNoTx orientGraphNoTx = null; ODatabaseDocument adminDatabaseDocument = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); adminDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz); return Utility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
} finally { } finally {
if(orientGraphNoTx != null) { if(adminDatabaseDocument != null) {
orientGraphNoTx.shutdown(); adminDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
} }
} }
} }
public static <El extends Element> El getElementByUUID(Graph graph, String elementType, UUID uuid, public static <El extends OElement> El getElementByUUID(ODatabaseDocument oDatabaseDocument, String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException { Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
if(elementType == null || elementType.compareTo("") == 0) { if(elementType == null || elementType.compareTo("") == 0) {
if(Vertex.class.isAssignableFrom(clz)) { if(OVertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME; elementType = Entity.NAME;
} }
if(Edge.class.isAssignableFrom(clz)) { if(OEdge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME; elementType = Relation.NAME;
} }
} }
@ -97,7 +99,7 @@ public class Utility {
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select); OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute(); Iterable<El> elements = oDatabaseDocument.command(osqlSynchQuery).execute();
if(elements == null || !elements.iterator().hasNext()) { if(elements == null || !elements.iterator().hasNext()) {
String error = String.format("No %s with UUID %s was found", elementType, uuid.toString()); String error = String.format("No %s with UUID %s was found", elementType, uuid.toString());
logger.info(error); logger.info(error);
@ -117,7 +119,7 @@ public class Utility {
return element; return element;
} }
public static <P extends BaseProperty> P getPropertyDocument(Class<P> clz, Element element, String property) public static <P extends BaseProperty> P getPropertyDocument(Class<P> clz, OElement element, String property)
throws ResourceRegistryException { throws ResourceRegistryException {
try { try {
ODocument oDocument = element.getProperty(property); ODocument oDocument = element.getProperty(property);
@ -129,7 +131,7 @@ public class Utility {
} }
} }
public static UUID getUUID(Element element) throws ResourceRegistryException { public static UUID getUUID(OElement element) throws ResourceRegistryException {
/* /*
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String * ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String
* contextID = header.field(Header.UUID_PROPERTY); return * contextID = header.field(Header.UUID_PROPERTY); return

View File

@ -27,7 +27,7 @@ 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.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.security.ORole; import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity; import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.core.metadata.security.OUser;
@ -64,8 +64,8 @@ public class ContextManagementTest extends ContextTest {
ContextUtility.getInstance().addSecurityContext(contextSecurityContext.getUUID().toString(), ContextUtility.getInstance().addSecurityContext(contextSecurityContext.getUUID().toString(),
contextSecurityContext); contextSecurityContext);
ODatabaseSession oDatabaseSession = contextSecurityContext.getDatabaseSession(PermissionMode.READER); ODatabaseDocument oDatabaseDocument = contextSecurityContext.getDatabaseDocument(PermissionMode.READER);
OSecurity oSecurity = oDatabaseSession.getMetadata().getSecurity(); OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity();
SecurityContext securityContext = null; SecurityContext securityContext = null;
if(deleted) { if(deleted) {

View File

@ -10,7 +10,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES; import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES;
import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
public class DatabaseEnvironmentTest { public class DatabaseEnvironmentTest {
@ -24,9 +24,9 @@ public class DatabaseEnvironmentTest {
@Test @Test
public void testAlterDateTimeFormat() throws ResourceRegistryException { public void testAlterDateTimeFormat() throws ResourceRegistryException {
ODatabaseSession oDatabaseSession = ContextUtility.getAdminSecurityContext().getDatabaseSession(PermissionMode.WRITER); ODatabaseDocument oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
DatabaseEnvironment.setDateTimeFormat(oDatabaseSession); DatabaseEnvironment.setDateTimeFormat(oDatabaseDocument);
String dateTime = oDatabaseSession.get(ATTRIBUTES.DATETIMEFORMAT).toString(); String dateTime = oDatabaseDocument.get(ATTRIBUTES.DATETIMEFORMAT).toString();
Assert.assertTrue(dateTime.compareTo(ISConstants.DATETIME_PATTERN)==0); Assert.assertTrue(dateTime.compareTo(ISConstants.DATETIME_PATTERN)==0);
} }

View File

@ -77,7 +77,7 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.tinkerpop.blueprints.Direction; import com.orientechnologies.orient.core.record.ODirection;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -714,31 +714,31 @@ public class ERManagementTest extends ContextTest {
resourceManagement.setElementType(Service.NAME); resourceManagement.setElementType(Service.NAME);
/* Getting Hosting Node */ /* Getting Hosting Node */
String json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.BOTH, true, null); String json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.BOTH, true, null);
List<Resource> resourceList = ISMapper.unmarshalList(Resource.class, json); List<Resource> resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==1); Assert.assertTrue(resourceList.size()==1);
Resource resource = resourceList.get(0); Resource resource = resourceList.get(0);
Assert.assertTrue(resource.getHeader().getUUID().compareTo(hostingNodeUUID)==0); Assert.assertTrue(resource.getHeader().getUUID().compareTo(hostingNodeUUID)==0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.OUT, true, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.OUT, true, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==1); Assert.assertTrue(resourceList.size()==1);
resource = resourceList.get(0); resource = resourceList.get(0);
Assert.assertTrue(resource.getHeader().getUUID().compareTo(hostingNodeUUID)==0); Assert.assertTrue(resource.getHeader().getUUID().compareTo(hostingNodeUUID)==0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.IN, true, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.IN, true, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.BOTH, false, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.BOTH, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.OUT, false, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.OUT, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, Direction.IN, false, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.IN, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
/* END Getting Hosting Node */ /* END Getting Hosting Node */
@ -746,29 +746,29 @@ public class ERManagementTest extends ContextTest {
/* Getting EService */ /* Getting EService */
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.BOTH, true, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.BOTH, true, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==1); Assert.assertTrue(resourceList.size()==1);
Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID)==0); Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID)==0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.OUT, true, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.OUT, true, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.IN, true, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.IN, true, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==1); Assert.assertTrue(resourceList.size()==1);
Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID)==0); Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID)==0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.BOTH, false, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.BOTH, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.OUT, false, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.OUT, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, Direction.IN, false, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.IN, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
/* END Getting HostingNode */ /* END Getting HostingNode */
@ -779,12 +779,12 @@ public class ERManagementTest extends ContextTest {
/* EService --ConsistsOf--> SoftwareFacet*/ /* EService --ConsistsOf--> SoftwareFacet*/
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.BOTH, true, null); json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.BOTH, true, null);
}catch(InvalidQueryException e) { }catch(InvalidQueryException e) {
// Ok expected // Ok expected
} }
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.OUT, true, null); json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.OUT, true, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==1); Assert.assertTrue(resourceList.size()==1);
resource = resourceList.get(0); resource = resourceList.get(0);
@ -793,24 +793,24 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(targetIdentificationFacet.getHeader().getUUID().compareTo(identificationFacetUUID)==0); Assert.assertTrue(targetIdentificationFacet.getHeader().getUUID().compareTo(identificationFacetUUID)==0);
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.IN, true, null); json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN, true, null);
}catch(InvalidQueryException e) { }catch(InvalidQueryException e) {
// Ok expected // Ok expected
} }
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.BOTH, false, null); json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.BOTH, false, null);
}catch(InvalidQueryException e) { }catch(InvalidQueryException e) {
// Ok expected // Ok expected
} }
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.OUT, false, null); json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.OUT, false, null);
resourceList = ISMapper.unmarshalList(Resource.class, json); resourceList = ISMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size()==0); Assert.assertTrue(resourceList.size()==0);
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, Direction.IN, false, null); json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN, false, null);
}catch(InvalidQueryException e) { }catch(InvalidQueryException e) {
// Ok expected // Ok expected
} }

View File

@ -23,7 +23,7 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.tinkerpop.blueprints.Direction; import com.orientechnologies.orient.core.record.ODirection;
public class ResourceManagementTest extends ContextTest { public class ResourceManagementTest extends ContextTest {
@ -104,7 +104,7 @@ public class ResourceManagementTest extends ContextTest {
if (erManagement instanceof ResourceManagement) { if (erManagement instanceof ResourceManagement) {
boolean[] booleans = new boolean[] {true, false}; boolean[] booleans = new boolean[] {true, false};
for(boolean bool : booleans) { for(boolean bool : booleans) {
String ret = ((ResourceManagement) erManagement).query(relationType, facetType, null, Direction.OUT, bool, constraint); String ret = ((ResourceManagement) erManagement).query(relationType, facetType, null, ODirection.OUT, bool, constraint);
logger.debug("Result of query for {}polymorphic {} --{}--> {} with constaint {} is {}", bool ? "" : "NOT ", logger.debug("Result of query for {}polymorphic {} --{}--> {} with constaint {} is {}", bool ? "" : "NOT ",
type, relationType, facetType, constraint, ret); type, relationType, facetType, constraint, ret);
} }