Compare commits

...

3 Commits

Author SHA1 Message Date
Luca Frosini 650b988706 Migrating code 2023-05-12 16:19:38 +02:00
Luca Frosini 972b8469e1 Migrating code 2023-05-12 16:06:48 +02:00
Luca Frosini 50ff2fa19a Porting code to ArcadeDB 2023-05-11 18:35:56 +02:00
47 changed files with 1442 additions and 1595 deletions

25
pom.xml
View File

@ -60,23 +60,18 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- ArcadeDB dependencies -->
<dependency> <dependency>
<groupId>com.orientechnologies</groupId> <groupId>com.arcadedb</groupId>
<!-- <artifactId>arcadedb-engine</artifactId>
To work with Thinkerpop® it is required to use this artifactId <version>23.4.1</version>
<artifactId>orientdb-graphdb</artifactId>
Giving that we just use OrientDB classes and not Thinkerpop®
implementation we use a lighter dependency
-->
<artifactId>orientdb-client</artifactId>
<version>3.0.42</version>
<exclusions>
<exclusion>
<groupId>org.graalvm.tools</groupId>
<artifactId>chromeinspector</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency>
<groupId>com.arcadedb</groupId>
<artifactId>arcadedb-network</artifactId>
<version>23.4.1</version>
</dependency>
<!-- ArcadeDB dependencies -->
<dependency> <dependency>
<groupId>org.gcube.common</groupId> <groupId>org.gcube.common</groupId>
<artifactId>gxHTTP</artifactId> <artifactId>gxHTTP</artifactId>

View File

@ -23,7 +23,7 @@ public class ResourceInitializer extends ResourceConfig {
public ResourceInitializer() { public ResourceInitializer() {
packages(Access.class.getPackage().toString()); packages(Access.class.getPackage().toString());
logger.info("The server is going to use OrientDB at {}", DatabaseEnvironment.DB_URI); logger.info("The server is going to use OrientDB at {}:{}/{}", DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB);
} }
} }

View File

@ -16,17 +16,18 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecur
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility; import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
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.arcadedb.graph.MutableVertex;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -76,8 +77,8 @@ public class ContextUtility {
} }
public synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException { public synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
SecurityContext securityContext = null; SecurityContext securityContext = null;
@ -91,9 +92,9 @@ public class ContextUtility {
if(securityContext==null) { if(securityContext==null) {
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);
oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER); database = getAdminSecurityContext().getRemoteDatabase(PermissionMode.READER);
OVertex contextVertex = getContextVertexByFullName(oDatabaseDocument, fullName); MutableVertex contextVertex = getContextVertexByFullName(database, fullName);
uuid = UUIDUtility.getUUID(contextVertex); uuid = UUIDUtility.getUUID(contextVertex);
@ -110,13 +111,13 @@ public class ContextUtility {
} catch(Exception e) { } catch(Exception e) {
throw new ContextException("Unable to retrieve Context UUID from current Context", e); throw new ContextException("Unable to retrieve Context UUID from current Context", e);
} finally { } finally {
if(oDatabaseDocument!=null) { if(database!=null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -124,36 +125,36 @@ public class ContextUtility {
return getSecurityContextByUUID(uuid, null); return getSecurityContextByUUID(uuid, null);
} }
public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() { public static RemoteDatabase getCurrentODatabaseDocumentFromThreadLocal() {
ODatabaseDocument current = null; RemoteDatabase current = null;
try { try {
current = (ODatabaseDocument) ODatabaseRecordThreadLocal.instance().get(); // current = (RemoteDatabase) ODatabaseRecordThreadLocal.instance().get();
}catch (Exception e) { }catch (Exception e) {
// It is possible that there is no current ODatabaseDocument // It is possible that there is no current ODatabaseDocument
} }
return current; return current;
} }
private OVertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException { private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER); database = getAdminSecurityContext().getRemoteDatabase(PermissionMode.READER);
OVertex oVertex = OrientDBUtility.getElementByUUID(oDatabaseDocument, Context.NAME, uuid, Vertex vertex = DBUtility.getElementByUUID(database, Context.NAME, uuid,
OVertex.class); Vertex.class);
return oVertex; return vertex;
} finally { } finally {
if(oDatabaseDocument!=null) { if(database!=null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
private SecurityContext getSecurityContextByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException { private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid); SecurityContext securityContext = contexts.get(uuid);
if(securityContext == null) { if(securityContext == null) {
@ -163,7 +164,7 @@ public class ContextUtility {
if(contextVertex == null) { if(contextVertex == null) {
contextVertex = getContextVertexByUUID(uuid); contextVertex = getContextVertexByUUID(uuid);
} }
OVertex parentVertex = contextVertex.getVertices(ODirection.IN, IsParentOf.NAME).iterator().next(); Vertex parentVertex = contextVertex.getVertices(DIRECTION.IN, IsParentOf.NAME).iterator().next();
if(parentVertex != null) { if(parentVertex != null) {
UUID parentUUID = UUIDUtility.getUUID(parentVertex); UUID parentUUID = UUIDUtility.getUUID(parentVertex);
@ -187,8 +188,8 @@ public class ContextUtility {
} }
*/ */
private OVertex getContextVertexByFullName(ODatabaseDocument oDatabaseDocument, String fullName) throws ResourceRegistryException { private MutableVertex getContextVertexByFullName(RemoteDatabase database , String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} with full name '{}'", Context.NAME, OVertex.class.getSimpleName(), fullName); logger.trace("Going to get {} {} with full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName);
ScopeBean scopeBean = new ScopeBean(fullName); ScopeBean scopeBean = new ScopeBean(fullName);
String name = scopeBean.name(); String name = scopeBean.name();
@ -198,16 +199,16 @@ public class ContextUtility {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("name", name); map.put("name", name);
OResultSet resultSet = oDatabaseDocument.query(select, map); ResultSet resultSet = database.command("sql", select, map);
if(resultSet == null || !resultSet.hasNext()) { if(resultSet == null || !resultSet.hasNext()) {
throw new ContextNotFoundException("Error retrieving context with name " + fullName); throw new ContextNotFoundException("Error retrieving context with name " + fullName);
} }
OResult oResult = resultSet.next(); Result result = resultSet.next();
OVertex context = ElementManagementUtility.getElementFromOptional(oResult.getVertex()); MutableVertex context = (MutableVertex) ElementManagementUtility.getElementFromOptional(result.getVertex());
logger.trace("Context Representing Vertex : {}", OrientDBUtility.getAsStringForLogging(context)); logger.trace("Context Representing Vertex : {}", DBUtility.getAsStringForLogging(context));
if(resultSet.hasNext()) { if(resultSet.hasNext()) {
throw new ContextNotFoundException("Found more than one context with name " + name throw new ContextNotFoundException("Found more than one context with name " + name

View File

@ -33,7 +33,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator; import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator; import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.serialization.ElementMapper; import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.utils.UUIDManager; import org.gcube.informationsystem.utils.UUIDManager;
@ -41,12 +41,12 @@ import org.gcube.informationsystem.utils.UUIDUtility;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -70,9 +70,9 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
init(); init();
} }
public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException { public ContextManagement(RemoteDatabase database) throws ResourceRegistryException {
this(); this();
this.oDatabaseDocument = oDatabaseDocument; this.database = database;
getWorkingContext(); getWorkingContext();
} }
@ -88,7 +88,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
name = jsonNode.get(Context.NAME_PROPERTY).asText(); name = jsonNode.get(Context.NAME_PROPERTY).asText();
} }
} else { } else {
name = element.getProperty(Context.NAME_PROPERTY); name = element.getString(Context.NAME_PROPERTY);
} }
} }
return name; return name;
@ -166,7 +166,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
} }
logger.trace("Checking if {} -> {}", errorMessage, select); logger.trace("Checking if {} -> {}", errorMessage, select);
OResultSet resultSet = oDatabaseDocument.command(select.toString(), new HashMap<>()); ResultSet resultSet = database.command("sql", select.toString(), new HashMap<>());
if (resultSet != null && resultSet.hasNext()) { if (resultSet != null && resultSet.hasNext()) {
throw new ContextAlreadyPresentException(errorMessage.toString()); throw new ContextAlreadyPresentException(errorMessage.toString());
@ -180,13 +180,13 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
JsonNode context = serializeSelfAsJsonNode(); JsonNode context = serializeSelfAsJsonNode();
int count = 0; int count = 0;
Iterable<OEdge> parents = getElement().getEdges(ODirection.IN); Iterable<Edge> parents = getElement().getEdges(DIRECTION.IN);
for (OEdge edge : parents) { for (Edge 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(oDatabaseDocument); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
isParentOfManagement.includeSource(true); isParentOfManagement.includeSource(true);
isParentOfManagement.includeTarget(false); isParentOfManagement.includeTarget(false);
@ -195,24 +195,24 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
((ObjectNode) context).replace(Context.PARENT_PROPERTY, isParentOf); ((ObjectNode) context).replace(Context.PARENT_PROPERTY, isParentOf);
} }
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ContextException(""); throw new ContextException("");
} }
} }
Iterable<OEdge> childrenEdges = getElement().getEdges(ODirection.OUT); Iterable<Edge> childrenEdges = getElement().getEdges(DIRECTION.OUT);
for (OEdge edge : childrenEdges) { for (Edge edge : childrenEdges) {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
try { try {
JsonNode isParentOf = isParentOfManagement.serializeAsJsonNode(); JsonNode isParentOf = isParentOfManagement.serializeAsJsonNode();
context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY); context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
@ -221,7 +221,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
} }
@Override @Override
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null; SecurityContext securityContext = null;
SecurityContext parentSecurityContext = null; SecurityContext parentSecurityContext = null;
@ -231,7 +231,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
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(oDatabaseDocument); ContextManagement parentContextManagement = new ContextManagement(database);
parentContextManagement.setJsonNode(parentJsonNode); parentContextManagement.setJsonNode(parentJsonNode);
UUID parentUUID = parentContextManagement.uuid; UUID parentUUID = parentContextManagement.uuid;
parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID); parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID);
@ -243,7 +243,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
createVertex(); createVertex();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(parentContextManagement); isParentOfManagement.setSourceEntityManagement(parentContextManagement);
isParentOfManagement.setTargetEntityManagement(this); isParentOfManagement.setTargetEntityManagement(this);
@ -257,15 +257,15 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
securityContext = new SecurityContext(uuid); securityContext = new SecurityContext(uuid);
securityContext.setParentSecurityContext(parentSecurityContext); securityContext.setParentSecurityContext(parentSecurityContext);
securityContext.create(oDatabaseDocument); securityContext.create(database);
ContextUtility.getInstance().addSecurityContext(securityContext); ContextUtility.getInstance().addSecurityContext(securityContext);
return getElement(); return getElement();
} catch (Exception e) { } catch (Exception e) {
oDatabaseDocument.rollback(); database.rollback();
if (securityContext != null) { if (securityContext != null) {
securityContext.delete(oDatabaseDocument); securityContext.delete(database);
if (parentSecurityContext != null && securityContext != null) { if (parentSecurityContext != null && securityContext != null) {
parentSecurityContext.getChildren().remove(securityContext); parentSecurityContext.getChildren().remove(securityContext);
} }
@ -276,19 +276,19 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
} }
@Override @Override
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
boolean parentChanged = false; boolean parentChanged = false;
boolean nameChanged = false; boolean nameChanged = false;
OVertex parent = null; Vertex parent = null;
boolean found = false; boolean found = false;
Iterable<OVertex> iterable = getElement().getVertices(ODirection.IN, IsParentOf.NAME); Iterable<Vertex> iterable = getElement().getVertices(DIRECTION.IN, IsParentOf.NAME);
for (OVertex p : iterable) { for (Vertex 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,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(message.toString()); throw new ResourceRegistryException(message.toString());
} }
parent = p; parent = p;
@ -297,7 +297,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
ContextManagement actualParentContextManagement = null; ContextManagement actualParentContextManagement = null;
if (parent != null) { if (parent != null) {
actualParentContextManagement = new ContextManagement(oDatabaseDocument); actualParentContextManagement = new ContextManagement(database);
actualParentContextManagement.setElement(parent); actualParentContextManagement.setElement(parent);
} }
@ -320,7 +320,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
} }
if (parentChanged) { if (parentChanged) {
newParentContextManagement = new ContextManagement(oDatabaseDocument); newParentContextManagement = new ContextManagement(database);
newParentContextManagement.setJsonNode(parentContextJsonNode); newParentContextManagement.setJsonNode(parentContextJsonNode);
} }
} else { } else {
@ -331,7 +331,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
} }
String oldName = getElement().getProperty(Context.NAME_PROPERTY); String oldName = getElement().getString(Context.NAME_PROPERTY);
String newName = jsonNode.get(Context.NAME_PROPERTY).asText(); String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
if (oldName.compareTo(newName) != 0) { if (oldName.compareTo(newName) != 0) {
nameChanged = true; nameChanged = true;
@ -346,7 +346,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
move(newParentContextManagement, false); move(newParentContextManagement, false);
} }
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys); element = (Vertex) updateProperties(documentType, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ServerContextCache.getInstance().cleanCache(); ServerContextCache.getInstance().cleanCache();
@ -362,23 +362,23 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
SecurityContext newParentSecurityContext = null; SecurityContext newParentSecurityContext = null;
// Removing the old parent relationship if any // Removing the old parent relationship if any
Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME); Iterable<Edge> edges = getElement().getEdges(DIRECTION.IN, IsParentOf.NAME);
if (edges != null && edges.iterator().hasNext()) { if (edges != null && edges.iterator().hasNext()) {
Iterator<OEdge> edgeIterator = edges.iterator(); Iterator<Edge> edgeIterator = edges.iterator();
OEdge edge = edgeIterator.next(); Edge edge = edgeIterator.next();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(); IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
isParentOfManagement.internalDelete(); isParentOfManagement.internalDelete();
if (edgeIterator.hasNext()) { if (edgeIterator.hasNext()) {
throw new ContextException( throw new ContextException(
"Seems that the Context has more than one Parent. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); "Seems that the Context has more than one Parent. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
if (newParentContextManagement != null) { if (newParentContextManagement != null) {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(newParentContextManagement); isParentOfManagement.setSourceEntityManagement(newParentContextManagement);
isParentOfManagement.setTargetEntityManagement(this); isParentOfManagement.setTargetEntityManagement(this);
@ -388,13 +388,13 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
} }
SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid); SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, oDatabaseDocument); thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, database);
} }
@Override @Override
protected void reallyDelete() throws NotFoundException, ResourceRegistryException { protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
Iterable<OEdge> iterable = getElement().getEdges(ODirection.OUT); Iterable<Edge> iterable = getElement().getEdges(DIRECTION.OUT);
Iterator<OEdge> iterator = iterable.iterator(); Iterator<Edge> 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");
} }
@ -403,7 +403,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
ContextUtility contextUtility = ContextUtility.getInstance(); ContextUtility contextUtility = ContextUtility.getInstance();
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid); SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(oDatabaseDocument); securityContext.delete(database);
ServerContextCache.getInstance().cleanCache(); ServerContextCache.getInstance().cleanCache();
} }
@ -412,18 +412,18 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
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<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic); Iterable<Document> iterable = database.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) { for (Document vertex : iterable) {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceIncludeMeta(forceIncludeMeta); contextManagement.setForceIncludeMeta(forceIncludeMeta);
contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta); contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta);
contextManagement.setElement((OVertex) vertex); contextManagement.setElement((Vertex) vertex);
try { try {
JsonNode jsonObject = contextManagement.serializeAsJsonNode(); JsonNode jsonObject = contextManagement.serializeAsJsonNode();
arrayNode.add(jsonObject); arrayNode.add(jsonObject);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
try { try {

View File

@ -18,12 +18,13 @@ import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextMan
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -34,9 +35,9 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
super(AccessType.IS_PARENT_OF, Context.class, Context.class); super(AccessType.IS_PARENT_OF, Context.class, Context.class);
} }
public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException { public IsParentOfManagement(RemoteDatabase database) throws ResourceRegistryException {
this(); this();
this.oDatabaseDocument = oDatabaseDocument; this.database = database;
getWorkingContext(); getWorkingContext();
this.includeSource = false; this.includeSource = false;
this.includeTarget = true; this.includeTarget = true;
@ -73,16 +74,16 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
JsonNode relation = serializeSelfAsJsonNode(); JsonNode relation = serializeSelfAsJsonNode();
try { try {
OVertex source = element.getVertex(ODirection.OUT); Vertex source = element.getVertex(DIRECTION.OUT);
ContextManagement sourceContextManagement = new ContextManagement(oDatabaseDocument); ContextManagement sourceContextManagement = new ContextManagement(database);
sourceContextManagement.setElement(source); sourceContextManagement.setElement(source);
if (includeSource) { if (includeSource) {
((ObjectNode) relation).replace(Relation.SOURCE_PROPERTY, ((ObjectNode) relation).replace(Relation.SOURCE_PROPERTY,
sourceContextManagement.serializeSelfAsJsonNode()); sourceContextManagement.serializeSelfAsJsonNode());
} }
OVertex target = element.getVertex(ODirection.IN); Vertex target = element.getVertex(DIRECTION.IN);
ContextManagement targetContextManagement = new ContextManagement(oDatabaseDocument); ContextManagement targetContextManagement = new ContextManagement(database);
targetContextManagement.setElement(target); targetContextManagement.setElement(target);
if (includeTarget) { if (includeTarget) {
((ObjectNode) relation).replace(Relation.TARGET_PROPERTY, ((ObjectNode) relation).replace(Relation.TARGET_PROPERTY,
@ -90,10 +91,10 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
} }
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
@ -102,12 +103,12 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
@Override @Override
protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException { protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ContextManagement(oDatabaseDocument); return new ContextManagement(database);
} }
@Override @Override
protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException { protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ContextManagement(oDatabaseDocument); return new ContextManagement(database);
} }
@Override @Override

View File

@ -8,9 +8,7 @@ import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnv
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -48,20 +46,20 @@ public class AdminSecurityContext extends SecurityContext {
} }
@Override @Override
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) { protected Role getSuperRole(RemoteDatabase database, PermissionMode permissionMode) {
return oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE); return database.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
} }
@Override @Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { protected Role addExtraRules(Role role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName()); logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) { switch(permissionMode) {
case WRITER: case WRITER:
role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.BYPASS_RESTRICTED, null, Role.PERMISSION_ALL);
break; break;
case READER: case READER:
role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.BYPASS_RESTRICTED, null, Role.PERMISSION_READ);
break; break;
default: default:

View File

@ -7,9 +7,6 @@ import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@ -41,19 +38,19 @@ public class ContextSecurityContext extends SecurityContext {
} }
@Override @Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { protected Role addExtraRules(Role role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName()); logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) { switch(permissionMode) {
case WRITER: case WRITER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_ALL);
break; break;
case READER: case READER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_READ);
break; break;
default: default:

View File

@ -7,9 +7,6 @@ import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@ -41,19 +38,19 @@ public class QueryTemplatesSecurityContext extends SecurityContext {
} }
@Override @Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { protected Role addExtraRules(Role role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName()); logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) { switch(permissionMode) {
case WRITER: case WRITER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL); role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_ALL);
break; break;
case READER: case READER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ); role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_READ);
break; break;
default: default:

View File

