diff --git a/pom.xml b/pom.xml index 828f842..709a593 100644 --- a/pom.xml +++ b/pom.xml @@ -60,23 +60,18 @@ + - com.orientechnologies - - orientdb-client - 3.0.42 - - - org.graalvm.tools - chromeinspector - - + com.arcadedb + arcadedb-engine + 23.4.1 + + com.arcadedb + arcadedb-network + 23.4.1 + + org.gcube.common gxHTTP diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java index c484721..3c30b77 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java @@ -23,7 +23,7 @@ public class ResourceInitializer extends ResourceConfig { public ResourceInitializer() { 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); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/ContextUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/ContextUtility.java index 71fdb48..74c81d7 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/ContextUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/ContextUtility.java @@ -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.PermissionMode; 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.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OVertex; -import com.orientechnologies.orient.core.sql.executor.OResult; -import com.orientechnologies.orient.core.sql.executor.OResultSet; +import com.arcadedb.graph.MutableVertex; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; +import com.arcadedb.remote.RemoteDatabase; + /** * @author Luca Frosini (ISTI - CNR) @@ -76,8 +77,8 @@ public class ContextUtility { } public synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument oDatabaseDocument = null; +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { SecurityContext securityContext = null; @@ -91,9 +92,9 @@ public class ContextUtility { if(securityContext==null) { logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(), 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); @@ -110,13 +111,13 @@ public class ContextUtility { } catch(Exception e) { throw new ContextException("Unable to retrieve Context UUID from current Context", e); } finally { - if(oDatabaseDocument!=null) { - oDatabaseDocument.close(); + if(database!=null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -124,36 +125,36 @@ public class ContextUtility { return getSecurityContextByUUID(uuid, null); } - public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() { - ODatabaseDocument current = null; + public static RemoteDatabase getCurrentODatabaseDocumentFromThreadLocal() { + RemoteDatabase current = null; try { - current = (ODatabaseDocument) ODatabaseRecordThreadLocal.instance().get(); + // current = (RemoteDatabase) ODatabaseRecordThreadLocal.instance().get(); }catch (Exception e) { // It is possible that there is no current ODatabaseDocument } return current; } - private OVertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument oDatabaseDocument = null; + private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException { + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { - oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER); - OVertex oVertex = OrientDBUtility.getElementByUUID(oDatabaseDocument, Context.NAME, uuid, - OVertex.class); - return oVertex; + database = getAdminSecurityContext().getRemoteDatabase(PermissionMode.READER); + Vertex vertex = DBUtility.getElementByUUID(database, Context.NAME, uuid, + Vertex.class); + return vertex; } finally { - if(oDatabaseDocument!=null) { - oDatabaseDocument.close(); + if(database!=null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// 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); if(securityContext == null) { @@ -163,7 +164,7 @@ public class ContextUtility { if(contextVertex == null) { 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) { UUID parentUUID = UUIDUtility.getUUID(parentVertex); @@ -187,8 +188,8 @@ public class ContextUtility { } */ - private OVertex getContextVertexByFullName(ODatabaseDocument oDatabaseDocument, String fullName) throws ResourceRegistryException { - logger.trace("Going to get {} {} with full name '{}'", Context.NAME, OVertex.class.getSimpleName(), fullName); + private MutableVertex getContextVertexByFullName(RemoteDatabase database , String fullName) throws ResourceRegistryException { + logger.trace("Going to get {} {} with full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName); ScopeBean scopeBean = new ScopeBean(fullName); String name = scopeBean.name(); @@ -198,16 +199,16 @@ public class ContextUtility { Map map = new HashMap<>(); map.put("name", name); - OResultSet resultSet = oDatabaseDocument.query(select, map); + ResultSet resultSet = database.command("sql", select, map); if(resultSet == null || !resultSet.hasNext()) { throw new ContextNotFoundException("Error retrieving context with name " + fullName); } - OResult oResult = resultSet.next(); - OVertex context = ElementManagementUtility.getElementFromOptional(oResult.getVertex()); + Result result = resultSet.next(); + 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()) { throw new ContextNotFoundException("Found more than one context with name " + name diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/entities/ContextManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/entities/ContextManagement.java index bbd34bd..7ce0367 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/entities/ContextManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/entities/ContextManagement.java @@ -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.queries.operators.QueryConditionalOperator; 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.types.reference.entities.EntityType; import org.gcube.informationsystem.utils.UUIDManager; @@ -41,12 +41,12 @@ import org.gcube.informationsystem.utils.UUIDUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OVertex; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.executor.OResultSet; +import com.arcadedb.database.Document; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.query.sql.executor.ResultSet; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -70,9 +70,9 @@ public class ContextManagement extends EntityElementManagement {}", errorMessage, select); - OResultSet resultSet = oDatabaseDocument.command(select.toString(), new HashMap<>()); + ResultSet resultSet = database.command("sql", select.toString(), new HashMap<>()); if (resultSet != null && resultSet.hasNext()) { throw new ContextAlreadyPresentException(errorMessage.toString()); @@ -180,13 +180,13 @@ public class ContextManagement extends EntityElementManagement parents = getElement().getEdges(ODirection.IN); - for (OEdge edge : parents) { + Iterable parents = getElement().getEdges(DIRECTION.IN); + for (Edge edge : parents) { if (++count > 1) { throw new ContextException("A " + Context.NAME + " can not have more than one parent"); } try { - IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument); + IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database); isParentOfManagement.setElement(edge); isParentOfManagement.includeSource(true); isParentOfManagement.includeTarget(false); @@ -195,24 +195,24 @@ public class ContextManagement extends EntityElementManagement childrenEdges = getElement().getEdges(ODirection.OUT); - for (OEdge edge : childrenEdges) { + Iterable childrenEdges = getElement().getEdges(DIRECTION.OUT); + for (Edge edge : childrenEdges) { - IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument); + IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database); isParentOfManagement.setElement(edge); try { JsonNode isParentOf = isParentOfManagement.serializeAsJsonNode(); context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY); } 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; } 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); } } @@ -221,7 +221,7 @@ public class ContextManagement extends EntityElementManagement iterable = getElement().getVertices(ODirection.IN, IsParentOf.NAME); - for (OVertex p : iterable) { + Iterable iterable = getElement().getVertices(DIRECTION.IN, IsParentOf.NAME); + for (Vertex p : iterable) { if (found) { 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()); } parent = p; @@ -297,7 +297,7 @@ public class ContextManagement extends EntityElementManagement edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME); + Iterable edges = getElement().getEdges(DIRECTION.IN, IsParentOf.NAME); if (edges != null && edges.iterator().hasNext()) { - Iterator edgeIterator = edges.iterator(); - OEdge edge = edgeIterator.next(); + Iterator edgeIterator = edges.iterator(); + Edge edge = edgeIterator.next(); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(); isParentOfManagement.setElement(edge); isParentOfManagement.internalDelete(); if (edgeIterator.hasNext()) { 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) { JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); - IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument); + IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database); isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setSourceEntityManagement(newParentContextManagement); isParentOfManagement.setTargetEntityManagement(this); @@ -388,13 +388,13 @@ public class ContextManagement extends EntityElementManagement iterable = getElement().getEdges(ODirection.OUT); - Iterator iterator = iterable.iterator(); + Iterable iterable = getElement().getEdges(DIRECTION.OUT); + Iterator iterator = iterable.iterator(); while (iterator.hasNext()) { throw new ContextException("Cannot remove a " + Context.NAME + " having children"); } @@ -403,7 +403,7 @@ public class ContextManagement extends EntityElementManagement iterable = oDatabaseDocument.browseClass(typeName, polymorphic); - for (ODocument vertex : iterable) { + Iterable iterable = database.browseClass(typeName, polymorphic); + for (Document vertex : iterable) { ContextManagement contextManagement = new ContextManagement(); contextManagement.setForceIncludeMeta(forceIncludeMeta); contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta); - contextManagement.setElement((OVertex) vertex); + contextManagement.setElement((Vertex) vertex); try { JsonNode jsonObject = contextManagement.serializeAsJsonNode(); arrayNode.add(jsonObject); } catch (ResourceRegistryException e) { 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 { diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/relations/IsParentOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/relations/IsParentOfManagement.java index 6c72e09..0173ee5 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/relations/IsParentOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/contexts/relations/IsParentOfManagement.java @@ -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.SecurityContext; 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 com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.remote.RemoteDatabase; + /** * @author Luca Frosini (ISTI - CNR) @@ -34,9 +35,9 @@ public class IsParentOfManagement extends RelationElementManagement> poolMap; + protected final Map> databasesMap; protected SecurityContext parentSecurityContext; @@ -120,8 +124,8 @@ public class SecurityContext { return this.children; } - protected ODatabaseDocument getAdminDatabaseDocument() throws ResourceRegistryException { - return ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER); + protected RemoteDatabase getAdminDatabaseDocument() throws ResourceRegistryException { + return ContextUtility.getAdminSecurityContext().getRemoteDatabase(PermissionMode.WRITER); } /** @@ -158,7 +162,7 @@ public class SecurityContext { * @param orientGraph * @throws ResourceRegistryException */ - public void changeParentSecurityContext(SecurityContext newParentSecurityContext, ODatabaseDocument orientGraph) throws ResourceRegistryException { + public void changeParentSecurityContext(SecurityContext newParentSecurityContext, RemoteDatabase database) throws ResourceRegistryException { if(!hierarchical) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Cannot change parent "); @@ -166,13 +170,13 @@ public class SecurityContext { errorMessage.append(" to non hierarchic "); errorMessage.append(SecurityContext.class.getSimpleName()); errorMessage.append(". "); - errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); final String error = errorMessage.toString(); logger.error(error); throw new RuntimeException(error); } - OSecurity oSecurity = getOSecurity(orientGraph); +// OSecurity oSecurity = getOSecurity(database); Set allChildren = getAllChildren(); @@ -191,19 +195,19 @@ public class SecurityContext { * */ oldParents.removeAll(newParents); - removeChildrenHRolesFromParents(oSecurity, oldParents, allChildren); + removeChildrenHRolesFromParents(database, oldParents, allChildren); setParentSecurityContext(newParentSecurityContext); if(newParentSecurityContext!=null){ for(PermissionMode permissionMode : PermissionMode.values()) { - List roles = new ArrayList<>(); + List roles = new ArrayList<>(); for(SecurityContext child : allChildren) { String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true); - ORole role = oSecurity.getRole(roleName); + Role role = database.getRole(roleName); 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 { this.context = context; - this.poolMap = new HashMap<>(); + this.databasesMap = new HashMap<>(); this.hierarchical = hierarchical; this.children = new HashSet<>(); } @@ -220,38 +224,38 @@ public class SecurityContext { this(context, true); } - private synchronized ODatabasePool getPool(PermissionMode permissionMode, boolean recreate) { - ODatabasePool pool = null; + private synchronized RemoteDatabase getPool(PermissionMode permissionMode, boolean recreate) { + RemoteDatabase db = null; Boolean h = isHierarchicalMode(); - Map pools = poolMap.get(h); - if(pools == null) { - pools = new HashMap<>(); - poolMap.put(h, pools); + Map databases = databasesMap.get(h); + if(databases == null) { + databases = new HashMap<>(); + databasesMap.put(h, databases); } else { if(recreate) { - pool = pools.get(permissionMode); - if(pool!=null) { - pool.close(); - pools.remove(permissionMode); + db = databases.get(permissionMode); + if(db!=null) { + db.close(); + 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 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() { @@ -283,16 +287,12 @@ public class SecurityContext { return stringBuilder.toString(); } - private OSecurity getOSecurity(ODatabaseDocument oDatabaseDocument) { - return oDatabaseDocument.getMetadata().getSecurity(); - } - - public static Set getContexts(OElement element) { + public static Set getContexts(Document element) { Set contexts = new HashSet<>(); ORecordLazySet oRecordLazySet = element.getProperty(OSecurity.ALLOW_ALL_FIELD); - for (OIdentifiable oIdentifiable : oRecordLazySet) { - ODocument oDocument = (ODocument) oIdentifiable; - String name = oDocument.getProperty("name"); + for (Identifiable identifiable : oRecordLazySet) { + Document oDocument = (Document) identifiable; + String name = oDocument.getString("name"); if (name.startsWith(getRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE)) || name.startsWith(getRoleOrUserName(PermissionMode.READER, SecurityType.ROLE))) { String[] list = name.split("_"); @@ -308,111 +308,104 @@ public class SecurityContext { } - public void addElement(OElement element) throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument adminDatabaseDocument = null; + public void addElement(Document element) throws ResourceRegistryException { + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase adminDatabase = null; try { - adminDatabaseDocument = getAdminDatabaseDocument(); - addElement(element, adminDatabaseDocument); + adminDatabase = getAdminDatabaseDocument(); + addElement(element, adminDatabase); }finally { - if(adminDatabaseDocument!=null) { - adminDatabaseDocument.close(); + if(adminDatabase!=null) { + adminDatabase.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// 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); - oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName); + + oSecurity.allowRole(document, RestrictedOperation.ALLOW_ALL, writerRoleName); + 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 { - ORID orid = element.getIdentity(); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument contextODatabaseDocument = null; + public boolean isElementInContext(final Document element) throws ResourceRegistryException { + RID rid = element.getIdentity(); + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { - contextODatabaseDocument = getDatabaseDocument(PermissionMode.READER); + database = getRemoteDatabase(PermissionMode.READER); - ORecord oRecord = contextODatabaseDocument.getRecord(orid); - if(oRecord==null) { - return false; - } - return true; + return database.existsRecord(rid); } finally { - if(contextODatabaseDocument!=null) { - contextODatabaseDocument.close(); + if(database!=null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } - public void addElement(OElement element, ODatabaseDocument oDatabaseDocument) { - ODocument oDocument = element.getRecord(); - OSecurity oSecurity = getOSecurity(oDatabaseDocument); - allow(oSecurity, oDocument, false); + public void addElement(Document document, RemoteDatabase database) { + allow(database, document, false); if(hierarchical) { - allow(oSecurity, oDocument, true); + allow(database, document, true); } - oDocument.save(); - element.save(); +// document.save(); } - public void removeElement(OElement element) throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument adminDatabaseDocument = null; + public void removeElement(Document document) throws ResourceRegistryException { + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase adminDatabase = null; try { - adminDatabaseDocument = getAdminDatabaseDocument(); - removeElement(element, adminDatabaseDocument); + adminDatabase = getAdminDatabaseDocument(); + removeElement(document, adminDatabase); }finally { - if(adminDatabaseDocument!=null) { - adminDatabaseDocument.close(); + if(adminDatabase!=null) { + adminDatabase.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// 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 // context is allowed by default because it was the creator 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); - oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName); + oSecurity.denyUser(document, RestrictedOperation.ALLOW_READ, readerUserName); 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); - oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); + oSecurity.denyRole(document, RestrictedOperation.ALLOW_READ, readerRoleName); } - public void removeElement(OElement element, ODatabaseDocument oDatabaseDocument) { - ODocument oDocument = element.getRecord(); - OSecurity oSecurity = getOSecurity(oDatabaseDocument); - deny(oSecurity, oDocument, false); + public void removeElement(Document document, RemoteDatabase database) { + deny(database, document, false); if(hierarchical) { - deny(oSecurity, oDocument, true); + deny(database, document, true); } - oDocument.save(); - element.save(); +// document.save(); } - protected boolean allowed(final ORole role, final ODocument oDocument) { + protected boolean allowed(final ORole role, final Document document) { ExecutorService executor = Executors.newSingleThreadExecutor(); @@ -422,26 +415,22 @@ public class SecurityContext { public Boolean call() throws Exception { RequestUtility.getRequestInfo().get().setHierarchicalMode(false); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { - oDatabaseDocument = getDatabaseDocument(PermissionMode.READER); - oDatabaseDocument.activateOnCurrentThread(); - ORecord element = oDatabaseDocument.getRecord(oDocument.getIdentity()); - if(element == null) { - return false; - } - return true; + database = getRemoteDatabase(PermissionMode.READER); + // database.activateOnCurrentThread(); + return database.existsRecord(document.getIdentity()); } catch(Exception e) { return false; } finally { - if(oDatabaseDocument!=null) { - oDatabaseDocument.close(); + if(database!=null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -456,48 +445,48 @@ public class SecurityContext { } public void create() throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument adminDatabaseDocument = null; + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase adminDatabase = null; try { - adminDatabaseDocument = getAdminDatabaseDocument(); + adminDatabase = getAdminDatabaseDocument(); - create(adminDatabaseDocument); + create(adminDatabase); - adminDatabaseDocument.commit(); + adminDatabase.commit(); } finally { - if(adminDatabaseDocument!=null) { - adminDatabaseDocument.close(); + if(adminDatabase!=null) { + adminDatabase.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } - protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { + protected Role addExtraRules(Role role, PermissionMode permissionMode) { return role; } - protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) { + protected Role getSuperRole(RemoteDatabase database, PermissionMode permissionMode) { 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); - OUser user = oSecurity.getUser(userName); - for(ORole role : roles) { + User user = database.getUser(userName); + for(Role role : roles) { user.addRole(role); } user.save(); 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; if(hierarchical) { booleanArray = new boolean[] {false, true}; @@ -507,20 +496,20 @@ public class SecurityContext { for(boolean hierarchical : booleanArray) { for(PermissionMode permissionMode : PermissionMode.values()) { - ORole superRole = getSuperRole(oSecurity, permissionMode); + Role superRole = getSuperRole(database, permissionMode); 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); role.save(); logger.trace("{} created", role); if(hierarchical && getParentSecurityContext() != null) { - getParentSecurityContext().addHierarchicalRoleToParent(oSecurity, permissionMode, role); + getParentSecurityContext().addHierarchicalRoleToParent(database, permissionMode, role); } 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); user.save(); logger.trace("{} created", user); @@ -529,70 +518,64 @@ public class SecurityContext { } - public void create(ODatabaseDocument oDatabaseDocument) { - OSecurity oSecurity = getOSecurity(oDatabaseDocument); - createRolesAndUsers(oSecurity); + public void create(RemoteDatabase database) { + createRolesAndUsers(database); logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); } - private void drop(OSecurity oSecurity, String name, SecurityType securityType) { - boolean dropped = false; + private void drop(RemoteDatabase database, String name, SecurityType securityType) { switch(securityType) { case ROLE: - dropped = oSecurity.dropRole(name); + database.dropRole(name); break; case USER: - dropped = oSecurity.dropUser(name); + database.dropUser(name); break; default: break; } - if(dropped) { - logger.trace("{} successfully dropped", name); - } else { - logger.error("{} was not dropped successfully", name); - } + logger.trace("{} successfully dropped", name); } public void delete() throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument adminDatabaseDocument = null; + RemoteDatabase remoteDatabase = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { - adminDatabaseDocument = getAdminDatabaseDocument(); + database = getAdminDatabaseDocument(); - delete(adminDatabaseDocument); + delete(database); - adminDatabaseDocument.commit(); + database.commit(); } finally { - if(adminDatabaseDocument!=null) { - adminDatabaseDocument.close(); + if(database!=null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } - protected void removeChildrenHRolesFromParents(OSecurity oSecurity) { + protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase) { Set parents = getAllParents(); Set allChildren = getAllChildren(); - removeChildrenHRolesFromParents(oSecurity, parents, allChildren); + removeChildrenHRolesFromParents(remoteDatabase, parents, allChildren); } - protected void removeChildrenHRolesFromParents(OSecurity oSecurity, Set parents, Set children) { + protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase, Set parents, Set children) { for(SecurityContext parent : parents) { - parent.removeChildrenHRolesFromMyHUsers(oSecurity, children); + parent.removeChildrenHRolesFromMyHUsers(remoteDatabase, children); } } - protected void removeChildrenHRolesFromMyHUsers(OSecurity oSecurity, Set children) { + protected void removeChildrenHRolesFromMyHUsers(RemoteDatabase database, Set children) { for(PermissionMode permissionMode : PermissionMode.values()) { String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true); - OUser user = oSecurity.getUser(userName); + User user = database.getUser(userName); for(SecurityContext child : children) { String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true); 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); - OUser user = oSecurity.getUser(userName); + User user = database.getUser(userName); logger.debug("Going to remove {} from {}", roleName, userName); boolean removed = user.removeRole(roleName); logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName); user.save(); } - protected void deleteRolesAndUsers(OSecurity oSecurity) { + protected void deleteRolesAndUsers(RemoteDatabase remoteDatabase) { boolean[] booleanArray; if(hierarchical) { booleanArray = new boolean[] {false, true}; @@ -622,47 +605,45 @@ public class SecurityContext { } for(boolean hierarchic : booleanArray) { if(hierarchic) { - removeChildrenHRolesFromParents(oSecurity); + removeChildrenHRolesFromParents(remoteDatabase); } for(PermissionMode permissionMode : PermissionMode.values()) { for(SecurityType securityType : SecurityType.values()) { String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic); - drop(oSecurity, name, securityType); + drop(remoteDatabase, name, securityType); } } } } - public void delete(ODatabaseDocument orientGraph) { - OSecurity oSecurity = getOSecurity(orientGraph); - delete(oSecurity); - } - - private void delete(OSecurity oSecurity) { + public void delete(RemoteDatabase remoteDatabase) { +// OSecurity oSecurity = getOSecurity(orientGraph); 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()); } - public ODatabaseDocument getDatabaseDocument(PermissionMode permissionMode) throws ResourceRegistryException { - try { - ODatabasePool oDatabasePool = getPool(permissionMode, false); - ODatabaseSession oDatabaseSession = null; - try { - oDatabaseSession = oDatabasePool.acquire(); - if(oDatabaseSession.isClosed()) { - // Enforcing pool recreation - throw new Exception(); - } - }catch (Exception e) { - oDatabasePool = getPool(permissionMode, true); - oDatabaseSession = oDatabasePool.acquire(); - } - oDatabaseSession.activateOnCurrentThread(); - return oDatabaseSession; - }catch (Exception e) { - throw new ResourceRegistryException(e); - } + public RemoteDatabase getRemoteDatabase(PermissionMode permissionMode) throws ResourceRegistryException { +// try { +// ODatabasePool oDatabasePool = getPool(permissionMode, false); +// ODatabaseSession oDatabaseSession = null; +// try { +// oDatabaseSession = oDatabasePool.acquire(); +// if(oDatabaseSession.isClosed()) { +// // Enforcing pool recreation +// throw new Exception(); +// } +// }catch (Exception e) { +// oDatabasePool = getPool(permissionMode, true); +// oDatabaseSession = oDatabasePool.acquire(); +// } +// oDatabaseSession.activateOnCurrentThread(); +// return oDatabaseSession; +// }catch (Exception e) { +// throw new ResourceRegistryException(e); +// } + + return null; } @Override diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java index 281e80b..2714324 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java @@ -45,22 +45,8 @@ import org.gcube.informationsystem.types.reference.relations.RelationType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY; -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; +import com.arcadedb.database.Document; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -71,12 +57,13 @@ public class DatabaseEnvironment { protected static final String PROPERTY_FILENAME = "config.properties"; + public static final String HOST; private static final String HOST_VARNAME = "HOST"; - private static final String REMOTE_PROTOCOL; - private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL"; + public static final int PORT; + 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 ROOT_USERNAME; @@ -87,36 +74,25 @@ public class DatabaseEnvironment { public static final String DEFAULT_ADMIN_ROLE = "admin"; - private static final String CHANGED_ADMIN_USERNAME; - private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME"; + private static final String ADMIN_USERNAME; + private static final String ADMIN_USERNAME_VARNAME = "ADMIN_USERNAME"; - private static final String CHANGED_ADMIN_PASSWORD; - private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD"; + private static final String ADMIN_PASSWORD; + private static final String ADMIN_PASSWORD_VARNAME = "ADMIN_PASSWORD"; - private static final String DEFAULT_CREATED_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; + private static final String WRITER_USER_PASSWORD_VARNAME = "WRITER_USER_PASSWORD"; - private static final String DEFAULT_CREATED_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; + private static final String READER_USER_PASSWORD_VARNAME = "READER_USER_PASSWORD"; public static final Map 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_ALGORITHM_VARNAME = "DB_KEY_ALGORITHM"; 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 { Properties properties = new Properties(); InputStream input = null; @@ -128,41 +104,25 @@ public class DatabaseEnvironment { // load a properties file 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); - SERVER_URI = REMOTE_PROTOCOL + HOSTS; - DB_URI = SERVER_URI + "/" + DB; ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME); ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME); - String changedAdminUsername = null; - try { - 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; + ADMIN_USERNAME = properties.getProperty(ADMIN_USERNAME_VARNAME); + ADMIN_PASSWORD = properties.getProperty(ADMIN_PASSWORD_VARNAME); - CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_ADMIN_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); + WRITER_USER_PASSWORD = properties.getProperty(WRITER_USER_PASSWORD_VARNAME); + READER_USER_PASSWORD = properties.getProperty(READER_USER_PASSWORD_VARNAME); DEFAULT_PASSWORDS = new HashMap(); - DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD); - DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD); + DEFAULT_PASSWORDS.put(PermissionMode.WRITER, WRITER_USER_PASSWORD); + DEFAULT_PASSWORDS.put(PermissionMode.READER, READER_USER_PASSWORD); } catch(Throwable e) { logger.error("Unable to load properties from {}", PROPERTY_FILENAME); @@ -172,16 +132,15 @@ public class DatabaseEnvironment { // Used to Persist Context and their relations 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) { - ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME, - CHANGED_ADMIN_PASSWORD); - ODatabaseDocument oDatabaseDocument = pool.acquire(); - AdminSecurityContext.getInstance().create(oDatabaseDocument); - oDatabaseDocument.commit(); - oDatabaseDocument.close(); - pool.close(); + + AdminSecurityContext.getInstance().create(database); QueryTemplatesSecurityContext.getInstance().create(); TypeSecurityContext.getInstance().create(); @@ -236,7 +195,7 @@ public class DatabaseEnvironment { schemaToBeCreated.add(Property.class); schemaToBeCreated.add(Metadata.class); for(Class clazz : schemaToBeCreated) { - ElementManagement erManagement = new PropertyTypeDefinitionManagement(); + ElementManagement erManagement = new PropertyTypeDefinitionManagement(); erManagement.setJson(TypeMapper.serializeType(clazz)); erManagement.create(); } @@ -310,15 +269,15 @@ public class DatabaseEnvironment { } } - protected static void setDateTimeFormat(ODatabaseDocument oDatabaseDocument) { - oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, Element.DATETIME_PATTERN); + protected static void setDateTimeFormat(RemoteDatabase database) { + // TODO + // oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, Element.DATETIME_PATTERN); } - @Deprecated - // This code must be removed for OrientDB versions higher than 3.2.X - 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)"); + protected static void setRecordLevelSecurity(RemoteDatabase database) { + logger.trace("Setting Record-level Security"); + + /* OSchema oSchema = oMetadata.getSchema(); OClass oRestricted = oSchema.getClass(OSecurity.RESTRICTED_CLASSNAME); @@ -327,51 +286,41 @@ public class DatabaseEnvironment { OClass e = oSchema.getClass(EDGE_CLASS_NAME); e.addSuperClass(oRestricted); + */ } - private static boolean initGraphDB() throws Exception { - OLogManager.instance().setWarnEnabled(false); - OLogManager.instance().setErrorEnabled(false); - OLogManager.instance().setInfoEnabled(false); - OLogManager.instance().setDebugEnabled(false); + private static boolean initGraphDB(RemoteDatabase database) throws Exception { + + - logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI); - OrientDB orientDB = new OrientDB(SERVER_URI, ROOT_USERNAME, ROOT_PASSWORD, OrientDBConfig.defaultConfig()); try { - if(!orientDB.exists(DB)) { + if(!!database.exists()) { - logger.info("The database {} does not exist. Going to create it.", DB_URI); - orientDB.create(DB, ODatabaseType.PLOCAL); + logger.info("The database {} does not exist. Going to create it.", DB); + database.create(); - ODatabasePool pool = new ODatabasePool(orientDB, DB, ROOT_USERNAME, ROOT_PASSWORD); - ODatabaseSession oDatabaseSession = pool.acquire(); + DatabaseEnvironment.setDateTimeFormat(database); - DatabaseEnvironment.setDateTimeFormat(oDatabaseSession); + List databases = new ArrayList<>(); + databases.add(DB); - OMetadata oMetadata = oDatabaseSession.getMetadata(); - OSecurity oSecurity = oMetadata.getSecurity(); + // TODO Create Role +// 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); - 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(); + database.commit(); return true; } return false; } finally { - orientDB.close(); + database.close(); } } @@ -379,28 +328,4 @@ public class DatabaseEnvironment { 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()); - } - } - } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagement.java index 97ece1e..49426b3 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagement.java @@ -30,7 +30,6 @@ import org.gcube.informationsystem.base.reference.Element; import org.gcube.informationsystem.base.reference.IdentifiableElement; import org.gcube.informationsystem.model.reference.ERElement; 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.resourceregistry.api.exceptions.AlreadyPresentException; 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.utils.MetadataOrient; 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.types.reference.Type; 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.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.metadata.schema.OProperty; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.util.ODateHelper; +import com.arcadedb.database.Document; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.remote.RemoteDatabase; +import com.arcadedb.schema.DocumentType; +import com.arcadedb.schema.Property; /** * @author Luca Frosini (ISTI - CNR) */ -public abstract class ElementManagement { +public abstract class ElementManagement { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @@ -89,11 +87,12 @@ public abstract class ElementManagement { protected Class elementClass; protected final AccessType accessType; - protected ODatabaseDocument oDatabaseDocument; + protected RemoteDatabase database; protected UUID uuid; protected JsonNode jsonNode; - protected OClass oClass; +// protected OClass documentType; + protected DocumentType documentType; protected String typeName; protected JsonNode self; @@ -182,6 +181,19 @@ public abstract class ElementManagement { this.forceIncludeMeta = 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() { return forceIncludeMeta; @@ -278,28 +290,24 @@ public abstract class ElementManagement { checkJsonNode(); } - public void setODatabaseDocument(ODatabaseDocument oDatabaseDocument) { - this.oDatabaseDocument = oDatabaseDocument; + public void setDatabase(RemoteDatabase remoteDatabase) { + this.database = remoteDatabase; } - public void setOClass(OClass oClass) { - this.oClass = oClass; - } - - protected OClass getOClass() throws SchemaException, ResourceRegistryException { - if(oClass == null) { + protected DocumentType getDocumentType() throws SchemaException, ResourceRegistryException { + if(documentType == null) { if(element != null) { try { - oClass = ElementManagementUtility.getOClass(element); + documentType = ElementManagementUtility.getDocumentType(element); if(typeName==null) { - typeName = oClass.getName(); + typeName = documentType.getName(); } - getCachedType().setOClass(oClass); + getCachedType().setDocumentType(documentType); }catch (ResourceRegistryException e) { try { - oClass = getCachedType().getOClass(); + documentType = getCachedType().getDocumentType(); if(typeName==null) { - typeName = oClass.getName(); + typeName = documentType.getName(); } }catch (Exception e1) { throw e; @@ -309,14 +317,14 @@ public abstract class ElementManagement { if(typeName==null) { throw new SchemaException("Unknown type name. Please set it first."); } - oClass = getCachedType().getOClass(); + documentType = getCachedType().getDocumentType(); AccessType gotAccessType = cachedType.getAccessType(); if(accessType!=gotAccessType) { throw new SchemaException(typeName + " is not a " + accessType.getName()); } } } - return oClass; + return documentType; } @SuppressWarnings("unchecked") @@ -349,7 +357,7 @@ public abstract class ElementManagement { public String getTypeName() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { if(typeName==null) { if(element!=null) { - typeName = getOClass().getName(); + typeName = getDocumentType().getName(); } if(typeName==null && jsonNode!=null) { @@ -380,7 +388,7 @@ public abstract class ElementManagement { if(this.typeName == null) { this.typeName = TypeUtility.getTypeName(jsonNode); - getOClass(); + getDocumentType(); } else { checkERMatch(); } @@ -396,7 +404,7 @@ public abstract class ElementManagement { throw new ResourceRegistryException(error); } } - getOClass(); + getDocumentType(); } @@ -414,8 +422,8 @@ public abstract class ElementManagement { } } - private void analizeProperty(OElement element, String key, ObjectNode objectNode) throws ResourceRegistryException { - Object object = element.getProperty(key); + private void analizeProperty(Document element, String key, ObjectNode objectNode) throws ResourceRegistryException { + Object object = element.get(key); if(object == null) { objectNode.replace(key, null); return; @@ -432,7 +440,7 @@ public abstract class ElementManagement { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode objectNode = objectMapper.createObjectNode(); - OElement element = getElement(); + El element = getElement(); Set keys = element.getPropertyNames(); /* Add first these key to provide an order in Json */ @@ -539,13 +547,13 @@ public abstract class ElementManagement { element = reallyCreate(); - element.setProperty(IdentifiableElement.ID_PROPERTY, uuid.toString()); + ((MutableDocument) element).set(IdentifiableElement.ID_PROPERTY, uuid.toString()); MetadataUtility.addMetadata(element); - getWorkingContext().addElement(element, oDatabaseDocument); + getWorkingContext().addElement(element, database); - element.save(); +// element.save(); sanityCheck(); @@ -567,7 +575,7 @@ public abstract class ElementManagement { MetadataUtility.updateModifiedByAndLastUpdate(element); - element.save(); +// element.save(); sanityCheck(); @@ -601,8 +609,8 @@ public abstract class ElementManagement { } this.element = element; this.uuid = UUIDUtility.getUUID(element); - OClass oClass = getOClass(); - this.typeName = oClass.getName(); + DocumentType documentType = getDocumentType(); + this.typeName = documentType.getName(); } protected abstract NotFoundException getSpecificNotFoundException(NotFoundException e); @@ -634,7 +642,7 @@ public abstract class ElementManagement { if(uuid == null) { 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); } catch(NotFoundException e) { throw getSpecificNotFoundException(e); @@ -647,7 +655,7 @@ public abstract class ElementManagement { public El retrieveElementFromAnyContext() throws NotFoundException, ResourceRegistryException { try { - return OrientDBUtility.getElementByUUIDAsAdmin(typeName == null ? accessType.getName() : typeName, uuid, + return DBUtility.getElementByUUIDAsAdmin(typeName == null ? accessType.getName() : typeName, uuid, elementClass); } catch(NotFoundException e) { throw getSpecificNotFoundException(e); @@ -661,9 +669,9 @@ public abstract class ElementManagement { public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException; public String all(boolean polymorphic) throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); + database = getWorkingContext().getRemoteDatabase(PermissionMode.READER); setAsEntryPoint(); setOperation(Operation.QUERY); return reallyGetAll(polymorphic); @@ -672,20 +680,19 @@ public abstract class ElementManagement { } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); - } - - if(current!=null) { - current.activateOnCurrentThread(); + if(database != null) { + database.close(); } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); + database = getWorkingContext().getRemoteDatabase(PermissionMode.READER); setAsEntryPoint(); setOperation(Operation.EXISTS); @@ -699,22 +706,22 @@ public abstract class ElementManagement { logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e); throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// database.activateOnCurrentThread(); +// } } } public String createOrUpdate() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER); + database.begin(); boolean update = false; try { setAsEntryPoint(); @@ -729,7 +736,7 @@ public abstract class ElementManagement { internalCreate(); } - oDatabaseDocument.commit(); + database.commit(); if(update) { setReload(true); @@ -741,38 +748,37 @@ public abstract class ElementManagement { } catch(ResourceRegistryException e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } public String create() throws AlreadyPresentException, ResourceRegistryException { - - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER); + database.begin(); setAsEntryPoint(); internalCreate(); - oDatabaseDocument.commit(); + database.commit(); // TODO Notify to subscriptionNotification @@ -780,32 +786,31 @@ public abstract class ElementManagement { } catch(ResourceRegistryException e) { logger.error("Unable to create {}", accessType.getName()); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { logger.error("Unable to create {}", accessType.getName(), e); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } public String read() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { - - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); + database = getWorkingContext().getRemoteDatabase(PermissionMode.READER); setAsEntryPoint(); setOperation(Operation.READ); @@ -820,27 +825,26 @@ public abstract class ElementManagement { logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e); throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { - - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER); + database.begin(); setAsEntryPoint(); internalUpdate(); - oDatabaseDocument.commit(); + database.commit(); setReload(true); @@ -850,74 +854,74 @@ public abstract class ElementManagement { } catch(ResourceRegistryException e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } public void delete() throws NotFoundException, AvailableInAnotherContextException, SchemaViolationException, ResourceRegistryException { logger.trace("Going to delete {} instance with UUID {}", accessType.getName(), uuid); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { // oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = getWorkingContext().getRemoteDatabase(PermissionMode.WRITER); + database.begin(); setAsEntryPoint(); internalDelete(); if(!dryRun) { - oDatabaseDocument.commit(); + database.commit(); logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid); }else { - oDatabaseDocument.rollback(); + database.rollback(); } } catch(ResourceRegistryException e) { logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } public Set getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException { logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); +// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); + database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER); setAsEntryPoint(); setOperation(Operation.GET_METADATA); @@ -931,13 +935,13 @@ public abstract class ElementManagement { logger.error("Unable to get contexts for {} with UUID {}", typeName, uuid, e); throw new ContextException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -1071,39 +1075,40 @@ public abstract class ElementManagement { return map; } - public void setProperty(OProperty oProperty, String key, JsonNode value) throws Exception { - switch (oProperty.getType()) { + public void setProperty(Property property, String key, JsonNode value) throws Exception { + + switch (property.getType()) { case EMBEDDED: - ODocument oDocument = PropertyElementManagement.getPropertyDocument(value); - element.setProperty(key, oDocument, OType.EMBEDDED); + Document document = PropertyElementManagement.getPropertyDocument(value); + ((MutableDocument) element).set(key, document, com.arcadedb.schema.Type.EMBEDDED); break; - case EMBEDDEDLIST: + case LIST: List list = new ArrayList(); Iterator arrayElement = value.elements(); while(arrayElement.hasNext()) { JsonNode elementOfArray = arrayElement.next(); Object object = null; - if(oProperty.getLinkedType()!=null) { + if(property.getLinkedType()!=null) { object = getObjectFromJsonNode(elementOfArray); }else { object = PropertyElementManagement.getPropertyDocument(elementOfArray); } list.add(object); } - element.setProperty(key, list, OType.EMBEDDEDLIST); + ((MutableDocument) element).set(key, list, com.arcadedb.schema.Type.LIST); break; - case EMBEDDEDSET: + case SET: Set set = new HashSet(); Iterator setElement = value.elements(); while(setElement.hasNext()) { JsonNode elementOfSet = setElement.next(); Object object = null; - if(oProperty.getLinkedType()!=null) { + if(property.getLinkedType()!=null) { object = getObjectFromJsonNode(elementOfSet); }else { object = PropertyElementManagement.getPropertyDocument(elementOfSet); @@ -1113,41 +1118,41 @@ public abstract class ElementManagement { element.setProperty(key, set, OType.EMBEDDEDSET); break; - case EMBEDDEDMAP: + case MAP: Map map = new HashMap<>(); Iterator fieldNames = value.fieldNames(); while(fieldNames.hasNext()) { String fieldKey = fieldNames.next(); Object object = null; - if(oProperty.getLinkedType()!=null) { + if(property.getLinkedType()!=null) { object = getObjectFromJsonNode(value.get(fieldKey)); }else { object = PropertyElementManagement.getPropertyDocument(value.get(fieldKey)); } map.put(fieldKey, object); } - element.setProperty(key, map, OType.EMBEDDEDMAP); + ((MutableDocument) element).set(key, map, com.arcadedb.schema.Type.MAP); break; case STRING: if(value.getNodeType() == JsonNodeType.OBJECT) { - element.setProperty(key, value.toString()); + ((MutableDocument) element).set(key, value.toString()); }else { - element.setProperty(key, getObjectFromJsonNode(value)); + ((MutableDocument) element).set(key, getObjectFromJsonNode(value)); } break; default: Object obj = getObjectFromJsonNode(value); if(obj != null) { - element.setProperty(key, obj); + element.set(key, obj); } break; } } - public OElement updateProperties(OClass oClass, OElement element, JsonNode jsonNode, Set ignoreKeys, + public Document updateProperties(DocumentType type, Document element, JsonNode jsonNode, Set ignoreKeys, Set ignoreStartWithKeys) throws ResourceRegistryException { Set oldKeys = element.getPropertyNames(); @@ -1161,27 +1166,27 @@ public abstract class ElementManagement { oldKeys.removeAll(properties.keySet()); - getOClass(); + getDocumentType(); for(String key : properties.keySet()) { try { JsonNode value = properties.get(key); - OProperty oProperty = oClass.getProperty(key); + OProperty oProperty = type.getProperty(key); if(oProperty==null) { Object object = getObjectFromJsonNode(value); if(object != null) { - if(object instanceof ODocument) { - element.setProperty(key, object, OType.EMBEDDED); + if(object instanceof Document) { + ((MutableDocument) element).set(key, object, com.arcadedb.schema.Type.EMBEDDED); /* * Due to bug https://github.com/orientechnologies/orientdb/issues/7354 * we should not support ArrayList */ } else if(object instanceof List){ - element.setProperty(key, object, OType.EMBEDDEDLIST); + ((MutableDocument) element).set(key, object, com.arcadedb.schema.Type.LIST); } else { - element.setProperty(key, object); + ((MutableDocument) element).set(key, object); } } }else { @@ -1233,7 +1238,7 @@ public abstract class ElementManagement { if(key.compareTo(IdentifiableElement.METADATA_PROPERTY) == 0) { // Keeping the metadata MetadataOrient metadataOrient = MetadataUtility.getMetadataOrient((ODocument) object); - ObjectNode metadataJson = (ObjectNode) OrientDBUtility.toJsonNode(metadataOrient); + ObjectNode metadataJson = (ObjectNode) DBUtility.toJsonNode(metadataOrient); if(!isUserAllowedToGetPrivacyMeta()) { metadataJson.replace(Metadata.CREATED_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER)); @@ -1266,13 +1271,13 @@ public abstract class ElementManagement { } } - if(object instanceof ODocument) { - ODocument oDocument = (ODocument) object; - return PropertyElementManagement.getJsonNode(oDocument); + if(object instanceof Document) { + Document document = (Document) object; + return PropertyElementManagement.getJsonNode(document); } if(object instanceof Date) { - OProperty oProperty = getOClass().getProperty(key); + OProperty oProperty = getDocumentType().getProperty(key); OType oType = oProperty.getType(); DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance(); switch(oType) { @@ -1420,7 +1425,7 @@ public abstract class ElementManagement { if(propertyDefinition.isNotnull()) { // If the field is mandatory but null value is accepted I add the // field as null value - element.setProperty(fieldName, null); + element.set(fieldName, null); } else { throw new SchemaViolationException(getMandatoryErrorMessage(fieldName)); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagementUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagementUtility.java index c3d227c..ec71ca0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagementUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ElementManagementUtility.java @@ -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.RelationManagement; 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.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.database.Document; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.Vertex; +import com.arcadedb.remote.RemoteDatabase; +import com.arcadedb.schema.DocumentType; /** * @author Luca Frosini (ISTI - CNR) @@ -68,22 +68,22 @@ public class ElementManagementUtility { return erManagement; } - public static ElementManagement getERManagement(SecurityContext workingContext, ODatabaseDocument orientGraph, - OElement element) throws ResourceRegistryException { - if(element instanceof OVertex) { - return getEntityManagement(workingContext, orientGraph, (OVertex) element); - } else if(element instanceof OEdge) { - return getRelationManagement(workingContext, orientGraph, (OEdge) element); + public static ElementManagement getERManagement(SecurityContext workingContext, RemoteDatabase database, + Document element) throws ResourceRegistryException { + if(element instanceof Vertex) { + return getEntityManagement(workingContext, database, (Vertex) element); + } else if(element instanceof Edge) { + return getRelationManagement(workingContext, database, (Edge) element); } throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(), Entity.NAME, Relation.NAME)); } - public static OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException { + public static Document getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException { try { - return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OVertex.class); + return DBUtility.getElementByUUIDAsAdmin(null, uuid, Vertex.class); } catch(NotFoundException e) { - return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OEdge.class); + return DBUtility.getElementByUUIDAsAdmin(null, uuid, Edge.class); } catch(ResourceRegistryException e) { throw 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 { try { - return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OVertex.class); + return DBUtility.getElementByUUID(database, null, uuid, Vertex.class); } catch(NotFoundException e) { - return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OEdge.class); + return DBUtility.getElementByUUID(database, null, uuid, Edge.class); } catch(ResourceRegistryException e) { throw 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 { - OElement element; try { - element = getAnyElementByUUID(orientGraph, uuid); - return getERManagement(workingContext, orientGraph, element); + Document element = getAnyElementByUUID(database, uuid); + return getERManagement(workingContext, database, element); } catch(Exception e) { throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s", uuid.toString(), Entity.NAME, Relation.NAME)); } } - public static EntityManagement getEntityManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument, - OVertex vertex) throws ResourceRegistryException { + public static EntityManagement getEntityManagement(SecurityContext workingContext, RemoteDatabase database, + Vertex vertex) throws ResourceRegistryException { - if(oDatabaseDocument == null) { - throw new ResourceRegistryException( - ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + if(database == null) { + throw new ResourceRegistryException("Database instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } if(vertex == null) { - throw new ResourceRegistryException( - OVertex.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + throw new ResourceRegistryException(Vertex.class.getSimpleName() + " instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - OClass oClass = null; + DocumentType documentType = null; try { - oClass = ElementManagementUtility.getOClass(vertex); + documentType = ElementManagementUtility.getDocumentType(vertex); } catch(Exception e) { 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); throw new ResourceRegistryException(error); } EntityManagement entityManagement = null; - if(oClass.isSubClassOf(Resource.NAME)) { + if(documentType.isSubTypeOf(Resource.NAME)) { entityManagement = new ResourceManagement(); - } else if(oClass.isSubClassOf(Facet.NAME)) { + } else if(documentType.isSubTypeOf(Facet.NAME)) { entityManagement = new FacetManagement(); } else { 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); } - entityManagement.setODatabaseDocument(oDatabaseDocument); + entityManagement.setDatabase(database); entityManagement.setWorkingContext(workingContext); entityManagement.setElement(vertex); return entityManagement; } - public static RelationManagement getRelationManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument, - OEdge edge) throws ResourceRegistryException { + public static RelationManagement getRelationManagement(SecurityContext workingContext, RemoteDatabase database, + Edge edge) throws ResourceRegistryException { - if(oDatabaseDocument == null) { - throw new ResourceRegistryException( - ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + if(database == null) { + throw new ResourceRegistryException("Database instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } if(edge == null) { 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; - if(oClass.isSubClassOf(ConsistsOf.NAME)) { + if(documentType.isSubTypeOf(ConsistsOf.NAME)) { relationManagement = new ConsistsOfManagement(); - } else if(oClass.isSubClassOf(IsRelatedTo.NAME)) { + } else if(documentType.isSubTypeOf(IsRelatedTo.NAME)) { relationManagement = new IsRelatedToManagement(); } else { 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); } - - relationManagement.setODatabaseDocument(oDatabaseDocument); + relationManagement.setDatabase(database); relationManagement.setWorkingContext(workingContext); relationManagement.setElement(edge); return relationManagement; } - public static E getElementFromOptional(Optional optional) throws ResourceRegistryException { + public static E getElementFromOptional(Optional optional) throws ResourceRegistryException { if(optional.isPresent()) { return optional.get(); }else { @@ -197,13 +192,12 @@ public class ElementManagementUtility { } } - public static OClass getOClass(OElement oElement) throws ResourceRegistryException { - Optional optional = oElement.getSchemaType(); - if(optional.isPresent()) { - return optional.get(); - }else { + public static DocumentType getDocumentType(Document document) throws ResourceRegistryException { + DocumentType documentType = document.getType(); + if(documentType==null) { throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator."); } + return documentType; } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/entities/EntityElementManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/entities/EntityElementManagement.java index 0af2d67..8039b83 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/entities/EntityElementManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/entities/EntityElementManagement.java @@ -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.ElementManagementUtility; 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 com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.database.Document; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.MutableVertex; +import com.arcadedb.graph.Vertex; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) */ -public abstract class EntityElementManagement extends ElementManagement { +public abstract class EntityElementManagement extends ElementManagement { public final static String IN_PREFIX = "in_"; public final static String OUT_PREFIX = "out_"; @@ -52,9 +53,9 @@ public abstract class EntityElementManagement getBaseRelationManagement(OEdge edge) throws ResourceRegistryException { + protected RelationElementManagement getBaseRelationManagement(Edge edge) throws ResourceRegistryException { String id = edge.getIdentity().toString(); RelationElementManagement relationManagement = relationManagements.get(id); if(relationManagement == null) { - relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); + relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge); relationManagements.put(id, relationManagement); } return relationManagement; @@ -76,7 +77,7 @@ public abstract class EntityElementManagement baseRelationManagement) throws ResourceRegistryException { - OElement elem = baseRelationManagement.getElement(); + Document elem = baseRelationManagement.getElement(); String id = elem.getIdentity().toString(); if(relationManagements.get(id) != null && relationManagements.get(id) != baseRelationManagement) { StringBuilder errorMessage = new StringBuilder(); @@ -85,7 +86,7 @@ public abstract class EntityElementManagement> cachedType = (CachedType>) typesCache.getCachedType(type); - oClass = cachedType.getOClass(); + documentType = cachedType.getDocumentType(); AccessType gotAccessType = cachedType.getAccessType(); if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) { throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName()); @@ -112,10 +114,10 @@ public class PropertyElementManagement { * 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. */ - if(oClass.isSubClassOf(Encrypted.NAME)) { + if(documentType.isSubTypeOf(Encrypted.NAME)) { EncryptedOrient encrypted = new EncryptedOrient(); - oDocument = encrypted; - oDocument.fromJSON(jsonNode.toString()); + document = encrypted; + document.fromJSON(jsonNode.toString()); try { String contextEncryptedValue = encrypted.getEncryptedValue(); @@ -126,21 +128,21 @@ public class PropertyElementManagement { } catch(Exception e) { 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 { - 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 { - String type = oDocument.getClassName(); - String json = OrientDBUtility.toJsonString(oDocument); + String type = oDocument.getTypeName(); + String json = DBUtility.toJsonString(oDocument); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); @@ -153,7 +155,7 @@ public class PropertyElementManagement { TypesCache typesCache = TypesCache.getInstance(); @SuppressWarnings("unchecked") CachedType> cachedType = (CachedType>) typesCache.getCachedType(type); - OClass oClass = cachedType.getOClass(); + DocumentType documentType = cachedType.getDocumentType(); AccessType gotAccessType = cachedType.getAccessType(); if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) { throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName()); @@ -169,11 +171,11 @@ public class PropertyElementManagement { * The opposite operation is done when the value is set from clients. * see {@link PropertyManagement#getPropertyDocument(JsonNode) getPropertyDocument()} */ - if(oClass.isSubClassOf(Encrypted.NAME)) { + if(documentType.isSubTypeOf(Encrypted.NAME)) { try { EncryptedOrient encrypted = null; - String encryptedValue = (String) oDocument.getProperty(Encrypted.VALUE); + String encryptedValue = (String) oDocument.getString(Encrypted.VALUE); if(oDocument instanceof EncryptedOrient) { encrypted = (EncryptedOrient) oDocument; @@ -182,7 +184,7 @@ public class PropertyElementManagement { } }else { encrypted = new EncryptedOrient(); - oDocument = (ODocument) encrypted; + oDocument = (Document) encrypted; // Decrypting with DB Key Key databaseKey = DatabaseEnvironment.getDatabaseKey(); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/RelationElementManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/RelationElementManagement.java index a8a3d9e..9b26872 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/RelationElementManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/RelationElementManagement.java @@ -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.instances.base.ElementManagement; 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.relations.RelationType; import org.gcube.informationsystem.utils.UUIDUtility; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.remote.RemoteDatabase; + /** * @author Luca Frosini (ISTI - CNR) */ public abstract class RelationElementManagement, TEM extends EntityElementManagement, SET extends EntityType, TET extends EntityType> - extends ElementManagement> { + extends ElementManagement> { public final static String IN = "in"; public final static String OUT = "out"; @@ -73,15 +74,15 @@ public abstract class RelationElementManagement sourceEntityClass, Class targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) { + protected RelationElementManagement(AccessType accessType, Class sourceEntityClass, Class targetEntityClass, SecurityContext workingContext, RemoteDatabase database) { this(accessType, sourceEntityClass, targetEntityClass); - this.oDatabaseDocument = orientGraph; + this.database = database; setWorkingContext(workingContext); } public SEM getSourceEntityManagement() throws ResourceRegistryException { if(sourceEntityManagement == null) { - OVertex source = getElement().getVertex(ODirection.OUT); + Vertex source = getElement().getVertex(DIRECTION.OUT); sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement.setElement(source); } @@ -91,7 +92,7 @@ public abstract class RelationElementManagement {}", 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; } @@ -197,12 +198,12 @@ public abstract class RelationElementManagement instances = expectedInstances.keySet(); staticLogger.info("Going to add {} to Context with UUID {} not following Propagation Constraints", instances, contextUUID); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER); + database.begin(); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); @@ -46,7 +46,7 @@ public class ERManagementUtility { String type = TypeUtility.getTypeName(expectedInstances.get(uuid)); ElementManagement elementManagement = ElementManagementUtility.getERManagement(type); elementManagement.setWorkingContext(adminSecurityContext); - elementManagement.setODatabaseDocument(oDatabaseDocument); + elementManagement.setDatabase(database); elementManagement.setUUID(uuid); elementManagement.setElementType(type); elementManagement.setDryRun(dryRun); @@ -68,12 +68,12 @@ public class ERManagementUtility { /* SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.ADD); if(operationValidator.isValidOperation(enforcedInstances)) { - oDatabaseDocument.commit(); + database.commit(); } */ - oDatabaseDocument.activateOnCurrentThread(); - oDatabaseDocument.commit(); +// database.activateOnCurrentThread(); + database.commit(); staticLogger.info("{} successfully added to Context with UUID {} not following Propagation Constraints", instances, contextUUID); /* @@ -85,24 +85,24 @@ public class ERManagementUtility { return expectedInstances; } catch(ResourceRegistryException e) { staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage()); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage()); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ContextException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -110,12 +110,12 @@ public class ERManagementUtility { throws NotFoundException, ContextException, ResourceRegistryException { Set instances = expectedInstances.keySet(); staticLogger.info("Going to remove {} from Context with UUID {} not following Propagation Constraints", instances, contextUUID); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER); + database.begin(); SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID); @@ -126,7 +126,7 @@ public class ERManagementUtility { String type = TypeUtility.getTypeName(expectedInstances.get(uuid)); ElementManagement elementManagement = ElementManagementUtility.getERManagement(type); elementManagement.setWorkingContext(adminSecurityContext); - elementManagement.setODatabaseDocument(oDatabaseDocument); + elementManagement.setDatabase(database); elementManagement.setUUID(uuid); ((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false); elementManagement.setDryRun(dryRun); @@ -146,11 +146,11 @@ public class ERManagementUtility { SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.REMOVE); 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); /* @@ -162,24 +162,24 @@ public class ERManagementUtility { return expectedInstances; } catch(ResourceRegistryException e) { staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage()); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage()); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ContextException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/EntityManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/EntityManagement.java index a47e99e..b8d0899 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/EntityManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/EntityManagement.java @@ -40,19 +40,24 @@ import org.gcube.informationsystem.resourceregistry.instances.model.Operation; import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement; import org.gcube.informationsystem.resourceregistry.types.TypesCache; 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 com.arcadedb.database.Document; +import com.arcadedb.database.RID; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.MutableVertex; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; +import com.arcadedb.remote.RemoteDatabase; +import com.arcadedb.schema.DocumentType; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.record.ODirection; import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OElement; import com.orientechnologies.orient.core.record.OVertex; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.executor.OResult; -import com.orientechnologies.orient.core.sql.executor.OResultSet; /** * @author Luca Frosini (ISTI - CNR) @@ -163,7 +168,7 @@ public abstract class EntityManagement } @Override - public OVertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { + public Vertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { try { element = super.getElement(); } catch(NotFoundException e) { @@ -191,11 +196,11 @@ public abstract class EntityManagement * fake id starting with - (minus) sign. This not imply any collateral effect * 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(); RelationManagement relationManagement = relationManagements.get(id); if(relationManagement == null) { - relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); + relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge); relationManagements.put(id, relationManagement); } return relationManagement; @@ -203,7 +208,7 @@ public abstract class EntityManagement public void addToRelationManagements(RelationManagement relationManagement) throws ResourceRegistryException { - OElement elem = relationManagement.getElement(); + Edge elem = relationManagement.getElement(); String id = elem.getIdentity().toString(); if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) { StringBuilder errorMessage = new StringBuilder(); @@ -212,7 +217,7 @@ public abstract class EntityManagement errorMessage.append(" point to the same "); errorMessage.append(elem.getClass().getSimpleName()); errorMessage.append(". "); - errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(errorMessage.toString()); } relationManagements.put(id, relationManagement); @@ -236,25 +241,26 @@ public abstract class EntityManagement } @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); try { - if(oClass.isAbstract()) { - String error = String.format( - "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", - accessType.getName(), typeName); - throw new SchemaViolationException(error); - } + // TODO +// if(documentType.isAbstract()) { +// String error = String.format( +// "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", +// accessType.getName(), typeName); +// throw new SchemaViolationException(error); +// } - OVertex vertexEntity = oDatabaseDocument.newVertex(typeName); + MutableVertex vertexEntity = database.newVertex(typeName); try { if(uuid != null) { - OVertex v = getElement(); + Vertex v = getElement(); if(v != null) { String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString()); throw getSpecificAlreadyPresentException(error); @@ -263,9 +269,9 @@ public abstract class EntityManagement } catch(NotFoundException e) { 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.", - uuid.toString(), (el instanceof OVertex) ? Entity.NAME : Relation.NAME); + uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME); throw getSpecificAvailableInAnotherContextException(error); } catch(NotFoundException e1) { @@ -280,17 +286,17 @@ public abstract class EntityManagement if(accessType == AccessType.RESOURCE) { // Facet and relation are created in calling method } else { - updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); + updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys); } - logger.debug("Created {} is {}", OVertex.class.getSimpleName(), - OrientDBUtility.getAsStringForLogging((OVertex) element)); + logger.debug("Created {} is {}", Vertex.class.getSimpleName(), + DBUtility.getAsStringForLogging((Vertex) element)); return element; } catch(ResourceRegistryException e) { throw 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); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); } @@ -305,7 +311,7 @@ public abstract class EntityManagement } - targetSecurityContext.addElement(getElement(), oDatabaseDocument); + targetSecurityContext.addElement(getElement(), database); /* * DO NOT UNCOMMENT @@ -314,9 +320,9 @@ public abstract class EntityManagement * the update of Metadata i.e. modifiedBy, lastUpdateTime */ if(honourPropagationConstraintsInContextSharing) { - Iterable edges = getElement().getEdges(ODirection.OUT); + Iterable edges = getElement().getEdges(DIRECTION.OUT); - for(OEdge edge : edges) { + for(Edge edge : edges) { RelationManagement relationManagement = getRelationManagement(edge); relationManagement.setDryRun(dryRun); relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing); @@ -336,7 +342,7 @@ public abstract class EntityManagement reallyAddToContext(); if(!skipped) { MetadataUtility.updateModifiedByAndLastUpdate(element); - element.save(); +// element.save(); affectedInstances.put(uuid, serializeAsAffectedInstance()); sanityCheck(); } @@ -352,11 +358,11 @@ public abstract class EntityManagement public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException { String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID); 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 { workingContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = workingContext.getRemoteDatabase(PermissionMode.WRITER); + database.begin(); setAsEntryPoint(); sourceSecurityContext = ContextUtility.getCurrentSecurityContext(); @@ -365,31 +371,31 @@ public abstract class EntityManagement internalAddToContext(); if(!dryRun) { - oDatabaseDocument.commit(); + database.commit(); }else { - oDatabaseDocument.rollback(); + database.rollback(); } logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName); } catch(ResourceRegistryException e) { logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {}) - Reason is {}", typeName, uuid, contextUUID, contextFullName, e.getMessage()); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName, e); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ContextException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -400,7 +406,7 @@ public abstract class EntityManagement setOperation(Operation.REMOVE_FROM_CONTEXT); reallyRemoveFromContext(); MetadataUtility.updateModifiedByAndLastUpdate(element); - element.save(); +// element.save(); affectedInstances.put(uuid, serializeAsAffectedInstance()); sanityCheck(); } catch(ResourceRegistryException e) { @@ -420,9 +426,9 @@ public abstract class EntityManagement } if(honourPropagationConstraintsInContextSharing) { - Iterable edges = getElement().getEdges(ODirection.OUT); + Iterable edges = getElement().getEdges(DIRECTION.OUT); - for(OEdge edge : edges) { + for(Edge edge : edges) { RelationManagement relationManagement = getRelationManagement(edge); relationManagement.setDryRun(dryRun); relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing); @@ -434,7 +440,7 @@ public abstract class EntityManagement } } - targetSecurityContext.removeElement(getElement(), oDatabaseDocument); + targetSecurityContext.removeElement(getElement(), database); /* * DO NOT UNCOMMENT @@ -449,11 +455,11 @@ public abstract class EntityManagement throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException { logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID); - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { workingContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER); - oDatabaseDocument.begin(); + database = workingContext.getRemoteDatabase(PermissionMode.WRITER); + database.begin(); setAsEntryPoint(); // Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext(); @@ -462,32 +468,32 @@ public abstract class EntityManagement internalRemoveFromContext(); if(!dryRun) { - oDatabaseDocument.commit(); + database.commit(); }else { - oDatabaseDocument.rollback(); + database.rollback(); } logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID); } catch(ResourceRegistryException e) { logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw e; } catch(Exception e) { logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID, e); - if(oDatabaseDocument != null) { - oDatabaseDocument.rollback(); + if(database != null) { + database.rollback(); } throw new ContextException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -496,17 +502,17 @@ public abstract class EntityManagement ObjectMapper objectMapper = new ObjectMapper(); ArrayNode arrayNode = objectMapper.createArrayNode(); - Iterable iterable = oDatabaseDocument.browseClass(typeName, polymorphic); - for(ODocument vertex : iterable) { + Iterable iterable = database.browseClass(typeName, polymorphic); + for(Document vertex : iterable) { EntityManagement entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), - oDatabaseDocument, (OVertex) vertex); + database, (Vertex) vertex); try { entityManagement.setAsEntryPoint(); JsonNode jsonNode = entityManagement.serializeAsJsonNode(); arrayNode.add(jsonNode); } catch(ResourceRegistryException e) { 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 { @@ -516,13 +522,13 @@ public abstract class EntityManagement } } - 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; /* - OClass oClass = ElementManagement.getOClass(v); - OProperty oProperty = oClass.getProperty(key); + OClass documentType = ElementManagement.getOClass(v); + OProperty oProperty = documentType.getProperty(key); if(oProperty==null){ // It is an additional property return requestedValue.compareTo(instanceValue.toString())==0; @@ -544,10 +550,10 @@ public abstract class EntityManagement /* - 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 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 constraint) throws ResourceRegistryException { ObjectMapper objectMapper = new ObjectMapper(); ArrayNode arrayNode = objectMapper.createArrayNode(); @@ -555,21 +561,21 @@ public abstract class EntityManagement Iterable references = null; if(referenceUUID != null) { - OElement element = null; + Document element = null; try { - element = ElementManagementUtility.getAnyElementByUUID(oDatabaseDocument, referenceUUID); + element = ElementManagementUtility.getAnyElementByUUID(database, referenceUUID); }catch (ResourceRegistryException e) { String error = String.format("No instace with UUID %s exists", referenceUUID.toString()); throw new InvalidQueryException(error); } - if(element instanceof OVertex) { + if(element instanceof Vertex) { EntityManagement entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), - oDatabaseDocument, (OVertex) element); + database, (Vertex) element); String elementType = entityManagement.getTypeName(); if(elementType.compareTo(referenceType) != 0) { - if(polymorphic && getOClass().isSubClassOf(referenceType)) { + if(polymorphic && getDocumentType().isSubTypeOf(referenceType)) { // OK } else { String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType); @@ -577,8 +583,8 @@ public abstract class EntityManagement } } - List vertexes = new ArrayList<>(); - vertexes.add((OVertex) element); + List vertexes = new ArrayList<>(); + vertexes.add((Vertex) element); references = vertexes; } else { @@ -587,19 +593,19 @@ public abstract class EntityManagement } } else { - references = oDatabaseDocument.browseClass(referenceType, polymorphic); + references = database.browseClass(referenceType, polymorphic); } - Set analysed = new HashSet<>(); + Set analysed = new HashSet<>(); for(Object r : references) { - OVertex v = (OVertex) r; + Vertex v = (Vertex) r; boolean skip = false; // checking if the constraints are satisfied for(String key : constraint.keySet()) { String value = constraint.get(key); - Object o = v.getProperty(key); + Object o = v.get(key); if(value==null) { if(o==null) { //ok @@ -627,42 +633,42 @@ public abstract class EntityManagement } - List directions = new ArrayList<>(); - if(direction==ODirection.BOTH) { - directions.add(ODirection.IN); - directions.add(ODirection.OUT); + List directions = new ArrayList<>(); + if(direction==DIRECTION.BOTH) { + directions.add(DIRECTION.IN); + directions.add(DIRECTION.OUT); }else { directions.add(direction); } - for(ODirection d : directions) { + for(DIRECTION d : directions) { - Iterable edges = v.getEdges(d.opposite(), relationType); - for(OEdge edge : edges) { - OVertex vertex = edge.getVertex(d); + Iterable edges = v.getEdges(ElementManagement.opposite(d), relationType); + for(Edge edge : edges) { + Vertex vertex = edge.getVertex(d); - ORID vertexORID = vertex.getIdentity(); + RID vertexRID = vertex.getIdentity(); - if(analysed.contains(vertexORID)) { + if(analysed.contains(vertexRID)) { continue; } - analysed.add(vertexORID); + analysed.add(vertexRID); - if(v.getIdentity().compareTo(vertexORID) == 0) { + if(v.getIdentity().compareTo(vertexRID) == 0) { continue; } - OClass oClass = ElementManagementUtility.getOClass(vertex); + DocumentType documentType = ElementManagementUtility.getDocumentType(vertex); /* * 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 * if the resulting type is a subclass of the requested type * */ - if(oClass.getName().compareTo(typeName)!=0) { - if(polymorphic && oClass.isSubClassOf(typeName)) { + if(documentType.getName().compareTo(typeName)!=0) { + if(polymorphic && documentType.isSubTypeOf(typeName)) { // OK } else { // excluding from results @@ -673,7 +679,7 @@ public abstract class EntityManagement EntityManagement entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), - oDatabaseDocument, vertex); + database, vertex); try { if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) { @@ -684,7 +690,7 @@ public abstract class EntityManagement JsonNode jsonNode; if(includeRelationInResult) { RelationManagement relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), - oDatabaseDocument, edge); + database, edge); jsonNode = relationManagement.serializeAsJsonNode(); }else { jsonNode = entityManagement.serializeAsJsonNode(); @@ -696,7 +702,7 @@ public abstract class EntityManagement arrayNode.add(node); } catch(ResourceRegistryException e) { 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 +716,7 @@ public abstract class EntityManagement } public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID, - ODirection direction, boolean polymorphic, Map constraint) throws ResourceRegistryException { + DIRECTION direction, boolean polymorphic, Map constraint) throws ResourceRegistryException { ObjectMapper objectMapper = new ObjectMapper(); ArrayNode arrayNode = objectMapper.createArrayNode(); @@ -732,7 +738,7 @@ public abstract class EntityManagement selectStringBuilder.append("E('"); selectStringBuilder.append(relationType); selectStringBuilder.append("'), "); - selectStringBuilder.append(direction.opposite().name().toLowerCase()); + selectStringBuilder.append(ElementManagement.opposite(direction).name().toLowerCase()); selectStringBuilder.append("V('"); selectStringBuilder.append(typeName); selectStringBuilder.append("') FROM (SELECT FROM "); @@ -763,36 +769,36 @@ public abstract class EntityManagement String select = selectStringBuilder.toString(); logger.trace(select); - OResultSet resultSet = oDatabaseDocument.command(select,new HashMap<>()); + ResultSet resultSet = database.command("sql", select); while(resultSet.hasNext()) { - OResult oResult = resultSet.next(); - OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); + Result oResult = resultSet.next(); + Document element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); if(polymorphic) { - OClass oClass = null; + DocumentType documentType = null; try { - if(element instanceof OEdge) { + if(element instanceof Edge) { continue; } - oClass = ElementManagementUtility.getOClass(element); + documentType = ElementManagementUtility.getDocumentType(element); } catch(Exception e) { 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); throw new ResourceRegistryException(error); } - if(oClass.isSubClassOf(typeName)) { + if(documentType.isSubTypeOf(typeName)) { continue; } } - OVertex vertex = (OVertex) element; + Vertex vertex = (Vertex) element; EntityManagement entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(), - oDatabaseDocument, vertex); + database, vertex); try { if(constraint.containsKey(Entity.ID_PROPERTY)) { String uuid = constraint.get(Entity.ID_PROPERTY); @@ -805,7 +811,7 @@ public abstract class EntityManagement arrayNode.add(jsonNode); } catch(ResourceRegistryException e) { 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 +826,13 @@ public abstract class EntityManagement public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction, boolean polymorphic, Map 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 constraint) throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { workingContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.READER); + database = workingContext.getRemoteDatabase(PermissionMode.READER); setAsEntryPoint(); setOperation(Operation.QUERY); @@ -853,9 +859,9 @@ public abstract class EntityManagement 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, - ODirection.OUT.name(), typeName); + DIRECTION.OUT.name(), typeName); throw new InvalidQueryException(error); } else { if(referenceAccessType != AccessType.FACET) { @@ -869,10 +875,10 @@ public abstract class EntityManagement break; case FACET: - if(relationAccessType != AccessType.CONSISTS_OF || direction != ODirection.IN + if(relationAccessType != AccessType.CONSISTS_OF || direction != DIRECTION.IN || referenceAccessType != AccessType.RESOURCE) { 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); } @@ -890,12 +896,12 @@ public abstract class EntityManagement } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); - } - if(current!=null) { - current.activateOnCurrentThread(); + if(database != null) { + database.close(); } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/FacetManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/FacetManagement.java index 783ed90..05e189b 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/FacetManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/FacetManagement.java @@ -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.types.reference.entities.FacetType; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -55,14 +55,14 @@ public class FacetManagement extends EntityManagement { } @Override - protected OVertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { + protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { return createVertex(); } @Override - protected OVertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException { - OVertex facet = getElement(); - facet = (OVertex) updateProperties(oClass, facet, jsonNode, ignoreKeys, ignoreStartWithKeys); + protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException { + Vertex facet = getElement(); + facet = (Vertex) updateProperties(documentType, facet, jsonNode, ignoreKeys, ignoreStartWithKeys); return facet; } @@ -70,9 +70,9 @@ public class FacetManagement extends EntityManagement { protected void reallyRemoveFromContext() throws ContextException, ResourceRegistryException { if(entryPoint) { - OEdge oEdge = getElement().getEdges(ODirection.IN).iterator().next(); + Edge edge = getElement().getEdges(DIRECTION.IN).iterator().next(); consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setElement(oEdge); + consistsOfManagement.setElement(edge); consistsOfManagement.setTargetEntityManagement(this); // Not needed consistsOfManagement.setSourceSecurityContext(sourceSecurityContext); consistsOfManagement.setTargetSecurityContext(targetSecurityContext); @@ -80,9 +80,9 @@ public class FacetManagement extends EntityManagement { 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.setElement(oVertex); + resourceManagement.setElement(vertex); // Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.addToRelationManagements(consistsOfManagement); @@ -93,15 +93,15 @@ public class FacetManagement extends EntityManagement { @Override protected void reallyDelete() throws FacetNotFoundException, ResourceRegistryException { if(entryPoint) { - OEdge oEdge = getElement().getEdges(ODirection.IN).iterator().next(); + Edge edge = getElement().getEdges(DIRECTION.IN).iterator().next(); consistsOfManagement = new ConsistsOfManagement(); - consistsOfManagement.setElement(oEdge); + consistsOfManagement.setElement(edge); consistsOfManagement.setTargetEntityManagement(this); 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.setElement(oVertex); + resourceManagement.setElement(vertex); resourceManagement.addToRelationManagements(consistsOfManagement); } @@ -125,33 +125,33 @@ public class FacetManagement extends EntityManagement { // an update to the Facet only modify the Facet properties, no need to check the source resource return; } - ODatabaseDocument targetSecurityContextODatabaseDocument = null; + RemoteDatabase targetSecurityContextDatabase = null; try { if(resourceManagement==null) { - OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next(); + Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next(); ResourceManagement resourceManagement = new ResourceManagement(); - resourceManagement.setElement(oVertex); + resourceManagement.setElement(vertex); } switch (operation) { case CREATE: case DELETE: resourceManagement.setWorkingContext(getWorkingContext()); - resourceManagement.setODatabaseDocument(oDatabaseDocument); + resourceManagement.setDatabase(database); break; case ADD_TO_CONTEXT: resourceManagement.setSourceSecurityContext(sourceSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.setWorkingContext(targetSecurityContext); - targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER); - resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument); + targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER); + resourceManagement.setDatabase(targetSecurityContextDatabase); break; case REMOVE_FROM_CONTEXT: // Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext); resourceManagement.setTargetSecurityContext(targetSecurityContext); resourceManagement.setWorkingContext(targetSecurityContext); - targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER); - resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument); + targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER); + resourceManagement.setDatabase(targetSecurityContextDatabase ); break; default: @@ -168,9 +168,9 @@ public class FacetManagement extends EntityManagement { }catch (Exception e) { throw new ResourceRegistryException(e); }finally { - if(targetSecurityContextODatabaseDocument!=null) { - targetSecurityContextODatabaseDocument.close(); - oDatabaseDocument.activateOnCurrentThread(); + if(targetSecurityContextDatabase !=null) { + targetSecurityContextDatabase.close(); +// database.activateOnCurrentThread(); } } } @@ -186,7 +186,7 @@ public class FacetManagement extends EntityManagement { 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) { throw new SchemaViolationException("You cannot create a stand alone Facet"); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/ResourceManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/ResourceManagement.java index dc565f7..67eee69 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/ResourceManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/entities/ResourceManagement.java @@ -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.types.CachedType; 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.properties.LinkedEntity; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.remote.RemoteDatabase; +import com.arcadedb.schema.DocumentType; /** * @author Luca Frosini (ISTI - CNR) @@ -89,8 +89,8 @@ public class ResourceManagement extends EntityManagement * ConsistsOf.NAME); TODO Looks for a different query */ - Iterable edges = getElement().getEdges(ODirection.OUT); - for(OEdge edge : edges) { + Iterable edges = getElement().getEdges(DIRECTION.OUT); + for(Edge edge : edges) { RelationManagement relationManagement = getRelationManagement(edge); relationManagement.setReload(reload); @@ -104,7 +104,7 @@ public class ResourceManagement extends EntityManagement errorMessage.append("SourceEntityManagement for "); errorMessage.append(relationManagement.getClass().getSimpleName()); 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()); } @@ -114,10 +114,10 @@ public class ResourceManagement extends EntityManagement JsonNode consistsOf = relationManagement.serializeAsJsonNode(); sourceResource = addConsistsOf(sourceResource, consistsOf); } 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; } 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); } @@ -146,7 +146,7 @@ public class ResourceManagement extends EntityManagement } @Override - protected OVertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException { + protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException { createVertex(); @@ -156,7 +156,7 @@ public class ResourceManagement extends EntityManagement for(JsonNode consistOfJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(); com.setWorkingContext(getWorkingContext()); - com.setODatabaseDocument(oDatabaseDocument); + com.setDatabase(database); com.setJsonNode(consistOfJsonNode); com.setSourceEntityManagement(this); com.internalCreate(); @@ -170,7 +170,7 @@ public class ResourceManagement extends EntityManagement for(JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement(); irtm.setWorkingContext(getWorkingContext()); - irtm.setODatabaseDocument(oDatabaseDocument); + irtm.setDatabase(database); irtm.setJsonNode(relationJsonNode); irtm.setSourceEntityManagement(this); irtm.internalCreate(); @@ -182,7 +182,7 @@ public class ResourceManagement extends EntityManagement } @Override - protected OVertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException { + protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException { getElement(); @@ -192,7 +192,7 @@ public class ResourceManagement extends EntityManagement for(JsonNode relationJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(); com.setWorkingContext(getWorkingContext()); - com.setODatabaseDocument(oDatabaseDocument); + com.setDatabase(database); com.setJsonNode(relationJsonNode); com.internalCreateOrUdate(); addToRelationManagement(com); @@ -205,7 +205,7 @@ public class ResourceManagement extends EntityManagement for(JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement(); irtm.setWorkingContext(getWorkingContext()); - irtm.setODatabaseDocument(oDatabaseDocument); + irtm.setDatabase(database); irtm.setJsonNode(relationJsonNode); irtm.internalUpdate(); addToRelationManagement(irtm); @@ -221,25 +221,25 @@ public class ResourceManagement extends EntityManagement getElement(); - Iterable iterable = element.getEdges(ODirection.OUT); - Iterator iterator = iterable.iterator(); + Iterable iterable = element.getEdges(DIRECTION.OUT); + Iterator iterator = iterable.iterator(); while(iterator.hasNext()) { - OEdge edge = iterator.next(); - OClass oClass = ElementManagementUtility.getOClass(edge); + Edge edge = iterator.next(); + DocumentType documentType = ElementManagementUtility.getDocumentType(edge); RelationManagement relationManagement = null; - if(oClass.isSubClassOf(IsRelatedTo.NAME)) { + if(documentType.isSubTypeOf(IsRelatedTo.NAME)) { relationManagement = new IsRelatedToManagement(); - } else if(oClass.isSubClassOf(ConsistsOf.NAME)) { + } else if(documentType.isSubTypeOf(ConsistsOf.NAME)) { relationManagement = new ConsistsOfManagement(); } else { - logger.warn("{} is not a {} nor a {}. {}", OrientDBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME, - ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + logger.warn("{} is not a {} nor a {}. {}", DBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME, + ConsistsOf.NAME, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } if(relationManagement != null) { relationManagement.setWorkingContext(getWorkingContext()); - relationManagement.setODatabaseDocument(oDatabaseDocument); + relationManagement.setDatabase(database); relationManagement.setElement(edge); relationManagement.internalDelete(); affectedInstances.putAll(relationManagement.getAffectedInstances()); @@ -247,7 +247,7 @@ public class ResourceManagement extends EntityManagement } - iterable = element.getEdges(ODirection.OUT); + iterable = element.getEdges(DIRECTION.OUT); iterator = iterable.iterator(); while(iterator.hasNext()) { // in relations are affected because is the system which ensure this integrity @@ -268,7 +268,7 @@ public class ResourceManagement extends EntityManagement return; } - targetSecurityContext.addElement(getElement(), oDatabaseDocument); + targetSecurityContext.addElement(getElement(), database); /* * DO NOT UNCOMMENT @@ -278,11 +278,11 @@ public class ResourceManagement extends EntityManagement */ if(honourPropagationConstraintsInContextSharing) { - Iterable edges = getElement().getEdges(ODirection.OUT); + Iterable edges = getElement().getEdges(DIRECTION.OUT); int facetCounter = 0; - for(OEdge edge : edges) { + for(Edge edge : edges) { RelationManagement relationManagement = getRelationManagement(edge); relationManagement.setDryRun(dryRun); relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing); @@ -315,21 +315,21 @@ public class ResourceManagement extends EntityManagement @Override public String all(boolean polymorphic) throws ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER); + database = getWorkingContext().getRemoteDatabase(PermissionMode.READER); return reallyGetAll(polymorphic); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); - } - if(current!=null) { - current.activateOnCurrentThread(); + if(database != null) { + database.close(); } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } @@ -439,9 +439,9 @@ public class ResourceManagement extends EntityManagement Map satisfiedConsistsOfFacet = new HashMap<>(); - Iterable edges = getElement().getEdges(ODirection.OUT); + Iterable edges = getElement().getEdges(DIRECTION.OUT); - for(OEdge edge : edges) { + for(Edge edge : edges) { String id = edge.getIdentity().toString(); RelationManagement relationManagement = relationManagements.get(id); @@ -452,7 +452,7 @@ public class ResourceManagement extends EntityManagement case ADD_TO_CONTEXT: if(relationManagement == null) { try { - relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge); + relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, database, edge); relationManagement.setSourceSecurityContext(sourceSecurityContext); relationManagements.put(id, relationManagement); }catch (AvailableInAnotherContextException e) { @@ -475,7 +475,7 @@ public class ResourceManagement extends EntityManagement */ continue; }else { - relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge); + relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, database, edge); relationManagements.put(id, relationManagement); } break; @@ -483,7 +483,7 @@ public class ResourceManagement extends EntityManagement case CREATE: case UPDATE: if(relationManagement == null) { - relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); + relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge); relationManagements.put(id, relationManagement); /* * Here the AvailableInAnotherContextException should not occur because the connection to the DB is with the diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java index 8e0443a..f03406c 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java @@ -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.types.reference.entities.FacetType; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.ODirection; -import com.orientechnologies.orient.core.record.OEdge; -import com.orientechnologies.orient.core.record.OVertex; +import com.arcadedb.graph.Edge; +import com.arcadedb.graph.Vertex; +import com.arcadedb.graph.Vertex.DIRECTION; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -64,20 +64,20 @@ public class ConsistsOfManagement extends RelationManagement iterable = target.getEdges(ODirection.IN); - Iterator iterator = iterable.iterator(); + Iterable iterable = target.getEdges(DIRECTION.IN); + Iterator iterator = iterable.iterator(); while(iterator.hasNext()) { iterator.next(); ++count; @@ -87,7 +87,7 @@ public class ConsistsOfManagement extends RelationManagement fullSerialize(Map visitedSourceResources) throws ResourceRegistryException { - OVertex source = getElement().getVertex(ODirection.OUT); + Vertex source = getElement().getVertex(DIRECTION.OUT); String id = source.getIdentity().toString(); @@ -209,7 +211,7 @@ public abstract class RelationManagement iterable = target.getEdges(ODirection.IN); - Iterator iterator = iterable.iterator(); + Iterable iterable = target.getEdges(DIRECTION.IN); + Iterator iterator = iterable.iterator(); int count = 0; - OEdge edge = null; + Edge edge = null; while(iterator.hasNext()) { - edge = (OEdge) iterator.next(); - OEdge thisOEdge = (OEdge) getElement(); - if(edge.compareTo(thisOEdge) != 0) { - if(thisOEdge.getVertex(ODirection.OUT).compareTo(edge.getVertex(ODirection.OUT)) != 0) { + edge = (Edge) iterator.next(); + Edge thisEdge = (Edge) getElement(); + if(edge.compareTo(thisEdge) != 0) { + if(thisEdge.getVertex(DIRECTION.OUT).compareTo(edge.getVertex(DIRECTION.OUT)) != 0) { count++; break; } @@ -651,7 +653,7 @@ public abstract class RelationManagement iterable = target.getEdges(ODirection.IN); - Iterator iterator = iterable.iterator(); + Vertex target = t.getElement(); + Iterable iterable = target.getEdges(DIRECTION.IN); + Iterator iterator = iterable.iterator(); if(iterator.hasNext()) { logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element, target, deleteConstraint); @@ -777,19 +779,19 @@ public abstract class RelationManagement serializeEdges(Iterable edges, boolean postFilterPolymorphic) + protected Collection serializeEdges(Iterable edges, boolean postFilterPolymorphic) throws ResourceRegistryException { // Map visitedSourceResources = new HashMap<>(); List serilizedEdges = new ArrayList<>(); - for(ODocument d : edges) { - OEdge edge = (OEdge) d; + for(Document d : edges) { + Edge edge = (Edge) d; - if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) { + if(postFilterPolymorphic && getDocumentType().isSubTypeOf(typeName)) { continue; } RelationManagement relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), - oDatabaseDocument, edge); + database, edge); // visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); serilizedEdges.add(relationManagement.serializeAsJsonNode()); } @@ -808,7 +810,7 @@ public abstract class RelationManagement edges = oDatabaseDocument.browseClass(typeName, polymorphic); + Iterable edges = database.browseClass(typeName, polymorphic); Collection collection = serializeEdges(edges, false); return serializeJsonNodeCollectionAsString(collection); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/queries/QueryImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/queries/QueryImpl.java index 3bdab1a..683998c 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/queries/QueryImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/queries/QueryImpl.java @@ -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.instances.base.ElementManagement; 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.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.sql.executor.OResult; -import com.orientechnologies.orient.core.sql.executor.OResultSet; +import com.arcadedb.database.Document; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -28,37 +28,37 @@ public class QueryImpl implements Query { @Override public String query(String query, boolean raw) throws InvalidQueryException { - ODatabaseDocument oDatabaseDocument = null; - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase oDatabaseDocument = null; + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); - oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER); + oDatabaseDocument = securityContext.getRemoteDatabase(PermissionMode.READER); oDatabaseDocument.begin(); logger.debug("Going to execute query '{} limit {}'", query); - OResultSet resultSet = oDatabaseDocument.query(query); + ResultSet resultSet = oDatabaseDocument.command("sql", query); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode arrayNode = objectMapper.createArrayNode(); while(resultSet.hasNext()) { - OResult oResult = resultSet.next(); + Result result = resultSet.next(); try { JsonNode jsonNode = null; if(raw) { - if(oResult.isElement()) { - OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); - jsonNode = OrientDBUtility.toJsonNode(element); + if(result.isElement()) { + Document element = ElementManagementUtility.getElementFromOptional(result.getElement()); + jsonNode = DBUtility.toJsonNode(element); }else { ObjectMapper mapper = new ObjectMapper(); - jsonNode = mapper.readTree(OrientDBUtility.toJsonString(oResult)); + jsonNode = mapper.readTree(DBUtility.toJsonString(result)); } } else { - OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); + Document element = ElementManagementUtility.getElementFromOptional(result.getElement()); ElementManagement erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument, element); erManagement.setAsEntryPoint(); @@ -68,7 +68,7 @@ public class QueryImpl implements Query { } catch(ResourceRegistryException e) { 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) { oDatabaseDocument.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/queries/json/JsonQuery.java b/src/main/java/org/gcube/informationsystem/resourceregistry/queries/json/JsonQuery.java index 077d0d4..2068c17 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/queries/json/JsonQuery.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/queries/json/JsonQuery.java @@ -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.types.CachedType; 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.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.sql.executor.OResult; -import com.orientechnologies.orient.core.sql.executor.OResultSet; +import com.arcadedb.database.Document; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -47,7 +47,7 @@ public class JsonQuery { protected ObjectMapper objectMapper; protected JsonNode jsonQuery; protected JsonQueryERElement entryPoint; - protected ODatabaseDocument oDatabaseDocument; + protected RemoteDatabase database; public JsonQuery() { this.objectMapper = new ObjectMapper(); @@ -106,13 +106,13 @@ public class JsonQuery { } public String query() throws InvalidQueryException, ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - oDatabaseDocument = null; + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + database = null; try { SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); - oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER); - oDatabaseDocument.begin(); + database = securityContext.getRemoteDatabase(PermissionMode.READER); + database.begin(); StringBuffer stringBuffer = createQuery(); stringBuffer.append(" limit :limit"); @@ -123,17 +123,17 @@ public class JsonQuery { String query = stringBuffer.toString(); 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(); while(resultSet.hasNext()) { - OResult oResult = resultSet.next(); - OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); + Result oResult = resultSet.next(); + Document element = ElementManagementUtility.getElementFromOptional(oResult.getElement()); try { JsonNode jsonNodeResult = null; - ElementManagement erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument, + ElementManagement erManagement = ElementManagementUtility.getERManagement(securityContext, database, element); // 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) { 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) { throw new InvalidQueryException(e.getMessage()); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); - } - if(current!=null) { - current.activateOnCurrentThread(); + if(database != null) { + database.close(); } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/queries/templates/QueryTemplateManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/queries/templates/QueryTemplateManagement.java index ff407b9..bff1436 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/queries/templates/QueryTemplateManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/queries/templates/QueryTemplateManagement.java @@ -19,7 +19,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement; 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.types.reference.entities.EntityType; import org.slf4j.Logger; @@ -53,7 +53,7 @@ public class QueryTemplateManagement extends EntityElementManagement { protected final String typeName; - protected OClass oClass; + protected DocumentType documentType; protected AccessType accessType; @@ -62,21 +59,21 @@ public class CachedType { this.typeName = typeName; } - private OClass retrieveOClass() throws SchemaException, SchemaNotFoundException, ResourceRegistryException { - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); - ODatabaseDocument oDatabaseDocument = null; + private DocumentType retrieveDocumentType() throws SchemaException, SchemaNotFoundException, ResourceRegistryException { + RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase database = null; try { logger.debug("GettingType {} schema", typeName); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); - OMetadata oMetadata = oDatabaseDocument.getMetadata(); + database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER); + OMetadata oMetadata = database.getMetadata(); OSchema oSchema = oMetadata.getSchema(); try { - OClass oClass = oSchema.getClass(typeName); - if(oClass == null) { + DocumentType documentType = oSchema.getClass(typeName); + if(documentType == null) { throw new SchemaNotFoundException(typeName + " was not registered"); } - return oClass; + return documentType; } catch(SchemaNotFoundException snfe) { throw snfe; } catch(Exception e) { @@ -87,29 +84,29 @@ public class CachedType { } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } - if(current!=null) { - current.activateOnCurrentThread(); - } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } - public synchronized void setOClass(OClass oClass) throws SchemaNotFoundException, SchemaException, ResourceRegistryException { - if(this.oClass==null) { - this.oClass = oClass; + public synchronized void setDocumentType(DocumentType documentType) throws SchemaNotFoundException, SchemaException, ResourceRegistryException { + if(this.documentType==null) { + this.documentType = documentType; } } - private AccessType getAccessTypeFromOClass(OClass oClass) throws ResourceRegistryException { + private AccessType getAccessTypeFromDocumentType(DocumentType documentType) throws ResourceRegistryException { AccessType[] accessTypes = AccessType.values(); for(int i=accessTypes.length-1; i>=0; i--) { AccessType accessType = accessTypes[i]; - if(oClass.isSubClassOf(accessType.getName())) { + if(documentType.isSubTypeOf(accessType.getName())) { return accessType; } } @@ -123,14 +120,14 @@ public class CachedType { // 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. - List superClasses = internalGetOClass().getSuperClasses(); + List superClasses = internalGetDocumentType().getSuperTypes(); while(superClasses.size()>0) { - List toBeAnalysed = new ArrayList<>(superClasses); + List toBeAnalysed = new ArrayList<>(superClasses); superClasses = new ArrayList<>(); - for(OClass oSuperClass : toBeAnalysed) { + for(DocumentType oSuperClass : toBeAnalysed) { String name = oSuperClass.getName(); 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 || name.compareTo(OSecurity.RESTRICTED_CLASSNAME) == 0) { continue; @@ -140,7 +137,7 @@ public class CachedType { continue; } allSuperClasses.add(allSuperClasses.size(), name); - superClasses.addAll(oSuperClass.getSuperClasses()); + superClasses.addAll(oSuperClass.getSuperTypes()); } } return allSuperClasses; @@ -150,32 +147,32 @@ public class CachedType { TypesCache typesCache = TypesCache.getInstance(); List allSubClasses = new ArrayList<>(); - Collection subclasses = internalGetOClass().getSubclasses(); + Collection subclasses = internalGetDocumentType().getSubTypes(); while(subclasses.size()>0) { - List toBeAnalysed = new ArrayList<>(subclasses); + List toBeAnalysed = new ArrayList<>(subclasses); subclasses = new ArrayList<>(); - for(OClass oSubClass : toBeAnalysed) { + for(DocumentType oSubClass : toBeAnalysed) { String name = oSubClass.getName(); CachedType cachedType = typesCache.getCachedType(name); - cachedType.setOClass(oSubClass); + cachedType.setDocumentType(oSubClass); allSubClasses.add(allSubClasses.size(), name); - subclasses.addAll(oSubClass.getSubclasses()); + subclasses.addAll(oSubClass.getSubTypes()); } } return allSubClasses; } - private OClass internalGetOClass() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { - if(oClass==null) { - oClass = retrieveOClass(); + private DocumentType internalGetDocumentType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { + if(documentType==null) { + documentType = retrieveDocumentType(); } - return oClass; + return documentType; } @SuppressWarnings("unchecked") private T internalGetType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { if(type==null) { - ElementManagement erManagement = TypeManagement.getTypeManagement(internalGetOClass()); + ElementManagement erManagement = TypeManagement.getTypeManagement(internalGetDocumentType()); String typeString = erManagement.read(); try { type = (T) TypeMapper.deserializeTypeDefinition(typeString); @@ -191,7 +188,7 @@ public class CachedType { if(type!=null) { accessType = type.getAccessType(); }else { - accessType = getAccessTypeFromOClass(internalGetOClass()); + accessType = getAccessTypeFromDocumentType(internalGetDocumentType()); } } return accessType; @@ -212,8 +209,8 @@ public class CachedType { } - public synchronized OClass getOClass() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { - return internalGetOClass(); + public synchronized DocumentType getDocumentType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { + return internalGetDocumentType(); } public synchronized T getType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException { diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/types/TypeManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/types/TypeManagement.java index 652ef45..5000461 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/types/TypeManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/types/TypeManagement.java @@ -56,14 +56,9 @@ import org.gcube.informationsystem.types.reference.relations.RelationType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.exception.OSchemaException; -import com.orientechnologies.orient.core.metadata.OMetadata; -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; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.remote.RemoteDatabase; +import com.arcadedb.schema.DocumentType; /** * @author Luca Frosini (ISTI - CNR) @@ -111,8 +106,8 @@ public class TypeManagement { } - protected OClass getOClass(OSchema oSchema, String typeName) throws SchemaException { - return oSchema.getClass(typeName); + protected DocumentType getOClass(RemoteDatabase database, String typeName) throws SchemaException { + return database.getClass(typeName); } public String getTypeName() { @@ -134,7 +129,7 @@ public class TypeManagement { } private static ElementManagement getTypeManagement(AccessType accessType, String name) { - ElementManagement erManagement = null; + ElementManagement erManagement = null; switch(accessType) { case PROPERTY: @@ -164,23 +159,23 @@ public class TypeManagement { return erManagement; } - public static ElementManagement getTypeManagement(OClass oClass) { + public static ElementManagement getTypeManagement(DocumentType documentType) { ElementManagement erManagement = null; - if(oClass.isSubClassOf(Property.NAME)) { + if(documentType.isSubTypeOf(Property.NAME)) { erManagement = new PropertyTypeDefinitionManagement(); - ((PropertyTypeDefinitionManagement) erManagement).setName(oClass.getName()); - } else if(oClass.isSubClassOf(Resource.NAME)) { + ((PropertyTypeDefinitionManagement) erManagement).setName(documentType.getName()); + } else if(documentType.isSubTypeOf(Resource.NAME)) { erManagement = new ResourceTypeDefinitionManagement(); - ((ResourceTypeDefinitionManagement) erManagement).setName(oClass.getName()); - } else if(oClass.isSubClassOf(Facet.NAME)) { + ((ResourceTypeDefinitionManagement) erManagement).setName(documentType.getName()); + } else if(documentType.isSubTypeOf(Facet.NAME)) { erManagement = new FacetTypeDefinitionManagement(); - ((FacetTypeDefinitionManagement) erManagement).setName(oClass.getName()); - } else if(oClass.isSubClassOf(IsRelatedTo.NAME)) { + ((FacetTypeDefinitionManagement) erManagement).setName(documentType.getName()); + } else if(documentType.isSubTypeOf(IsRelatedTo.NAME)) { erManagement = new IsRelatedToTypeDefinitionManagement(); - ((IsRelatedToTypeDefinitionManagement) erManagement).setName(oClass.getName()); - } else if(oClass.isSubClassOf(ConsistsOf.NAME)) { + ((IsRelatedToTypeDefinitionManagement) erManagement).setName(documentType.getName()); + } else if(documentType.isSubTypeOf(ConsistsOf.NAME)) { erManagement = new ConsistsOfTypeDefinitionManagement(); - ((ConsistsOfTypeDefinitionManagement) erManagement).setName(oClass.getName()); + ((ConsistsOfTypeDefinitionManagement) erManagement).setName(documentType.getName()); } return erManagement; } @@ -197,9 +192,9 @@ public class TypeManagement { } } - private String getTypeAsString(OClass oClass) throws SchemaException { + private String getTypeAsString(DocumentType documentType) throws SchemaException { try { - ElementManagement erManagement = getTypeManagement(oClass); + ElementManagement erManagement = getTypeManagement(documentType); return getTypeAsString(erManagement); } catch(Exception 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 { - String typeString = getTypeAsString(oClass); + String typeString = getTypeAsString(documentType); return TypeMapper.deserializeTypeDefinition(typeString); } catch(Exception e) { throw new SchemaException(e); } } - protected List getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument, + protected List getSuperTypesAndCheckCompliancy(RemoteDatabase database, Type type, String baseType) throws SchemaException, SchemaNotFoundException { Set superClasses = type.getTypeSuperTypes(); @@ -236,27 +231,27 @@ public class TypeManagement { } } - OMetadata oMetadata = oDatabaseDocument.getMetadata(); + OMetadata oMetadata = database.getMetadata(); OSchema oSchema = oMetadata.getSchema(); - List oSuperclasses = new ArrayList<>(); + List superTypes = new ArrayList<>(); for(String superClass : superClasses) { - OClass oSuperClass = getOClass(oSchema, superClass); - if(oSuperClass == null) { + DocumentType superType = getOClass(oSchema, superClass); + if(superType == null) { throw new SchemaNotFoundException("Superclass " + superClass + " does not exists"); } if(baseType != null) { if(type.getName().compareTo(baseType) != 0) { - if(!oSuperClass.isSubClassOf(baseType)) { + if(!superType.isSubTypeOf(baseType)) { throw new RuntimeException(superClass + " is not a subsclass of " + baseType + ". Each Superclass MUST be a subclass of " + baseType); } } } - oSuperclasses.add(oSuperClass); + superTypes.add(superType); } - return oSuperclasses; + return superTypes; } private static Set baseElementTypes; @@ -282,7 +277,7 @@ public class TypeManagement { protected void registerTypeSchema() throws SchemaAlreadyPresentException, SchemaException { - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase database = null; try { if(typeName.compareTo(type.getName()) != 0) { @@ -293,23 +288,23 @@ public class TypeManagement { } 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(); - OClass oClass = null; + DocumentType documentType = null; AccessType accessType = type.getAccessType(); Class typeClass = accessType.getTypeClass(); String typeName = type.getName(); if(EntityElement.class.isAssignableFrom(typeClass)) { - oClass = oDatabaseDocument.createVertexClass(typeName); + documentType = database.createVertexClass(typeName); } else if(RelationElement.class.isAssignableFrom(typeClass)) { - oClass = oDatabaseDocument.createEdgeClass(typeName); + documentType = database.createEdgeClass(typeName); } else if(PropertyElement.class.isAssignableFrom(typeClass)) { - oClass = oSchema.createClass(typeName); + documentType = oSchema.createClass(typeName); } else { String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.", Entity.NAME, Relation.NAME, Property.NAME); @@ -321,7 +316,7 @@ public class TypeManagement { String description = type.getDescription(); if(description != null && description.compareTo("") != 0) { try { - oClass.setDescription(description); + documentType.setDescription(description); } catch(Exception e) { logger.warn( "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 { - // oClass.setAbstract(false); // Used to allow to persist Schema in Context + // documentType.setAbstract(false); // Used to allow to persist Schema in Context // Management - oClass.setAbstract(type.isAbstract()); + documentType.setAbstract(type.isAbstract()); } catch(Exception e) { 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.", @@ -339,9 +334,9 @@ public class TypeManagement { } if(!baseElementTypes.contains(type.getName())) { - List oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseDocument, type, + List oSuperclasses = getSuperTypesAndCheckCompliancy(database, type, accessType.getName()); - oClass.setSuperClasses(oSuperclasses); + documentType.setSuperClasses(oSuperclasses); } if(!(type instanceof ResourceType)) { @@ -373,9 +368,9 @@ public class TypeManagement { } } - OType oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType()); + com.arcadedb.schema.Type oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType()); - OProperty op = oClass.createProperty(propertyDefinition.getName(), oType); + com.arcadedb.schema.Property op = documentType.createProperty(propertyDefinition.getName(), oType); op.setDescription(propertyDefinition.getDescription()); /* @@ -394,7 +389,7 @@ public class TypeManagement { if (propertyTypeName.isGenericType()) { if (propertyTypeName.getGenericClassName() != null) { - OClass linkedClass = getOClass(oSchema, propertyTypeName.getGenericClassName()); + DocumentType linkedClass = getOClass(oSchema, propertyTypeName.getGenericClassName()); if (linkedClass == null) { logger.trace("Class {} not found.", propertyTypeName.getGenericClassName()); @@ -419,7 +414,7 @@ public class TypeManagement { } } - oDatabaseDocument.commit(); + database.commit(); logger.info("{} {} registered successfully", accessType.getName(), type.getName()); } catch(Exception e) { @@ -436,7 +431,7 @@ public class TypeManagement { } catch(Exception ex) { throw new SchemaCreationException(ex); } finally { - oDatabaseDocument.close(); + database.close(); } } @@ -466,17 +461,17 @@ public class TypeManagement { protected void updateTypeSchema(Type actualTypeDefinition, Type newTypeDefinition, AccessType baseElementAccessType) throws SchemaNotFoundException, SchemaException { - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase database = null; try { 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(); - OClass oClass = oSchema.getClass(typeName); - if(oClass == null) { + DocumentType documentType = oSchema.getClass(typeName); + if(documentType == null) { throw new SchemaNotFoundException(typeName + " does not Exists"); } @@ -495,7 +490,7 @@ public class TypeManagement { String description = newTypeDefinition.getDescription(); if(description != null && description.compareTo("") != 0) { try { - oClass.setDescription(description); + documentType.setDescription(description); } catch(Exception e) { logger.warn( "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 { - // oClass.setAbstract(false); // Used to allow to persist Schema in Context + // documentType.setAbstract(false); // Used to allow to persist Schema in Context // Management - oClass.setAbstract(newTypeDefinition.isAbstract()); + documentType.setAbstract(newTypeDefinition.isAbstract()); } catch(Exception e) { 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.", @@ -547,7 +542,7 @@ public class TypeManagement { } PropertyTypeName newPropertyTypeName = ((PropertyDefinitionImpl) newPropertyDefinition).getPropertyTypeName(); - OType oType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getBaseType()); + com.arcadedb.schema.Type dbType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getBaseType()); /* * Excluding EMBEDDEDLIST and EMBEDDEDSET @@ -555,8 +550,8 @@ public class TypeManagement { * */ if(!typeList.contains(newTypeDefinition.getName())) { - switch(oType) { - case EMBEDDEDLIST: + switch(dbType) { + case LIST: throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); case EMBEDDEDSET: @@ -567,15 +562,15 @@ public class TypeManagement { } } - OProperty op; + com.arcadedb.schema.Property dbProperty; if(actualPropertyDefinition!=null) { // The property already exists and has changed (the check has been performed few lines above). - op = oClass.getProperty(propertyName); + dbProperty = documentType.getProperty(propertyName); }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 @@ -584,16 +579,16 @@ public class TypeManagement { * ovp.setNotNull(property.isNotnull()); This information are persisted in * Management Context */ - op.setMandatory(false); - op.setNotNull(false); + dbProperty.setMandatory(false); + dbProperty.setNotNull(false); - op.setReadonly(newPropertyDefinition.isReadonly()); - op.setRegexp(newPropertyDefinition.getRegexp()); + dbProperty.setReadonly(newPropertyDefinition.isReadonly()); + dbProperty.setRegexp(newPropertyDefinition.getRegexp()); if (newPropertyTypeName.isGenericType()) { if (newPropertyTypeName.getGenericClassName() != null) { - OClass linkedClass = getOClass(oSchema, newPropertyTypeName.getGenericClassName()); + DocumentType linkedClass = getOClass(oSchema, newPropertyTypeName.getGenericClassName()); if (linkedClass == null) { 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"); } - op.setLinkedClass(linkedClass); + dbProperty.setLinkedClass(linkedClass); } else { - OType linkedOType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getGenericBaseType()); - op.setLinkedType(OType.getById(Integer.valueOf(linkedOType.ordinal()).byteValue())); + com.arcadedb.schema.Type linkedOType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getGenericBaseType()); + 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 for(String propertyNameToRemove : actualPropertyDefinitionMap.keySet()) { - oClass.dropProperty(propertyNameToRemove); + documentType.dropProperty(propertyNameToRemove); } } - oDatabaseDocument.commit(); + database.commit(); logger.info("{} {} updated successfully", baseElementAccessType.getName(), newTypeDefinition.getName()); } catch(Exception e) { @@ -641,30 +636,30 @@ public class TypeManagement { } catch(Exception ex) { throw new SchemaException(ex); } finally { - oDatabaseDocument.close(); + database.close(); } } protected List getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase database = null; try { 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(); - OClass baseOClass = oSchema.getClass(typeName); - if(baseOClass == null) { + DocumentType baseDocumentType = oSchema.getClass(typeName); + if(baseDocumentType == null) { throw new SchemaNotFoundException(typeName + " does not Exists"); } List typeDefinitions = new ArrayList<>(); - typeDefinitions.add(getType(baseOClass)); + typeDefinitions.add(getType(baseDocumentType)); if(includeSubtypes) { - Collection subClasses = baseOClass.getAllSubclasses(); - for(OClass oClass : subClasses) { - typeDefinitions.add(getType(oClass)); + Collection subClasses = baseDocumentType.getAllSubclasses(); + for(DocumentType documentType : subClasses) { + typeDefinitions.add(getType(documentType)); } } @@ -676,8 +671,8 @@ public class TypeManagement { } catch(Exception e) { throw new SchemaException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } } } @@ -787,12 +782,12 @@ public class TypeManagement { } protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{ - ODatabaseDocument oDatabaseDocument = null; + RemoteDatabase database = null; try { 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.dropClass(typeName); @@ -800,7 +795,7 @@ public class TypeManagement { ElementManagement erManagement = getTypeManagement(accessType, typeName); erManagement.delete(); - oDatabaseDocument.commit(); + database.commit(); return true; } catch(SchemaException e) { @@ -816,8 +811,8 @@ public class TypeManagement { } catch(Exception e) { throw new SchemaException(e); } finally { - if(oDatabaseDocument != null) { - oDatabaseDocument.close(); + if(database != null) { + database.close(); } } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/types/entities/EntityTypeDefinitionManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/types/entities/EntityTypeDefinitionManagement.java index a13096a..5f75093 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/types/entities/EntityTypeDefinitionManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/types/entities/EntityTypeDefinitionManagement.java @@ -1,6 +1,5 @@ package org.gcube.informationsystem.resourceregistry.types.entities; -import java.util.HashMap; import java.util.Map; 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.SchemaNotFoundException; 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.TypeSecurityContext; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility; 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.reference.entities.EntityType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.record.OVertex; -import com.orientechnologies.orient.core.sql.executor.OResult; -import com.orientechnologies.orient.core.sql.executor.OResultSet; +import com.arcadedb.graph.Vertex; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; /** * @author Luca Frosini (ISTI - CNR) @@ -66,7 +65,7 @@ public abstract class EntityTypeDefinitionManagement exten name = jsonNode.get(EntityType.NAME_PROPERTY).asText(); } } else { - name = element.getProperty(EntityType.NAME_PROPERTY); + name = element.getString(EntityType.NAME_PROPERTY); } } return name; @@ -78,16 +77,16 @@ public abstract class EntityTypeDefinitionManagement exten } @Override - protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException { + protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException { logger.debug("Going to create {} for {}", this.typeName, getName()); return createVertex(); } @Override - protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException { + protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException { logger.debug("Going to update {} for {}", this.typeName, getName()); - OVertex entityTypeDefinition = getElement(); - entityTypeDefinition = (OVertex) updateProperties(oClass, entityTypeDefinition, jsonNode, ignoreKeys, + Vertex entityTypeDefinition = getElement(); + entityTypeDefinition = (Vertex) updateProperties(documentType, entityTypeDefinition, jsonNode, ignoreKeys, ignoreStartWithKeys); return entityTypeDefinition; } @@ -99,7 +98,7 @@ public abstract class EntityTypeDefinitionManagement exten } @Override - public OVertex getElement() throws NotFoundException, ResourceRegistryException { + public Vertex getElement() throws NotFoundException, ResourceRegistryException { if (element == null) { try { element = retrieveElement(); @@ -120,7 +119,7 @@ public abstract class EntityTypeDefinitionManagement exten } @Override - public OVertex retrieveElement() throws NotFoundException, ResourceRegistryException { + public Vertex retrieveElement() throws NotFoundException, ResourceRegistryException { try { if (getName() == null) { throw new NotFoundException("null name does not allow to retrieve the Element"); @@ -129,7 +128,7 @@ public abstract class EntityTypeDefinitionManagement exten 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()) { String error = String.format("No %s with name %s was found", typeName, getName()); @@ -137,10 +136,10 @@ public abstract class EntityTypeDefinitionManagement exten throw new NotFoundException(error); } - OResult oResult = resultSet.next(); - OVertex element = (OVertex) ElementManagementUtility.getElementFromOptional(oResult.getElement()); + Result oResult = resultSet.next(); + 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()) { throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName() @@ -158,24 +157,24 @@ public abstract class EntityTypeDefinitionManagement exten } @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); 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; } catch (ResourceRegistryException e) { throw 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); throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause()); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/types/properties/PropertyTypeDefinitionManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/types/properties/PropertyTypeDefinitionManagement.java index 5f4f65f..cd4c089 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/types/properties/PropertyTypeDefinitionManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/types/properties/PropertyTypeDefinitionManagement.java @@ -1,6 +1,5 @@ package org.gcube.informationsystem.resourceregistry.types.properties; -import java.util.HashMap; import java.util.Map; 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.SchemaNotFoundException; 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.TypeSecurityContext; import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement; 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.properties.PropertyType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.executor.OResult; -import com.orientechnologies.orient.core.sql.executor.OResultSet; +import com.arcadedb.database.Document; +import com.arcadedb.query.sql.executor.Result; +import com.arcadedb.query.sql.executor.ResultSet; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) */ -public class PropertyTypeDefinitionManagement extends ElementManagement> { +public class PropertyTypeDefinitionManagement extends ElementManagement> { private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class); @@ -42,9 +40,9 @@ public class PropertyTypeDefinitionManagement extends ElementManagement()); + ResultSet resultSet = database.query("sql", select); if(resultSet == null || !resultSet.hasNext()) { String error = String.format("No %s with name %s was found", typeName, getName()); @@ -143,10 +141,10 @@ public class PropertyTypeDefinitionManagement extends ElementManagement clz) throws ResourceRegistryException { this(clz); - this.oDatabaseDocument = oDatabaseDocument; + this.database = database; setWorkingContext(securityContext); } @@ -77,14 +76,14 @@ public abstract class RelationTypeDefinitionManagement {}", 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; } @Override - protected OEdge reallyUpdate() throws NotFoundException, ResourceRegistryException { + protected Edge reallyUpdate() throws NotFoundException, ResourceRegistryException { logger.debug("Going to update {} for {}", RelationType.NAME, getName()); - OEdge relationTypeDefinition = getElement(); - relationTypeDefinition = (OEdge) updateProperties(oClass, relationTypeDefinition, jsonNode, ignoreKeys, + Edge relationTypeDefinition = getElement(); + relationTypeDefinition = (Edge) updateProperties(documentType, relationTypeDefinition, jsonNode, ignoreKeys, ignoreStartWithKeys); return relationTypeDefinition; @@ -136,7 +135,7 @@ public abstract class RelationTypeDefinitionManagement()); + ResultSet resultSet = database.query("sql",select); if (resultSet == null || !resultSet.hasNext()) { String error = String.format("No %s with name %s was found", typeName, getName()); @@ -174,10 +173,10 @@ public abstract class RelationTypeDefinitionManagement El getElementByUUIDAsAdmin(String elementType, UUID uuid, + public static El getElementByUUIDAsAdmin(String elementType, UUID uuid, Class clz) throws NotFoundException, ResourceRegistryException { - ODatabaseDocument adminDatabaseDocument = null; - ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); + RemoteDatabase adminDatabase = null; +// RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); try { - current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - adminDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER); - return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz); + adminDatabase = adminSecurityContext.getRemoteDatabase(PermissionMode.READER); + return DBUtility.getElementByUUID(adminDatabase, elementType, uuid, clz); } finally { - if(adminDatabaseDocument != null) { - adminDatabaseDocument.close(); - } - if(current!=null) { - current.activateOnCurrentThread(); + if(adminDatabase != null) { + adminDatabase.close(); } +// if(current!=null) { +// current.activateOnCurrentThread(); +// } } } - public static El getElementByUUID(ODatabaseDocument oDatabaseDocument, String elementType, UUID uuid, + public static El getElementByUUID(RemoteDatabase database, String elementType, UUID uuid, Class clz) throws NotFoundException, ResourceRegistryException { if(elementType == null || elementType.compareTo("") == 0) { - if(OVertex.class.isAssignableFrom(clz)) { + if(Vertex.class.isAssignableFrom(clz)) { elementType = Entity.NAME; } - if(OEdge.class.isAssignableFrom(clz)) { + if(Edge.class.isAssignableFrom(clz)) { elementType = Relation.NAME; } } @@ -121,7 +104,7 @@ public class OrientDBUtility { // TODO Rewrite using Gremlin 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()) { @@ -130,11 +113,11 @@ public class OrientDBUtility { throw new NotFoundException(error); } - OResult oResult = resultSet.next(); + Result result = resultSet.next(); @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()) { throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString() @@ -144,11 +127,11 @@ public class OrientDBUtility { return element; } - public static

P getPropertyDocument(Class

clz, OElement element, String property) + public static

P getPropertyDocument(Class

clz, Document element, String property) throws ResourceRegistryException { try { - ODocument oDocument = element.getProperty(property); - P e = ElementMapper.unmarshal(clz, OrientDBUtility.toJsonString(oDocument)); + MutableEmbeddedDocument document = (MutableEmbeddedDocument) element.getEmbedded(property); + P e = ElementMapper.unmarshal(clz, DBUtility.toJsonString(document)); return e; } catch(Exception ex) { String error = String.format("Error while getting %s from %s", property, getAsStringForException(element)); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java index cce06bc..2e66c04 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.lucene.document.Document; import org.gcube.common.encryption.encrypter.StringEncrypter; import org.gcube.informationsystem.base.reference.properties.PropertyElement; import org.gcube.informationsystem.model.reference.properties.Encrypted; @@ -15,12 +16,10 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache; import org.gcube.informationsystem.types.reference.properties.PropertyType; import org.gcube.informationsystem.utils.TypeUtility; -import com.orientechnologies.orient.core.record.impl.ODocument; - /** * @author Luca Frosini (ISTI - CNR) */ -public class EncryptedOrient extends ODocument implements Encrypted { +public class EncryptedOrient extends Document implements Encrypted { public static final String NAME = "Encrypted"; public static final String VALUE = "value"; @@ -133,7 +132,7 @@ public class EncryptedOrient extends ODocument implements Encrypted { @Override public String toJSON(String iFormat) { String ret = super.toJSON(iFormat); - ret = OrientDBUtility.replaceType(ret); + ret = DBUtility.replaceType(ret); return ret; } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataOrient.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataOrient.java index ce6fc1f..2980914 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataOrient.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataOrient.java @@ -5,6 +5,7 @@ import java.util.Date; import java.util.List; import java.util.Map; +import org.apache.lucene.document.Document; import org.gcube.informationsystem.base.reference.properties.PropertyElement; import org.gcube.informationsystem.model.reference.properties.Metadata; 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.utils.TypeUtility; -import com.orientechnologies.orient.core.record.impl.ODocument; +import com.arcadedb.database.MutableDocument; /** * @author Luca Frosini (ISTI - CNR) */ -public class MetadataOrient extends ODocument implements Metadata { +public class MetadataOrient extends MutableDocument implements Metadata { public MetadataOrient() { super(Metadata.NAME); @@ -111,7 +112,7 @@ public class MetadataOrient extends ODocument implements Metadata { @Override public String toJSON(String iFormat) { String ret = super.toJSON(iFormat); - ret = OrientDBUtility.replaceType(ret); + ret = DBUtility.replaceType(ret); return ret; } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataUtility.java index f1a7453..7cab8a8 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/MetadataUtility.java @@ -18,8 +18,9 @@ import org.gcube.informationsystem.serialization.ElementMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.record.OElement; -import com.orientechnologies.orient.core.record.impl.ODocument; +import com.arcadedb.database.Document; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.database.MutableEmbeddedDocument; /** * @author Luca Frosini (ISTI - CNR) @@ -63,7 +64,7 @@ public class MetadataUtility { return null; } 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); metadata.fromJSON(metadataNode.toString()); return metadata; @@ -71,13 +72,13 @@ public class MetadataUtility { return null; } - public static MetadataOrient getMetadataOrient(ODocument oDocument) throws ResourceRegistryException { - if(oDocument instanceof MetadataOrient) { - return (MetadataOrient) oDocument; + public static MetadataOrient getMetadataOrient(Document document) throws ResourceRegistryException { + if(document instanceof MetadataOrient) { + return (MetadataOrient) document; } else { try { MetadataOrient metadataOrient = new MetadataOrient(); - String json = OrientDBUtility.toJsonString(oDocument); + String json = DBUtility.toJsonString(document); Metadata metadata = ElementMapper.unmarshal(Metadata.class, json); metadataOrient.setCreatedBy(metadata.getCreatedBy()); metadataOrient.setCreationTime(metadata.getCreationTime()); @@ -86,28 +87,28 @@ public class MetadataUtility { return metadataOrient; } catch(Exception e) { 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(); - element.setProperty(IdentifiableElement.METADATA_PROPERTY, metadata); + ((MutableDocument) element).set(IdentifiableElement.METADATA_PROPERTY, metadata); return metadata; } - public static Metadata getMetadata(OElement element) throws ResourceRegistryException { - return OrientDBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY); + public static Metadata getMetadata(Document element) throws ResourceRegistryException { + return DBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY); } - public static void updateModifiedByAndLastUpdate(OElement element) throws ResourceRegistryException { - ODocument oDocument = element.getProperty(IdentifiableElement.METADATA_PROPERTY); + public static void updateModifiedByAndLastUpdate(Document element) throws ResourceRegistryException { + MutableEmbeddedDocument document = (MutableEmbeddedDocument) element.getEmbedded(IdentifiableElement.METADATA_PROPERTY); String lastUpdateBy = getUser(); - oDocument.field(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy); + document.set(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy); Date lastUpdateTime = Calendar.getInstance().getTime(); - oDocument.field(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); - element.setProperty(IdentifiableElement.METADATA_PROPERTY, oDocument); + document.set(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); + ((MutableDocument) element).set(IdentifiableElement.METADATA_PROPERTY, document); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java index a8a1259..2d51a53 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java @@ -104,7 +104,7 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio @Override public String toJSON(String iFormat) { String ret = super.toJSON(iFormat); - ret = OrientDBUtility.replaceType(ret); + ret = DBUtility.replaceType(ret); return ret; } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/UUIDUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/UUIDUtility.java index dcd6446..3dbe9f9 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/UUIDUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/UUIDUtility.java @@ -5,15 +5,15 @@ import java.util.UUID; import org.gcube.informationsystem.base.reference.IdentifiableElement; 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) */ public class UUIDUtility extends org.gcube.informationsystem.utils.UUIDUtility { - public static UUID getUUID(OElement element) throws ResourceRegistryException { - String uuidString = element.getProperty(IdentifiableElement.ID_PROPERTY); + public static UUID getUUID(Document element) throws ResourceRegistryException { + String uuidString = element.getString(IdentifiableElement.ID_PROPERTY); UUID uuid = UUID.fromString(uuidString); return uuid; } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/contexts/ContextManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/contexts/ContextManagementTest.java index 81d1112..fc5bebf 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/contexts/ContextManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/contexts/ContextManagementTest.java @@ -27,10 +27,8 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -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.arcadedb.remote.RemoteDatabase; + /** * @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 { ContextSecurityContext contextSecurityContext = ContextSecurityContext.getInstance(); - ODatabaseDocument oDatabaseDocument = contextSecurityContext.getDatabaseDocument(PermissionMode.READER); - OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity(); + RemoteDatabase database = contextSecurityContext.getRemoteDatabase(PermissionMode.READER); +// OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity(); SecurityContext securityContext = null; if(deleted) { @@ -98,11 +96,11 @@ public class ContextManagementTest extends ContextTest { for(boolean hierarchic : booleanArray) { for(PermissionMode permissionMode : PermissionMode.values()) { String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic); - ORole oRole = oSecurity.getRole(role); + Role oRole = oSecurity.getRole(role); Assert.assertEquals(oRole == null, deleted); String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic); - OUser oUser = oSecurity.getUser(user); + User oUser = oSecurity.getUser(user); Assert.assertEquals(oUser == null, deleted); if(oUser != null) { Assert.assertTrue(oUser.hasRole(oRole.getName(), false)); @@ -119,7 +117,7 @@ public class ContextManagementTest extends ContextTest { while(parent != null) { String parentUser = parent.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic); - OUser parentOUser = oSecurity.getUser(parentUser); + User parentOUser = oSecurity.getUser(parentUser); Assert.assertTrue(parentOUser != null); Assert.assertEquals(parentOUser.hasRole(oRole.getName(), false), !deleted); parent = parent.getParentSecurityContext(); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java index d61707b..8f70a71 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java @@ -9,8 +9,7 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; +import com.arcadedb.remote.RemoteDatabase; /** * @author Luca Frosini (ISTI - CNR) @@ -21,14 +20,13 @@ public class DatabaseEnvironmentTest { // @Test public void createDB() throws Exception{ - String db = DatabaseEnvironment.DB_URI; - logger.trace("Created DB is {}", db); + logger.trace("Created DB is {}:{}/{}", DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB); } @Test public void testDateTimeFormat() throws ResourceRegistryException { - ODatabaseDocument oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER); - String dateTime = oDatabaseDocument.get(ATTRIBUTES.DATETIMEFORMAT).toString(); + RemoteDatabase database = ContextUtility.getAdminSecurityContext().getRemoteDatabase(PermissionMode.WRITER); + String dateTime = database.get(ATTRIBUTES.DATETIMEFORMAT).toString(); Assert.assertTrue(dateTime.compareTo(Element.DATETIME_PATTERN)==0); } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/instances/multicontext/MultiContextTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/instances/multicontext/MultiContextTest.java index 2ea8567..60695eb 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/instances/multicontext/MultiContextTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/instances/multicontext/MultiContextTest.java @@ -30,7 +30,7 @@ import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.record.ODirection; +import com.arcadedb.graph.Vertex.DIRECTION; public class MultiContextTest extends ERManagementTest { @@ -136,16 +136,16 @@ public class MultiContextTest extends ERManagementTest { @SuppressWarnings("rawtypes") protected List getIncomingIsRelatedTo(Resource r) throws Exception { - return getIsRelatedTo(r, ODirection.OUT); + return getIsRelatedTo(r, DIRECTION.OUT); } @SuppressWarnings("rawtypes") protected List getOutcomingIsRelatedTo(Resource r) throws Exception { - return getIsRelatedTo(r, ODirection.IN); + return getIsRelatedTo(r, DIRECTION.IN); } @SuppressWarnings("rawtypes") - protected List getIsRelatedTo(Resource r, ODirection oDirection) throws Exception { + protected List getIsRelatedTo(Resource r, DIRECTION direction) throws Exception { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(Resource.NAME); @@ -153,7 +153,7 @@ public class MultiContextTest extends ERManagementTest { UUID resourceUUID = r.getID(); // 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<>()); List isRelatedToList = ElementMapper.unmarshalList(IsRelatedTo.class, ret); return isRelatedToList; diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/queries/QueryTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/queries/QueryTest.java index 921ed49..a4de203 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/queries/QueryTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/queries/QueryTest.java @@ -42,7 +42,7 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.record.ODirection; +import com.arcadedb.graph.Vertex.DIRECTION; /** * @author Luca Frosini (ISTI - CNR) @@ -169,61 +169,61 @@ public class QueryTest extends ERManagementTest { resourceManagement.setElementType(Service.NAME); /* 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); List resourceList = ElementMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size() == 1); Resource resource = resourceList.get(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); Assert.assertTrue(resourceList.size() == 1); resource = resourceList.get(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); 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); 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); 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); Assert.assertTrue(resourceList.size() == 0); /* END Getting Hosting Node */ /* 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); resourceList = ElementMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size() == 1); 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); 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); Assert.assertTrue(resourceList.size() == 1); 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); resourceList = ElementMapper.unmarshalList(Resource.class, json); 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); resourceList = ElementMapper.unmarshalList(Resource.class, json); 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); Assert.assertTrue(resourceList.size() == 0); /* END Getting HostingNode */ @@ -234,12 +234,12 @@ public class QueryTest extends ERManagementTest { /* EService --ConsistsOf--> SoftwareFacet */ try { json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, - ODirection.BOTH, true, null); + DIRECTION.BOTH, true, null); } catch (InvalidQueryException e) { // Ok expected } - json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.OUT, + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.OUT, true, null); resourceList = ElementMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size() == 1); @@ -249,7 +249,7 @@ public class QueryTest extends ERManagementTest { Assert.assertTrue(targetIdentificationFacet.getID().compareTo(identificationFacetUUID) == 0); try { - json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN, + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.IN, true, null); throw new Exception("Expected InvalidQueryException"); } catch (InvalidQueryException e) { @@ -258,19 +258,19 @@ public class QueryTest extends ERManagementTest { try { json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, - ODirection.BOTH, false, null); + DIRECTION.BOTH, false, null); throw new Exception("Expected InvalidQueryException"); } catch (InvalidQueryException e) { // Ok expected } - json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.OUT, + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.OUT, false, null); resourceList = ElementMapper.unmarshalList(Resource.class, json); Assert.assertTrue(resourceList.size() == 0); try { - json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN, + json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, DIRECTION.IN, false, null); throw new Exception("Expected InvalidQueryException"); } catch (InvalidQueryException e) { @@ -303,7 +303,7 @@ public class QueryTest extends ERManagementTest { if (erManagement instanceof ResourceManagement) { boolean[] booleans = new boolean[] {true, false}; 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 ", type, relationType, facetType, constraint, ret); } @@ -358,7 +358,7 @@ public class QueryTest extends ERManagementTest { parentResourceManagement.setElementType(parentResourceType); - ODirection directionEnum = ODirection.OUT; + DIRECTION directionEnum = DIRECTION.OUT; UUID refereceUUID = null; Boolean[] polymorphics = new Boolean[] {true, false}; diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/types/TypesCacheTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/types/TypesCacheTest.java index 419e260..9af9778 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/types/TypesCacheTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/types/TypesCacheTest.java @@ -19,7 +19,7 @@ public class TypesCacheTest { protected CachedType getCachedType(TypesCache typesCache, String typeName) throws Exception { CachedType cachedType = typesCache.getCachedType(typeName); - OClass oClass = cachedType.getOClass(); + OClass oClass = cachedType.getDocumentType(); AccessType accessType = cachedType.getAccessType(); Type type = cachedType.getType(); logger.debug("{} ({}) : {}", oClass.toString(), accessType.toString(), TypeMapper.serializeTypeDefinition(type));