@ -20,17 +20,21 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility; import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility; import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.utils.UUIDManager; import org.gcube.informationsystem.utils.UUIDManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.database.Identifiable;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.database.RID;
import com.arcadedb.database.Record;
import com.arcadedb.remote.RemoteDatabase;
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.document.ODatabaseDocument; import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordLazySet; import com.orientechnologies.orient.core.db.record.ORecordLazySet;
import com.orientechnologies.orient.core.id.ORID;
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;
@ -87,7 +91,7 @@ public class SecurityContext {
protected final UUID context; protected final UUID context;
protected final Map<Boolean,Map<PermissionMode,ODatabasePool>> poolMap; protected final Map<Boolean,Map<PermissionMode,RemoteDatabase>> databasesMap;
protected SecurityContext parentSecurityContext; protected SecurityContext parentSecurityContext;
@ -120,8 +124,8 @@ public class SecurityContext {
return this.children; return this.children;
} }
protected ODatabaseDocument getAdminDatabaseDocument() throws ResourceRegistryException { protected RemoteDatabase getAdminDatabaseDocument() throws ResourceRegistryException {
return ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER); return ContextUtility.getAdminSecurityContext().getRemoteDatabase(PermissionMode.WRITER);
} }
/** /**
@ -158,7 +162,7 @@ public class SecurityContext {
* @param orientGraph * @param orientGraph
* @throws ResourceRegistryException * @throws ResourceRegistryException
*/ */
public void changeParentSecurityContext(SecurityContext newParentSecurityContext, ODatabaseDocument orientGraph) throws ResourceRegistryException { public void changeParentSecurityContext(SecurityContext newParentSecurityContext, RemoteDatabase database) throws ResourceRegistryException {
if(!hierarchical) { if(!hierarchical) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Cannot change parent "); errorMessage.append("Cannot change parent ");
@ -166,13 +170,13 @@ public class SecurityContext {
errorMessage.append(" to non hierarchic "); errorMessage.append(" to non hierarchic ");
errorMessage.append(SecurityContext.class.getSimpleName()); errorMessage.append(SecurityContext.class.getSimpleName());
errorMessage.append(". "); errorMessage.append(". ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
final String error = errorMessage.toString(); final String error = errorMessage.toString();
logger.error(error); logger.error(error);
throw new RuntimeException(error); throw new RuntimeException(error);
} }
OSecurity oSecurity = getOSecurity(orientGraph); // OSecurity oSecurity = getOSecurity(database);
Set<SecurityContext> allChildren = getAllChildren(); Set<SecurityContext> allChildren = getAllChildren();
@ -191,19 +195,19 @@ public class SecurityContext {
* *
*/ */
oldParents.removeAll(newParents); oldParents.removeAll(newParents);
removeChildrenHRolesFromParents(oSecurity, oldParents, allChildren); removeChildrenHRolesFromParents(database, oldParents, allChildren);
setParentSecurityContext(newParentSecurityContext); setParentSecurityContext(newParentSecurityContext);
if(newParentSecurityContext!=null){ if(newParentSecurityContext!=null){
for(PermissionMode permissionMode : PermissionMode.values()) { for(PermissionMode permissionMode : PermissionMode.values()) {
List<ORole> roles = new ArrayList<>(); List<Role> roles = new ArrayList<>();
for(SecurityContext child : allChildren) { for(SecurityContext child : allChildren) {
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true); String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
ORole role = oSecurity.getRole(roleName); Role role = database.getRole(roleName);
roles.add(role); roles.add(role);
} }
newParentSecurityContext.addHierarchicalRoleToParent(oSecurity, permissionMode, roles.toArray(new ORole[allChildren.size()])); newParentSecurityContext.addHierarchicalRoleToParent(database, permissionMode, roles.toArray(new Role[allChildren.size()]));
} }
} }
@ -211,7 +215,7 @@ public class SecurityContext {
protected SecurityContext(UUID context, boolean hierarchical) throws ResourceRegistryException { protected SecurityContext(UUID context, boolean hierarchical) throws ResourceRegistryException {
this.context = context; this.context = context;
this.poolMap = new HashMap<>(); this.databasesMap = new HashMap<>();
this.hierarchical = hierarchical; this.hierarchical = hierarchical;
this.children = new HashSet<>(); this.children = new HashSet<>();
} }
@ -220,38 +224,38 @@ public class SecurityContext {
this(context, true); this(context, true);
} }
private synchronized ODatabasePool getPool(PermissionMode permissionMode, boolean recreate) { private synchronized RemoteDatabase getPool(PermissionMode permissionMode, boolean recreate) {
ODatabasePool pool = null; RemoteDatabase db = null;
Boolean h = isHierarchicalMode(); Boolean h = isHierarchicalMode();
Map<PermissionMode,ODatabasePool> pools = poolMap.get(h); Map<PermissionMode,RemoteDatabase> databases = databasesMap.get(h);
if(pools == null) { if(databases == null) {
pools = new HashMap<>(); databases = new HashMap<>();
poolMap.put(h, pools); databasesMap.put(h, databases);
} else { } else {
if(recreate) { if(recreate) {
pool = pools.get(permissionMode); db = databases.get(permissionMode);
if(pool!=null) { if(db!=null) {
pool.close(); db.close();
pools.remove(permissionMode); databases.remove(permissionMode);
} }
} }
} }
pool = pools.get(permissionMode); db = databases.get(permissionMode);
if(pool == null) { if(db == null) {
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h); String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode); String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password); db = new RemoteDatabase(DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB ,username, password);
pools.put(permissionMode, pool); databases.put(permissionMode, db);
} }
return pool; return db;
} }
public UUID getUUID() { public UUID getUUID() {
@ -283,16 +287,12 @@ public class SecurityContext {
return stringBuilder.toString(); return stringBuilder.toString();
} }
private OSecurity getOSecurity(ODatabaseDocument oDatabaseDocument) { public static Set<String> getContexts(Document element) {
return oDatabaseDocument.getMetadata().getSecurity();
}
public static Set<String> getContexts(OElement element) {
Set<String> contexts = new HashSet<>(); Set<String> contexts = new HashSet<>();
ORecordLazySet oRecordLazySet = element.getProperty(OSecurity.ALLOW_ALL_FIELD); ORecordLazySet oRecordLazySet = element.getProperty(OSecurity.ALLOW_ALL_FIELD);
for (OIdentifiable oIdentifiable : oRecordLazySet) { for (Identifiable identifiable : oRecordLazySet) {
ODocument oDocument = (ODocument) oIdentifiable; Document oDocument = (Document) identifiable;
String name = oDocument.getProperty("name"); String name = oDocument.getString("name");
if (name.startsWith(getRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE)) if (name.startsWith(getRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE))
|| name.startsWith(getRoleOrUserName(PermissionMode.READER, SecurityType.ROLE))) { || name.startsWith(getRoleOrUserName(PermissionMode.READER, SecurityType.ROLE))) {
String[] list = name.split("_"); String[] list = name.split("_");
@ -308,111 +308,104 @@ public class SecurityContext {
} }
public void addElement(OElement element) throws ResourceRegistryException { public void addElement(Document element) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument adminDatabaseDocument = null; RemoteDatabase adminDatabase = null;
try { try {
adminDatabaseDocument = getAdminDatabaseDocument(); adminDatabase = getAdminDatabaseDocument();
addElement(element, adminDatabaseDocument); addElement(element, adminDatabase);
}finally { }finally {
if(adminDatabaseDocument!=null) { if(adminDatabase!=null) {
adminDatabaseDocument.close(); adminDatabase.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) { protected void allow(RemoteDatabase database, Document document, boolean hierarchic) {
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic); String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
oSecurity.allowRole(document, RestrictedOperation.ALLOW_ALL, writerRoleName);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic); String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
oSecurity.allowRole(document, RestrictedOperation.ALLOW_READ, readerRoleName);
} }
public boolean isElementInContext(final OElement element) throws ResourceRegistryException { public boolean isElementInContext(final Document element) throws ResourceRegistryException {
ORID orid = element.getIdentity(); RID rid = element.getIdentity();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument contextODatabaseDocument = null; RemoteDatabase database = null;
try { try {
contextODatabaseDocument = getDatabaseDocument(PermissionMode.READER); database = getRemoteDatabase(PermissionMode.READER);
ORecord oRecord = contextODatabaseDocument.getRecord(orid); return database.existsRecord(rid);
if(oRecord==null) {
return false;
}
return true;
} finally { } finally {
if(contextODatabaseDocument!=null) { if(database!=null) {
contextODatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public void addElement(OElement element, ODatabaseDocument oDatabaseDocument) { public void addElement(Document document, RemoteDatabase database) {
ODocument oDocument = element.getRecord(); allow(database, document, false);
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
allow(oSecurity, oDocument, false);
if(hierarchical) { if(hierarchical) {
allow(oSecurity, oDocument, true); allow(database, document, true);
} }
oDocument.save(); // document.save();
element.save();
} }
public void removeElement(OElement element) throws ResourceRegistryException { public void removeElement(Document document) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument adminDatabaseDocument = null; RemoteDatabase adminDatabase = null;
try { try {
adminDatabaseDocument = getAdminDatabaseDocument(); adminDatabase = getAdminDatabaseDocument();
removeElement(element, adminDatabaseDocument); removeElement(document, adminDatabase);
}finally { }finally {
if(adminDatabaseDocument!=null) { if(adminDatabase!=null) {
adminDatabaseDocument.close(); adminDatabase.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchical) { protected void deny(RemoteDatabase database, Document document, boolean hierarchical) {
// The element could be created in such a context so the writerUser for the // The element could be created in such a context so the writerUser for the
// context is allowed by default because it was the creator // context is allowed by default because it was the creator
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical); String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_ALL, writerUserName); oSecurity.denyUser(document, RestrictedOperation.ALLOW_ALL, writerUserName);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical); String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName); oSecurity.denyUser(document, RestrictedOperation.ALLOW_READ, readerUserName);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchical); String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchical);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName); oSecurity.denyRole(document, RestrictedOperation.ALLOW_ALL, writerRoleName);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchical); String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchical);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); oSecurity.denyRole(document, RestrictedOperation.ALLOW_READ, readerRoleName);
} }
public void removeElement(OElement element, ODatabaseDocument oDatabaseDocument) { public void removeElement(Document document, RemoteDatabase database) {
ODocument oDocument = element.getRecord(); deny(database, document, false);
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
deny(oSecurity, oDocument, false);
if(hierarchical) { if(hierarchical) {
deny(oSecurity, oDocument, true); deny(database, document, true);
} }
oDocument.save(); // document.save();
element.save();
} }
protected boolean allowed(final ORole role, final ODocument oDocument) { protected boolean allowed(final ORole role, final Document document) {
ExecutorService executor = Executors.newSingleThreadExecutor(); ExecutorService executor = Executors.newSingleThreadExecutor();
@ -422,26 +415,22 @@ public class SecurityContext {
public Boolean call() throws Exception { public Boolean call() throws Exception {
RequestUtility.getRequestInfo().get().setHierarchicalMode(false); RequestUtility.getRequestInfo().get().setHierarchicalMode(false);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
oDatabaseDocument = getDatabaseDocument(PermissionMode.READER); database = getRemoteDatabase(PermissionMode.READER);
oDatabaseDocument.activateOnCurrentThread(); // database.activateOnCurrentThread();
ORecord element = oDatabaseDocument.getRecord(oDocument.getIdentity()); return database.existsRecord(document.getIdentity());
if(element == null) {
return false;
}
return true;
} catch(Exception e) { } catch(Exception e) {
return false; return false;
} finally { } finally {
if(oDatabaseDocument!=null) { if(database!=null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -456,48 +445,48 @@ public class SecurityContext {
} }
public void create() throws ResourceRegistryException { public void create() throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument adminDatabaseDocument = null; RemoteDatabase adminDatabase = null;
try { try {
adminDatabaseDocument = getAdminDatabaseDocument(); adminDatabase = getAdminDatabaseDocument();
create(adminDatabaseDocument); create(adminDatabase);
adminDatabaseDocument.commit(); adminDatabase.commit();
} finally { } finally {
if(adminDatabaseDocument!=null) { if(adminDatabase!=null) {
adminDatabaseDocument.close(); adminDatabase.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { protected Role addExtraRules(Role role, PermissionMode permissionMode) {
return role; return role;
} }
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) { protected Role getSuperRole(RemoteDatabase database, PermissionMode permissionMode) {
String superRoleName = permissionMode.name().toLowerCase(); String superRoleName = permissionMode.name().toLowerCase();
return oSecurity.getRole(superRoleName); return database.getRole(superRoleName);
} }
protected void addHierarchicalRoleToParent(OSecurity oSecurity, PermissionMode permissionMode, ORole... roles) { protected void addHierarchicalRoleToParent(RemoteDatabase database, PermissionMode permissionMode, ORole... roles) {
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true); String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
OUser user = oSecurity.getUser(userName); User user = database.getUser(userName);
for(ORole role : roles) { for(Role role : roles) {
user.addRole(role); user.addRole(role);
} }
user.save(); user.save();
if(getParentSecurityContext() != null) { if(getParentSecurityContext() != null) {
getParentSecurityContext().addHierarchicalRoleToParent(oSecurity, permissionMode, roles); getParentSecurityContext().addHierarchicalRoleToParent(database, permissionMode, roles);
} }
} }
protected void createRolesAndUsers(OSecurity oSecurity) { protected void createRolesAndUsers(RemoteDatabase database) {
boolean[] booleanArray; boolean[] booleanArray;
if(hierarchical) { if(hierarchical) {
booleanArray = new boolean[] {false, true}; booleanArray = new boolean[] {false, true};
@ -507,20 +496,20 @@ public class SecurityContext {
for(boolean hierarchical : booleanArray) { for(boolean hierarchical : booleanArray) {
for(PermissionMode permissionMode : PermissionMode.values()) { for(PermissionMode permissionMode : PermissionMode.values()) {
ORole superRole = getSuperRole(oSecurity, permissionMode); Role superRole = getSuperRole(database, permissionMode);
String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchical); String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchical);
ORole role = oSecurity.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT); Role role = database.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT);
addExtraRules(role, permissionMode); addExtraRules(role, permissionMode);
role.save(); role.save();
logger.trace("{} created", role); logger.trace("{} created", role);
if(hierarchical && getParentSecurityContext() != null) { if(hierarchical && getParentSecurityContext() != null) {
getParentSecurityContext().addHierarchicalRoleToParent(oSecurity, permissionMode, role); getParentSecurityContext().addHierarchicalRoleToParent(database, permissionMode, role);
} }
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchical); String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchical);
OUser user = oSecurity.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode), User user = database.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode),
role); role);
user.save(); user.save();
logger.trace("{} created", user); logger.trace("{} created", user);
@ -529,70 +518,64 @@ public class SecurityContext {
} }
public void create(ODatabaseDocument oDatabaseDocument) { public void create(RemoteDatabase database) {
OSecurity oSecurity = getOSecurity(oDatabaseDocument); createRolesAndUsers(database);
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());
} }
private void drop(OSecurity oSecurity, String name, SecurityType securityType) { private void drop(RemoteDatabase database, String name, SecurityType securityType) {
boolean dropped = false;
switch(securityType) { switch(securityType) {
case ROLE: case ROLE:
dropped = oSecurity.dropRole(name); database.dropRole(name);
break; break;
case USER: case USER:
dropped = oSecurity.dropUser(name); database.dropUser(name);
break; break;
default: default:
break; break;
} }
if(dropped) { logger.trace("{} successfully dropped", name);
logger.trace("{} successfully dropped", name);
} else {
logger.error("{} was not dropped successfully", name);
}
} }
public void delete() throws ResourceRegistryException { public void delete() throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase remoteDatabase = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument adminDatabaseDocument = null; RemoteDatabase database = null;
try { try {
adminDatabaseDocument = getAdminDatabaseDocument(); database = getAdminDatabaseDocument();
delete(adminDatabaseDocument); delete(database);
adminDatabaseDocument.commit(); database.commit();
} finally { } finally {
if(adminDatabaseDocument!=null) { if(database!=null) {
adminDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
protected void removeChildrenHRolesFromParents(OSecurity oSecurity) { protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase) {
Set<SecurityContext> parents = getAllParents(); Set<SecurityContext> parents = getAllParents();
Set<SecurityContext> allChildren = getAllChildren(); Set<SecurityContext> allChildren = getAllChildren();
removeChildrenHRolesFromParents(oSecurity, parents, allChildren); removeChildrenHRolesFromParents(remoteDatabase, parents, allChildren);
} }
protected void removeChildrenHRolesFromParents(OSecurity oSecurity, Set<SecurityContext> parents, Set<SecurityContext> children) { protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase, Set<SecurityContext> parents, Set<SecurityContext> children) {
for(SecurityContext parent : parents) { for(SecurityContext parent : parents) {
parent.removeChildrenHRolesFromMyHUsers(oSecurity, children); parent.removeChildrenHRolesFromMyHUsers(remoteDatabase, children);
} }
} }
protected void removeChildrenHRolesFromMyHUsers(OSecurity oSecurity, Set<SecurityContext> children) { protected void removeChildrenHRolesFromMyHUsers(RemoteDatabase database, Set<SecurityContext> children) {
for(PermissionMode permissionMode : PermissionMode.values()) { for(PermissionMode permissionMode : PermissionMode.values()) {
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true); String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
OUser user = oSecurity.getUser(userName); User user = database.getUser(userName);
for(SecurityContext child : children) { for(SecurityContext child : children) {
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true); String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
logger.debug("Going to remove {} from {}", roleName, userName); logger.debug("Going to remove {} from {}", roleName, userName);
@ -604,16 +587,16 @@ public class SecurityContext {
} }
protected void removeHierarchicRoleFromMyHUser(OSecurity oSecurity, PermissionMode permissionMode, String roleName) { protected void removeHierarchicRoleFromMyHUser(RemoteDatabase database, PermissionMode permissionMode, String roleName) {
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true); String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
OUser user = oSecurity.getUser(userName); User user = database.getUser(userName);
logger.debug("Going to remove {} from {}", roleName, userName); logger.debug("Going to remove {} from {}", roleName, userName);
boolean removed = user.removeRole(roleName); boolean removed = user.removeRole(roleName);
logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName); logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName);
user.save(); user.save();
} }
protected void deleteRolesAndUsers(OSecurity oSecurity) { protected void deleteRolesAndUsers(RemoteDatabase remoteDatabase) {
boolean[] booleanArray; boolean[] booleanArray;
if(hierarchical) { if(hierarchical) {
booleanArray = new boolean[] {false, true}; booleanArray = new boolean[] {false, true};
@ -622,47 +605,45 @@ public class SecurityContext {
} }
for(boolean hierarchic : booleanArray) { for(boolean hierarchic : booleanArray) {
if(hierarchic) { if(hierarchic) {
removeChildrenHRolesFromParents(oSecurity); removeChildrenHRolesFromParents(remoteDatabase);
} }
for(PermissionMode permissionMode : PermissionMode.values()) { for(PermissionMode permissionMode : PermissionMode.values()) {
for(SecurityType securityType : SecurityType.values()) { for(SecurityType securityType : SecurityType.values()) {
String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic); String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic);
drop(oSecurity, name, securityType); drop(remoteDatabase, name, securityType);
} }
} }
} }
} }
public void delete(ODatabaseDocument orientGraph) { public void delete(RemoteDatabase remoteDatabase) {
OSecurity oSecurity = getOSecurity(orientGraph); // OSecurity oSecurity = getOSecurity(orientGraph);
delete(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(remoteDatabase);
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 ODatabaseDocument getDatabaseDocument(PermissionMode permissionMode) throws ResourceRegistryException { public RemoteDatabase getRemoteDatabase(PermissionMode permissionMode) throws ResourceRegistryException {
try { // try {
ODatabasePool oDatabasePool = getPool(permissionMode, false); // ODatabasePool oDatabasePool = getPool(permissionMode, false);
ODatabaseSession oDatabaseSession = null; // ODatabaseSession oDatabaseSession = null;
try { // try {
oDatabaseSession = oDatabasePool.acquire(); // oDatabaseSession = oDatabasePool.acquire();
if(oDatabaseSession.isClosed()) { // if(oDatabaseSession.isClosed()) {
// Enforcing pool recreation // // Enforcing pool recreation
throw new Exception(); // throw new Exception();
} // }
}catch (Exception e) { // }catch (Exception e) {
oDatabasePool = getPool(permissionMode, true); // oDatabasePool = getPool(permissionMode, true);
oDatabaseSession = oDatabasePool.acquire(); // oDatabaseSession = oDatabasePool.acquire();
} // }
oDatabaseSession.activateOnCurrentThread(); // oDatabaseSession.activateOnCurrentThread();
return oDatabaseSession; // return oDatabaseSession;
}catch (Exception e) { // }catch (Exception e) {
throw new ResourceRegistryException(e); // throw new ResourceRegistryException(e);
} // }
return null;
} }
@Override @Override

View File

@ -7,9 +7,6 @@ import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */

View File

@ -45,22 +45,8 @@ import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.common.log.OLogManager; import com.arcadedb.database.Document;
import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES;
import com.orientechnologies.orient.core.db.ODatabasePool;
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.db.OrientDB;
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.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.OElement;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -71,12 +57,13 @@ public class DatabaseEnvironment {
protected static final String PROPERTY_FILENAME = "config.properties"; protected static final String PROPERTY_FILENAME = "config.properties";
public static final String HOST;
private static final String HOST_VARNAME = "HOST"; private static final String HOST_VARNAME = "HOST";
private static final String REMOTE_PROTOCOL; public static final int PORT;
private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL"; private static final String PORT_VARNAME = "REMOTE_PROTOCOL";
private static final String DB; public static final String DB;
private static final String DB_VARNAME = "DB"; private static final String DB_VARNAME = "DB";
private static final String ROOT_USERNAME; private static final String ROOT_USERNAME;
@ -87,36 +74,25 @@ public class DatabaseEnvironment {
public static final String DEFAULT_ADMIN_ROLE = "admin"; public static final String DEFAULT_ADMIN_ROLE = "admin";
private static final String CHANGED_ADMIN_USERNAME; private static final String ADMIN_USERNAME;
private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME"; private static final String ADMIN_USERNAME_VARNAME = "ADMIN_USERNAME";
private static final String CHANGED_ADMIN_PASSWORD; private static final String ADMIN_PASSWORD;
private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD"; private static final String ADMIN_PASSWORD_VARNAME = "ADMIN_PASSWORD";
private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD; private static final String WRITER_USER_PASSWORD;
private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_WRITER_USER_PASSWORD"; private static final String WRITER_USER_PASSWORD_VARNAME = "WRITER_USER_PASSWORD";
private static final String DEFAULT_CREATED_READER_USER_PASSWORD; private static final String READER_USER_PASSWORD;
private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD"; private static final String READER_USER_PASSWORD_VARNAME = "READER_USER_PASSWORD";
public static final Map<PermissionMode,String> DEFAULT_PASSWORDS; public static final Map<PermissionMode,String> DEFAULT_PASSWORDS;
private static final String HOSTS;
private static final String SERVER_URI;
public static final String DB_URI;
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
protected static final String DB_KEY_FILENAME_VARNAME = "DB_KEY_FILENAME"; protected static final String DB_KEY_FILENAME_VARNAME = "DB_KEY_FILENAME";
protected static final String DB_KEY_ALGORITHM_VARNAME = "DB_KEY_ALGORITHM"; protected static final String DB_KEY_ALGORITHM_VARNAME = "DB_KEY_ALGORITHM";
private static final Key KEY; private static final Key KEY;
public static final String VERTEX_CLASS_NAME = OClass.VERTEX_CLASS_NAME;
public static final String EDGE_CLASS_NAME = OClass.EDGE_CLASS_NAME;
static { static {
Properties properties = new Properties(); Properties properties = new Properties();
InputStream input = null; InputStream input = null;
@ -128,41 +104,25 @@ public class DatabaseEnvironment {
// load a properties file // load a properties file
properties.load(input); properties.load(input);
HOSTS = properties.getProperty(HOST_VARNAME); HOST = properties.getProperty(HOST_VARNAME);
REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME); PORT = Integer.valueOf(properties.getProperty(PORT_VARNAME));
DB = properties.getProperty(DB_VARNAME); DB = properties.getProperty(DB_VARNAME);
SERVER_URI = REMOTE_PROTOCOL + HOSTS;
DB_URI = SERVER_URI + "/" + DB;
ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME); ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME);
ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME); ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME);
String changedAdminUsername = null; ADMIN_USERNAME = properties.getProperty(ADMIN_USERNAME_VARNAME);
try { ADMIN_PASSWORD = properties.getProperty(ADMIN_PASSWORD_VARNAME);
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
if(changedAdminUsername == null) {
// To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB;
}
} catch(Exception e) {
// To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB;
}
CHANGED_ADMIN_USERNAME = changedAdminUsername;
CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_ADMIN_PASSWORD_VARNAME); WRITER_USER_PASSWORD = properties.getProperty(WRITER_USER_PASSWORD_VARNAME);
READER_USER_PASSWORD = properties.getProperty(READER_USER_PASSWORD_VARNAME);
DEFAULT_CREATED_WRITER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME);
DEFAULT_CREATED_READER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME);
DEFAULT_PASSWORDS = new HashMap<PermissionMode,String>(); DEFAULT_PASSWORDS = new HashMap<PermissionMode,String>();
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.WRITER, WRITER_USER_PASSWORD);
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.READER, READER_USER_PASSWORD);
} catch(Throwable e) { } catch(Throwable e) {
logger.error("Unable to load properties from {}", PROPERTY_FILENAME); logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
@ -172,16 +132,15 @@ public class DatabaseEnvironment {
// Used to Persist Context and their relations // Used to Persist Context and their relations
try { try {
boolean created = initGraphDB();
logger.info("Connecting as {} to {}:{}/{}", ROOT_USERNAME, HOST, PORT, DB);
RemoteDatabase database = new RemoteDatabase(HOST, PORT, DB, ADMIN_USERNAME, ADMIN_PASSWORD);
boolean created = initGraphDB(database);
if(created) { if(created) {
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD); AdminSecurityContext.getInstance().create(database);
ODatabaseDocument oDatabaseDocument = pool.acquire();
AdminSecurityContext.getInstance().create(oDatabaseDocument);
oDatabaseDocument.commit();
oDatabaseDocument.close();
pool.close();
QueryTemplatesSecurityContext.getInstance().create(); QueryTemplatesSecurityContext.getInstance().create();
TypeSecurityContext.getInstance().create(); TypeSecurityContext.getInstance().create();
@ -236,7 +195,7 @@ public class DatabaseEnvironment {
schemaToBeCreated.add(Property.class); schemaToBeCreated.add(Property.class);
schemaToBeCreated.add(Metadata.class); schemaToBeCreated.add(Metadata.class);
for(Class<? extends Element> clazz : schemaToBeCreated) { for(Class<? extends Element> clazz : schemaToBeCreated) {
ElementManagement<? extends OElement,?> erManagement = new PropertyTypeDefinitionManagement(); ElementManagement<? extends Document,?> erManagement = new PropertyTypeDefinitionManagement();
erManagement.setJson(TypeMapper.serializeType(clazz)); erManagement.setJson(TypeMapper.serializeType(clazz));
erManagement.create(); erManagement.create();
} }
@ -310,15 +269,15 @@ public class DatabaseEnvironment {
} }
} }
protected static void setDateTimeFormat(ODatabaseDocument oDatabaseDocument) { protected static void setDateTimeFormat(RemoteDatabase database) {
oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, Element.DATETIME_PATTERN); // TODO
// oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, Element.DATETIME_PATTERN);
} }
@Deprecated protected static void setRecordLevelSecurity(RemoteDatabase database) {
// This code must be removed for OrientDB versions higher than 3.2.X logger.trace("Setting Record-level Security");
protected static void setRecordLevelSecurity(OMetadata oMetadata) {
logger.trace( /*
"Setting Record-level Security (see https://orientdb.org/docs/3.2.x/security/Database-Security.html#record-level-security-deprecated-in-v-31)");
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass oRestricted = oSchema.getClass(OSecurity.RESTRICTED_CLASSNAME); OClass oRestricted = oSchema.getClass(OSecurity.RESTRICTED_CLASSNAME);
@ -327,51 +286,41 @@ public class DatabaseEnvironment {
OClass e = oSchema.getClass(EDGE_CLASS_NAME); OClass e = oSchema.getClass(EDGE_CLASS_NAME);
e.addSuperClass(oRestricted); e.addSuperClass(oRestricted);
*/
} }
private static boolean initGraphDB() throws Exception { private static boolean initGraphDB(RemoteDatabase database) throws Exception {
OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false);
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
OrientDB orientDB = new OrientDB(SERVER_URI, ROOT_USERNAME, ROOT_PASSWORD, OrientDBConfig.defaultConfig());
try { try {
if(!orientDB.exists(DB)) { if(!!database.exists()) {
logger.info("The database {} does not exist. Going to create it.", DB_URI); logger.info("The database {} does not exist. Going to create it.", DB);
orientDB.create(DB, ODatabaseType.PLOCAL); database.create();
ODatabasePool pool = new ODatabasePool(orientDB, DB, ROOT_USERNAME, ROOT_PASSWORD); DatabaseEnvironment.setDateTimeFormat(database);
ODatabaseSession oDatabaseSession = pool.acquire();
DatabaseEnvironment.setDateTimeFormat(oDatabaseSession); List<String> databases = new ArrayList<>();
databases.add(DB);
OMetadata oMetadata = oDatabaseSession.getMetadata(); // TODO Create Role
OSecurity oSecurity = oMetadata.getSecurity(); // ORole adminRole = oSecurity.getRole(DEFAULT_ADMIN_ROLE);
// OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
//
logger.trace("Creating new admin named '{}'", ADMIN_USERNAME);
database.createUser(ADMIN_USERNAME, ADMIN_PASSWORD, databases);
setRecordLevelSecurity(database);
logger.trace("Creating new admin named '{}'", CHANGED_ADMIN_USERNAME); database.commit();
ORole adminRole = oSecurity.getRole(DEFAULT_ADMIN_ROLE);
OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
newAdminUser.save();
DatabaseEnvironment.changeDefaultAdminPassword(oSecurity);
setRecordLevelSecurity(oMetadata);
oDatabaseSession.commit();
oDatabaseSession.close();
pool.close();
return true; return true;
} }
return false; return false;
} finally { } finally {
orientDB.close(); database.close();
} }
} }
@ -379,28 +328,4 @@ public class DatabaseEnvironment {
return KEY; return KEY;
} }
@Deprecated
// This code must be removed for OrientDB versions higher than 3.2.X
public static void changeDefaultAdminPassword(OSecurity oSecurity) {
for(PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
try {
logger.trace("Going to update password for user {}", permissionMode.toString());
OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
oUser.save();
logger.trace("Updated password for user {}", permissionMode.toString());
}catch (Exception e) {
logger.trace("Unable to update password for user {}. {}", permissionMode.toString(), e.getMessage());
throw new RuntimeException(e);
}
}
try {
logger.trace("Removing 'admin' user");
oSecurity.dropUser("admin");
}catch (Exception e) {
logger.info("Unable to delete admin user. {}", e.getMessage());
}
}
} }

View File

@ -30,7 +30,6 @@ import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement; import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.ERElement; import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.properties.Metadata; import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
@ -52,7 +51,7 @@ import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataOrient; import org.gcube.informationsystem.resourceregistry.utils.MetadataOrient;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility; import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility; import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.types.reference.Type; import org.gcube.informationsystem.types.reference.Type;
import org.gcube.informationsystem.types.reference.entities.ResourceType; import org.gcube.informationsystem.types.reference.entities.ResourceType;
@ -63,18 +62,17 @@ import org.gcube.informationsystem.utils.UUIDManager;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.arcadedb.database.MutableDocument;
import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.metadata.schema.OType; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.schema.Property;
import com.orientechnologies.orient.core.util.ODateHelper;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class ElementManagement<El extends OElement, T extends Type> { public abstract class ElementManagement<El extends Document, T extends Type> {
protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Logger logger = LoggerFactory.getLogger(this.getClass());
@ -89,11 +87,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
protected Class<El> elementClass; protected Class<El> elementClass;
protected final AccessType accessType; protected final AccessType accessType;
protected ODatabaseDocument oDatabaseDocument; protected RemoteDatabase database;
protected UUID uuid; protected UUID uuid;
protected JsonNode jsonNode; protected JsonNode jsonNode;
protected OClass oClass; // protected OClass documentType;
protected DocumentType documentType;
protected String typeName; protected String typeName;
protected JsonNode self; protected JsonNode self;
@ -182,6 +181,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
this.forceIncludeMeta = false; this.forceIncludeMeta = false;
this.forceIncludeAllMeta = false; this.forceIncludeAllMeta = false;
} }
public static DIRECTION opposite(DIRECTION d) {
switch (d) {
case IN:
return DIRECTION.OUT;
case OUT:
return DIRECTION.IN;
default:
return d;
}
}
public boolean isForceIncludeMeta() { public boolean isForceIncludeMeta() {
return forceIncludeMeta; return forceIncludeMeta;
@ -278,28 +290,24 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
checkJsonNode(); checkJsonNode();
} }
public void setODatabaseDocument(ODatabaseDocument oDatabaseDocument) { public void setDatabase(RemoteDatabase remoteDatabase) {
this.oDatabaseDocument = oDatabaseDocument; this.database = remoteDatabase;
} }
public void setOClass(OClass oClass) { protected DocumentType getDocumentType() throws SchemaException, ResourceRegistryException {
this.oClass = oClass; if(documentType == null) {
}
protected OClass getOClass() throws SchemaException, ResourceRegistryException {
if(oClass == null) {
if(element != null) { if(element != null) {
try { try {
oClass = ElementManagementUtility.getOClass(element); documentType = ElementManagementUtility.getDocumentType(element);
if(typeName==null) { if(typeName==null) {
typeName = oClass.getName(); typeName = documentType.getName();
} }
getCachedType().setOClass(oClass); getCachedType().setDocumentType(documentType);
}catch (ResourceRegistryException e) { }catch (ResourceRegistryException e) {
try { try {
oClass = getCachedType().getOClass(); documentType = getCachedType().getDocumentType();
if(typeName==null) { if(typeName==null) {
typeName = oClass.getName(); typeName = documentType.getName();
} }
}catch (Exception e1) { }catch (Exception e1) {
throw e; throw e;
@ -309,14 +317,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
if(typeName==null) { if(typeName==null) {
throw new SchemaException("Unknown type name. Please set it first."); throw new SchemaException("Unknown type name. Please set it first.");
} }
oClass = getCachedType().getOClass(); documentType = getCachedType().getDocumentType();
AccessType gotAccessType = cachedType.getAccessType(); AccessType gotAccessType = cachedType.getAccessType();
if(accessType!=gotAccessType) { if(accessType!=gotAccessType) {
throw new SchemaException(typeName + " is not a " + accessType.getName()); throw new SchemaException(typeName + " is not a " + accessType.getName());
} }
} }
} }
return oClass; return documentType;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -349,7 +357,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
public String getTypeName() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public String getTypeName() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
if(typeName==null) { if(typeName==null) {
if(element!=null) { if(element!=null) {
typeName = getOClass().getName(); typeName = getDocumentType().getName();
} }
if(typeName==null && jsonNode!=null) { if(typeName==null && jsonNode!=null) {
@ -380,7 +388,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
if(this.typeName == null) { if(this.typeName == null) {
this.typeName = TypeUtility.getTypeName(jsonNode); this.typeName = TypeUtility.getTypeName(jsonNode);
getOClass(); getDocumentType();
} else { } else {
checkERMatch(); checkERMatch();
} }
@ -396,7 +404,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} }
getOClass(); getDocumentType();
} }
@ -414,8 +422,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} }
} }
private void analizeProperty(OElement element, String key, ObjectNode objectNode) throws ResourceRegistryException { private void analizeProperty(Document element, String key, ObjectNode objectNode) throws ResourceRegistryException {
Object object = element.getProperty(key); Object object = element.get(key);
if(object == null) { if(object == null) {
objectNode.replace(key, null); objectNode.replace(key, null);
return; return;
@ -432,7 +440,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode(); ObjectNode objectNode = objectMapper.createObjectNode();
OElement element = getElement(); El element = getElement();
Set<String> keys = element.getPropertyNames(); Set<String> keys = element.getPropertyNames();
/* Add first these key to provide an order in Json */ /* Add first these key to provide an order in Json */
@ -539,13 +547,13 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
element = reallyCreate(); element = reallyCreate();
element.setProperty(IdentifiableElement.ID_PROPERTY, uuid.toString()); ((MutableDocument) element).set(IdentifiableElement.ID_PROPERTY, uuid.toString());
MetadataUtility.addMetadata(element); MetadataUtility.addMetadata(element);
getWorkingContext().addElement(element, oDatabaseDocument); getWorkingContext().addElement(element, database);
element.save(); // element.save();
sanityCheck(); sanityCheck();
@ -567,7 +575,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
MetadataUtility.updateModifiedByAndLastUpdate(element); MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save(); // element.save();
sanityCheck(); sanityCheck();
@ -601,8 +609,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} }
this.element = element; this.element = element;
this.uuid = UUIDUtility.getUUID(element); this.uuid = UUIDUtility.getUUID(element);
OClass oClass = getOClass(); DocumentType documentType = getDocumentType();
this.typeName = oClass.getName(); this.typeName = documentType.getName();
} }
protected abstract NotFoundException getSpecificNotFoundException(NotFoundException e); protected abstract NotFoundException getSpecificNotFoundException(NotFoundException e);
@ -634,7 +642,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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 OrientDBUtility.getElementByUUID(oDatabaseDocument, typeName == null ? accessType.getName() : typeName, uuid, return DBUtility.getElementByUUID(database, typeName == null ? accessType.getName() : typeName, uuid,
elementClass); elementClass);
} catch(NotFoundException e) { } catch(NotFoundException e) {
throw getSpecificNotFoundException(e); throw getSpecificNotFoundException(e);
@ -647,7 +655,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
public El retrieveElementFromAnyContext() throws NotFoundException, ResourceRegistryException { public El retrieveElementFromAnyContext() throws NotFoundException, ResourceRegistryException {
try { try {
return OrientDBUtility.getElementByUUIDAsAdmin(typeName == null ? accessType.getName() : typeName, uuid, return DBUtility.getElementByUUIDAsAdmin(typeName == null ? accessType.getName() : typeName, uuid,
elementClass); elementClass);
} catch(NotFoundException e) { } catch(NotFoundException e) {
throw getSpecificNotFoundException(e); throw getSpecificNotFoundException(e);
@ -661,9 +669,9 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException; public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException;
public String all(boolean polymorphic) throws ResourceRegistryException { public String all(boolean polymorphic) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); database = getWorkingContext().getRemoteDatabase(PermissionMode.READER);
setAsEntryPoint(); setAsEntryPoint();
setOperation(Operation.QUERY); setOperation(Operation.QUERY);
return reallyGetAll(polymorphic); return reallyGetAll(polymorphic);
@ -672,20 +680,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
}
if(current!=null) {
current.activateOnCurrentThread();
} }
// if(current!=null) {
// current.activateOnCurrentThread();
// }
} }
} }
public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); database = getWorkingContext().getRemoteDatabase(PermissionMode.READER);
setAsEntryPoint(); setAsEntryPoint();
setOperation(Operation.EXISTS); setOperation(Operation.EXISTS);
@ -699,22 +706,22 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // database.activateOnCurrentThread();
} // }
} }
} }
public String createOrUpdate() public String createOrUpdate()
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
boolean update = false; boolean update = false;
try { try {
setAsEntryPoint(); setAsEntryPoint();
@ -729,7 +736,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
internalCreate(); internalCreate();
} }
oDatabaseDocument.commit(); database.commit();
if(update) { if(update) {
setReload(true); setReload(true);
@ -741,38 +748,37 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} 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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public String create() throws AlreadyPresentException, ResourceRegistryException { public String create() throws AlreadyPresentException, ResourceRegistryException {
// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
setAsEntryPoint(); setAsEntryPoint();
internalCreate(); internalCreate();
oDatabaseDocument.commit(); database.commit();
// TODO Notify to subscriptionNotification // TODO Notify to subscriptionNotification
@ -780,32 +786,31 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to create {}", accessType.getName()); logger.error("Unable to create {}", accessType.getName());
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public String read() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public String read() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); database = getWorkingContext().getRemoteDatabase(PermissionMode.READER);
setAsEntryPoint(); setAsEntryPoint();
setOperation(Operation.READ); setOperation(Operation.READ);
@ -820,27 +825,26 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
setAsEntryPoint(); setAsEntryPoint();
internalUpdate(); internalUpdate();
oDatabaseDocument.commit(); database.commit();
setReload(true); setReload(true);
@ -850,74 +854,74 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} 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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public void delete() throws NotFoundException, AvailableInAnotherContextException, SchemaViolationException, ResourceRegistryException { public void delete() throws NotFoundException, AvailableInAnotherContextException, SchemaViolationException, ResourceRegistryException {
logger.trace("Going to delete {} instance with UUID {}", accessType.getName(), uuid); logger.trace("Going to delete {} instance with UUID {}", accessType.getName(), uuid);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
// oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER); // oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
setAsEntryPoint(); setAsEntryPoint();
internalDelete(); internalDelete();
if(!dryRun) { if(!dryRun) {
oDatabaseDocument.commit(); database.commit();
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid); logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
}else { }else {
oDatabaseDocument.rollback(); database.rollback();
} }
} 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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public Set<String> getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException { public Set<String> getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException {
logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid); logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
setAsEntryPoint(); setAsEntryPoint();
setOperation(Operation.GET_METADATA); setOperation(Operation.GET_METADATA);
@ -931,13 +935,13 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
logger.error("Unable to get contexts for {} with UUID {}", typeName, uuid, e); logger.error("Unable to get contexts for {} with UUID {}", typeName, uuid, e);
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -1071,83 +1075,67 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
return map; return map;
} }
public void setProperty(OProperty oProperty, String key, JsonNode value) throws Exception { public void setProperty(Property property, String key, JsonNode value) throws Exception {
switch (oProperty.getType()) {
switch (property.getType()) {
case EMBEDDED: case EMBEDDED:
ODocument oDocument = PropertyElementManagement.getPropertyDocument(value); Document document = PropertyElementManagement.getPropertyDocument(value);
element.setProperty(key, oDocument, OType.EMBEDDED); ((MutableDocument) element).set(key, document, com.arcadedb.schema.Type.EMBEDDED);
break; break;
case EMBEDDEDLIST: case LIST:
List<Object> list = new ArrayList<Object>(); List<Object> list = new ArrayList<Object>();
Iterator<JsonNode> arrayElement = value.elements(); Iterator<JsonNode> arrayElement = value.elements();
while(arrayElement.hasNext()) { while(arrayElement.hasNext()) {
JsonNode elementOfArray = arrayElement.next(); JsonNode elementOfArray = arrayElement.next();
Object object = null; Object object = null;
if(oProperty.getLinkedType()!=null) { if(property.getType()!=null) {
object = getObjectFromJsonNode(elementOfArray); object = getObjectFromJsonNode(elementOfArray);
}else { }else {
object = PropertyElementManagement.getPropertyDocument(elementOfArray); object = PropertyElementManagement.getPropertyDocument(elementOfArray);
} }
list.add(object); list.add(object);
} }
element.setProperty(key, list, OType.EMBEDDEDLIST); ((MutableDocument) element).set(key, list, com.arcadedb.schema.Type.LIST);
break; break;
case EMBEDDEDSET: case MAP:
Set<Object> set = new HashSet<Object>();
Iterator<JsonNode> setElement = value.elements();
while(setElement.hasNext()) {
JsonNode elementOfSet = setElement.next();
Object object = null;
if(oProperty.getLinkedType()!=null) {
object = getObjectFromJsonNode(elementOfSet);
}else {
object = PropertyElementManagement.getPropertyDocument(elementOfSet);
}
set.add(object);
}
element.setProperty(key, set, OType.EMBEDDEDSET);
break;
case EMBEDDEDMAP:
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
Iterator<String> fieldNames = value.fieldNames(); Iterator<String> fieldNames = value.fieldNames();
while(fieldNames.hasNext()) { while(fieldNames.hasNext()) {
String fieldKey = fieldNames.next(); String fieldKey = fieldNames.next();
Object object = null; Object object = null;
if(oProperty.getLinkedType()!=null) { if(property.getType()!=null) {
object = getObjectFromJsonNode(value.get(fieldKey)); object = getObjectFromJsonNode(value.get(fieldKey));
}else { }else {
object = PropertyElementManagement.getPropertyDocument(value.get(fieldKey)); object = PropertyElementManagement.getPropertyDocument(value.get(fieldKey));
} }
map.put(fieldKey, object); map.put(fieldKey, object);
} }
element.setProperty(key, map, OType.EMBEDDEDMAP); ((MutableDocument) element).set(key, map, com.arcadedb.schema.Type.MAP);
break; break;
case STRING: case STRING:
if(value.getNodeType() == JsonNodeType.OBJECT) { if(value.getNodeType() == JsonNodeType.OBJECT) {
element.setProperty(key, value.toString()); ((MutableDocument) element).set(key, value.toString());
}else { }else {
element.setProperty(key, getObjectFromJsonNode(value)); ((MutableDocument) element).set(key, getObjectFromJsonNode(value));
} }
break; break;
default: default:
Object obj = getObjectFromJsonNode(value); Object obj = getObjectFromJsonNode(value);
if(obj != null) { if(obj != null) {
element.setProperty(key, obj); ((MutableDocument) element).set(key, obj);
} }
break; break;
} }
} }
public OElement updateProperties(OClass oClass, OElement element, JsonNode jsonNode, Set<String> ignoreKeys, public Document updateProperties(DocumentType type, Document element, JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreStartWithKeys) throws ResourceRegistryException { Set<String> ignoreStartWithKeys) throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyNames(); Set<String> oldKeys = element.getPropertyNames();
@ -1161,31 +1149,31 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
oldKeys.removeAll(properties.keySet()); oldKeys.removeAll(properties.keySet());
getOClass(); getDocumentType();
for(String key : properties.keySet()) { for(String key : properties.keySet()) {
try { try {
JsonNode value = properties.get(key); JsonNode value = properties.get(key);
OProperty oProperty = oClass.getProperty(key); Property property = type.getProperty(key);
if(oProperty==null) { if(property==null) {
Object object = getObjectFromJsonNode(value); Object object = getObjectFromJsonNode(value);
if(object != null) { if(object != null) {
if(object instanceof ODocument) { if(object instanceof Document) {
element.setProperty(key, object, OType.EMBEDDED); ((MutableDocument) element).set(key, object, com.arcadedb.schema.Type.EMBEDDED);
/* /*
* Due to bug https://github.com/orientechnologies/orientdb/issues/7354 * Due to bug https://github.com/orientechnologies/orientdb/issues/7354
* we should not support ArrayList * we should not support ArrayList
*/ */
} else if(object instanceof List){ } else if(object instanceof List){
element.setProperty(key, object, OType.EMBEDDEDLIST); ((MutableDocument) element).set(key, object, com.arcadedb.schema.Type.LIST);
} else { } else {
element.setProperty(key, object); ((MutableDocument) element).set(key, object);
} }
} }
}else { }else {
setProperty(oProperty, key, value); setProperty(property, key, value);
} }
} catch(Exception e) { } catch(Exception e) {
@ -1209,7 +1197,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} }
} }
element.removeProperty(key); ((MutableDocument) element).remove(key);
} }
return element; return element;
@ -1232,8 +1220,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
if(key.compareTo(IdentifiableElement.METADATA_PROPERTY) == 0) { if(key.compareTo(IdentifiableElement.METADATA_PROPERTY) == 0) {
// Keeping the metadata // Keeping the metadata
MetadataOrient metadataOrient = MetadataUtility.getMetadataOrient((ODocument) object); MetadataOrient metadataOrient = MetadataUtility.getMetadataOrient((Document) object);
ObjectNode metadataJson = (ObjectNode) OrientDBUtility.toJsonNode(metadataOrient); ObjectNode metadataJson = (ObjectNode) DBUtility.toJsonNode(metadataOrient);
if(!isUserAllowedToGetPrivacyMeta()) { if(!isUserAllowedToGetPrivacyMeta()) {
metadataJson.replace(Metadata.CREATED_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER)); metadataJson.replace(Metadata.CREATED_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER));
@ -1243,7 +1231,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
// TODO check a solution for supertypes // TODO check a solution for supertypes
TypesCache typesCache = TypesCache.getInstance(); TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
CachedType<PropertyType<Property>> metadataType = (CachedType<PropertyType<Property>>) typesCache.getCachedType(Metadata.NAME); CachedType<PropertyType<org.gcube.informationsystem.model.reference.properties.Property>> metadataType = (CachedType<PropertyType<org.gcube.informationsystem.model.reference.properties.Property>>) typesCache.getCachedType(Metadata.NAME);
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
Collection<String> superClasses = metadataType.getSuperTypes(); Collection<String> superClasses = metadataType.getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(superClasses); ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
@ -1266,16 +1254,16 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} }
} }
if(object instanceof ODocument) { if(object instanceof Document) {
ODocument oDocument = (ODocument) object; Document document = (Document) object;
return PropertyElementManagement.getJsonNode(oDocument); return PropertyElementManagement.getJsonNode(document);
} }
if(object instanceof Date) { if(object instanceof Date) {
OProperty oProperty = getOClass().getProperty(key); Property property = getDocumentType().getProperty(key);
OType oType = oProperty.getType(); com.arcadedb.schema.Type type = property.getType();
DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance(); DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance();
switch(oType) { switch(type) {
case DATE: case DATE:
dateFormat = ODateHelper.getDateFormatInstance(); dateFormat = ODateHelper.getDateFormatInstance();
break; break;
@ -1420,7 +1408,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
if(propertyDefinition.isNotnull()) { if(propertyDefinition.isNotnull()) {
// If the field is mandatory but null value is accepted I add the // If the field is mandatory but null value is accepted I add the
// field as null value // field as null value
element.setProperty(fieldName, null); ((MutableDocument) element).set(fieldName, null);
} else { } else {
throw new SchemaViolationException(getMandatoryErrorMessage(fieldName)); throw new SchemaViolationException(getMandatoryErrorMessage(fieldName));
} }

View File

@ -20,15 +20,15 @@ import org.gcube.informationsystem.resourceregistry.instances.model.relations.Co
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement; import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement; import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.schema.DocumentType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -68,22 +68,22 @@ public class ElementManagementUtility {
return erManagement; return erManagement;
} }
public static ElementManagement<?,?> getERManagement(SecurityContext workingContext, ODatabaseDocument orientGraph, public static ElementManagement<?,?> getERManagement(SecurityContext workingContext, RemoteDatabase database,
OElement element) throws ResourceRegistryException { Document element) throws ResourceRegistryException {
if(element instanceof OVertex) { if(element instanceof Vertex) {
return getEntityManagement(workingContext, orientGraph, (OVertex) element); return getEntityManagement(workingContext, database, (Vertex) element);
} else if(element instanceof OEdge) { } else if(element instanceof Edge) {
return getRelationManagement(workingContext, orientGraph, (OEdge) element); return getRelationManagement(workingContext, database, (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 OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException { public static Document getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
try { try {
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OVertex.class); return DBUtility.getElementByUUIDAsAdmin(null, uuid, Vertex.class);
} catch(NotFoundException e) { } catch(NotFoundException e) {
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OEdge.class); return DBUtility.getElementByUUIDAsAdmin(null, uuid, Edge.class);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
@ -91,12 +91,12 @@ public class ElementManagementUtility {
} }
} }
public static OElement getAnyElementByUUID(ODatabaseDocument oDatabaseDocument, UUID uuid) public static Document getAnyElementByUUID(RemoteDatabase database, UUID uuid)
throws NotFoundException, ResourceRegistryException { throws NotFoundException, ResourceRegistryException {
try { try {
return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OVertex.class); return DBUtility.getElementByUUID(database, null, uuid, Vertex.class);
} catch(NotFoundException e) { } catch(NotFoundException e) {
return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OEdge.class); return DBUtility.getElementByUUID(database, null, uuid, Edge.class);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
@ -104,92 +104,87 @@ public class ElementManagementUtility {
} }
} }
public static ElementManagement<?, ?> getERManagementFromUUID(SecurityContext workingContext, ODatabaseDocument orientGraph, public static ElementManagement<?, ?> getERManagementFromUUID(SecurityContext workingContext, RemoteDatabase database,
UUID uuid) throws ResourceRegistryException { UUID uuid) throws ResourceRegistryException {
OElement element;
try { try {
element = getAnyElementByUUID(orientGraph, uuid); Document element = getAnyElementByUUID(database, uuid);
return getERManagement(workingContext, orientGraph, element); return getERManagement(workingContext, database, element);
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s", throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
uuid.toString(), Entity.NAME, Relation.NAME)); uuid.toString(), Entity.NAME, Relation.NAME));
} }
} }
public static EntityManagement<?, ?> getEntityManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument, public static EntityManagement<?, ?> getEntityManagement(SecurityContext workingContext, RemoteDatabase database,
OVertex vertex) throws ResourceRegistryException { Vertex vertex) throws ResourceRegistryException {
if(oDatabaseDocument == null) { if(database == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException("Database instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if(vertex == null) { if(vertex == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException(Vertex.class.getSimpleName() + " instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OVertex.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
OClass oClass = null; DocumentType documentType = null;
try { try {
oClass = ElementManagementUtility.getOClass(vertex); documentType = ElementManagementUtility.getDocumentType(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(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e); logger.error(error, e);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
EntityManagement<?, ?> entityManagement = null; EntityManagement<?, ?> entityManagement = null;
if(oClass.isSubClassOf(Resource.NAME)) { if(documentType.isSubTypeOf(Resource.NAME)) {
entityManagement = new ResourceManagement(); entityManagement = new ResourceManagement();
} else if(oClass.isSubClassOf(Facet.NAME)) { } else if(documentType.isSubTypeOf(Facet.NAME)) {
entityManagement = new FacetManagement(); entityManagement = new FacetManagement();
} 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,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
entityManagement.setODatabaseDocument(oDatabaseDocument); entityManagement.setDatabase(database);
entityManagement.setWorkingContext(workingContext); entityManagement.setWorkingContext(workingContext);
entityManagement.setElement(vertex); entityManagement.setElement(vertex);
return entityManagement; return entityManagement;
} }
public static RelationManagement<?,?> getRelationManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument, public static RelationManagement<?,?> getRelationManagement(SecurityContext workingContext, RemoteDatabase database,
OEdge edge) throws ResourceRegistryException { Edge edge) throws ResourceRegistryException {
if(oDatabaseDocument == null) { if(database == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException("Database instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if(edge == null) { if(edge == null) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
OEdge.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Edge.class.getSimpleName() + " instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
OClass oClass = ElementManagementUtility.getOClass(edge); DocumentType documentType = ElementManagementUtility.getDocumentType(edge);
RelationManagement<?,?> relationManagement = null; RelationManagement<?,?> relationManagement = null;
if(oClass.isSubClassOf(ConsistsOf.NAME)) { if(documentType.isSubTypeOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(); relationManagement = new ConsistsOfManagement();
} else if(oClass.isSubClassOf(IsRelatedTo.NAME)) { } else if(documentType.isSubTypeOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(); relationManagement = new IsRelatedToManagement();
} 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,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
relationManagement.setDatabase(database);
relationManagement.setODatabaseDocument(oDatabaseDocument);
relationManagement.setWorkingContext(workingContext); relationManagement.setWorkingContext(workingContext);
relationManagement.setElement(edge); relationManagement.setElement(edge);
return relationManagement; return relationManagement;
} }
public static <E extends OElement> E getElementFromOptional(Optional<E> optional) throws ResourceRegistryException { public static <E extends Document> E getElementFromOptional(Optional<E> optional) throws ResourceRegistryException {
if(optional.isPresent()) { if(optional.isPresent()) {
return optional.get(); return optional.get();
}else { }else {
@ -197,13 +192,12 @@ public class ElementManagementUtility {
} }
} }
public static OClass getOClass(OElement oElement) throws ResourceRegistryException { public static DocumentType getDocumentType(Document document) throws ResourceRegistryException {
Optional<OClass> optional = oElement.getSchemaType(); DocumentType documentType = document.getType();
if(optional.isPresent()) { if(documentType==null) {
return optional.get();
}else {
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator."); throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
} }
return documentType;
} }
} }

View File

@ -18,18 +18,19 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.graph.MutableVertex;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.graph.Vertex;
import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class EntityElementManagement<E extends EntityElement, ET extends EntityType> extends ElementManagement<OVertex, ET> { public abstract class EntityElementManagement<E extends EntityElement, ET extends EntityType> extends ElementManagement<Vertex, ET> {
public final static String IN_PREFIX = "in_"; public final static String IN_PREFIX = "in_";
public final static String OUT_PREFIX = "out_"; public final static String OUT_PREFIX = "out_";
@ -52,9 +53,9 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
} }
protected EntityElementManagement(AccessType accessType, SecurityContext workingContext, ODatabaseDocument oDatabaseDocument) { protected EntityElementManagement(AccessType accessType, SecurityContext workingContext, RemoteDatabase database) {
this(accessType); this(accessType);
this.oDatabaseDocument = oDatabaseDocument; this.database = database;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
@ -64,11 +65,11 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
* 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 RelationElementManagement<?,?,?,?> getBaseRelationManagement(OEdge edge) throws ResourceRegistryException { protected RelationElementManagement<?,?,?,?> getBaseRelationManagement(Edge edge) throws ResourceRegistryException {
String id = edge.getIdentity().toString(); String id = edge.getIdentity().toString();
RelationElementManagement<?,?,?,?> relationManagement = relationManagements.get(id); RelationElementManagement<?,?,?,?> relationManagement = relationManagements.get(id);
if(relationManagement == null) { if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
return relationManagement; return relationManagement;
@ -76,7 +77,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
protected void addToRelationManagement(RelationElementManagement<?,?,?,?> baseRelationManagement) protected void addToRelationManagement(RelationElementManagement<?,?,?,?> baseRelationManagement)
throws ResourceRegistryException { throws ResourceRegistryException {
OElement elem = baseRelationManagement.getElement(); Document elem = baseRelationManagement.getElement();
String id = elem.getIdentity().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();
@ -85,7 +86,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
errorMessage.append(" point to the same "); errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName()); errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". "); errorMessage.append(". ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString()); throw new ResourceRegistryException(errorMessage.toString());
} }
relationManagements.put(id, baseRelationManagement); relationManagements.put(id, baseRelationManagement);
@ -108,23 +109,24 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
return sourceResource; return sourceResource;
} }
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(), logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode); typeName, jsonNode);
try { try {
if(oClass.isAbstract()) { // TODO
String error = String.format( // if(documentType.isAbstract()) {
"Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", // String error = String.format(
accessType.getName(), typeName); // "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
throw new ResourceRegistryException(error); // accessType.getName(), typeName);
} // throw new ResourceRegistryException(error);
// }
try { try {
if(uuid != null) { if(uuid != null) {
OVertex v = getElement(); Vertex v = getElement();
if(v != null) { if(v != null) {
String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString()); String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString());
throw getSpecificAlreadyPresentException(error); throw getSpecificAlreadyPresentException(error);
@ -133,10 +135,10 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
} catch(NotFoundException e) { } catch(NotFoundException e) {
try { try {
OElement el = ElementManagementUtility.getAnyElementByUUID(uuid); Document el = ElementManagementUtility.getAnyElementByUUID(uuid);
String error = String.format("UUID %s is already used by another Element. This is not allowed.", String error = String.format("UUID %s is already used by another Element. This is not allowed.",
uuid.toString(), uuid.toString(),
(el instanceof OVertex) ? EntityElement.NAME : RelationElement.NAME); (el instanceof Vertex) ? EntityElement.NAME : RelationElement.NAME);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} catch(NotFoundException e1) { } catch(NotFoundException e1) {
@ -146,23 +148,23 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
throw e; throw e;
} }
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName); MutableVertex vertexEntity = database.newVertex(typeName);
this.element = vertexEntity; this.element = vertexEntity;
if(accessType == AccessType.RESOURCE) { if(accessType == AccessType.RESOURCE) {
// Facet and relation are created in calling method // Facet and relation are created in calling method
} else { } else {
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
} }
logger.info("Created {} is {}", OVertex.class.getSimpleName(), logger.info("Created {} is {}", Vertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging(element)); DBUtility.getAsStringForLogging(element));
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 {}", OVertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e); accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
} }

View File

@ -26,15 +26,15 @@ import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient; import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility; import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility; import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.types.reference.properties.PropertyType; import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility; import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.schema.DocumentType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -55,8 +55,8 @@ public class PropertyElementManagement {
} }
public static ODocument getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException { public static Document getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException {
ODocument oDocument = null; Document document = null;
if(jsonNodeOrig.isNull()) { if(jsonNodeOrig.isNull()) {
return null; return null;
} }
@ -70,13 +70,13 @@ public class PropertyElementManagement {
String type = TypeUtility.getTypeName(jsonNode); String type = TypeUtility.getTypeName(jsonNode);
if(type!=null) { if(type!=null) {
// Complex type // Complex type
OClass oClass = null; DocumentType documentType = null;
try { try {
TypesCache typesCache = TypesCache.getInstance(); TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type); CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
oClass = cachedType.getOClass(); documentType = cachedType.getDocumentType();
AccessType gotAccessType = cachedType.getAccessType(); AccessType gotAccessType = cachedType.getAccessType();
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) { if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName()); throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName());
@ -112,10 +112,10 @@ public class PropertyElementManagement {
* Resource Registry must decrypt the value with the Context Key and Encrypt it with DB key. * Resource Registry must decrypt the value with the Context Key and Encrypt it with DB key.
* The opposite operation is done when the value is read by clients. * The opposite operation is done when the value is read by clients.
*/ */
if(oClass.isSubClassOf(Encrypted.NAME)) { if(documentType.isSubTypeOf(Encrypted.NAME)) {
EncryptedOrient encrypted = new EncryptedOrient(); EncryptedOrient encrypted = new EncryptedOrient();
oDocument = encrypted; document = encrypted;
oDocument.fromJSON(jsonNode.toString()); document.fromJSON(jsonNode.toString());
try { try {
String contextEncryptedValue = encrypted.getEncryptedValue(); String contextEncryptedValue = encrypted.getEncryptedValue();
@ -126,21 +126,21 @@ public class PropertyElementManagement {
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException("Unable to manage " + Encrypted.NAME + " " + org.gcube.informationsystem.model.reference.properties.Property.NAME); throw new ResourceRegistryException("Unable to manage " + Encrypted.NAME + " " + org.gcube.informationsystem.model.reference.properties.Property.NAME);
} }
return oDocument; return document;
} }
oDocument = new ODocument(type); document = new Document(type);
} else { } else {
oDocument = new ODocument(); document = new Document();
} }
return oDocument.fromJSON(jsonNode.toString()); return document.fromJSON(jsonNode.toString());
} }
public static JsonNode getJsonNode(ODocument oDocument) throws ResourceRegistryException { public static JsonNode getJsonNode(Document oDocument) throws ResourceRegistryException {
try { try {
String type = oDocument.getClassName(); String type = oDocument.getTypeName();
String json = OrientDBUtility.toJsonString(oDocument); String json = DBUtility.toJsonString(oDocument);
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json); JsonNode jsonNode = objectMapper.readTree(json);
@ -153,7 +153,7 @@ public class PropertyElementManagement {
TypesCache typesCache = TypesCache.getInstance(); TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type); CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
OClass oClass = cachedType.getOClass(); DocumentType documentType = cachedType.getDocumentType();
AccessType gotAccessType = cachedType.getAccessType(); AccessType gotAccessType = cachedType.getAccessType();
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) { if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName()); throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName());
@ -169,11 +169,11 @@ public class PropertyElementManagement {
* The opposite operation is done when the value is set from clients. * The opposite operation is done when the value is set from clients.
* see {@link PropertyManagement#getPropertyDocument(JsonNode) getPropertyDocument()} * see {@link PropertyManagement#getPropertyDocument(JsonNode) getPropertyDocument()}
*/ */
if(oClass.isSubClassOf(Encrypted.NAME)) { if(documentType.isSubTypeOf(Encrypted.NAME)) {
try { try {
EncryptedOrient encrypted = null; EncryptedOrient encrypted = null;
String encryptedValue = (String) oDocument.getProperty(Encrypted.VALUE); String encryptedValue = (String) oDocument.getString(Encrypted.VALUE);
if(oDocument instanceof EncryptedOrient) { if(oDocument instanceof EncryptedOrient) {
encrypted = (EncryptedOrient) oDocument; encrypted = (EncryptedOrient) oDocument;
@ -182,7 +182,7 @@ public class PropertyElementManagement {
} }
}else { }else {
encrypted = new EncryptedOrient(); encrypted = new EncryptedOrient();
oDocument = (ODocument) encrypted; oDocument = (Document) encrypted;
// Decrypting with DB Key // Decrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey(); Key databaseKey = DatabaseEnvironment.getDatabaseKey();

View File

@ -16,21 +16,22 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaV
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.relations.RelationType; import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.gcube.informationsystem.utils.UUIDUtility; import org.gcube.informationsystem.utils.UUIDUtility;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class RelationElementManagement<SEM extends EntityElementManagement<? extends EntityElement, SET>, TEM extends EntityElementManagement<? extends EntityElement, TET>, SET extends EntityType, TET extends EntityType> public abstract class RelationElementManagement<SEM extends EntityElementManagement<? extends EntityElement, SET>, TEM extends EntityElementManagement<? extends EntityElement, TET>, SET extends EntityType, TET extends EntityType>
extends ElementManagement<OEdge, RelationType<SET, TET>> { extends ElementManagement<Edge, RelationType<SET, TET>> {
public final static String IN = "in"; public final static String IN = "in";
public final static String OUT = "out"; public final static String OUT = "out";
@ -73,15 +74,15 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
this.includeTarget = includeTarget; this.includeTarget = includeTarget;
} }
protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) { protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass, SecurityContext workingContext, RemoteDatabase database) {
this(accessType, sourceEntityClass, targetEntityClass); this(accessType, sourceEntityClass, targetEntityClass);
this.oDatabaseDocument = orientGraph; this.database = database;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
public SEM getSourceEntityManagement() throws ResourceRegistryException { public SEM getSourceEntityManagement() throws ResourceRegistryException {
if(sourceEntityManagement == null) { if(sourceEntityManagement == null) {
OVertex source = getElement().getVertex(ODirection.OUT); Vertex source = getElement().getVertex(DIRECTION.OUT);
sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElement(source); sourceEntityManagement.setElement(source);
} }
@ -91,7 +92,7 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
public TEM getTargetEntityManagement() throws ResourceRegistryException { public TEM getTargetEntityManagement() throws ResourceRegistryException {
if(targetEntityManagement == null) { if(targetEntityManagement == null) {
OVertex target = getElement().getVertex(ODirection.IN); Vertex target = getElement().getVertex(DIRECTION.IN);
targetEntityManagement = newTargetEntityManagement(); targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElement(target); targetEntityManagement.setElement(target);
} }
@ -123,10 +124,10 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
} }
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
@ -136,7 +137,7 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
protected abstract void checksourceAndTargetEntityCompliancy() throws NotFoundException, AvailableInAnotherContextException, SchemaViolationException, ResourceRegistryException; protected abstract void checksourceAndTargetEntityCompliancy() throws NotFoundException, AvailableInAnotherContextException, SchemaViolationException, ResourceRegistryException;
@Override @Override
protected OEdge reallyCreate() throws ResourceRegistryException { protected Edge reallyCreate() throws ResourceRegistryException {
if(sourceEntityManagement == null) { if(sourceEntityManagement == null) {
@ -178,16 +179,16 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
} }
} }
OVertex source = (OVertex) getSourceEntityManagement().getElement(); Vertex source = (Vertex) getSourceEntityManagement().getElement();
OVertex target = (OVertex) getTargetEntityManagement().getElement(); Vertex target = (Vertex) getTargetEntityManagement().getElement();
checksourceAndTargetEntityCompliancy(); checksourceAndTargetEntityCompliancy();
logger.trace("Going to create {} beetween {} -> {}", typeName, source.toString(), target.toString()); logger.trace("Going to create {} beetween {} -> {}", typeName, source.toString(), target.toString());
element = oDatabaseDocument.newEdge(source, target, typeName); element = source.newEdge(typeName, target, true);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
return element; return element;
} }
@ -197,12 +198,12 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
protected abstract TEM newTargetEntityManagement() throws ResourceRegistryException; protected abstract TEM newTargetEntityManagement() throws ResourceRegistryException;
@Override @Override
protected OEdge reallyUpdate() throws ResourceRegistryException { protected Edge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", typeName, jsonNode); logger.debug("Trying to update {} : {}", typeName, jsonNode);
OEdge edge = getElement(); Edge edge = getElement();
updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, 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);

View File

@ -19,7 +19,7 @@ import org.gcube.informationsystem.utils.TypeUtility;
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.arcadedb.remote.RemoteDatabase;
public class ERManagementUtility { public class ERManagementUtility {
@ -29,12 +29,12 @@ public class ERManagementUtility {
throws NotFoundException, ContextException, ResourceRegistryException { throws NotFoundException, ContextException, ResourceRegistryException {
Set<UUID> instances = expectedInstances.keySet(); Set<UUID> instances = expectedInstances.keySet();
staticLogger.info("Going to add {} to Context with UUID {} not following Propagation Constraints", instances, contextUUID); staticLogger.info("Going to add {} to Context with UUID {} not following Propagation Constraints", instances, contextUUID);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
@ -46,7 +46,7 @@ public class ERManagementUtility {
String type = TypeUtility.getTypeName(expectedInstances.get(uuid)); String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type); ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setWorkingContext(adminSecurityContext); elementManagement.setWorkingContext(adminSecurityContext);
elementManagement.setODatabaseDocument(oDatabaseDocument); elementManagement.setDatabase(database);
elementManagement.setUUID(uuid); elementManagement.setUUID(uuid);
elementManagement.setElementType(type); elementManagement.setElementType(type);
elementManagement.setDryRun(dryRun); elementManagement.setDryRun(dryRun);
@ -68,12 +68,12 @@ public class ERManagementUtility {
/* /*
SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.ADD); SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.ADD);
if(operationValidator.isValidOperation(enforcedInstances)) { if(operationValidator.isValidOperation(enforcedInstances)) {
oDatabaseDocument.commit(); database.commit();
} }
*/ */
oDatabaseDocument.activateOnCurrentThread(); // database.activateOnCurrentThread();
oDatabaseDocument.commit(); database.commit();
staticLogger.info("{} successfully added to Context with UUID {} not following Propagation Constraints", instances, contextUUID); staticLogger.info("{} successfully added to Context with UUID {} not following Propagation Constraints", instances, contextUUID);
/* /*
@ -85,24 +85,24 @@ public class ERManagementUtility {
return expectedInstances; return expectedInstances;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage()); staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage());
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage()); staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage());
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -110,12 +110,12 @@ public class ERManagementUtility {
throws NotFoundException, ContextException, ResourceRegistryException { throws NotFoundException, ContextException, ResourceRegistryException {
Set<UUID> instances = expectedInstances.keySet(); Set<UUID> instances = expectedInstances.keySet();
staticLogger.info("Going to remove {} from Context with UUID {} not following Propagation Constraints", instances, contextUUID); staticLogger.info("Going to remove {} from Context with UUID {} not following Propagation Constraints", instances, contextUUID);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
@ -126,7 +126,7 @@ public class ERManagementUtility {
String type = TypeUtility.getTypeName(expectedInstances.get(uuid)); String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type); ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setWorkingContext(adminSecurityContext); elementManagement.setWorkingContext(adminSecurityContext);
elementManagement.setODatabaseDocument(oDatabaseDocument); elementManagement.setDatabase(database);
elementManagement.setUUID(uuid); elementManagement.setUUID(uuid);
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false); ((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
elementManagement.setDryRun(dryRun); elementManagement.setDryRun(dryRun);
@ -146,11 +146,11 @@ public class ERManagementUtility {
SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.REMOVE); SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.REMOVE);
if(operationValidator.isValidOperation(enforcedInstances)) { if(operationValidator.isValidOperation(enforcedInstances)) {
oDatabaseDocument.commit(); database.commit();
} }
*/ */
oDatabaseDocument.commit(); database.commit();
staticLogger.info("{} successfully removed from Context with UUID {} not following Propagation Constraints", instances, contextUUID); staticLogger.info("{} successfully removed from Context with UUID {} not following Propagation Constraints", instances, contextUUID);
/* /*
@ -162,24 +162,24 @@ public class ERManagementUtility {
return expectedInstances; return expectedInstances;
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage()); staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage());
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage()); staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage());
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }

View File

@ -40,19 +40,19 @@ import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement; import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility; import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.database.Document;
import com.orientechnologies.orient.core.id.ORID; import com.arcadedb.database.RID;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.MutableVertex;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.schema.DocumentType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -163,7 +163,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
@Override @Override
public OVertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public Vertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try { try {
element = super.getElement(); element = super.getElement();
} catch(NotFoundException e) { } catch(NotFoundException e) {
@ -191,11 +191,11 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* 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(OEdge edge) throws ResourceRegistryException { protected RelationManagement<?,?> getRelationManagement(Edge edge) throws ResourceRegistryException {
String id = edge.getIdentity().toString(); String id = edge.getIdentity().toString();
RelationManagement<?,?> relationManagement = relationManagements.get(id); RelationManagement<?,?> relationManagement = relationManagements.get(id);
if(relationManagement == null) { if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
return relationManagement; return relationManagement;
@ -203,7 +203,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
public void addToRelationManagements(RelationManagement<?,?> relationManagement) public void addToRelationManagements(RelationManagement<?,?> relationManagement)
throws ResourceRegistryException { throws ResourceRegistryException {
OElement elem = relationManagement.getElement(); Edge elem = relationManagement.getElement();
String id = elem.getIdentity().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();
@ -212,7 +212,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
errorMessage.append(" point to the same "); errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName()); errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". "); errorMessage.append(". ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString()); throw new ResourceRegistryException(errorMessage.toString());
} }
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
@ -236,25 +236,26 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
@Override @Override
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(), logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode); typeName, jsonNode);
try { try {
if(oClass.isAbstract()) { // TODO
String error = String.format( // if(documentType.isAbstract()) {
"Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", // String error = String.format(
accessType.getName(), typeName); // "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
throw new SchemaViolationException(error); // accessType.getName(), typeName);
} // throw new SchemaViolationException(error);
// }
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName); MutableVertex vertexEntity = database.newVertex(typeName);
try { try {
if(uuid != null) { if(uuid != null) {
OVertex v = getElement(); Vertex v = getElement();
if(v != null) { if(v != null) {
String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString()); String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString());
throw getSpecificAlreadyPresentException(error); throw getSpecificAlreadyPresentException(error);
@ -263,9 +264,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} catch(NotFoundException e) { } catch(NotFoundException e) {
try { try {
OElement el = ElementManagementUtility.getAnyElementByUUID(uuid); Document el = ElementManagementUtility.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 OVertex) ? Entity.NAME : Relation.NAME); uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME);
throw getSpecificAvailableInAnotherContextException(error); throw getSpecificAvailableInAnotherContextException(error);
} catch(NotFoundException e1) { } catch(NotFoundException e1) {
@ -280,17 +281,17 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
if(accessType == AccessType.RESOURCE) { if(accessType == AccessType.RESOURCE) {
// Facet and relation are created in calling method // Facet and relation are created in calling method
} else { } else {
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
} }
logger.debug("Created {} is {}", OVertex.class.getSimpleName(), logger.debug("Created {} is {}", Vertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging((OVertex) element)); DBUtility.getAsStringForLogging((Vertex) element));
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 {}", OVertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e); accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
} }
@ -305,7 +306,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
targetSecurityContext.addElement(getElement(), oDatabaseDocument); targetSecurityContext.addElement(getElement(), database);
/* /*
* DO NOT UNCOMMENT * DO NOT UNCOMMENT
@ -314,9 +315,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* the update of Metadata i.e. modifiedBy, lastUpdateTime * the update of Metadata i.e. modifiedBy, lastUpdateTime
*/ */
if(honourPropagationConstraintsInContextSharing) { if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT); Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) { for(Edge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge); RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun); relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing); relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
@ -336,7 +337,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
reallyAddToContext(); reallyAddToContext();
if(!skipped) { if(!skipped) {
MetadataUtility.updateModifiedByAndLastUpdate(element); MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save(); // element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance()); affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck(); sanityCheck();
} }
@ -352,11 +353,11 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException { public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID); String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName); logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
workingContext = ContextUtility.getAdminSecurityContext(); workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER); database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
setAsEntryPoint(); setAsEntryPoint();
sourceSecurityContext = ContextUtility.getCurrentSecurityContext(); sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
@ -365,31 +366,31 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
internalAddToContext(); internalAddToContext();
if(!dryRun) { if(!dryRun) {
oDatabaseDocument.commit(); database.commit();
}else { }else {
oDatabaseDocument.rollback(); database.rollback();
} }
logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName); logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {}) - Reason is {}", typeName, uuid, contextUUID, contextFullName, e.getMessage()); logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {}) - Reason is {}", typeName, uuid, contextUUID, contextFullName, e.getMessage());
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName, e); logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName, e);
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -400,7 +401,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
setOperation(Operation.REMOVE_FROM_CONTEXT); setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext(); reallyRemoveFromContext();
MetadataUtility.updateModifiedByAndLastUpdate(element); MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save(); // element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance()); affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck(); sanityCheck();
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
@ -420,9 +421,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
if(honourPropagationConstraintsInContextSharing) { if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT); Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) { for(Edge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge); RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun); relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing); relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
@ -434,7 +435,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
} }
targetSecurityContext.removeElement(getElement(), oDatabaseDocument); targetSecurityContext.removeElement(getElement(), database);
/* /*
* DO NOT UNCOMMENT * DO NOT UNCOMMENT
@ -449,11 +450,11 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException { throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID); logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
workingContext = ContextUtility.getAdminSecurityContext(); workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER); database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
setAsEntryPoint(); setAsEntryPoint();
// Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext(); // Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
@ -462,32 +463,32 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
internalRemoveFromContext(); internalRemoveFromContext();
if(!dryRun) { if(!dryRun) {
oDatabaseDocument.commit(); database.commit();
}else { }else {
oDatabaseDocument.rollback(); database.rollback();
} }
logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID); logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID); logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID, logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID,
e); e);
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -496,17 +497,17 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic); Iterable<Document> iterable = database.browseClass(typeName, polymorphic);
for(ODocument vertex : iterable) { for(Document vertex : iterable) {
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) vertex); database, (Vertex) vertex);
try { try {
entityManagement.setAsEntryPoint(); entityManagement.setAsEntryPoint();
JsonNode jsonNode = entityManagement.serializeAsJsonNode(); JsonNode jsonNode = entityManagement.serializeAsJsonNode();
arrayNode.add(jsonNode); arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
try { try {
@ -516,13 +517,13 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
} }
public boolean propertyMatchRequestedValue(OVertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException { public boolean propertyMatchRequestedValue(Vertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
return requestedValue.compareTo(instanceValue.toString())==0; return requestedValue.compareTo(instanceValue.toString())==0;
/* /*
OClass oClass = ElementManagement.getOClass(v); OClass documentType = ElementManagement.getOClass(v);
OProperty oProperty = oClass.getProperty(key); OProperty oProperty = documentType.getProperty(key);
if(oProperty==null){ if(oProperty==null){
// It is an additional property // It is an additional property
return requestedValue.compareTo(instanceValue.toString())==0; return requestedValue.compareTo(instanceValue.toString())==0;
@ -544,10 +545,10 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
/* /*
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction, public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException { boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/ */
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction, public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, DIRECTION 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();
@ -555,21 +556,21 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
Iterable<?> references = null; Iterable<?> references = null;
if(referenceUUID != null) { if(referenceUUID != null) {
OElement element = null; Document element = null;
try { try {
element = ElementManagementUtility.getAnyElementByUUID(oDatabaseDocument, referenceUUID); element = ElementManagementUtility.getAnyElementByUUID(database, referenceUUID);
}catch (ResourceRegistryException e) { }catch (ResourceRegistryException e) {
String error = String.format("No instace with UUID %s exists", referenceUUID.toString()); String error = String.format("No instace with UUID %s exists", referenceUUID.toString());
throw new InvalidQueryException(error); throw new InvalidQueryException(error);
} }
if(element instanceof OVertex) { if(element instanceof Vertex) {
EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) element); database, (Vertex) element);
String elementType = entityManagement.getTypeName(); String elementType = entityManagement.getTypeName();
if(elementType.compareTo(referenceType) != 0) { if(elementType.compareTo(referenceType) != 0) {
if(polymorphic && getOClass().isSubClassOf(referenceType)) { if(polymorphic && getDocumentType().isSubTypeOf(referenceType)) {
// OK // OK
} else { } else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType); String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
@ -577,8 +578,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
} }
List<OVertex> vertexes = new ArrayList<>(); List<Vertex> vertexes = new ArrayList<>();
vertexes.add((OVertex) element); vertexes.add((Vertex) element);
references = vertexes; references = vertexes;
} else { } else {
@ -587,19 +588,19 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
} else { } else {
references = oDatabaseDocument.browseClass(referenceType, polymorphic); references = database.browseClass(referenceType, polymorphic);
} }
Set<ORID> analysed = new HashSet<>(); Set<RID> analysed = new HashSet<>();
for(Object r : references) { for(Object r : references) {
OVertex v = (OVertex) r; Vertex v = (Vertex) r;
boolean skip = false; boolean skip = false;
// checking if the constraints are satisfied // checking if the constraints are satisfied
for(String key : constraint.keySet()) { for(String key : constraint.keySet()) {
String value = constraint.get(key); String value = constraint.get(key);
Object o = v.getProperty(key); Object o = v.get(key);
if(value==null) { if(value==null) {
if(o==null) { if(o==null) {
//ok //ok
@ -627,42 +628,42 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
List<ODirection> directions = new ArrayList<>(); List<DIRECTION> directions = new ArrayList<>();
if(direction==ODirection.BOTH) { if(direction==DIRECTION.BOTH) {
directions.add(ODirection.IN); directions.add(DIRECTION.IN);
directions.add(ODirection.OUT); directions.add(DIRECTION.OUT);
}else { }else {
directions.add(direction); directions.add(direction);
} }
for(ODirection d : directions) { for(DIRECTION d : directions) {
Iterable<OEdge> edges = v.getEdges(d.opposite(), relationType); Iterable<Edge> edges = v.getEdges(ElementManagement.opposite(d), relationType);
for(OEdge edge : edges) { for(Edge edge : edges) {
OVertex vertex = edge.getVertex(d); Vertex vertex = edge.getVertex(d);
ORID vertexORID = vertex.getIdentity(); RID vertexRID = vertex.getIdentity();
if(analysed.contains(vertexORID)) { if(analysed.contains(vertexRID)) {
continue; continue;
} }
analysed.add(vertexORID); analysed.add(vertexRID);
if(v.getIdentity().compareTo(vertexORID) == 0) { if(v.getIdentity().compareTo(vertexRID) == 0) {
continue; continue;
} }
OClass oClass = ElementManagementUtility.getOClass(vertex); DocumentType documentType = ElementManagementUtility.getDocumentType(vertex);
/* /*
* If the requested type (i.e. elementType) * If the requested type (i.e. elementType)
* differs form the resulting type (i.e. oClass.getName()) * differs form the resulting type (i.e. documentType.getName())
* we need to evaluate if polymorphism is requested and * we need to evaluate if polymorphism is requested and
* if the resulting type is a subclass of the requested type * if the resulting type is a subclass of the requested type
* *
*/ */
if(oClass.getName().compareTo(typeName)!=0) { if(documentType.getName().compareTo(typeName)!=0) {
if(polymorphic && oClass.isSubClassOf(typeName)) { if(polymorphic && documentType.isSubTypeOf(typeName)) {
// OK // OK
} else { } else {
// excluding from results // excluding from results
@ -673,7 +674,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex); database, vertex);
try { try {
if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) { if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
@ -684,7 +685,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
JsonNode jsonNode; JsonNode jsonNode;
if(includeRelationInResult) { if(includeRelationInResult) {
RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
oDatabaseDocument, edge); database, edge);
jsonNode = relationManagement.serializeAsJsonNode(); jsonNode = relationManagement.serializeAsJsonNode();
}else { }else {
jsonNode = entityManagement.serializeAsJsonNode(); jsonNode = entityManagement.serializeAsJsonNode();
@ -696,7 +697,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
arrayNode.add(node); arrayNode.add(node);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
} }
@ -710,7 +711,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} }
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID, public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
ODirection direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException { DIRECTION 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();
@ -732,7 +733,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
selectStringBuilder.append("E('"); selectStringBuilder.append("E('");
selectStringBuilder.append(relationType); selectStringBuilder.append(relationType);
selectStringBuilder.append("'), "); selectStringBuilder.append("'), ");
selectStringBuilder.append(direction.opposite().name().toLowerCase()); selectStringBuilder.append(ElementManagement.opposite(direction).name().toLowerCase());
selectStringBuilder.append("V('"); selectStringBuilder.append("V('");
selectStringBuilder.append(typeName); selectStringBuilder.append(typeName);
selectStringBuilder.append("') FROM (SELECT FROM "); selectStringBuilder.append("') FROM (SELECT FROM ");
@ -763,36 +764,36 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
String select = selectStringBuilder.toString(); String select = selectStringBuilder.toString();
logger.trace(select); logger.trace(select);
OResultSet resultSet = oDatabaseDocument.command(select,new HashMap<>()); ResultSet resultSet = database.command("sql", select);
while(resultSet.hasNext()) { while(resultSet.hasNext()) {
OResult oResult = resultSet.next(); Result oResult = resultSet.next();
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); Document element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
if(polymorphic) { if(polymorphic) {
OClass oClass = null; DocumentType documentType = null;
try { try {
if(element instanceof OEdge) { if(element instanceof Edge) {
continue; continue;
} }
oClass = ElementManagementUtility.getOClass(element); documentType = ElementManagementUtility.getDocumentType(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(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e); logger.error(error, e);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
if(oClass.isSubClassOf(typeName)) { if(documentType.isSubTypeOf(typeName)) {
continue; continue;
} }
} }
OVertex vertex = (OVertex) element; Vertex vertex = (Vertex) element;
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex); database, vertex);
try { try {
if(constraint.containsKey(Entity.ID_PROPERTY)) { if(constraint.containsKey(Entity.ID_PROPERTY)) {
String uuid = constraint.get(Entity.ID_PROPERTY); String uuid = constraint.get(Entity.ID_PROPERTY);
@ -805,7 +806,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
arrayNode.add(jsonNode); arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
@ -820,13 +821,13 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction, public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException { boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/ */
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction, public String query(String relationType, String referenceType, UUID referenceUUID, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException { boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
workingContext = ContextUtility.getAdminSecurityContext(); workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.READER); database = workingContext.getRemoteDatabase(PermissionMode.READER);
setAsEntryPoint(); setAsEntryPoint();
setOperation(Operation.QUERY); setOperation(Operation.QUERY);
@ -853,9 +854,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
if(relationAccessType == AccessType.CONSISTS_OF) { if(relationAccessType == AccessType.CONSISTS_OF) {
if(direction != ODirection.OUT) { if(direction != DIRECTION.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,
ODirection.OUT.name(), typeName); DIRECTION.OUT.name(), typeName);
throw new InvalidQueryException(error); throw new InvalidQueryException(error);
} else { } else {
if(referenceAccessType != AccessType.FACET) { if(referenceAccessType != AccessType.FACET) {
@ -869,10 +870,10 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
break; break;
case FACET: case FACET:
if(relationAccessType != AccessType.CONSISTS_OF || direction != ODirection.IN if(relationAccessType != AccessType.CONSISTS_OF || direction != DIRECTION.IN
|| referenceAccessType != AccessType.RESOURCE) { || referenceAccessType != AccessType.RESOURCE) {
String error = String.format("%s can only has %s %s from a %s.", typeName, String error = String.format("%s can only has %s %s from a %s.", typeName,
ODirection.IN.name(), ConsistsOf.NAME, Resource.NAME); DIRECTION.IN.name(), ConsistsOf.NAME, Resource.NAME);
throw new InvalidQueryException(error); throw new InvalidQueryException(error);
} }
@ -890,12 +891,12 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
}
if(current!=null) {
current.activateOnCurrentThread();
} }
// if(current!=null) {
// current.activateOnCurrentThread();
// }
} }
} }

View File

@ -16,10 +16,10 @@ import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.types.reference.entities.FacetType; import org.gcube.informationsystem.types.reference.entities.FacetType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -55,14 +55,14 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
} }
@Override @Override
protected OVertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
return createVertex(); return createVertex();
} }
@Override @Override
protected OVertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException {
OVertex facet = getElement(); Vertex facet = getElement();
facet = (OVertex) updateProperties(oClass, facet, jsonNode, ignoreKeys, ignoreStartWithKeys); facet = (Vertex) updateProperties(documentType, facet, jsonNode, ignoreKeys, ignoreStartWithKeys);
return facet; return facet;
} }
@ -70,9 +70,9 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
protected void reallyRemoveFromContext() protected void reallyRemoveFromContext()
throws ContextException, ResourceRegistryException { throws ContextException, ResourceRegistryException {
if(entryPoint) { if(entryPoint) {
OEdge oEdge = getElement().getEdges(ODirection.IN).iterator().next(); Edge edge = getElement().getEdges(DIRECTION.IN).iterator().next();
consistsOfManagement = new ConsistsOfManagement(); consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElement(oEdge); consistsOfManagement.setElement(edge);
consistsOfManagement.setTargetEntityManagement(this); consistsOfManagement.setTargetEntityManagement(this);
// Not needed consistsOfManagement.setSourceSecurityContext(sourceSecurityContext); // Not needed consistsOfManagement.setSourceSecurityContext(sourceSecurityContext);
consistsOfManagement.setTargetSecurityContext(targetSecurityContext); consistsOfManagement.setTargetSecurityContext(targetSecurityContext);
@ -80,9 +80,9 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance()); affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance());
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next(); Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next();
resourceManagement = new ResourceManagement(); resourceManagement = new ResourceManagement();
resourceManagement.setElement(oVertex); resourceManagement.setElement(vertex);
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext); // Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.addToRelationManagements(consistsOfManagement); resourceManagement.addToRelationManagements(consistsOfManagement);
@ -93,15 +93,15 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
@Override @Override
protected void reallyDelete() throws FacetNotFoundException, ResourceRegistryException { protected void reallyDelete() throws FacetNotFoundException, ResourceRegistryException {
if(entryPoint) { if(entryPoint) {
OEdge oEdge = getElement().getEdges(ODirection.IN).iterator().next(); Edge edge = getElement().getEdges(DIRECTION.IN).iterator().next();
consistsOfManagement = new ConsistsOfManagement(); consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElement(oEdge); consistsOfManagement.setElement(edge);
consistsOfManagement.setTargetEntityManagement(this); consistsOfManagement.setTargetEntityManagement(this);
affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance()); affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance());
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next(); Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next();
resourceManagement = new ResourceManagement(); resourceManagement = new ResourceManagement();
resourceManagement.setElement(oVertex); resourceManagement.setElement(vertex);
resourceManagement.addToRelationManagements(consistsOfManagement); resourceManagement.addToRelationManagements(consistsOfManagement);
} }
@ -125,33 +125,33 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
// an update to the Facet only modify the Facet properties, no need to check the source resource // an update to the Facet only modify the Facet properties, no need to check the source resource
return; return;
} }
ODatabaseDocument targetSecurityContextODatabaseDocument = null; RemoteDatabase targetSecurityContextDatabase = null;
try { try {
if(resourceManagement==null) { if(resourceManagement==null) {
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next(); Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next();
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElement(oVertex); resourceManagement.setElement(vertex);
} }
switch (operation) { switch (operation) {
case CREATE: case DELETE: case CREATE: case DELETE:
resourceManagement.setWorkingContext(getWorkingContext()); resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setODatabaseDocument(oDatabaseDocument); resourceManagement.setDatabase(database);
break; break;
case ADD_TO_CONTEXT: case ADD_TO_CONTEXT:
resourceManagement.setSourceSecurityContext(sourceSecurityContext); resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext); resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER); targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument); resourceManagement.setDatabase(targetSecurityContextDatabase);
break; break;
case REMOVE_FROM_CONTEXT: case REMOVE_FROM_CONTEXT:
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext); // Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext); resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER); targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument); resourceManagement.setDatabase(targetSecurityContextDatabase );
break; break;
default: default:
@ -168,9 +168,9 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}catch (Exception e) { }catch (Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
}finally { }finally {
if(targetSecurityContextODatabaseDocument!=null) { if(targetSecurityContextDatabase !=null) {
targetSecurityContextODatabaseDocument.close(); targetSecurityContextDatabase.close();
oDatabaseDocument.activateOnCurrentThread(); // database.activateOnCurrentThread();
} }
} }
} }
@ -186,7 +186,7 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
throw new SchemaViolationException("You cannot create a stand alone Facet"); throw new SchemaViolationException("You cannot create a stand alone Facet");
} }
public OVertex internalCreate() throws AlreadyPresentException, ResourceRegistryException { public Vertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
if(entryPoint && operation == Operation.CREATE) { if(entryPoint && operation == Operation.CREATE) {
throw new SchemaViolationException("You cannot create a stand alone Facet"); throw new SchemaViolationException("You cannot create a stand alone Facet");
} }

View File

@ -32,15 +32,15 @@ import org.gcube.informationsystem.resourceregistry.instances.model.relations.Is
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement; import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.CachedType; import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.ResourceType; import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.properties.LinkedEntity; import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.metadata.schema.OClass; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.schema.DocumentType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -89,8 +89,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
* ConsistsOf.NAME); TODO Looks for a different query * ConsistsOf.NAME); TODO Looks for a different query
*/ */
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT); Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) { for(Edge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge); RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setReload(reload); relationManagement.setReload(reload);
@ -104,7 +104,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
errorMessage.append("SourceEntityManagement for "); errorMessage.append("SourceEntityManagement for ");
errorMessage.append(relationManagement.getClass().getSimpleName()); errorMessage.append(relationManagement.getClass().getSimpleName());
errorMessage.append(" is not the one expected. "); errorMessage.append(" is not the one expected. ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString()); throw new ResourceRegistryException(errorMessage.toString());
} }
@ -114,10 +114,10 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode consistsOf = relationManagement.serializeAsJsonNode(); JsonNode consistsOf = relationManagement.serializeAsJsonNode();
sourceResource = addConsistsOf(sourceResource, consistsOf); sourceResource = addConsistsOf(sourceResource, consistsOf);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
@ -146,7 +146,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
} }
@Override @Override
protected OVertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
createVertex(); createVertex();
@ -156,7 +156,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
for(JsonNode consistOfJsonNode : jsonNodeArray) { for(JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(); ConsistsOfManagement com = new ConsistsOfManagement();
com.setWorkingContext(getWorkingContext()); com.setWorkingContext(getWorkingContext());
com.setODatabaseDocument(oDatabaseDocument); com.setDatabase(database);
com.setJsonNode(consistOfJsonNode); com.setJsonNode(consistOfJsonNode);
com.setSourceEntityManagement(this); com.setSourceEntityManagement(this);
com.internalCreate(); com.internalCreate();
@ -170,7 +170,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
for(JsonNode relationJsonNode : jsonNodeArray) { for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(); IsRelatedToManagement irtm = new IsRelatedToManagement();
irtm.setWorkingContext(getWorkingContext()); irtm.setWorkingContext(getWorkingContext());
irtm.setODatabaseDocument(oDatabaseDocument); irtm.setDatabase(database);
irtm.setJsonNode(relationJsonNode); irtm.setJsonNode(relationJsonNode);
irtm.setSourceEntityManagement(this); irtm.setSourceEntityManagement(this);
irtm.internalCreate(); irtm.internalCreate();
@ -182,7 +182,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
} }
@Override @Override
protected OVertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
getElement(); getElement();
@ -192,7 +192,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
for(JsonNode relationJsonNode : jsonNodeArray) { for(JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(); ConsistsOfManagement com = new ConsistsOfManagement();
com.setWorkingContext(getWorkingContext()); com.setWorkingContext(getWorkingContext());
com.setODatabaseDocument(oDatabaseDocument); com.setDatabase(database);
com.setJsonNode(relationJsonNode); com.setJsonNode(relationJsonNode);
com.internalCreateOrUdate(); com.internalCreateOrUdate();
addToRelationManagement(com); addToRelationManagement(com);
@ -205,7 +205,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
for(JsonNode relationJsonNode : jsonNodeArray) { for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(); IsRelatedToManagement irtm = new IsRelatedToManagement();
irtm.setWorkingContext(getWorkingContext()); irtm.setWorkingContext(getWorkingContext());
irtm.setODatabaseDocument(oDatabaseDocument); irtm.setDatabase(database);
irtm.setJsonNode(relationJsonNode); irtm.setJsonNode(relationJsonNode);
irtm.internalUpdate(); irtm.internalUpdate();
addToRelationManagement(irtm); addToRelationManagement(irtm);
@ -221,25 +221,25 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
getElement(); getElement();
Iterable<OEdge> iterable = element.getEdges(ODirection.OUT); Iterable<Edge> iterable = element.getEdges(DIRECTION.OUT);
Iterator<OEdge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
while(iterator.hasNext()) { while(iterator.hasNext()) {
OEdge edge = iterator.next(); Edge edge = iterator.next();
OClass oClass = ElementManagementUtility.getOClass(edge); DocumentType documentType = ElementManagementUtility.getDocumentType(edge);
RelationManagement<?,?> relationManagement = null; RelationManagement<?,?> relationManagement = null;
if(oClass.isSubClassOf(IsRelatedTo.NAME)) { if(documentType.isSubTypeOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(); relationManagement = new IsRelatedToManagement();
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) { } else if(documentType.isSubTypeOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(); relationManagement = new ConsistsOfManagement();
} else { } else {
logger.warn("{} is not a {} nor a {}. {}", OrientDBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME, logger.warn("{} is not a {} nor a {}. {}", DBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME,
ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); ConsistsOf.NAME, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if(relationManagement != null) { if(relationManagement != null) {
relationManagement.setWorkingContext(getWorkingContext()); relationManagement.setWorkingContext(getWorkingContext());
relationManagement.setODatabaseDocument(oDatabaseDocument); relationManagement.setDatabase(database);
relationManagement.setElement(edge); relationManagement.setElement(edge);
relationManagement.internalDelete(); relationManagement.internalDelete();
affectedInstances.putAll(relationManagement.getAffectedInstances()); affectedInstances.putAll(relationManagement.getAffectedInstances());
@ -247,7 +247,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
} }
iterable = element.getEdges(ODirection.OUT); iterable = element.getEdges(DIRECTION.OUT);
iterator = iterable.iterator(); iterator = iterable.iterator();
while(iterator.hasNext()) { while(iterator.hasNext()) {
// in relations are affected because is the system which ensure this integrity // in relations are affected because is the system which ensure this integrity
@ -268,7 +268,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
return; return;
} }
targetSecurityContext.addElement(getElement(), oDatabaseDocument); targetSecurityContext.addElement(getElement(), database);
/* /*
* DO NOT UNCOMMENT * DO NOT UNCOMMENT
@ -278,11 +278,11 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
*/ */
if(honourPropagationConstraintsInContextSharing) { if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT); Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
int facetCounter = 0; int facetCounter = 0;
for(OEdge edge : edges) { for(Edge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge); RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun); relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing); relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
@ -315,21 +315,21 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
@Override @Override
public String all(boolean polymorphic) throws ResourceRegistryException { public String all(boolean polymorphic) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); database = getWorkingContext().getRemoteDatabase(PermissionMode.READER);
return reallyGetAll(polymorphic); return reallyGetAll(polymorphic);
} 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(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
}
if(current!=null) {
current.activateOnCurrentThread();
} }
// if(current!=null) {
// current.activateOnCurrentThread();
// }
} }
} }
@ -439,9 +439,9 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
Map<LinkedEntity, Integer> satisfiedConsistsOfFacet = new HashMap<>(); Map<LinkedEntity, Integer> satisfiedConsistsOfFacet = new HashMap<>();
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT); Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) { for(Edge edge : edges) {
String id = edge.getIdentity().toString(); String id = edge.getIdentity().toString();
RelationManagement<?,?> relationManagement = relationManagements.get(id); RelationManagement<?,?> relationManagement = relationManagements.get(id);
@ -452,7 +452,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
case ADD_TO_CONTEXT: case ADD_TO_CONTEXT:
if(relationManagement == null) { if(relationManagement == null) {
try { try {
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge); relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, database, edge);
relationManagement.setSourceSecurityContext(sourceSecurityContext); relationManagement.setSourceSecurityContext(sourceSecurityContext);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
}catch (AvailableInAnotherContextException e) { }catch (AvailableInAnotherContextException e) {
@ -475,7 +475,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
*/ */
continue; continue;
}else { }else {
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge); relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, database, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
break; break;
@ -483,7 +483,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
case CREATE: case UPDATE: case CREATE: case UPDATE:
if(relationManagement == null) { if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
/* /*
* Here the AvailableInAnotherContextException should not occur because the connection to the DB is with the * Here the AvailableInAnotherContextException should not occur because the connection to the DB is with the

View File

@ -22,10 +22,10 @@ import org.gcube.informationsystem.resourceregistry.instances.model.entities.Fac
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement; import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.types.reference.entities.FacetType; import org.gcube.informationsystem.types.reference.entities.FacetType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -64,20 +64,20 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
@Override @Override
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException { protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setODatabaseDocument(oDatabaseDocument); facetManagement.setDatabase(database);
facetManagement.setWorkingContext(getWorkingContext()); facetManagement.setWorkingContext(getWorkingContext());
return facetManagement; return facetManagement;
} }
@Override @Override
protected OEdge reallyCreate() throws ResourceRegistryException { protected Edge reallyCreate() throws ResourceRegistryException {
OEdge thisOEdge = super.reallyCreate(); Edge thisEdge = super.reallyCreate();
OVertex target = (OVertex) getTargetEntityManagement().getElement(); Vertex target = (Vertex) getTargetEntityManagement().getElement();
int count = 0; int count = 0;
Iterable<OEdge> iterable = target.getEdges(ODirection.IN); Iterable<Edge> iterable = target.getEdges(DIRECTION.IN);
Iterator<OEdge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
while(iterator.hasNext()) { while(iterator.hasNext()) {
iterator.next(); iterator.next();
++count; ++count;
@ -87,7 +87,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
throw new SchemaViolationException("It is not possible to create multiple " + ConsistsOf.NAME + " between the same " + Facet.NAME); throw new SchemaViolationException("It is not possible to create multiple " + ConsistsOf.NAME + " between the same " + Facet.NAME);
} }
return thisOEdge; return thisEdge;
} }
protected void checkResource() throws SchemaViolationException, ResourceRegistryException { protected void checkResource() throws SchemaViolationException, ResourceRegistryException {
@ -107,7 +107,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
return; return;
} }
ODatabaseDocument targetSecurityContextODatabaseDocument = null; RemoteDatabase targetSecurityContextDatabase = null;
try { try {
ResourceManagement resourceManagement = getSourceEntityManagement(); ResourceManagement resourceManagement = getSourceEntityManagement();
@ -124,8 +124,8 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
} }
resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext); resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER); targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument); resourceManagement.setDatabase(targetSecurityContextDatabase);
break; break;
default: default:
@ -140,9 +140,9 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
}catch (Exception e) { }catch (Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
}finally { }finally {
if(targetSecurityContextODatabaseDocument!=null) { if(targetSecurityContextDatabase!=null) {
targetSecurityContextODatabaseDocument.close(); targetSecurityContextDatabase.close();
oDatabaseDocument.activateOnCurrentThread(); // database.activateOnCurrentThread();
} }
} }
} }

View File

@ -19,7 +19,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isr
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement; import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType; import org.gcube.informationsystem.types.reference.entities.ResourceType;
@ -61,7 +61,7 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException { protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setWorkingContext(getWorkingContext()); resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setODatabaseDocument(oDatabaseDocument); resourceManagement.setDatabase(database);
return resourceManagement; return resourceManagement;
} }
@ -88,10 +88,10 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
} }
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }

View File

@ -40,20 +40,22 @@ import org.gcube.informationsystem.resourceregistry.instances.model.entities.Ent
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement; import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement; import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility; import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.PropagationConstraintOrient; import org.gcube.informationsystem.resourceregistry.utils.PropagationConstraintOrient;
import org.gcube.informationsystem.serialization.ElementMapper; import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType; import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.RelationType; import org.gcube.informationsystem.types.reference.relations.RelationType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.database.Document;
import com.orientechnologies.orient.core.metadata.schema.OType; import com.arcadedb.database.MutableDocument;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.Type;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -166,7 +168,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected boolean skipped; protected boolean skipped;
@Override @Override
public OEdge getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { public Edge getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try { try {
element = super.getElement(); element = super.getElement();
} catch(NotFoundException e) { } catch(NotFoundException e) {
@ -200,7 +202,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected Map<String,JsonNode> fullSerialize(Map<String,JsonNode> visitedSourceResources) protected Map<String,JsonNode> fullSerialize(Map<String,JsonNode> visitedSourceResources)
throws ResourceRegistryException { throws ResourceRegistryException {
OVertex source = getElement().getVertex(ODirection.OUT); Vertex source = getElement().getVertex(DIRECTION.OUT);
String id = source.getIdentity().toString(); String id = source.getIdentity().toString();
@ -209,7 +211,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
if(sourceResource == null) { if(sourceResource == null) {
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingContext(), resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, source); database, source);
if(this instanceof IsRelatedToManagement) { if(this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.createCompleteJsonNode(); sourceResource = resourceManagement.createCompleteJsonNode();
} else if(this instanceof ConsistsOfManagement) { } else if(this instanceof ConsistsOfManagement) {
@ -219,7 +221,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", this, String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(), IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} }
@ -231,7 +233,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", this, String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(), IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
@ -240,23 +242,23 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
return visitedSourceResources; return visitedSourceResources;
} }
protected PropagationConstraintOrient getPropagationConstraint(ODocument oDocument) protected PropagationConstraintOrient getPropagationConstraint(Document document)
throws ResourceRegistryException { throws ResourceRegistryException {
PropagationConstraintOrient propagationConstraintOrient = new PropagationConstraintOrient(); PropagationConstraintOrient propagationConstraintOrient = new PropagationConstraintOrient();
PropagationConstraint propagationConstraint = null; PropagationConstraint propagationConstraint = null;
if(oDocument == null) { if(document == null) {
propagationConstraint = defaultPropagationConstraint; propagationConstraint = defaultPropagationConstraint;
} else if(oDocument instanceof PropagationConstraintOrient) { } else if(document instanceof PropagationConstraintOrient) {
propagationConstraint = (PropagationConstraint) oDocument; propagationConstraint = (PropagationConstraint) document;
} else { } else {
try { try {
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, OrientDBUtility.toJsonString(oDocument)); propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, DBUtility.toJsonString(document));
} catch(Exception e) { } catch(Exception e) {
logger.warn("Unable to recreate {}. {}", PropagationConstraint.NAME, logger.warn("Unable to recreate {}. {}", PropagationConstraint.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
@ -303,13 +305,13 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} }
protected void checkPropagationConstraint() throws ResourceRegistryException { protected void checkPropagationConstraint() throws ResourceRegistryException {
Object object = getElement().getProperty(Relation.PROPAGATION_CONSTRAINT_PROPERTY); Object object = getElement().get(Relation.PROPAGATION_CONSTRAINT_PROPERTY);
PropagationConstraintOrient pc = getPropagationConstraint((ODocument) object); PropagationConstraintOrient pc = getPropagationConstraint((Document) object);
getElement().setProperty(Relation.PROPAGATION_CONSTRAINT_PROPERTY, pc, OType.EMBEDDED); ((MutableDocument) getElement()).set(Relation.PROPAGATION_CONSTRAINT_PROPERTY, pc, Type.EMBEDDED);
} }
@Override @Override
protected OEdge reallyCreate() throws ResourceRegistryException { protected Edge reallyCreate() throws ResourceRegistryException {
element = super.reallyCreate(); element = super.reallyCreate();
checkPropagationConstraint(); checkPropagationConstraint();
@ -323,7 +325,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setWorkingContext(getWorkingContext()); resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setODatabaseDocument(oDatabaseDocument); resourceManagement.setDatabase(database);
return resourceManagement; return resourceManagement;
} }
@ -368,20 +370,20 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} }
@Override @Override
protected OEdge reallyUpdate() throws ResourceRegistryException { protected Edge reallyUpdate() throws ResourceRegistryException {
logger.trace("Trying to update {} with UUID {}", typeName, uuid); logger.trace("Trying to update {} with UUID {}", typeName, uuid);
logger.trace("Trying to update {} : {}", typeName, jsonNode); logger.trace("Trying to update {} : {}", typeName, jsonNode);
OEdge edge = getElement(); Edge edge = getElement();
updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, 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 facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setWorkingContext(getWorkingContext()); facetManagement.setWorkingContext(getWorkingContext());
facetManagement.setODatabaseDocument(oDatabaseDocument); facetManagement.setDatabase(database);
facetManagement.setJsonNode(target); facetManagement.setJsonNode(target);
facetManagement.internalUpdate(); facetManagement.internalUpdate();
} }
@ -406,21 +408,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
AddConstraint addConstraint = AddConstraint.unpropagate; AddConstraint addConstraint = AddConstraint.unpropagate;
try { try {
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element, propagationConstraint = DBUtility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY); Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getAddConstraint() != null) { if(propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint(); addConstraint = propagationConstraint.getAddConstraint();
} else { } else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY, String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.ADD_PROPERTY, OrientDBUtility.getAsStringForException(element), PropagationConstraint.ADD_PROPERTY, DBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch(Exception e) { } catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing AddToContext. %s", String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element), Relation.PROPAGATION_CONSTRAINT_PROPERTY, DBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error); logger.warn(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
} }
@ -438,7 +440,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
targetEntityManagement.internalAddToContext(); targetEntityManagement.internalAddToContext();
affectedInstances.putAll(targetEntityManagement.getAffectedInstances()); affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
targetSecurityContext.addElement(getElement(), oDatabaseDocument); targetSecurityContext.addElement(getElement(), database);
/* /*
* DO NOT UNCOMMENT * DO NOT UNCOMMENT
@ -456,7 +458,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break; break;
} }
}else { }else {
targetSecurityContext.addElement(getElement(), oDatabaseDocument); targetSecurityContext.addElement(getElement(), database);
/* /*
* DO NOT UNCOMMENT * DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly()); * // affectedInstances.put(uuid, serializeSelfOnly());
@ -474,7 +476,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
reallyAddToContext(); reallyAddToContext();
if(!skipped && propagationConstraint.getAddConstraint()==PropagationConstraint.AddConstraint.propagate) { if(!skipped && propagationConstraint.getAddConstraint()==PropagationConstraint.AddConstraint.propagate) {
MetadataUtility.updateModifiedByAndLastUpdate(element); MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save(); // element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance()); affectedInstances.put(uuid, serializeAsAffectedInstance());
} }
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
@ -503,7 +505,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
targetEntityManagement.internalAddToContext(); targetEntityManagement.internalAddToContext();
affectedInstances.putAll(targetEntityManagement.getAffectedInstances()); affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
targetSecurityContext.addElement(getElement(), oDatabaseDocument); targetSecurityContext.addElement(getElement(), database);
affectedInstances.put(uuid, serializeAsAffectedInstance()); affectedInstances.put(uuid, serializeAsAffectedInstance());
} }
@ -512,10 +514,10 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException { public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID); String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName); logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
workingContext = ContextUtility.getAdminSecurityContext(); workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER); database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
setAsEntryPoint(); setAsEntryPoint();
sourceSecurityContext = ContextUtility.getCurrentSecurityContext(); sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
@ -526,26 +528,26 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
sanityCheck(); sanityCheck();
if(!dryRun) { if(!dryRun) {
oDatabaseDocument.commit(); database.commit();
}else { }else {
oDatabaseDocument.rollback(); database.rollback();
} }
logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName); logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid,
contextUUID, contextFullName, e); contextUUID, contextFullName, e);
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -561,21 +563,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element, propagationConstraint = DBUtility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY); Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getRemoveConstraint() != null) { if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
} else { } else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY, String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.REMOVE_PROPERTY, OrientDBUtility.getAsStringForException(element), PropagationConstraint.REMOVE_PROPERTY, DBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch(Exception e) { } catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s", String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element), Relation.PROPAGATION_CONSTRAINT_PROPERTY, DBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
@ -585,7 +587,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
* 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(), oDatabaseDocument); targetSecurityContext.removeElement(getElement(), database);
affectedInstances.put(uuid, serializeAsAffectedInstance()); affectedInstances.put(uuid, serializeAsAffectedInstance());
@ -604,17 +606,17 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break; break;
case cascadeWhenOrphan: case cascadeWhenOrphan:
OVertex target = (OVertex) targetEntityManagement.getElement(); Vertex target = (Vertex) targetEntityManagement.getElement();
Iterable<OEdge> iterable = target.getEdges(ODirection.IN); Iterable<Edge> iterable = target.getEdges(DIRECTION.IN);
Iterator<OEdge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
int count = 0; int count = 0;
OEdge edge = null; Edge edge = null;
while(iterator.hasNext()) { while(iterator.hasNext()) {
edge = (OEdge) iterator.next(); edge = (Edge) iterator.next();
OEdge thisOEdge = (OEdge) getElement(); Edge thisEdge = (Edge) getElement();
if(edge.compareTo(thisOEdge) != 0) { if(edge.compareTo(thisEdge) != 0) {
if(thisOEdge.getVertex(ODirection.OUT).compareTo(edge.getVertex(ODirection.OUT)) != 0) { if(thisEdge.getVertex(DIRECTION.OUT).compareTo(edge.getVertex(DIRECTION.OUT)) != 0) {
count++; count++;
break; break;
} }
@ -651,7 +653,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
setOperation(Operation.REMOVE_FROM_CONTEXT); setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext(); reallyRemoveFromContext();
MetadataUtility.updateModifiedByAndLastUpdate(element); MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save(); // element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance()); affectedInstances.put(uuid, serializeAsAffectedInstance());
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
@ -665,11 +667,11 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
public void removeFromContext(UUID contextUUID) public void removeFromContext(UUID contextUUID)
throws NotFoundException, ContextException, ResourceRegistryException { throws NotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID); logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
workingContext = ContextUtility.getAdminSecurityContext(); workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER); database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
oDatabaseDocument.begin(); database.begin();
setAsEntryPoint(); setAsEntryPoint();
@ -681,32 +683,32 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
sanityCheck(); sanityCheck();
if(!dryRun) { if(!dryRun) {
oDatabaseDocument.commit(); database.commit();
}else { }else {
oDatabaseDocument.rollback(); database.rollback();
} }
logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID); logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID);
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID); logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID, logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID,
e); e);
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.rollback(); database.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
@ -722,14 +724,14 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
DeleteConstraint deleteConstraint = DeleteConstraint.keep; DeleteConstraint deleteConstraint = DeleteConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, PropagationConstraint propagationConstraint = DBUtility.getPropertyDocument(PropagationConstraint.class,
element, Relation.PROPAGATION_CONSTRAINT_PROPERTY); element, Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getDeleteConstraint() != null) { if(propagationConstraint.getDeleteConstraint() != null) {
deleteConstraint = propagationConstraint.getDeleteConstraint(); deleteConstraint = propagationConstraint.getDeleteConstraint();
} else { } else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY, String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.DELETE_PROPERTY, OrientDBUtility.getAsStringForException(element), PropagationConstraint.DELETE_PROPERTY, DBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
deleteConstraint = DeleteConstraint.values()[propagationConstraint.getRemoveConstraint().ordinal()]; deleteConstraint = DeleteConstraint.values()[propagationConstraint.getRemoveConstraint().ordinal()];
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
@ -737,7 +739,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} catch(Exception e) { } catch(Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT_PROPERTY, logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
OrientDBUtility.getAsStringForException(element), deleteConstraint, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.getAsStringForException(element), deleteConstraint, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
// pre-loading target entity because after deleting the relation we will not be able to get it // pre-loading target entity because after deleting the relation we will not be able to get it
@ -755,9 +757,9 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break; break;
case cascadeWhenOrphan: case cascadeWhenOrphan:
OVertex target = t.getElement(); Vertex target = t.getElement();
Iterable<OEdge> iterable = target.getEdges(ODirection.IN); Iterable<Edge> iterable = target.getEdges(DIRECTION.IN);
Iterator<OEdge> iterator = iterable.iterator(); Iterator<Edge> 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, deleteConstraint); target, deleteConstraint);
@ -777,19 +779,19 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} }
protected Collection<JsonNode> serializeEdges(Iterable<ODocument> edges, boolean postFilterPolymorphic) protected Collection<JsonNode> serializeEdges(Iterable<Document> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException { throws ResourceRegistryException {
// Map<String,JsonNode> visitedSourceResources = new HashMap<>(); // Map<String,JsonNode> visitedSourceResources = new HashMap<>();
List<JsonNode> serilizedEdges = new ArrayList<>(); List<JsonNode> serilizedEdges = new ArrayList<>();
for(ODocument d : edges) { for(Document d : edges) {
OEdge edge = (OEdge) d; Edge edge = (Edge) d;
if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) { if(postFilterPolymorphic && getDocumentType().isSubTypeOf(typeName)) {
continue; continue;
} }
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
oDatabaseDocument, edge); database, edge);
// visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); // visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
serilizedEdges.add(relationManagement.serializeAsJsonNode()); serilizedEdges.add(relationManagement.serializeAsJsonNode());
} }
@ -808,7 +810,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
@Override @Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
Iterable<ODocument> edges = oDatabaseDocument.browseClass(typeName, polymorphic); Iterable<Document> edges = database.browseClass(typeName, polymorphic);
Collection<JsonNode> collection = serializeEdges(edges, false); Collection<JsonNode> collection = serializeEdges(edges, false);
return serializeJsonNodeCollectionAsString(collection); return serializeJsonNodeCollectionAsString(collection);
} }

View File

@ -10,14 +10,14 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -28,37 +28,37 @@ public class QueryImpl implements Query {
@Override @Override
public String query(String query, boolean raw) throws InvalidQueryException { public String query(String query, boolean raw) throws InvalidQueryException {
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase oDatabaseDocument = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER); oDatabaseDocument = securityContext.getRemoteDatabase(PermissionMode.READER);
oDatabaseDocument.begin(); oDatabaseDocument.begin();
logger.debug("Going to execute query '{} limit {}'", query); logger.debug("Going to execute query '{} limit {}'", query);
OResultSet resultSet = oDatabaseDocument.query(query); ResultSet resultSet = oDatabaseDocument.command("sql", query);
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
while(resultSet.hasNext()) { while(resultSet.hasNext()) {
OResult oResult = resultSet.next(); Result result = resultSet.next();
try { try {
JsonNode jsonNode = null; JsonNode jsonNode = null;
if(raw) { if(raw) {
if(oResult.isElement()) { if(result.isElement()) {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); Document element = ElementManagementUtility.getElementFromOptional(result.getElement());
jsonNode = OrientDBUtility.toJsonNode(element); jsonNode = DBUtility.toJsonNode(element);
}else { }else {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
jsonNode = mapper.readTree(OrientDBUtility.toJsonString(oResult)); jsonNode = mapper.readTree(DBUtility.toJsonString(result));
} }
} else { } else {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); Document element = ElementManagementUtility.getElementFromOptional(result.getElement());
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument, ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
element); element);
erManagement.setAsEntryPoint(); erManagement.setAsEntryPoint();
@ -68,7 +68,7 @@ public class QueryImpl implements Query {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
OrientDBUtility.toJsonString(oResult), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); DBUtility.toJsonString(result), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
@ -80,9 +80,9 @@ public class QueryImpl implements Query {
if(oDatabaseDocument != null) { if(oDatabaseDocument != null) {
oDatabaseDocument.close(); oDatabaseDocument.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }

View File

@ -25,15 +25,15 @@ import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo; import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
import org.gcube.informationsystem.resourceregistry.types.CachedType; import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.utils.TypeUtility; import org.gcube.informationsystem.utils.TypeUtility;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -47,7 +47,7 @@ public class JsonQuery {
protected ObjectMapper objectMapper; protected ObjectMapper objectMapper;
protected JsonNode jsonQuery; protected JsonNode jsonQuery;
protected JsonQueryERElement entryPoint; protected JsonQueryERElement entryPoint;
protected ODatabaseDocument oDatabaseDocument; protected RemoteDatabase database;
public JsonQuery() { public JsonQuery() {
this.objectMapper = new ObjectMapper(); this.objectMapper = new ObjectMapper();
@ -106,13 +106,13 @@ public class JsonQuery {
} }
public String query() throws InvalidQueryException, ResourceRegistryException { public String query() throws InvalidQueryException, ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
oDatabaseDocument = null; database = null;
try { try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER); database = securityContext.getRemoteDatabase(PermissionMode.READER);
oDatabaseDocument.begin(); database.begin();
StringBuffer stringBuffer = createQuery(); StringBuffer stringBuffer = createQuery();
stringBuffer.append(" limit :limit"); stringBuffer.append(" limit :limit");
@ -123,17 +123,17 @@ public class JsonQuery {
String query = stringBuffer.toString(); String query = stringBuffer.toString();
logger.trace("Going to execute the following query:\n{} \n from the JSONQuery\n{}", query, objectMapper.writeValueAsString(jsonQuery)); logger.trace("Going to execute the following query:\n{} \n from the JSONQuery\n{}", query, objectMapper.writeValueAsString(jsonQuery));
OResultSet resultSet = oDatabaseDocument.query(query, map); ResultSet resultSet = database.command("sql", query, map);
ArrayNode arrayNode = objectMapper.createArrayNode(); ArrayNode arrayNode = objectMapper.createArrayNode();
while(resultSet.hasNext()) { while(resultSet.hasNext()) {
OResult oResult = resultSet.next(); Result oResult = resultSet.next();
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); Document element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
try { try {
JsonNode jsonNodeResult = null; JsonNode jsonNodeResult = null;
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument, ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, database,
element); element);
// To support polymorphism we do not include ="TypeName" in query. So we need post processing filtering of results // To support polymorphism we do not include ="TypeName" in query. So we need post processing filtering of results
@ -159,7 +159,7 @@ public class JsonQuery {
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
element.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); element.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
@ -168,12 +168,12 @@ public class JsonQuery {
} catch(Exception e) { } catch(Exception e) {
throw new InvalidQueryException(e.getMessage()); throw new InvalidQueryException(e.getMessage());
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
}
if(current!=null) {
current.activateOnCurrentThread();
} }
// if(current!=null) {
// current.activateOnCurrentThread();
// }
} }
} }

View File

@ -1,7 +1,5 @@
package org.gcube.informationsystem.resourceregistry.queries.templates; package org.gcube.informationsystem.resourceregistry.queries.templates;
import java.util.HashMap;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException; import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode; import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper; import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
@ -19,17 +17,17 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery; import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.serialization.ElementMapper; import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -46,14 +44,14 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
this.typeName = QueryTemplate.NAME; this.typeName = QueryTemplate.NAME;
} }
public QueryTemplateManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException { public QueryTemplateManagement(RemoteDatabase database) throws ResourceRegistryException {
this(); this();
this.oDatabaseDocument = oDatabaseDocument; this.database = database;
getWorkingContext(); getWorkingContext();
} }
protected void checkERMatch() throws ResourceRegistryException { protected void checkERMatch() throws ResourceRegistryException {
getOClass(); getDocumentType();
} }
protected void checkNameMatch() throws ResourceRegistryException { protected void checkNameMatch() throws ResourceRegistryException {
@ -85,7 +83,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
name = jsonNode.get(QueryTemplate.NAME_PROPERTY).asText(); name = jsonNode.get(QueryTemplate.NAME_PROPERTY).asText();
} }
} else { } else {
name = element.getProperty(QueryTemplate.NAME_PROPERTY); name = element.getString(QueryTemplate.NAME_PROPERTY);
} }
} }
return name; return name;
@ -104,7 +102,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
try { try {
JsonNode queryTemplate = serializeSelfAsJsonNode(); JsonNode queryTemplate = serializeSelfAsJsonNode();
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
String templateString = element.getProperty(QueryTemplate.TEMPLATE_PROPERTY); String templateString = element.getString(QueryTemplate.TEMPLATE_PROPERTY);
JsonNode templateJsonNode = objectMapper.readTree(templateString); JsonNode templateJsonNode = objectMapper.readTree(templateString);
((ObjectNode) queryTemplate).replace(QueryTemplate.TEMPLATE_PROPERTY, templateJsonNode); ((ObjectNode) queryTemplate).replace(QueryTemplate.TEMPLATE_PROPERTY, templateJsonNode);
return queryTemplate; return queryTemplate;
@ -141,7 +139,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
logger.trace("Checking if {} -> {}", errorMessage, select); logger.trace("Checking if {} -> {}", errorMessage, select);
OResultSet resultSet = oDatabaseDocument.command(select.toString(), new HashMap<>()); ResultSet resultSet = database.command("sql", select.toString());
if (resultSet != null) { if (resultSet != null) {
try { try {
@ -170,10 +168,10 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
} }
@Override @Override
public OVertex retrieveElement() throws NotFoundException, ResourceRegistryException { public Vertex retrieveElement() throws NotFoundException, ResourceRegistryException {
try { try {
StringBuffer select = getSelectQuery(); StringBuffer select = getSelectQuery();
OResultSet resultSet = oDatabaseDocument.query(select.toString(), new HashMap<>()); ResultSet resultSet = database.query("sql", select.toString());
if(resultSet == null || !resultSet.hasNext()) { if(resultSet == null || !resultSet.hasNext()) {
if(resultSet!=null) { if(resultSet!=null) {
@ -182,10 +180,10 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
throw new NotFoundException("Error retrieving " + QueryTemplate.NAME + " with name " + getName()); throw new NotFoundException("Error retrieving " + QueryTemplate.NAME + " with name " + getName());
} }
OResult oResult = resultSet.next(); Result result = resultSet.next();
OVertex queryTemplate = ElementManagementUtility.getElementFromOptional(oResult.getVertex()); Vertex queryTemplate = ElementManagementUtility.getElementFromOptional(result.getVertex());
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, OrientDBUtility.getAsStringForLogging(queryTemplate)); logger.trace("{} representing vertex is {}", QueryTemplate.NAME, DBUtility.getAsStringForLogging(queryTemplate));
if(resultSet.hasNext()) { if(resultSet.hasNext()) {
resultSet.close(); resultSet.close();
@ -204,7 +202,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
} }
@Override @Override
protected OVertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException { protected Vertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException {
try { try {
checkIfNameAlreadyExists(); checkIfNameAlreadyExists();
tryTemplate(); tryTemplate();
@ -213,23 +211,23 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e); accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
} }
} }
@Override @Override
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
try { try {
tryTemplate(); tryTemplate();
OVertex queryTemplate = getElement(); Vertex queryTemplate = getElement();
queryTemplate = (OVertex) updateProperties(oClass, queryTemplate, jsonNode, ignoreKeys, ignoreStartWithKeys); queryTemplate = (Vertex) updateProperties(documentType, queryTemplate, jsonNode, ignoreKeys, ignoreStartWithKeys);
return getElement(); return getElement();
} catch(ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e) { } catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e); accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
} }
@ -255,16 +253,16 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
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<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic); Iterable<Document> iterable = database.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) { for (Document vertex : iterable) {
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement(); QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setElement((OVertex) vertex); queryTemplateManagement.setElement((Vertex) vertex);
try { try {
JsonNode jsonObject = queryTemplateManagement.serializeAsJsonNode(); JsonNode jsonObject = queryTemplateManagement.serializeAsJsonNode();
arrayNode.add(jsonObject); arrayNode.add(jsonObject);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
try { try {

View File

@ -45,7 +45,7 @@ import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.types.TypeMapper; import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type; import org.gcube.informationsystem.types.reference.Type;
import com.orientechnologies.orient.core.record.ODirection; import com.arcadedb.graph.Vertex.DIRECTION;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -372,7 +372,7 @@ public class Access extends BaseRest {
if(erManagement instanceof ResourceManagement) { if(erManagement instanceof ResourceManagement) {
UUID refereceUUID = null; UUID refereceUUID = null;
ODirection directionEnum = ODirection.OUT; DIRECTION directionEnum = DIRECTION.OUT;
Map<String,String> constraint = new HashMap<>(); Map<String,String> constraint = new HashMap<>();
@ -414,9 +414,9 @@ public class Access extends BaseRest {
} }
} }
try { try {
directionEnum = ODirection.valueOf(direction.toUpperCase()); directionEnum = DIRECTION.valueOf(direction.toUpperCase());
} catch(Exception e) { } catch(Exception e) {
String error = String.format("%s is not a valid. Allowed values are %s", direction, ODirection.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

@ -21,11 +21,8 @@ import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
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.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.metadata.OMetadata; import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -46,7 +43,7 @@ public class CachedType<T extends Type> {
protected final String typeName; protected final String typeName;
protected OClass oClass; protected DocumentType documentType;
protected AccessType accessType; protected AccessType accessType;
@ -62,21 +59,21 @@ public class CachedType<T extends Type> {
this.typeName = typeName; this.typeName = typeName;
} }
private OClass retrieveOClass() throws SchemaException, SchemaNotFoundException, ResourceRegistryException { private DocumentType retrieveDocumentType() throws SchemaException, SchemaNotFoundException, ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
logger.debug("GettingType {} schema", typeName); logger.debug("GettingType {} schema", typeName);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata(); OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
try { try {
OClass oClass = oSchema.getClass(typeName); DocumentType documentType = oSchema.getClass(typeName);
if(oClass == null) { if(documentType == null) {
throw new SchemaNotFoundException(typeName + " was not registered"); throw new SchemaNotFoundException(typeName + " was not registered");
} }
return oClass; return documentType;
} catch(SchemaNotFoundException snfe) { } catch(SchemaNotFoundException snfe) {
throw snfe; throw snfe;
} catch(Exception e) { } catch(Exception e) {
@ -87,29 +84,29 @@ public class CachedType<T extends Type> {
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
if(current!=null) { // if(current!=null) {
current.activateOnCurrentThread(); // current.activateOnCurrentThread();
} // }
} }
} }
public synchronized void setOClass(OClass oClass) throws SchemaNotFoundException, SchemaException, ResourceRegistryException { public synchronized void setDocumentType(DocumentType documentType) throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(this.oClass==null) { if(this.documentType==null) {
this.oClass = oClass; this.documentType = documentType;
} }
} }
private AccessType getAccessTypeFromOClass(OClass oClass) throws ResourceRegistryException { private AccessType getAccessTypeFromDocumentType(DocumentType documentType) throws ResourceRegistryException {
AccessType[] accessTypes = AccessType.values(); AccessType[] accessTypes = AccessType.values();
for(int i=accessTypes.length-1; i>=0; i--) { for(int i=accessTypes.length-1; i>=0; i--) {
AccessType accessType = accessTypes[i]; AccessType accessType = accessTypes[i];
if(oClass.isSubClassOf(accessType.getName())) { if(documentType.isSubTypeOf(accessType.getName())) {
return accessType; return accessType;
} }
} }
@ -123,14 +120,14 @@ public class CachedType<T extends Type> {
// Instead of using getAllSuperClasses() we get just the first level superclasses and so on. // Instead of using getAllSuperClasses() we get just the first level superclasses and so on.
// This allow to have an order list where the first superclass is a a first level superclass. // This allow to have an order list where the first superclass is a a first level superclass.
List<OClass> superClasses = internalGetOClass().getSuperClasses(); List<DocumentType> superClasses = internalGetDocumentType().getSuperTypes();
while(superClasses.size()>0) { while(superClasses.size()>0) {
List<OClass> toBeAnalysed = new ArrayList<>(superClasses); List<DocumentType> toBeAnalysed = new ArrayList<>(superClasses);
superClasses = new ArrayList<>(); superClasses = new ArrayList<>();
for(OClass oSuperClass : toBeAnalysed) { for(DocumentType oSuperClass : toBeAnalysed) {
String name = oSuperClass.getName(); String name = oSuperClass.getName();
CachedType<?> cachedType = typesCache.getCachedType(name); CachedType<?> cachedType = typesCache.getCachedType(name);
cachedType.setOClass(oSuperClass); cachedType.setDocumentType(oSuperClass);
if(name.compareTo(DatabaseEnvironment.VERTEX_CLASS_NAME) == 0 || name.compareTo(DatabaseEnvironment.EDGE_CLASS_NAME) == 0 if(name.compareTo(DatabaseEnvironment.VERTEX_CLASS_NAME) == 0 || name.compareTo(DatabaseEnvironment.EDGE_CLASS_NAME) == 0
|| name.compareTo(OSecurity.RESTRICTED_CLASSNAME) == 0) { || name.compareTo(OSecurity.RESTRICTED_CLASSNAME) == 0) {
continue; continue;
@ -140,7 +137,7 @@ public class CachedType<T extends Type> {
continue; continue;
} }
allSuperClasses.add(allSuperClasses.size(), name); allSuperClasses.add(allSuperClasses.size(), name);
superClasses.addAll(oSuperClass.getSuperClasses()); superClasses.addAll(oSuperClass.getSuperTypes());
} }
} }
return allSuperClasses; return allSuperClasses;
@ -150,32 +147,32 @@ public class CachedType<T extends Type> {
TypesCache typesCache = TypesCache.getInstance(); TypesCache typesCache = TypesCache.getInstance();
List<String> allSubClasses = new ArrayList<>(); List<String> allSubClasses = new ArrayList<>();
Collection<OClass> subclasses = internalGetOClass().getSubclasses(); Collection<DocumentType> subclasses = internalGetDocumentType().getSubTypes();
while(subclasses.size()>0) { while(subclasses.size()>0) {
List<OClass> toBeAnalysed = new ArrayList<>(subclasses); List<DocumentType> toBeAnalysed = new ArrayList<>(subclasses);
subclasses = new ArrayList<>(); subclasses = new ArrayList<>();
for(OClass oSubClass : toBeAnalysed) { for(DocumentType oSubClass : toBeAnalysed) {
String name = oSubClass.getName(); String name = oSubClass.getName();
CachedType<?> cachedType = typesCache.getCachedType(name); CachedType<?> cachedType = typesCache.getCachedType(name);
cachedType.setOClass(oSubClass); cachedType.setDocumentType(oSubClass);
allSubClasses.add(allSubClasses.size(), name); allSubClasses.add(allSubClasses.size(), name);
subclasses.addAll(oSubClass.getSubclasses()); subclasses.addAll(oSubClass.getSubTypes());
} }
} }
return allSubClasses; return allSubClasses;
} }
private OClass internalGetOClass() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { private DocumentType internalGetDocumentType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(oClass==null) { if(documentType==null) {
oClass = retrieveOClass(); documentType = retrieveDocumentType();
} }
return oClass; return documentType;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private T internalGetType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { private T internalGetType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(type==null) { if(type==null) {
ElementManagement<?,?> erManagement = TypeManagement.getTypeManagement(internalGetOClass()); ElementManagement<?,?> erManagement = TypeManagement.getTypeManagement(internalGetDocumentType());
String typeString = erManagement.read(); String typeString = erManagement.read();
try { try {
type = (T) TypeMapper.deserializeTypeDefinition(typeString); type = (T) TypeMapper.deserializeTypeDefinition(typeString);
@ -191,7 +188,7 @@ public class CachedType<T extends Type> {
if(type!=null) { if(type!=null) {
accessType = type.getAccessType(); accessType = type.getAccessType();
}else { }else {
accessType = getAccessTypeFromOClass(internalGetOClass()); accessType = getAccessTypeFromDocumentType(internalGetDocumentType());
} }
} }
return accessType; return accessType;
@ -212,8 +209,8 @@ public class CachedType<T extends Type> {
} }
public synchronized OClass getOClass() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { public synchronized DocumentType getDocumentType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
return internalGetOClass(); return internalGetDocumentType();
} }
public synchronized T getType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { public synchronized T getType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {

View File

@ -0,0 +1,57 @@
package org.gcube.informationsystem.resourceregistry.types;
import java.util.HashMap;
import java.util.Map;
import org.gcube.informationsystem.types.PropertyTypeName.BaseType;
import com.arcadedb.schema.Type;
/**
* @author Luca Frosini (ISTI - CNR)
*
* Create a mapping between OrientDB {@link Type}
* https://orientdb.gitbooks.io/orientdb-manual/content/orientdb.wiki/Types.html
* and {@link BaseType}
*/
public class DBTypeMapping {
protected static final Map<BaseType,Type> IS_BASE_TYPE_TO_DB_TYPE;
protected static final Map<Type,BaseType> DB_TYPE_TO_IS_BASE_TYPE;
static {
IS_BASE_TYPE_TO_DB_TYPE = new HashMap<>();
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.BOOLEAN, Type.BOOLEAN);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.INTEGER, Type.INTEGER);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.SHORT, Type.SHORT);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.LONG, Type.LONG);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.FLOAT, Type.FLOAT);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.DOUBLE, Type.DOUBLE);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.DATE, Type.DATETIME);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.STRING, Type.STRING);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.BINARY, Type.BINARY);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.BYTE, Type.BYTE);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.PROPERTY, Type.EMBEDDED);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.LIST, Type.LIST);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.SET, Type.LIST);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.MAP, Type.MAP);
DB_TYPE_TO_IS_BASE_TYPE = new HashMap<>();
for(BaseType baseType : IS_BASE_TYPE_TO_DB_TYPE.keySet()) {
DB_TYPE_TO_IS_BASE_TYPE.put(IS_BASE_TYPE_TO_DB_TYPE.get(baseType), baseType);
}
}
public static Type getDBType(final BaseType baseType) {
return IS_BASE_TYPE_TO_DB_TYPE.get(baseType);
}
public static BaseType getISBaseType(final Type oType) {
return DB_TYPE_TO_IS_BASE_TYPE.get(oType);
}
}

View File

@ -1,57 +0,0 @@
package org.gcube.informationsystem.resourceregistry.types;
import java.util.HashMap;
import java.util.Map;
import org.gcube.informationsystem.types.PropertyTypeName.BaseType;
import com.orientechnologies.orient.core.metadata.schema.OType;
/**
* @author Luca Frosini (ISTI - CNR)
*
* Create a mapping between OrientDB {@link OType}
* https://orientdb.gitbooks.io/orientdb-manual/content/orientdb.wiki/Types.html
* and {@link BaseType}
*/
public class OrientDBTypeMapping {
protected static final Map<BaseType,OType> BASE_TYPE_TO_OTYPE;
protected static final Map<OType,BaseType> OTYPE_TO_BASE_TYPE;
static {
BASE_TYPE_TO_OTYPE = new HashMap<>();
BASE_TYPE_TO_OTYPE.put(BaseType.BOOLEAN, OType.BOOLEAN);
BASE_TYPE_TO_OTYPE.put(BaseType.INTEGER, OType.INTEGER);
BASE_TYPE_TO_OTYPE.put(BaseType.SHORT, OType.SHORT);
BASE_TYPE_TO_OTYPE.put(BaseType.LONG, OType.LONG);
BASE_TYPE_TO_OTYPE.put(BaseType.FLOAT, OType.FLOAT);
BASE_TYPE_TO_OTYPE.put(BaseType.DOUBLE, OType.DOUBLE);
BASE_TYPE_TO_OTYPE.put(BaseType.DATE, OType.DATETIME);
BASE_TYPE_TO_OTYPE.put(BaseType.STRING, OType.STRING);
BASE_TYPE_TO_OTYPE.put(BaseType.BINARY, OType.BINARY);
BASE_TYPE_TO_OTYPE.put(BaseType.BYTE, OType.BYTE);
BASE_TYPE_TO_OTYPE.put(BaseType.PROPERTY, OType.EMBEDDED);
BASE_TYPE_TO_OTYPE.put(BaseType.LIST, OType.EMBEDDEDLIST);
BASE_TYPE_TO_OTYPE.put(BaseType.SET, OType.EMBEDDEDSET);
BASE_TYPE_TO_OTYPE.put(BaseType.MAP, OType.EMBEDDEDMAP);
OTYPE_TO_BASE_TYPE = new HashMap<>();
for(BaseType baseType : BASE_TYPE_TO_OTYPE.keySet()) {
OTYPE_TO_BASE_TYPE.put(BASE_TYPE_TO_OTYPE.get(baseType), baseType);
}
}
public static OType getOTypeByBaseType(final BaseType baseType) {
return BASE_TYPE_TO_OTYPE.get(baseType);
}
public static BaseType getBaseTypeByOType(final OType oType) {
return OTYPE_TO_BASE_TYPE.get(oType);
}
}

View File

@ -56,14 +56,9 @@ import org.gcube.informationsystem.types.reference.relations.RelationType;
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.arcadedb.database.MutableDocument;
import com.orientechnologies.orient.core.exception.OSchemaException; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.metadata.OMetadata; import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.metadata.schema.OClass;
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.record.OElement;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -111,8 +106,8 @@ public class TypeManagement {
} }
protected OClass getOClass(OSchema oSchema, String typeName) throws SchemaException { protected DocumentType getOClass(RemoteDatabase database, String typeName) throws SchemaException {
return oSchema.getClass(typeName); return database.getClass(typeName);
} }
public String getTypeName() { public String getTypeName() {
@ -134,7 +129,7 @@ public class TypeManagement {
} }
private static ElementManagement<?,?> getTypeManagement(AccessType accessType, String name) { private static ElementManagement<?,?> getTypeManagement(AccessType accessType, String name) {
ElementManagement<? extends OElement,?> erManagement = null; ElementManagement<? extends MutableDocument,?> erManagement = null;
switch(accessType) { switch(accessType) {
case PROPERTY: case PROPERTY:
@ -164,23 +159,23 @@ public class TypeManagement {
return erManagement; return erManagement;
} }
public static ElementManagement<?,?> getTypeManagement(OClass oClass) { public static ElementManagement<?,?> getTypeManagement(DocumentType documentType) {
ElementManagement<?,?> erManagement = null; ElementManagement<?,?> erManagement = null;
if(oClass.isSubClassOf(Property.NAME)) { if(documentType.isSubTypeOf(Property.NAME)) {
erManagement = new PropertyTypeDefinitionManagement(); erManagement = new PropertyTypeDefinitionManagement();
((PropertyTypeDefinitionManagement) erManagement).setName(oClass.getName()); ((PropertyTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(oClass.isSubClassOf(Resource.NAME)) { } else if(documentType.isSubTypeOf(Resource.NAME)) {
erManagement = new ResourceTypeDefinitionManagement(); erManagement = new ResourceTypeDefinitionManagement();
((ResourceTypeDefinitionManagement) erManagement).setName(oClass.getName()); ((ResourceTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(oClass.isSubClassOf(Facet.NAME)) { } else if(documentType.isSubTypeOf(Facet.NAME)) {
erManagement = new FacetTypeDefinitionManagement(); erManagement = new FacetTypeDefinitionManagement();
((FacetTypeDefinitionManagement) erManagement).setName(oClass.getName()); ((FacetTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(oClass.isSubClassOf(IsRelatedTo.NAME)) { } else if(documentType.isSubTypeOf(IsRelatedTo.NAME)) {
erManagement = new IsRelatedToTypeDefinitionManagement(); erManagement = new IsRelatedToTypeDefinitionManagement();
((IsRelatedToTypeDefinitionManagement) erManagement).setName(oClass.getName()); ((IsRelatedToTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) { } else if(documentType.isSubTypeOf(ConsistsOf.NAME)) {
erManagement = new ConsistsOfTypeDefinitionManagement(); erManagement = new ConsistsOfTypeDefinitionManagement();
((ConsistsOfTypeDefinitionManagement) erManagement).setName(oClass.getName()); ((ConsistsOfTypeDefinitionManagement) erManagement).setName(documentType.getName());
} }
return erManagement; return erManagement;
} }
@ -197,9 +192,9 @@ public class TypeManagement {
} }
} }
private String getTypeAsString(OClass oClass) throws SchemaException { private String getTypeAsString(DocumentType documentType) throws SchemaException {
try { try {
ElementManagement<?,?> erManagement = getTypeManagement(oClass); ElementManagement<?,?> erManagement = getTypeManagement(documentType);
return getTypeAsString(erManagement); return getTypeAsString(erManagement);
} catch(Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
@ -215,16 +210,16 @@ public class TypeManagement {
} }
} }
private Type getType(OClass oClass) throws SchemaException { private Type getType(DocumentType documentType) throws SchemaException {
try { try {
String typeString = getTypeAsString(oClass); String typeString = getTypeAsString(documentType);
return TypeMapper.deserializeTypeDefinition(typeString); return TypeMapper.deserializeTypeDefinition(typeString);
} catch(Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} }
} }
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument, protected List<DocumentType> getSuperTypesAndCheckCompliancy(RemoteDatabase database,
Type type, String baseType) throws SchemaException, SchemaNotFoundException { Type type, String baseType) throws SchemaException, SchemaNotFoundException {
Set<String> superClasses = type.getTypeSuperTypes(); Set<String> superClasses = type.getTypeSuperTypes();
@ -236,27 +231,27 @@ public class TypeManagement {
} }
} }
OMetadata oMetadata = oDatabaseDocument.getMetadata(); OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
List<OClass> oSuperclasses = new ArrayList<>(); List<DocumentType> superTypes = new ArrayList<>();
for(String superClass : superClasses) { for(String superClass : superClasses) {
OClass oSuperClass = getOClass(oSchema, superClass); DocumentType superType = getOClass(oSchema, superClass);
if(oSuperClass == null) { if(superType == null) {
throw new SchemaNotFoundException("Superclass " + superClass + " does not exists"); throw new SchemaNotFoundException("Superclass " + superClass + " does not exists");
} }
if(baseType != null) { if(baseType != null) {
if(type.getName().compareTo(baseType) != 0) { if(type.getName().compareTo(baseType) != 0) {
if(!oSuperClass.isSubClassOf(baseType)) { if(!superType.isSubTypeOf(baseType)) {
throw new RuntimeException(superClass + " is not a subsclass of " + baseType throw new RuntimeException(superClass + " is not a subsclass of " + baseType
+ ". Each Superclass MUST be a subclass of " + baseType); + ". Each Superclass MUST be a subclass of " + baseType);
} }
} }
} }
oSuperclasses.add(oSuperClass); superTypes.add(superType);
} }
return oSuperclasses; return superTypes;
} }
private static Set<String> baseElementTypes; private static Set<String> baseElementTypes;
@ -282,7 +277,7 @@ public class TypeManagement {
protected void registerTypeSchema() protected void registerTypeSchema()
throws SchemaAlreadyPresentException, SchemaException { throws SchemaAlreadyPresentException, SchemaException {
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
if(typeName.compareTo(type.getName()) != 0) { if(typeName.compareTo(type.getName()) != 0) {
@ -293,23 +288,23 @@ public class TypeManagement {
} }
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
OMetadata oMetadata = oDatabaseDocument.getMetadata(); OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass oClass = null; DocumentType documentType = null;
AccessType accessType = type.getAccessType(); AccessType accessType = type.getAccessType();
Class<? extends Element> typeClass = accessType.getTypeClass(); Class<? extends Element> typeClass = accessType.getTypeClass();
String typeName = type.getName(); String typeName = type.getName();
if(EntityElement.class.isAssignableFrom(typeClass)) { if(EntityElement.class.isAssignableFrom(typeClass)) {
oClass = oDatabaseDocument.createVertexClass(typeName); documentType = database.createVertexClass(typeName);
} else if(RelationElement.class.isAssignableFrom(typeClass)) { } else if(RelationElement.class.isAssignableFrom(typeClass)) {
oClass = oDatabaseDocument.createEdgeClass(typeName); documentType = database.createEdgeClass(typeName);
} else if(PropertyElement.class.isAssignableFrom(typeClass)) { } else if(PropertyElement.class.isAssignableFrom(typeClass)) {
oClass = oSchema.createClass(typeName); documentType = oSchema.createClass(typeName);
} else { } else {
String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.", String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.",
Entity.NAME, Relation.NAME, Property.NAME); Entity.NAME, Relation.NAME, Property.NAME);
@ -321,7 +316,7 @@ public class TypeManagement {
String description = type.getDescription(); String description = type.getDescription();
if(description != null && description.compareTo("") != 0) { if(description != null && description.compareTo("") != 0) {
try { try {
oClass.setDescription(description); documentType.setDescription(description);
} catch(Exception e) { } catch(Exception e) {
logger.warn( logger.warn(
"Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065"); "Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
@ -329,9 +324,9 @@ public class TypeManagement {
} }
try { try {
// oClass.setAbstract(false); // Used to allow to persist Schema in Context // documentType.setAbstract(false); // Used to allow to persist Schema in Context
// Management // Management
oClass.setAbstract(type.isAbstract()); documentType.setAbstract(type.isAbstract());
} catch(Exception e) { } catch(Exception e) {
logger.error( logger.error(
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.", "Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
@ -339,9 +334,9 @@ public class TypeManagement {
} }
if(!baseElementTypes.contains(type.getName())) { if(!baseElementTypes.contains(type.getName())) {
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseDocument, type, List<DocumentType> oSuperclasses = getSuperTypesAndCheckCompliancy(database, type,
accessType.getName()); accessType.getName());
oClass.setSuperClasses(oSuperclasses); documentType.setSuperClasses(oSuperclasses);
} }
if(!(type instanceof ResourceType)) { if(!(type instanceof ResourceType)) {
@ -373,9 +368,9 @@ public class TypeManagement {
} }
} }
OType oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType()); com.arcadedb.schema.Type oType = DBTypeMapping.getDBType(propertyTypeName.getBaseType());
OProperty op = oClass.createProperty(propertyDefinition.getName(), oType); com.arcadedb.schema.Property op = documentType.createProperty(propertyDefinition.getName(), oType);
op.setDescription(propertyDefinition.getDescription()); op.setDescription(propertyDefinition.getDescription());
/* /*
@ -394,7 +389,7 @@ public class TypeManagement {
if (propertyTypeName.isGenericType()) { if (propertyTypeName.isGenericType()) {
if (propertyTypeName.getGenericClassName() != null) { if (propertyTypeName.getGenericClassName() != null) {
OClass linkedClass = getOClass(oSchema, propertyTypeName.getGenericClassName()); DocumentType linkedClass = getOClass(oSchema, propertyTypeName.getGenericClassName());
if (linkedClass == null) { if (linkedClass == null) {
logger.trace("Class {} not found.", propertyTypeName.getGenericClassName()); logger.trace("Class {} not found.", propertyTypeName.getGenericClassName());
@ -409,8 +404,8 @@ public class TypeManagement {
op.setLinkedClass(linkedClass); op.setLinkedClass(linkedClass);
} else { } else {
OType linkedOType = OrientDBTypeMapping OType linkedOType = DBTypeMapping
.getOTypeByBaseType(propertyTypeName.getGenericBaseType()); .getDBType(propertyTypeName.getGenericBaseType());
op.setLinkedType(OType.getById(Integer.valueOf(linkedOType.ordinal()).byteValue())); op.setLinkedType(OType.getById(Integer.valueOf(linkedOType.ordinal()).byteValue()));
} }
@ -419,7 +414,7 @@ public class TypeManagement {
} }
} }
oDatabaseDocument.commit(); database.commit();
logger.info("{} {} registered successfully", accessType.getName(), type.getName()); logger.info("{} {} registered successfully", accessType.getName(), type.getName());
} catch(Exception e) { } catch(Exception e) {
@ -436,7 +431,7 @@ public class TypeManagement {
} catch(Exception ex) { } catch(Exception ex) {
throw new SchemaCreationException(ex); throw new SchemaCreationException(ex);
} finally { } finally {
oDatabaseDocument.close(); database.close();
} }
} }
@ -466,17 +461,17 @@ public class TypeManagement {
protected void updateTypeSchema(Type actualTypeDefinition, Type newTypeDefinition, AccessType baseElementAccessType) protected void updateTypeSchema(Type actualTypeDefinition, Type newTypeDefinition, AccessType baseElementAccessType)
throws SchemaNotFoundException, SchemaException { throws SchemaNotFoundException, SchemaException {
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
OMetadata oMetadata = oDatabaseDocument.getMetadata(); OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass oClass = oSchema.getClass(typeName); DocumentType documentType = oSchema.getClass(typeName);
if(oClass == null) { if(documentType == null) {
throw new SchemaNotFoundException(typeName + " does not Exists"); throw new SchemaNotFoundException(typeName + " does not Exists");
} }
@ -495,7 +490,7 @@ public class TypeManagement {
String description = newTypeDefinition.getDescription(); String description = newTypeDefinition.getDescription();
if(description != null && description.compareTo("") != 0) { if(description != null && description.compareTo("") != 0) {
try { try {
oClass.setDescription(description); documentType.setDescription(description);
} catch(Exception e) { } catch(Exception e) {
logger.warn( logger.warn(
"Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065"); "Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
@ -503,9 +498,9 @@ public class TypeManagement {
} }
try { try {
// oClass.setAbstract(false); // Used to allow to persist Schema in Context // documentType.setAbstract(false); // Used to allow to persist Schema in Context
// Management // Management
oClass.setAbstract(newTypeDefinition.isAbstract()); documentType.setAbstract(newTypeDefinition.isAbstract());
} catch(Exception e) { } catch(Exception e) {
logger.error( logger.error(
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.", "Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
@ -547,7 +542,7 @@ public class TypeManagement {
} }
PropertyTypeName newPropertyTypeName = ((PropertyDefinitionImpl) newPropertyDefinition).getPropertyTypeName(); PropertyTypeName newPropertyTypeName = ((PropertyDefinitionImpl) newPropertyDefinition).getPropertyTypeName();
OType oType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getBaseType()); com.arcadedb.schema.Type dbType = DBTypeMapping.getDBType(newPropertyTypeName.getBaseType());
/* /*
* Excluding EMBEDDEDLIST and EMBEDDEDSET * Excluding EMBEDDEDLIST and EMBEDDEDSET
@ -555,8 +550,8 @@ public class TypeManagement {
* *
*/ */
if(!typeList.contains(newTypeDefinition.getName())) { if(!typeList.contains(newTypeDefinition.getName())) {
switch(oType) { switch(dbType) {
case EMBEDDEDLIST: case LIST:
throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
case EMBEDDEDSET: case EMBEDDEDSET:
@ -567,15 +562,15 @@ public class TypeManagement {
} }
} }
OProperty op; com.arcadedb.schema.Property dbProperty;
if(actualPropertyDefinition!=null) { if(actualPropertyDefinition!=null) {
// The property already exists and has changed (the check has been performed few lines above). // The property already exists and has changed (the check has been performed few lines above).
op = oClass.getProperty(propertyName); dbProperty = documentType.getProperty(propertyName);
}else { }else {
op = oClass.createProperty(propertyName, oType); dbProperty = documentType.createProperty(propertyName, dbType);
} }
op.setDescription(newPropertyDefinition.getDescription()); dbProperty.setDescription(newPropertyDefinition.getDescription());
/* /*
* Mandatory and notNull does not work in distributed mode: so that on Type * Mandatory and notNull does not work in distributed mode: so that on Type
@ -584,16 +579,16 @@ public class TypeManagement {
* ovp.setNotNull(property.isNotnull()); This information are persisted in * ovp.setNotNull(property.isNotnull()); This information are persisted in
* Management Context * Management Context
*/ */
op.setMandatory(false); dbProperty.setMandatory(false);
op.setNotNull(false); dbProperty.setNotNull(false);
op.setReadonly(newPropertyDefinition.isReadonly()); dbProperty.setReadonly(newPropertyDefinition.isReadonly());
op.setRegexp(newPropertyDefinition.getRegexp()); dbProperty.setRegexp(newPropertyDefinition.getRegexp());
if (newPropertyTypeName.isGenericType()) { if (newPropertyTypeName.isGenericType()) {
if (newPropertyTypeName.getGenericClassName() != null) { if (newPropertyTypeName.getGenericClassName() != null) {
OClass linkedClass = getOClass(oSchema, newPropertyTypeName.getGenericClassName()); DocumentType linkedClass = getOClass(oSchema, newPropertyTypeName.getGenericClassName());
if (linkedClass == null) { if (linkedClass == null) {
logger.trace("Class {} not found.", newPropertyTypeName.getGenericClassName()); logger.trace("Class {} not found.", newPropertyTypeName.getGenericClassName());
@ -606,10 +601,10 @@ public class TypeManagement {
"A PropertyType cannot be an Entity type or a Relation type"); "A PropertyType cannot be an Entity type or a Relation type");
} }
op.setLinkedClass(linkedClass); dbProperty.setLinkedClass(linkedClass);
} else { } else {
OType linkedOType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getGenericBaseType()); com.arcadedb.schema.Type linkedOType = DBTypeMapping.getDBType(newPropertyTypeName.getGenericBaseType());
op.setLinkedType(OType.getById(Integer.valueOf(linkedOType.ordinal()).byteValue())); dbProperty.setLinkedType(Type.getById(Integer.valueOf(linkedOType.ordinal()).byteValue()));
} }
} }
@ -622,12 +617,12 @@ public class TypeManagement {
// Removing old properties which are no more present in the new type definition // Removing old properties which are no more present in the new type definition
for(String propertyNameToRemove : actualPropertyDefinitionMap.keySet()) { for(String propertyNameToRemove : actualPropertyDefinitionMap.keySet()) {
oClass.dropProperty(propertyNameToRemove); documentType.dropProperty(propertyNameToRemove);
} }
} }
oDatabaseDocument.commit(); database.commit();
logger.info("{} {} updated successfully", baseElementAccessType.getName(), newTypeDefinition.getName()); logger.info("{} {} updated successfully", baseElementAccessType.getName(), newTypeDefinition.getName());
} catch(Exception e) { } catch(Exception e) {
@ -641,30 +636,30 @@ public class TypeManagement {
} catch(Exception ex) { } catch(Exception ex) {
throw new SchemaException(ex); throw new SchemaException(ex);
} finally { } finally {
oDatabaseDocument.close(); database.close();
} }
} }
protected List<Type> getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { protected List<Type> getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata(); OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass baseOClass = oSchema.getClass(typeName); DocumentType baseDocumentType = oSchema.getClass(typeName);
if(baseOClass == null) { if(baseDocumentType == null) {
throw new SchemaNotFoundException(typeName + " does not Exists"); throw new SchemaNotFoundException(typeName + " does not Exists");
} }
List<Type> typeDefinitions = new ArrayList<>(); List<Type> typeDefinitions = new ArrayList<>();
typeDefinitions.add(getType(baseOClass)); typeDefinitions.add(getType(baseDocumentType));
if(includeSubtypes) { if(includeSubtypes) {
Collection<OClass> subClasses = baseOClass.getAllSubclasses(); Collection<DocumentType> subClasses = baseDocumentType.getAllSubclasses();
for(OClass oClass : subClasses) { for(DocumentType documentType : subClasses) {
typeDefinitions.add(getType(oClass)); typeDefinitions.add(getType(documentType));
} }
} }
@ -676,8 +671,8 @@ public class TypeManagement {
} catch(Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
} }
} }
@ -787,12 +782,12 @@ public class TypeManagement {
} }
protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{ protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{
ODatabaseDocument oDatabaseDocument = null; RemoteDatabase database = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata(); OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
oSchema.dropClass(typeName); oSchema.dropClass(typeName);
@ -800,7 +795,7 @@ public class TypeManagement {
ElementManagement<?,?> erManagement = getTypeManagement(accessType, typeName); ElementManagement<?,?> erManagement = getTypeManagement(accessType, typeName);
erManagement.delete(); erManagement.delete();
oDatabaseDocument.commit(); database.commit();
return true; return true;
} catch(SchemaException e) { } catch(SchemaException e) {
@ -816,8 +811,8 @@ public class TypeManagement {
} catch(Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} finally { } finally {
if(oDatabaseDocument != null) { if(database != null) {
oDatabaseDocument.close(); database.close();
} }
} }
} }

View File

@ -1,6 +1,5 @@
package org.gcube.informationsystem.resourceregistry.types.entities; package org.gcube.informationsystem.resourceregistry.types.entities;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -13,19 +12,19 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.Enti
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.TypeMapper; import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.query.sql.executor.ResultSet;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -66,7 +65,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
name = jsonNode.get(EntityType.NAME_PROPERTY).asText(); name = jsonNode.get(EntityType.NAME_PROPERTY).asText();
} }
} else { } else {
name = element.getProperty(EntityType.NAME_PROPERTY); name = element.getString(EntityType.NAME_PROPERTY);
} }
} }
return name; return name;
@ -78,16 +77,16 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
} }
@Override @Override
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", this.typeName, getName()); logger.debug("Going to create {} for {}", this.typeName, getName());
return createVertex(); return createVertex();
} }
@Override @Override
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", this.typeName, getName()); logger.debug("Going to update {} for {}", this.typeName, getName());
OVertex entityTypeDefinition = getElement(); Vertex entityTypeDefinition = getElement();
entityTypeDefinition = (OVertex) updateProperties(oClass, entityTypeDefinition, jsonNode, ignoreKeys, entityTypeDefinition = (Vertex) updateProperties(documentType, entityTypeDefinition, jsonNode, ignoreKeys,
ignoreStartWithKeys); ignoreStartWithKeys);
return entityTypeDefinition; return entityTypeDefinition;
} }
@ -99,7 +98,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
} }
@Override @Override
public OVertex getElement() throws NotFoundException, ResourceRegistryException { public Vertex getElement() throws NotFoundException, ResourceRegistryException {
if (element == null) { if (element == null) {
try { try {
element = retrieveElement(); element = retrieveElement();
@ -120,7 +119,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
} }
@Override @Override
public OVertex retrieveElement() throws NotFoundException, ResourceRegistryException { public Vertex retrieveElement() throws NotFoundException, ResourceRegistryException {
try { try {
if (getName() == null) { if (getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element"); throw new NotFoundException("null name does not allow to retrieve the Element");
@ -129,7 +128,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
String select = "SELECT FROM " + typeName + " WHERE " + EntityType.NAME_PROPERTY + " = \"" + getName() String select = "SELECT FROM " + typeName + " WHERE " + EntityType.NAME_PROPERTY + " = \"" + getName()
+ "\""; + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>()); ResultSet resultSet = database.command("sql", select);
if (resultSet == null || !resultSet.hasNext()) { if (resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", typeName, getName()); String error = String.format("No %s with name %s was found", typeName, getName());
@ -137,10 +136,10 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
throw new NotFoundException(error); throw new NotFoundException(error);
} }
OResult oResult = resultSet.next(); Result oResult = resultSet.next();
OVertex element = (OVertex) ElementManagementUtility.getElementFromOptional(oResult.getElement()); Vertex element = (Vertex) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element)); logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
if (resultSet.hasNext()) { if (resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName() throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -158,24 +157,24 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
} }
@Override @Override
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(), logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode); typeName, jsonNode);
try { try {
this.element = oDatabaseDocument.newVertex(typeName); this.element = database.newVertex(typeName);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", OVertex.class.getSimpleName(), OrientDBUtility.getAsStringForLogging(element)); logger.debug("Created {} is {}", Vertex.class.getSimpleName(), DBUtility.getAsStringForLogging(element));
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 {}", OVertex.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e); accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
} }

View File

@ -1,6 +1,5 @@
package org.gcube.informationsystem.resourceregistry.types.properties; package org.gcube.informationsystem.resourceregistry.types.properties;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -12,26 +11,25 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.properties.PropertyType; import org.gcube.informationsystem.types.reference.properties.PropertyType;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class PropertyTypeDefinitionManagement extends ElementManagement<OElement, PropertyType<?>> { public class PropertyTypeDefinitionManagement extends ElementManagement<Document, PropertyType<?>> {
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class); private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
@ -42,9 +40,9 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
this.typeName = PropertyType.NAME; this.typeName = PropertyType.NAME;
} }
public PropertyTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException { public PropertyTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database) throws ResourceRegistryException {
this(); this();
this.oDatabaseDocument = oDatabaseDocument; this.database = database;
setWorkingContext(securityContext); setWorkingContext(securityContext);
} }
@ -72,7 +70,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
name = jsonNode.get(PropertyType.NAME_PROPERTY).asText(); name = jsonNode.get(PropertyType.NAME_PROPERTY).asText();
} }
} else { } else {
name = element.getProperty(PropertyType.NAME_PROPERTY); name = element.getString(PropertyType.NAME_PROPERTY);
} }
} }
return name; return name;
@ -84,16 +82,16 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
} }
@Override @Override
protected OElement reallyCreate() throws AlreadyPresentException, ResourceRegistryException { protected Document reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", PropertyType.NAME, getName()); logger.debug("Going to create {} for {}", PropertyType.NAME, getName());
return createElement(); return createElement();
} }
@Override @Override
protected OElement reallyUpdate() throws NotFoundException, ResourceRegistryException { protected Document reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", PropertyType.NAME, getName()); logger.debug("Going to update {} for {}", PropertyType.NAME, getName());
OElement propertyTypeDefinition = getElement(); Document propertyTypeDefinition = getElement();
propertyTypeDefinition = updateProperties(oClass, propertyTypeDefinition, jsonNode, propertyTypeDefinition = updateProperties(documentType, propertyTypeDefinition, jsonNode,
ignoreKeys, ignoreStartWithKeys); ignoreKeys, ignoreStartWithKeys);
return propertyTypeDefinition; return propertyTypeDefinition;
} }
@ -105,7 +103,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
} }
@Override @Override
public OElement getElement() throws NotFoundException, ResourceRegistryException { public Document getElement() throws NotFoundException, ResourceRegistryException {
if(element == null) { if(element == null) {
try { try {
element = retrieveElement(); element = retrieveElement();
@ -126,7 +124,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
} }
@Override @Override
public OElement retrieveElement() throws NotFoundException, ResourceRegistryException { public Document retrieveElement() throws NotFoundException, ResourceRegistryException {
try { try {
if(getName() == null) { if(getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element"); throw new NotFoundException("null name does not allow to retrieve the Element");
@ -135,7 +133,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
String select = "SELECT FROM " + typeName + " WHERE " + PropertyType.NAME_PROPERTY + " = \"" String select = "SELECT FROM " + typeName + " WHERE " + PropertyType.NAME_PROPERTY + " = \""
+ getName() + "\""; + getName() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>()); ResultSet resultSet = database.query("sql", select);
if(resultSet == null || !resultSet.hasNext()) { if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", typeName, getName()); String error = String.format("No %s with name %s was found", typeName, getName());
@ -143,10 +141,10 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
throw new NotFoundException(error); throw new NotFoundException(error);
} }
OResult oResult = resultSet.next(); Result oResult = resultSet.next();
OElement element = (OElement) ElementManagementUtility.getElementFromOptional(oResult.getElement()); Document element = (Document) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element)); logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
if(resultSet.hasNext()) { if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName() throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -163,19 +161,19 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
} }
} }
protected OElement createElement() throws AlreadyPresentException, ResourceRegistryException { protected Document createElement() throws AlreadyPresentException, ResourceRegistryException {
try { try {
this.element = new ODocument(typeName); this.element = database.newDocument(typeName);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", PropertyType.NAME, OrientDBUtility.getAsStringForLogging(element)); logger.debug("Created {} is {}", PropertyType.NAME, DBUtility.getAsStringForLogging(element));
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 {}", OElement.class.getSimpleName(), logger.trace("Error while creating {} for {} ({}) using {}", Document.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e); accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
} }

View File

@ -7,7 +7,7 @@ import org.gcube.informationsystem.resourceregistry.types.entities.FacetTypeDefi
import org.gcube.informationsystem.types.reference.entities.FacetType; import org.gcube.informationsystem.types.reference.entities.FacetType;
import org.gcube.informationsystem.types.reference.relations.ConsistsOfType; import org.gcube.informationsystem.types.reference.relations.ConsistsOfType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -20,9 +20,9 @@ public class ConsistsOfTypeDefinitionManagement
this.typeName = ConsistsOfType.NAME; this.typeName = ConsistsOfType.NAME;
} }
public ConsistsOfTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument) public ConsistsOfTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database)
throws ResourceRegistryException { throws ResourceRegistryException {
super(securityContext, oDatabaseDocument, FacetType.class); super(securityContext, database, FacetType.class);
this.typeName = ConsistsOfType.NAME; this.typeName = ConsistsOfType.NAME;
} }
@ -30,7 +30,7 @@ public class ConsistsOfTypeDefinitionManagement
protected FacetTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException { protected FacetTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
FacetTypeDefinitionManagement ftdm = new FacetTypeDefinitionManagement(); FacetTypeDefinitionManagement ftdm = new FacetTypeDefinitionManagement();
ftdm.setWorkingContext(getWorkingContext()); ftdm.setWorkingContext(getWorkingContext());
ftdm.setODatabaseDocument(oDatabaseDocument); ftdm.setDatabase(database);
return ftdm; return ftdm;
} }

View File

@ -7,7 +7,7 @@ import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeD
import org.gcube.informationsystem.types.reference.entities.ResourceType; import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.IsRelatedToType; import org.gcube.informationsystem.types.reference.relations.IsRelatedToType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -20,9 +20,9 @@ public class IsRelatedToTypeDefinitionManagement
this.typeName = IsRelatedToType.NAME; this.typeName = IsRelatedToType.NAME;
} }
public IsRelatedToTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument) public IsRelatedToTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database)
throws ResourceRegistryException { throws ResourceRegistryException {
super(securityContext, oDatabaseDocument, ResourceType.class); super(securityContext, database, ResourceType.class);
this.typeName = IsRelatedToType.NAME; this.typeName = IsRelatedToType.NAME;
} }
@ -30,7 +30,7 @@ public class IsRelatedToTypeDefinitionManagement
protected ResourceTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException { protected ResourceTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement(); ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
rtdm.setWorkingContext(getWorkingContext()); rtdm.setWorkingContext(getWorkingContext());
rtdm.setODatabaseDocument(oDatabaseDocument); rtdm.setDatabase(database);
return rtdm; return rtdm;
} }

View File

@ -1,6 +1,5 @@
package org.gcube.informationsystem.resourceregistry.types.relations; package org.gcube.informationsystem.resourceregistry.types.relations;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -15,22 +14,22 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.Rel
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement; import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.types.entities.EntityTypeDefinitionManagement; import org.gcube.informationsystem.resourceregistry.types.entities.EntityTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement; import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility; import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType; import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType; import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.RelationType; import org.gcube.informationsystem.types.reference.relations.RelationType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.sql.executor.OResult; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.arcadedb.remote.RemoteDatabase;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -46,10 +45,10 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
this.forceIncludeAllMeta = true; this.forceIncludeAllMeta = true;
} }
public RelationTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument, public RelationTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database,
Class<TT> clz) throws ResourceRegistryException { Class<TT> clz) throws ResourceRegistryException {
this(clz); this(clz);
this.oDatabaseDocument = oDatabaseDocument; this.database = database;
setWorkingContext(securityContext); setWorkingContext(securityContext);
} }
@ -77,14 +76,14 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
name = jsonNode.get(RelationType.NAME_PROPERTY).asText(); name = jsonNode.get(RelationType.NAME_PROPERTY).asText();
} }
} else { } else {
name = element.getProperty(RelationType.NAME_PROPERTY); name = element.getString(RelationType.NAME_PROPERTY);
} }
} }
return name; return name;
} }
@Override @Override
protected OEdge reallyCreate() throws ResourceRegistryException { protected Edge reallyCreate() throws ResourceRegistryException {
logger.debug("Going to create {} for {}", RelationType.NAME, getName()); logger.debug("Going to create {} for {}", RelationType.NAME, getName());
if (sourceEntityManagement == null) { if (sourceEntityManagement == null) {
if (!jsonNode.has(Relation.SOURCE_PROPERTY)) { if (!jsonNode.has(Relation.SOURCE_PROPERTY)) {
@ -107,23 +106,23 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
targetEntityManagement.setJsonNode(jsonNode.get(Relation.TARGET_PROPERTY)); targetEntityManagement.setJsonNode(jsonNode.get(Relation.TARGET_PROPERTY));
} }
OVertex source = (OVertex) getSourceEntityManagement().getElement(); Vertex source = (Vertex) getSourceEntityManagement().getElement();
OVertex target = (OVertex) getTargetEntityManagement().getElement(); Vertex target = (Vertex) getTargetEntityManagement().getElement();
logger.trace("Creating {} beetween {} -> {}", typeName, source.toString(), target.toString()); logger.trace("Creating {} beetween {} -> {}", typeName, source.toString(), target.toString());
element = oDatabaseDocument.newEdge(source, target, typeName); element = source.newEdge(typeName, target, true);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
return element; return element;
} }
@Override @Override
protected OEdge reallyUpdate() throws NotFoundException, ResourceRegistryException { protected Edge reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", RelationType.NAME, getName()); logger.debug("Going to update {} for {}", RelationType.NAME, getName());
OEdge relationTypeDefinition = getElement(); Edge relationTypeDefinition = getElement();
relationTypeDefinition = (OEdge) updateProperties(oClass, relationTypeDefinition, jsonNode, ignoreKeys, relationTypeDefinition = (Edge) updateProperties(documentType, relationTypeDefinition, jsonNode, ignoreKeys,
ignoreStartWithKeys); ignoreStartWithKeys);
return relationTypeDefinition; return relationTypeDefinition;
@ -136,7 +135,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
} }
@Override @Override
public OEdge getElement() throws NotFoundException, ResourceRegistryException { public Edge getElement() throws NotFoundException, ResourceRegistryException {
if (element == null) { if (element == null) {
try { try {
element = retrieveElement(); element = retrieveElement();
@ -157,7 +156,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
} }
@Override @Override
public OEdge retrieveElement() throws NotFoundException, ResourceRegistryException { public Edge retrieveElement() throws NotFoundException, ResourceRegistryException {
try { try {
if (getName() == null) { if (getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element"); throw new NotFoundException("null name does not allow to retrieve the Element");
@ -166,7 +165,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
String select = "SELECT FROM " + typeName + " WHERE " + RelationType.NAME_PROPERTY + " = \"" + getName() String select = "SELECT FROM " + typeName + " WHERE " + RelationType.NAME_PROPERTY + " = \"" + getName()
+ "\""; + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>()); ResultSet resultSet = database.query("sql",select);
if (resultSet == null || !resultSet.hasNext()) { if (resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", typeName, getName()); String error = String.format("No %s with name %s was found", typeName, getName());
@ -174,10 +173,10 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
throw new NotFoundException(error); throw new NotFoundException(error);
} }
OResult oResult = resultSet.next(); Result oResult = resultSet.next();
OEdge element = (OEdge) ElementManagementUtility.getElementFromOptional(oResult.getElement()); Edge element = (Edge) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element)); logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
if (resultSet.hasNext()) { if (resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName() throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -213,7 +212,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
protected ResourceTypeDefinitionManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceTypeDefinitionManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement(); ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
rtdm.setWorkingContext(getWorkingContext()); rtdm.setWorkingContext(getWorkingContext());
rtdm.setODatabaseDocument(oDatabaseDocument); rtdm.setDatabase(database);
return rtdm; return rtdm;
} }

View File

@ -1,6 +1,5 @@
package org.gcube.informationsystem.resourceregistry.utils; package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode; import org.gcube.com.fasterxml.jackson.databind.JsonNode;
@ -21,36 +20,29 @@ import org.gcube.informationsystem.serialization.ElementMapper;
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.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.OEdge; import com.arcadedb.database.MutableEmbeddedDocument;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.graph.Edge;
import com.orientechnologies.orient.core.record.ORecord; import com.arcadedb.graph.Vertex;
import com.orientechnologies.orient.core.record.OVertex; import com.arcadedb.query.sql.executor.Result;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class OrientDBUtility { public class DBUtility {
private static final Logger logger = LoggerFactory.getLogger(OrientDBUtility.class); private static final Logger logger = LoggerFactory.getLogger(DBUtility.class);
public static final String ORIENTDB_CLASS_PROPERTY = ODocumentHelper.ATTRIBUTE_CLASS; public static final String DB_TYPE_PROPERTY = "@type";
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(OElement element) throws ResourceRegistryException { public static JsonNode toJsonNode(Document document) throws ResourceRegistryException {
ORecord oRecord = element.getRecord();
return OrientDBUtility.toJsonNode(oRecord);
}
public static JsonNode toJsonNode(ORecord oRecord) throws ResourceRegistryException {
try { try {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
String string = toJsonString(oRecord); String string = toJsonString(document);
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(string); ObjectNode objectNode = (ObjectNode) objectMapper.readTree(string);
return objectNode; return objectNode;
} catch(Exception e) { } catch(Exception e) {
@ -59,61 +51,52 @@ public class OrientDBUtility {
} }
public static String replaceType(String s) { public static String replaceType(String s) {
s = s.replace("\"" + ORIENTDB_CLASS_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\""); s = s.replace("\"" + DB_TYPE_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\"");
return s; return s;
} }
public static String toJsonString(OResult oResult) { public static String toJsonString(Document document) {
String ret = oResult.toJSON(); String ret = document.toJSON().toString();
// The above method set the type in @class property // The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY // We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret); ret = replaceType(ret);
return ret; return ret;
} }
public static String toJsonString(ORecord oRecord) { public static String getAsStringForLogging(Document document) {
String ret = oRecord.toJSON("class"); return document.toJSON().toString();
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
} }
public static String getAsStringForLogging(ORecord oRecord) { public static String getAsStringForException(Document document) {
return oRecord.toJSON(); return toJsonString(document);
} }
public static String getAsStringForException(ORecord oRecord) { public static <El extends Document> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
return toJsonString(oRecord);
}
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 {
ODatabaseDocument adminDatabaseDocument = null; RemoteDatabase adminDatabase = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); // RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try { try {
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
adminDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); adminDatabase = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz); return DBUtility.getElementByUUID(adminDatabase, elementType, uuid, clz);
} finally { } finally {
if(adminDatabaseDocument != null) { if(adminDatabase != null) {
adminDatabaseDocument.close(); adminDatabase.close();
}
if(current!=null) {
current.activateOnCurrentThread();
} }
// if(current!=null) {
// current.activateOnCurrentThread();
// }
} }
} }
public static <El extends OElement> El getElementByUUID(ODatabaseDocument oDatabaseDocument, String elementType, UUID uuid, public static <El extends Document> El getElementByUUID(RemoteDatabase database, 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(OVertex.class.isAssignableFrom(clz)) { if(Vertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME; elementType = Entity.NAME;
} }
if(OEdge.class.isAssignableFrom(clz)) { if(Edge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME; elementType = Relation.NAME;
} }
} }
@ -121,7 +104,7 @@ public class OrientDBUtility {
// TODO Rewrite using Gremlin // TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE " + IdentifiableElement.ID_PROPERTY + " = \"" + uuid.toString() + "\""; String select = "SELECT FROM " + elementType + " WHERE " + IdentifiableElement.ID_PROPERTY + " = \"" + uuid.toString() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>()); ResultSet resultSet = database.command("sql", select);
if(resultSet == null || !resultSet.hasNext()) { if(resultSet == null || !resultSet.hasNext()) {
@ -130,11 +113,11 @@ public class OrientDBUtility {
throw new NotFoundException(error); throw new NotFoundException(error);
} }
OResult oResult = resultSet.next(); Result result = resultSet.next();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
El element = (El) ElementManagementUtility.getElementFromOptional(oResult.getElement()); El element = (El) ElementManagementUtility.getElementFromOptional(result.getElement());
logger.trace("{} with id {} is : {}", elementType, uuid.toString(), OrientDBUtility.getAsStringForLogging(element)); logger.trace("{} with id {} is : {}", elementType, uuid.toString(), DBUtility.getAsStringForLogging(element));
if(resultSet.hasNext()) { if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString() throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
@ -144,11 +127,11 @@ public class OrientDBUtility {
return element; return element;
} }
public static <P extends PropertyElement> P getPropertyDocument(Class<P> clz, OElement element, String property) public static <P extends PropertyElement> P getPropertyDocument(Class<P> clz, Document element, String property)
throws ResourceRegistryException { throws ResourceRegistryException {
try { try {
ODocument oDocument = element.getProperty(property); MutableEmbeddedDocument document = (MutableEmbeddedDocument) element.getEmbedded(property);
P e = ElementMapper.unmarshal(clz, OrientDBUtility.toJsonString(oDocument)); P e = ElementMapper.unmarshal(clz, DBUtility.toJsonString(document));
return e; return e;
} catch(Exception ex) { } catch(Exception ex) {
String error = String.format("Error while getting %s from %s", property, getAsStringForException(element)); String error = String.format("Error while getting %s from %s", property, getAsStringForException(element));

View File

@ -15,12 +15,12 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType; import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility; import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.database.MutableDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class EncryptedOrient extends ODocument implements Encrypted { public class EncryptedOrient extends MutableDocument implements Encrypted {
public static final String NAME = "Encrypted"; public static final String NAME = "Encrypted";
public static final String VALUE = "value"; public static final String VALUE = "value";
@ -62,11 +62,11 @@ public class EncryptedOrient extends ODocument implements Encrypted {
} }
public String getEncryptedValue() { public String getEncryptedValue() {
return this.field(EncryptedOrient.VALUE); return this.getString(EncryptedOrient.VALUE);
} }
public void setEncryptedValue(String encryptedValue) { public void setEncryptedValue(String encryptedValue) {
this.field(EncryptedOrient.VALUE, encryptedValue); this.set(EncryptedOrient.VALUE, encryptedValue);
} }
public String getDecryptedValue() { public String getDecryptedValue() {
@ -133,7 +133,7 @@ public class EncryptedOrient extends ODocument implements Encrypted {
@Override @Override
public String toJSON(String iFormat) { public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat); String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret); ret = DBUtility.replaceType(ret);
return ret; return ret;
} }

View File

@ -5,6 +5,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.lucene.document.Document;
import org.gcube.informationsystem.base.reference.properties.PropertyElement; import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.Metadata; import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property; import org.gcube.informationsystem.model.reference.properties.Property;
@ -13,12 +14,12 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType; import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility; import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.database.MutableDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class MetadataOrient extends ODocument implements Metadata { public class MetadataOrient extends MutableDocument implements Metadata {
public MetadataOrient() { public MetadataOrient() {
super(Metadata.NAME); super(Metadata.NAME);
@ -111,7 +112,7 @@ public class MetadataOrient extends ODocument implements Metadata {
@Override @Override
public String toJSON(String iFormat) { public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat); String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret); ret = DBUtility.replaceType(ret);
return ret; return ret;
} }

View File

@ -18,8 +18,9 @@ import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.database.Document;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.database.MutableDocument;
import com.arcadedb.database.MutableEmbeddedDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -63,7 +64,7 @@ public class MetadataUtility {
return null; return null;
} }
MetadataOrient metadata = new MetadataOrient(); MetadataOrient metadata = new MetadataOrient();
metadataNode.set(OrientDBUtility.ORIENTDB_CLASS_PROPERTY, metadataNode.get(Element.TYPE_PROPERTY)); metadataNode.set(DBUtility.DB_TYPE_PROPERTY, metadataNode.get(Element.TYPE_PROPERTY));
metadataNode.remove(Element.TYPE_PROPERTY); metadataNode.remove(Element.TYPE_PROPERTY);
metadata.fromJSON(metadataNode.toString()); metadata.fromJSON(metadataNode.toString());
return metadata; return metadata;
@ -71,13 +72,13 @@ public class MetadataUtility {
return null; return null;
} }
public static MetadataOrient getMetadataOrient(ODocument oDocument) throws ResourceRegistryException { public static MetadataOrient getMetadataOrient(Document document) throws ResourceRegistryException {
if(oDocument instanceof MetadataOrient) { if(document instanceof MetadataOrient) {
return (MetadataOrient) oDocument; return (MetadataOrient) document;
} else { } else {
try { try {
MetadataOrient metadataOrient = new MetadataOrient(); MetadataOrient metadataOrient = new MetadataOrient();
String json = OrientDBUtility.toJsonString(oDocument); String json = DBUtility.toJsonString(document);
Metadata metadata = ElementMapper.unmarshal(Metadata.class, json); Metadata metadata = ElementMapper.unmarshal(Metadata.class, json);
metadataOrient.setCreatedBy(metadata.getCreatedBy()); metadataOrient.setCreatedBy(metadata.getCreatedBy());
metadataOrient.setCreationTime(metadata.getCreationTime()); metadataOrient.setCreationTime(metadata.getCreationTime());
@ -86,28 +87,28 @@ public class MetadataUtility {
return metadataOrient; return metadataOrient;
} catch(Exception e) { } catch(Exception e) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
"Unable to recreate Metadata. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); "Unable to recreate Metadata. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
} }
public static Metadata addMetadata(OElement element) { public static Metadata addMetadata(Document element) {
Metadata metadata = createMetadata(); Metadata metadata = createMetadata();
element.setProperty(IdentifiableElement.METADATA_PROPERTY, metadata); ((MutableDocument) element).set(IdentifiableElement.METADATA_PROPERTY, metadata);
return metadata; return metadata;
} }
public static Metadata getMetadata(OElement element) throws ResourceRegistryException { public static Metadata getMetadata(Document element) throws ResourceRegistryException {
return OrientDBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY); return DBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY);
} }
public static void updateModifiedByAndLastUpdate(OElement element) throws ResourceRegistryException { public static void updateModifiedByAndLastUpdate(Document element) throws ResourceRegistryException {
ODocument oDocument = element.getProperty(IdentifiableElement.METADATA_PROPERTY); MutableEmbeddedDocument document = (MutableEmbeddedDocument) element.getEmbedded(IdentifiableElement.METADATA_PROPERTY);
String lastUpdateBy = getUser(); String lastUpdateBy = getUser();
oDocument.field(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy); document.set(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
Date lastUpdateTime = Calendar.getInstance().getTime(); Date lastUpdateTime = Calendar.getInstance().getTime();
oDocument.field(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); document.set(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
element.setProperty(IdentifiableElement.METADATA_PROPERTY, oDocument); ((MutableDocument) element).set(IdentifiableElement.METADATA_PROPERTY, document);
} }
} }

View File

@ -12,12 +12,12 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType; import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility; import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument; import com.arcadedb.database.MutableDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class PropagationConstraintOrient extends ODocument implements PropagationConstraint { public class PropagationConstraintOrient extends MutableDocument implements PropagationConstraint {
public PropagationConstraintOrient() { public PropagationConstraintOrient() {
super(PropagationConstraint.NAME); super(PropagationConstraint.NAME);
@ -104,7 +104,7 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio
@Override @Override
public String toJSON(String iFormat) { public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat); String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret); ret = DBUtility.replaceType(ret);
return ret; return ret;
} }

View File

@ -5,15 +5,15 @@ import java.util.UUID;
import org.gcube.informationsystem.base.reference.IdentifiableElement; import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import com.orientechnologies.orient.core.record.OElement; import com.arcadedb.database.Document;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class UUIDUtility extends org.gcube.informationsystem.utils.UUIDUtility { public class UUIDUtility extends org.gcube.informationsystem.utils.UUIDUtility {
public static UUID getUUID(OElement element) throws ResourceRegistryException { public static UUID getUUID(Document element) throws ResourceRegistryException {
String uuidString = element.getProperty(IdentifiableElement.ID_PROPERTY); String uuidString = element.getString(IdentifiableElement.ID_PROPERTY);
UUID uuid = UUID.fromString(uuidString); UUID uuid = UUID.fromString(uuidString);
return uuid; return uuid;
} }

View File

@ -27,10 +27,8 @@ import org.junit.Test;
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.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -84,8 +82,8 @@ public class ContextManagementTest extends ContextTest {
protected void roleUserAssertions(UUID uuid, UUID oldParentUUID, boolean deleted) throws ResourceRegistryException { protected void roleUserAssertions(UUID uuid, UUID oldParentUUID, boolean deleted) throws ResourceRegistryException {
ContextSecurityContext contextSecurityContext = ContextSecurityContext.getInstance(); ContextSecurityContext contextSecurityContext = ContextSecurityContext.getInstance();
ODatabaseDocument oDatabaseDocument = contextSecurityContext.getDatabaseDocument(PermissionMode.READER); RemoteDatabase database = contextSecurityContext.getRemoteDatabase(PermissionMode.READER);
OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity(); // OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity();
SecurityContext securityContext = null; SecurityContext securityContext = null;
if(deleted) { if(deleted) {
@ -98,11 +96,11 @@ public class ContextManagementTest extends ContextTest {
for(boolean hierarchic : booleanArray) { for(boolean hierarchic : booleanArray) {
for(PermissionMode permissionMode : PermissionMode.values()) { for(PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic); String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
ORole oRole = oSecurity.getRole(role); Role oRole = oSecurity.getRole(role);
Assert.assertEquals(oRole == null, deleted); Assert.assertEquals(oRole == null, deleted);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic); String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
OUser oUser = oSecurity.getUser(user); User oUser = oSecurity.getUser(user);
Assert.assertEquals(oUser == null, deleted); Assert.assertEquals(oUser == null, deleted);
if(oUser != null) { if(oUser != null) {
Assert.assertTrue(oUser.hasRole(oRole.getName(), false)); Assert.assertTrue(oUser.hasRole(oRole.getName(), false));
@ -119,7 +117,7 @@ public class ContextManagementTest extends ContextTest {
while(parent != null) { while(parent != null) {
String parentUser = parent.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, String parentUser = parent.getSecurityRoleOrUserName(permissionMode, SecurityType.USER,
hierarchic); hierarchic);
OUser parentOUser = oSecurity.getUser(parentUser); User parentOUser = oSecurity.getUser(parentUser);
Assert.assertTrue(parentOUser != null); Assert.assertTrue(parentOUser != null);
Assert.assertEquals(parentOUser.hasRole(oRole.getName(), false), !deleted); Assert.assertEquals(parentOUser.hasRole(oRole.getName(), false), !deleted);
parent = parent.getParentSecurityContext(); parent = parent.getParentSecurityContext();

View File

@ -9,8 +9,7 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES; import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -21,14 +20,13 @@ public class DatabaseEnvironmentTest {
// @Test // @Test
public void createDB() throws Exception{ public void createDB() throws Exception{
String db = DatabaseEnvironment.DB_URI; logger.trace("Created DB is {}:{}/{}", DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB);
logger.trace("Created DB is {}", db);
} }
@Test @Test
public void testDateTimeFormat() throws ResourceRegistryException { public void testDateTimeFormat() throws ResourceRegistryException {
ODatabaseDocument oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER); RemoteDatabase database = ContextUtility.getAdminSecurityContext().getRemoteDatabase(PermissionMode.WRITER);
String dateTime = oDatabaseDocument.get(ATTRIBUTES.DATETIMEFORMAT).toString(); String dateTime = database.get(ATTRIBUTES.DATETIMEFORMAT).toString();
Assert.assertTrue(dateTime.compareTo(Element.DATETIME_PATTERN)==0); Assert.assertTrue(dateTime.compareTo(Element.DATETIME_PATTERN)==0);
} }

View File

@ -30,7 +30,7 @@ import org.junit.Assert;
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.arcadedb.graph.Vertex.DIRECTION;
public class MultiContextTest extends ERManagementTest { public class MultiContextTest extends ERManagementTest {
@ -136,16 +136,16 @@ public class MultiContextTest extends ERManagementTest {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getIncomingIsRelatedTo(Resource r) throws Exception { protected List<IsRelatedTo> getIncomingIsRelatedTo(Resource r) throws Exception {
return getIsRelatedTo(r, ODirection.OUT); return getIsRelatedTo(r, DIRECTION.OUT);
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getOutcomingIsRelatedTo(Resource r) throws Exception { protected List<IsRelatedTo> getOutcomingIsRelatedTo(Resource r) throws Exception {
return getIsRelatedTo(r, ODirection.IN); return getIsRelatedTo(r, DIRECTION.IN);
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getIsRelatedTo(Resource r, ODirection oDirection) throws Exception { protected List<IsRelatedTo> getIsRelatedTo(Resource r, DIRECTION direction) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(Resource.NAME); resourceManagement.setElementType(Resource.NAME);
@ -153,7 +153,7 @@ public class MultiContextTest extends ERManagementTest {
UUID resourceUUID = r.getID(); UUID resourceUUID = r.getID();
// resourceManagement.setUUID(resourceUUID); // resourceManagement.setUUID(resourceUUID);
String ret = resourceManagement.query(IsRelatedTo.NAME, resourceType, resourceUUID, oDirection, true, String ret = resourceManagement.query(IsRelatedTo.NAME, resourceType, resourceUUID, direction, true,
new HashMap<>()); new HashMap<>());
List<IsRelatedTo> isRelatedToList = ElementMapper.unmarshalList(IsRelatedTo.class, ret); List<IsRelatedTo> isRelatedToList = ElementMapper.unmarshalList(IsRelatedTo.class, ret);
return isRelatedToList; return isRelatedToList;

View File

@ -42,7 +42,7 @@ import org.junit.Test;
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.arcadedb.graph.Vertex.DIRECTION;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -169,61 +169,61 @@ public class QueryTest extends ERManagementTest {
resourceManagement.setElementType(Service.NAME); resourceManagement.setElementType(Service.NAME);
/* Getting Hosting Node */ /* Getting Hosting Node */
String json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.BOTH, true, String json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, DIRECTION.BOTH, true,
null); null);
List<Resource> resourceList = ElementMapper.unmarshalList(Resource.class, json); List<Resource> resourceList = ElementMapper.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.getID().compareTo(hostingNodeUUID) == 0); Assert.assertTrue(resource.getID().compareTo(hostingNodeUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.OUT, true, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, DIRECTION.OUT, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.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.getID().compareTo(hostingNodeUUID) == 0); Assert.assertTrue(resource.getID().compareTo(hostingNodeUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.IN, true, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, DIRECTION.IN, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.BOTH, false, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, DIRECTION.BOTH, false, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.OUT, false, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, DIRECTION.OUT, false, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.IN, false, null); json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, DIRECTION.IN, false, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
/* END Getting Hosting Node */ /* END Getting Hosting Node */
/* Getting EService */ /* Getting EService */
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.BOTH, true, json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, DIRECTION.BOTH, true,
null); null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1); Assert.assertTrue(resourceList.size() == 1);
Assert.assertTrue(resourceList.get(0).getID().compareTo(eServiceUUID) == 0); Assert.assertTrue(resourceList.get(0).getID().compareTo(eServiceUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.OUT, true, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, DIRECTION.OUT, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.IN, true, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, DIRECTION.IN, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1); Assert.assertTrue(resourceList.size() == 1);
Assert.assertTrue(resourceList.get(0).getID().compareTo(eServiceUUID) == 0); Assert.assertTrue(resourceList.get(0).getID().compareTo(eServiceUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.BOTH, false, json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, DIRECTION.BOTH, false,
null); null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.OUT, false, json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, DIRECTION.OUT, false,
null); null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.IN, false, null); json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, DIRECTION.IN, false, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
/* END Getting HostingNode */ /* END Getting HostingNode */
@ -234,12 +234,12 @@ public class QueryTest extends ERManagementTest {
/* EService --ConsistsOf--> SoftwareFacet */ /* EService --ConsistsOf--> SoftwareFacet */
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID,
ODirection.BOTH, true, null); DIRECTION.BOTH, true, null);
} catch (InvalidQueryException e) { } catch (InvalidQueryException e) {
// Ok expected // Ok expected
} }
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.OUT, json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.OUT,
true, null); true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1); Assert.assertTrue(resourceList.size() == 1);
@ -249,7 +249,7 @@ public class QueryTest extends ERManagementTest {
Assert.assertTrue(targetIdentificationFacet.getID().compareTo(identificationFacetUUID) == 0); Assert.assertTrue(targetIdentificationFacet.getID().compareTo(identificationFacetUUID) == 0);
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN, json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.IN,
true, null); true, null);
throw new Exception("Expected InvalidQueryException"); throw new Exception("Expected InvalidQueryException");
} catch (InvalidQueryException e) { } catch (InvalidQueryException e) {
@ -258,19 +258,19 @@ public class QueryTest extends ERManagementTest {
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID,
ODirection.BOTH, false, null); DIRECTION.BOTH, false, null);
throw new Exception("Expected InvalidQueryException"); throw new Exception("Expected InvalidQueryException");
} catch (InvalidQueryException e) { } catch (InvalidQueryException e) {
// Ok expected // Ok expected
} }
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.OUT, json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.OUT,
false, null); false, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json); resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 0); Assert.assertTrue(resourceList.size() == 0);
try { try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN, json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.IN,
false, null); false, null);
throw new Exception("Expected InvalidQueryException"); throw new Exception("Expected InvalidQueryException");
} catch (InvalidQueryException e) { } catch (InvalidQueryException e) {
@ -303,7 +303,7 @@ public class QueryTest extends ERManagementTest {
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, ODirection.OUT, bool, constraint); String ret = ((ResourceManagement) erManagement).query(relationType, facetType, null, DIRECTION.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);
} }
@ -358,7 +358,7 @@ public class QueryTest extends ERManagementTest {
parentResourceManagement.setElementType(parentResourceType); parentResourceManagement.setElementType(parentResourceType);
ODirection directionEnum = ODirection.OUT; DIRECTION directionEnum = DIRECTION.OUT;
UUID refereceUUID = null; UUID refereceUUID = null;
Boolean[] polymorphics = new Boolean[] {true, false}; Boolean[] polymorphics = new Boolean[] {true, false};

View File

@ -19,7 +19,7 @@ public class TypesCacheTest {
protected CachedType<?> getCachedType(TypesCache typesCache, String typeName) throws Exception { protected CachedType<?> getCachedType(TypesCache typesCache, String typeName) throws Exception {
CachedType<?> cachedType = typesCache.getCachedType(typeName); CachedType<?> cachedType = typesCache.getCachedType(typeName);
OClass oClass = cachedType.getOClass(); OClass oClass = cachedType.getDocumentType();
AccessType accessType = cachedType.getAccessType(); AccessType accessType = cachedType.getAccessType();
Type type = cachedType.getType(); Type type = cachedType.getType();
logger.debug("{} ({}) : {}", oClass.toString(), accessType.toString(), TypeMapper.serializeTypeDefinition(type)); logger.debug("{} ({}) : {}", oClass.toString(), accessType.toString(), TypeMapper.serializeTypeDefinition(type));