Porting code to ArcadeDB

This commit is contained in:
Luca Frosini 2023-05-11 18:35:56 +02:00
parent a8fb9de301
commit 50ff2fa19a
43 changed files with 1347 additions and 1472 deletions

25
pom.xml
View File

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

View File

@ -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);
}
}

View File

@ -16,17 +16,18 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecur
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.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<String, String> 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

View File

@ -33,7 +33,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.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<Context, EntityTy
init();
}
public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
public ContextManagement(RemoteDatabase database) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
this.database = database;
getWorkingContext();
}
@ -88,7 +88,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
name = jsonNode.get(Context.NAME_PROPERTY).asText();
}
} else {
name = element.getProperty(Context.NAME_PROPERTY);
name = element.getString(Context.NAME_PROPERTY);
}
}
return name;
@ -166,7 +166,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
logger.trace("Checking if {} -> {}", errorMessage, select);
OResultSet resultSet = oDatabaseDocument.command(select.toString(), new HashMap<>());
ResultSet resultSet = database.command("sql", select.toString(), new HashMap<>());
if (resultSet != null && resultSet.hasNext()) {
throw new ContextAlreadyPresentException(errorMessage.toString());
@ -180,13 +180,13 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
JsonNode context = serializeSelfAsJsonNode();
int count = 0;
Iterable<OEdge> parents = getElement().getEdges(ODirection.IN);
for (OEdge edge : parents) {
Iterable<Edge> 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<Context, EntityTy
((ObjectNode) context).replace(Context.PARENT_PROPERTY, isParentOf);
}
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ContextException("");
}
}
Iterable<OEdge> childrenEdges = getElement().getEdges(ODirection.OUT);
for (OEdge edge : childrenEdges) {
Iterable<Edge> 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<Context, EntityTy
}
@Override
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null;
SecurityContext parentSecurityContext = null;
@ -231,7 +231,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
if (isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
ContextManagement parentContextManagement = new ContextManagement(oDatabaseDocument);
ContextManagement parentContextManagement = new ContextManagement(database);
parentContextManagement.setJsonNode(parentJsonNode);
UUID parentUUID = parentContextManagement.uuid;
parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID);
@ -243,7 +243,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
createVertex();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(parentContextManagement);
isParentOfManagement.setTargetEntityManagement(this);
@ -257,15 +257,15 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
securityContext = new SecurityContext(uuid);
securityContext.setParentSecurityContext(parentSecurityContext);
securityContext.create(oDatabaseDocument);
securityContext.create(database);
ContextUtility.getInstance().addSecurityContext(securityContext);
return getElement();
} catch (Exception e) {
oDatabaseDocument.rollback();
database.rollback();
if (securityContext != null) {
securityContext.delete(oDatabaseDocument);
securityContext.delete(database);
if (parentSecurityContext != null && securityContext != null) {
parentSecurityContext.getChildren().remove(securityContext);
}
@ -276,19 +276,19 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
@Override
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
boolean parentChanged = false;
boolean nameChanged = false;
OVertex parent = null;
Vertex parent = null;
boolean found = false;
Iterable<OVertex> iterable = getElement().getVertices(ODirection.IN, IsParentOf.NAME);
for (OVertex p : iterable) {
Iterable<Vertex> 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<Context, EntityTy
ContextManagement actualParentContextManagement = null;
if (parent != null) {
actualParentContextManagement = new ContextManagement(oDatabaseDocument);
actualParentContextManagement = new ContextManagement(database);
actualParentContextManagement.setElement(parent);
}
@ -320,7 +320,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
if (parentChanged) {
newParentContextManagement = new ContextManagement(oDatabaseDocument);
newParentContextManagement = new ContextManagement(database);
newParentContextManagement.setJsonNode(parentContextJsonNode);
}
} else {
@ -331,7 +331,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
String oldName = getElement().getProperty(Context.NAME_PROPERTY);
String oldName = getElement().getString(Context.NAME_PROPERTY);
String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
if (oldName.compareTo(newName) != 0) {
nameChanged = true;
@ -346,7 +346,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
move(newParentContextManagement, false);
}
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
element = (Vertex) updateProperties(documentType, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ServerContextCache.getInstance().cleanCache();
@ -362,23 +362,23 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
SecurityContext newParentSecurityContext = null;
// Removing the old parent relationship if any
Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME);
Iterable<Edge> edges = getElement().getEdges(DIRECTION.IN, IsParentOf.NAME);
if (edges != null && edges.iterator().hasNext()) {
Iterator<OEdge> edgeIterator = edges.iterator();
OEdge edge = edgeIterator.next();
Iterator<Edge> 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<Context, EntityTy
}
SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, oDatabaseDocument);
thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, database);
}
@Override
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
Iterable<OEdge> iterable = getElement().getEdges(ODirection.OUT);
Iterator<OEdge> iterator = iterable.iterator();
Iterable<Edge> iterable = getElement().getEdges(DIRECTION.OUT);
Iterator<Edge> 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<Context, EntityTy
ContextUtility contextUtility = ContextUtility.getInstance();
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(oDatabaseDocument);
securityContext.delete(database);
ServerContextCache.getInstance().cleanCache();
}
@ -412,18 +412,18 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) {
Iterable<Document> 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 {

View File

@ -18,12 +18,13 @@ import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextMan
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.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<ContextManag
super(AccessType.IS_PARENT_OF, Context.class, Context.class);
}
public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
public IsParentOfManagement(RemoteDatabase database) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
this.database = database;
getWorkingContext();
this.includeSource = false;
this.includeTarget = true;
@ -73,16 +74,16 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
JsonNode relation = serializeSelfAsJsonNode();
try {
OVertex source = element.getVertex(ODirection.OUT);
ContextManagement sourceContextManagement = new ContextManagement(oDatabaseDocument);
Vertex source = element.getVertex(DIRECTION.OUT);
ContextManagement sourceContextManagement = new ContextManagement(database);
sourceContextManagement.setElement(source);
if (includeSource) {
((ObjectNode) relation).replace(Relation.SOURCE_PROPERTY,
sourceContextManagement.serializeSelfAsJsonNode());
}
OVertex target = element.getVertex(ODirection.IN);
ContextManagement targetContextManagement = new ContextManagement(oDatabaseDocument);
Vertex target = element.getVertex(DIRECTION.IN);
ContextManagement targetContextManagement = new ContextManagement(database);
targetContextManagement.setElement(target);
if (includeTarget) {
((ObjectNode) relation).replace(Relation.TARGET_PROPERTY,
@ -90,10 +91,10 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e;
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}
@ -102,12 +103,12 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
@Override
protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ContextManagement(oDatabaseDocument);
return new ContextManagement(database);
}
@Override
protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ContextManagement(oDatabaseDocument);
return new ContextManagement(database);
}
@Override

View File

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

View File

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

View File

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

View File

@ -20,17 +20,21 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.utils.UUIDManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.database.Identifiable;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.database.RID;
import com.arcadedb.database.Record;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.ODatabasePool;
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordLazySet;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
@ -87,7 +91,7 @@ public class SecurityContext {
protected final UUID context;
protected final Map<Boolean,Map<PermissionMode,ODatabasePool>> poolMap;
protected final Map<Boolean,Map<PermissionMode,RemoteDatabase>> 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<SecurityContext> 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<ORole> roles = new ArrayList<>();
List<Role> 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<PermissionMode,ODatabasePool> pools = poolMap.get(h);
if(pools == null) {
pools = new HashMap<>();
poolMap.put(h, pools);
Map<PermissionMode,RemoteDatabase> 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<String> getContexts(OElement element) {
public static Set<String> getContexts(Document element) {
Set<String> 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);
}
}
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<SecurityContext> parents = getAllParents();
Set<SecurityContext> allChildren = getAllChildren();
removeChildrenHRolesFromParents(oSecurity, parents, allChildren);
removeChildrenHRolesFromParents(remoteDatabase, parents, allChildren);
}
protected void removeChildrenHRolesFromParents(OSecurity oSecurity, Set<SecurityContext> parents, Set<SecurityContext> children) {
protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase, Set<SecurityContext> parents, Set<SecurityContext> children) {
for(SecurityContext parent : parents) {
parent.removeChildrenHRolesFromMyHUsers(oSecurity, children);
parent.removeChildrenHRolesFromMyHUsers(remoteDatabase, children);
}
}
protected void removeChildrenHRolesFromMyHUsers(OSecurity oSecurity, Set<SecurityContext> children) {
protected void removeChildrenHRolesFromMyHUsers(RemoteDatabase database, Set<SecurityContext> children) {
for(PermissionMode permissionMode : PermissionMode.values()) {
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

View File

@ -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<PermissionMode,String> DEFAULT_PASSWORDS;
private static final String HOSTS;
private static final String SERVER_URI;
public static final String DB_URI;
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
protected static final String DB_KEY_FILENAME_VARNAME = "DB_KEY_FILENAME";
protected static final String DB_KEY_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<PermissionMode,String>();
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<? extends Element> clazz : schemaToBeCreated) {
ElementManagement<? extends OElement,?> erManagement = new PropertyTypeDefinitionManagement();
ElementManagement<? extends Document,?> 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<String> 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());
}
}
}

View File

@ -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<El extends OElement, T extends Type> {
public abstract class ElementManagement<El extends Document, T extends Type> {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@ -89,11 +87,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
protected Class<El> elementClass;
protected 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;
@ -183,6 +182,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
if(this.typeName == null) {
this.typeName = TypeUtility.getTypeName(jsonNode);
getOClass();
getDocumentType();
} else {
checkERMatch();
}
@ -396,7 +404,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
throw new ResourceRegistryException(error);
}
}
getOClass();
getDocumentType();
}
@ -414,8 +422,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
}
private void analizeProperty(OElement element, String key, ObjectNode objectNode) throws ResourceRegistryException {
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<El extends OElement, T extends Type> {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
OElement element = getElement();
El element = getElement();
Set<String> keys = element.getPropertyNames();
/* Add first these key to provide an order in Json */
@ -539,13 +547,13 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
element = reallyCreate();
element.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<El extends OElement, T extends Type> {
MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save();
// element.save();
sanityCheck();
@ -601,8 +609,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
} 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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
internalCreate();
}
oDatabaseDocument.commit();
database.commit();
if(update) {
setReload(true);
@ -741,38 +748,37 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
} 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<El extends OElement, T extends Type> {
} 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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
} 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<String> 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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<Object> list = new ArrayList<Object>();
Iterator<JsonNode> 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<Object> set = new HashSet<Object>();
Iterator<JsonNode> 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<El extends OElement, T extends Type> {
element.setProperty(key, set, OType.EMBEDDEDSET);
break;
case EMBEDDEDMAP:
case MAP:
Map<String, Object> map = new HashMap<>();
Iterator<String> 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<String> ignoreKeys,
public Document updateProperties(DocumentType type, Document element, JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreStartWithKeys) throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyNames();
@ -1161,27 +1166,27 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
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<El extends OElement, T extends Type> {
}
}
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<El extends OElement, T extends Type> {
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));
}

View File

@ -20,15 +20,15 @@ import org.gcube.informationsystem.resourceregistry.instances.model.relations.Co
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.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 extends OElement> E getElementFromOptional(Optional<E> optional) throws ResourceRegistryException {
public static <E extends Document> E getElementFromOptional(Optional<E> 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<OClass> 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;
}
}

View File

@ -18,18 +18,19 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.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<E extends EntityElement, ET extends EntityType> extends ElementManagement<OVertex, ET> {
public abstract class EntityElementManagement<E extends EntityElement, ET extends EntityType> extends ElementManagement<Vertex, ET> {
public final static String IN_PREFIX = "in_";
public final static String OUT_PREFIX = "out_";
@ -52,9 +53,9 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
}
protected EntityElementManagement(AccessType accessType, SecurityContext workingContext, ODatabaseDocument oDatabaseDocument) {
protected EntityElementManagement(AccessType accessType, SecurityContext workingContext, RemoteDatabase database) {
this(accessType);
this.oDatabaseDocument = oDatabaseDocument;
this.database = database;
setWorkingContext(workingContext);
}
@ -64,11 +65,11 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
* fake id starting with - (minus) sign. This not imply any collateral effect
* but a better solution is a desiderata.
*/
protected RelationElementManagement<?,?,?,?> getBaseRelationManagement(OEdge edge) throws ResourceRegistryException {
protected RelationElementManagement<?,?,?,?> getBaseRelationManagement(Edge edge) throws ResourceRegistryException {
String id = edge.getIdentity().toString();
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<E extends EntityElement, ET extend
protected void addToRelationManagement(RelationElementManagement<?,?,?,?> 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<E extends EntityElement, ET extend
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, baseRelationManagement);
@ -108,23 +109,24 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
return sourceResource;
}
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode);
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 ResourceRegistryException(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 ResourceRegistryException(error);
// }
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);
@ -133,10 +135,10 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
} 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 Element. This is not allowed.",
uuid.toString(),
(el instanceof OVertex) ? EntityElement.NAME : RelationElement.NAME);
(el instanceof Vertex) ? EntityElement.NAME : RelationElement.NAME);
throw new ResourceRegistryException(error);
} catch(NotFoundException e1) {
@ -146,23 +148,23 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
throw e;
}
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName);
MutableVertex vertexEntity = database.newVertex(typeName);
this.element = vertexEntity;
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.info("Created {} is {}", OVertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging(element));
logger.info("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());
}

View File

@ -26,13 +26,15 @@ import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient;
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.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.impl.ODocument;
@ -55,8 +57,8 @@ public class PropertyElementManagement {
}
public static ODocument getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException {
ODocument oDocument = null;
public static Document getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException {
Document document = null;
if(jsonNodeOrig.isNull()) {
return null;
}
@ -70,13 +72,13 @@ public class PropertyElementManagement {
String type = TypeUtility.getTypeName(jsonNode);
if(type!=null) {
// Complex type
OClass oClass = null;
DocumentType documentType = null;
try {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) 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<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) 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();

View File

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

View File

@ -19,7 +19,7 @@ import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.arcadedb.remote.RemoteDatabase;
public class ERManagementUtility {
@ -29,12 +29,12 @@ public class ERManagementUtility {
throws NotFoundException, ContextException, ResourceRegistryException {
Set<UUID> 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<UUID> 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();
// }
}
}

View File

@ -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<E extends Entity, ET extends EntityType>
}
@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<E extends Entity, ET extends EntityType>
* 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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
}
@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<E extends Entity, ET extends EntityType>
} 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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
}
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetSecurityContext.addElement(getElement(), database);
/*
* DO NOT UNCOMMENT
@ -314,9 +320,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* the update of Metadata i.e. modifiedBy, lastUpdateTime
*/
if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) {
for(Edge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
@ -336,7 +342,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
reallyAddToContext();
if(!skipped) {
MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save();
// element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
}
@ -352,11 +358,11 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
}
if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) {
for(Edge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
@ -434,7 +440,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
}
targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
targetSecurityContext.removeElement(getElement(), database);
/*
* DO NOT UNCOMMENT
@ -449,11 +455,11 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for(ODocument vertex : iterable) {
Iterable<Document> 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<E extends Entity, ET extends EntityType>
}
}
public boolean propertyMatchRequestedValue(OVertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
public boolean propertyMatchRequestedValue(Vertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
return requestedValue.compareTo(instanceValue.toString())==0;
/*
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<E extends Entity, ET extends EntityType>
/*
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
@ -555,21 +561,21 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
}
}
List<OVertex> vertexes = new ArrayList<>();
vertexes.add((OVertex) element);
List<Vertex> vertexes = new ArrayList<>();
vertexes.add((Vertex) element);
references = vertexes;
} else {
@ -587,19 +593,19 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
} else {
references = oDatabaseDocument.browseClass(referenceType, polymorphic);
references = database.browseClass(referenceType, polymorphic);
}
Set<ORID> analysed = new HashSet<>();
Set<RID> analysed = new HashSet<>();
for(Object r : references) {
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<E extends Entity, ET extends EntityType>
}
List<ODirection> directions = new ArrayList<>();
if(direction==ODirection.BOTH) {
directions.add(ODirection.IN);
directions.add(ODirection.OUT);
List<DIRECTION> 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<OEdge> edges = v.getEdges(d.opposite(), relationType);
for(OEdge edge : edges) {
OVertex vertex = edge.getVertex(d);
Iterable<Edge> 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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
}
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
ODirection direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
DIRECTION direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
@ -732,7 +738,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
public String query(String relationType, String referenceType, UUID referenceUUID, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
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<E extends Entity, ET extends EntityType>
} 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();
// }
}
}

View File

@ -16,10 +16,10 @@ import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.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<Facet, FacetType> {
}
@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<Facet, FacetType> {
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<Facet, FacetType> {
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<Facet, FacetType> {
@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<Facet, FacetType> {
// 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<Facet, FacetType> {
}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<Facet, FacetType> {
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");
}

View File

@ -32,15 +32,15 @@ import org.gcube.informationsystem.resourceregistry.instances.model.relations.Is
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.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<Resource, ResourceType>
* ConsistsOf.NAME); TODO Looks for a different query
*/
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(OEdge edge : edges) {
Iterable<Edge> 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<Resource, ResourceType>
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<Resource, ResourceType>
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<Resource, ResourceType>
}
@Override
protected OVertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
createVertex();
@ -156,7 +156,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
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<Resource, ResourceType>
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<Resource, ResourceType>
}
@Override
protected OVertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
getElement();
@ -192,7 +192,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
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<Resource, ResourceType>
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<Resource, ResourceType>
getElement();
Iterable<OEdge> iterable = element.getEdges(ODirection.OUT);
Iterator<OEdge> iterator = iterable.iterator();
Iterable<Edge> iterable = element.getEdges(DIRECTION.OUT);
Iterator<Edge> 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<Resource, ResourceType>
}
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<Resource, ResourceType>
return;
}
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetSecurityContext.addElement(getElement(), database);
/*
* DO NOT UNCOMMENT
@ -278,11 +278,11 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
*/
if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
Iterable<Edge> 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<Resource, ResourceType>
@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<Resource, ResourceType>
Map<LinkedEntity, Integer> satisfiedConsistsOfFacet = new HashMap<>();
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(OEdge edge : edges) {
for(Edge edge : edges) {
String id = edge.getIdentity().toString();
RelationManagement<?,?> relationManagement = relationManagements.get(id);
@ -452,7 +452,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
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<Resource, ResourceType>
*/
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<Resource, ResourceType>
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

View File

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

View File

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

View File

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

View File

@ -10,14 +10,14 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.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();
// }
}
}

View File

@ -25,15 +25,15 @@ import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
import org.gcube.informationsystem.resourceregistry.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();
// }
}
}

View File

@ -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<QueryTempla
}
protected void checkERMatch() throws ResourceRegistryException {
getOClass();
getDocumentType();
}
protected void checkNameMatch() throws ResourceRegistryException {
@ -185,7 +185,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
OResult oResult = resultSet.next();
OVertex queryTemplate = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, OrientDBUtility.getAsStringForLogging(queryTemplate));
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, DBUtility.getAsStringForLogging(queryTemplate));
if(resultSet.hasNext()) {
resultSet.close();
@ -264,7 +264,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
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 {

View File

@ -21,11 +21,8 @@ import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.OSecurity;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.DocumentType;
/**
* @author Luca Frosini (ISTI - CNR)
@ -46,7 +43,7 @@ public class CachedType<T extends Type> {
protected final String typeName;
protected OClass oClass;
protected DocumentType documentType;
protected AccessType accessType;
@ -62,21 +59,21 @@ public class CachedType<T extends Type> {
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<T extends Type> {
} 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<T extends Type> {
// 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<OClass> superClasses = internalGetOClass().getSuperClasses();
List<DocumentType> superClasses = internalGetDocumentType().getSuperTypes();
while(superClasses.size()>0) {
List<OClass> toBeAnalysed = new ArrayList<>(superClasses);
List<DocumentType> 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<T extends Type> {
continue;
}
allSuperClasses.add(allSuperClasses.size(), name);
superClasses.addAll(oSuperClass.getSuperClasses());
superClasses.addAll(oSuperClass.getSuperTypes());
}
}
return allSuperClasses;
@ -150,32 +147,32 @@ public class CachedType<T extends Type> {
TypesCache typesCache = TypesCache.getInstance();
List<String> allSubClasses = new ArrayList<>();
Collection<OClass> subclasses = internalGetOClass().getSubclasses();
Collection<DocumentType> subclasses = internalGetDocumentType().getSubTypes();
while(subclasses.size()>0) {
List<OClass> toBeAnalysed = new ArrayList<>(subclasses);
List<DocumentType> 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<T extends Type> {
if(type!=null) {
accessType = type.getAccessType();
}else {
accessType = getAccessTypeFromOClass(internalGetOClass());
accessType = getAccessTypeFromDocumentType(internalGetDocumentType());
}
}
return accessType;
@ -212,8 +209,8 @@ public class CachedType<T extends Type> {
}
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 {

View File

@ -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<? extends OElement,?> erManagement = null;
ElementManagement<? extends MutableDocument,?> 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<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
protected List<DocumentType> getSuperTypesAndCheckCompliancy(RemoteDatabase database,
Type type, String baseType) throws SchemaException, SchemaNotFoundException {
Set<String> superClasses = type.getTypeSuperTypes();
@ -236,27 +231,27 @@ public class TypeManagement {
}
}
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OMetadata oMetadata = database.getMetadata();
OSchema oSchema = oMetadata.getSchema();
List<OClass> oSuperclasses = new ArrayList<>();
List<DocumentType> 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<String> 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<? extends Element> 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<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseDocument, type,
List<DocumentType> 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<Type> 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<Type> typeDefinitions = new ArrayList<>();
typeDefinitions.add(getType(baseOClass));
typeDefinitions.add(getType(baseDocumentType));
if(includeSubtypes) {
Collection<OClass> subClasses = baseOClass.getAllSubclasses();
for(OClass oClass : subClasses) {
typeDefinitions.add(getType(oClass));
Collection<DocumentType> 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();
}
}
}

View File

@ -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<E extends EntityType> 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<E extends EntityType> 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<E extends EntityType> 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<E extends EntityType> 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<E extends EntityType> 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<E extends EntityType> 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<E extends EntityType> 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());
}

View File

@ -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<OElement, PropertyType<?>> {
public class PropertyTypeDefinitionManagement extends ElementManagement<Document, PropertyType<?>> {
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
@ -42,9 +40,9 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
this.typeName = PropertyType.NAME;
}
public PropertyTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
public PropertyTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
this.database = database;
setWorkingContext(securityContext);
}
@ -72,7 +70,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
name = jsonNode.get(PropertyType.NAME_PROPERTY).asText();
}
} else {
name = element.getProperty(PropertyType.NAME_PROPERTY);
name = element.getString(PropertyType.NAME_PROPERTY);
}
}
return name;
@ -84,16 +82,16 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
}
@Override
protected OElement reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
protected Document reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", PropertyType.NAME, getName());
return createElement();
}
@Override
protected OElement reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected Document reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", PropertyType.NAME, getName());
OElement propertyTypeDefinition = getElement();
propertyTypeDefinition = updateProperties(oClass, propertyTypeDefinition, jsonNode,
Document propertyTypeDefinition = getElement();
propertyTypeDefinition = updateProperties(documentType, propertyTypeDefinition, jsonNode,
ignoreKeys, ignoreStartWithKeys);
return propertyTypeDefinition;
}
@ -105,7 +103,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
}
@Override
public OElement getElement() throws NotFoundException, ResourceRegistryException {
public Document getElement() throws NotFoundException, ResourceRegistryException {
if(element == null) {
try {
element = retrieveElement();
@ -126,7 +124,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
}
@Override
public OElement retrieveElement() throws NotFoundException, ResourceRegistryException {
public Document retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if(getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
@ -135,7 +133,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
String select = "SELECT FROM " + typeName + " WHERE " + PropertyType.NAME_PROPERTY + " = \""
+ getName() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
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<OElement
throw new NotFoundException(error);
}
OResult oResult = resultSet.next();
OElement element = (OElement) ElementManagementUtility.getElementFromOptional(oResult.getElement());
Result oResult = resultSet.next();
Document element = (Document) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -163,19 +161,19 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
}
}
protected OElement createElement() throws AlreadyPresentException, ResourceRegistryException {
protected Document createElement() throws AlreadyPresentException, ResourceRegistryException {
try {
this.element = new ODocument(typeName);
this.element = database.newDocument(typeName);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", PropertyType.NAME, OrientDBUtility.getAsStringForLogging(element));
logger.debug("Created {} is {}", PropertyType.NAME, DBUtility.getAsStringForLogging(element));
return element;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", OElement.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", Document.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}

View File

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

View File

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

View File

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

View File

@ -1,6 +1,5 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashMap;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
@ -21,36 +20,29 @@ import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import com.arcadedb.database.Document;
import com.arcadedb.database.MutableEmbeddedDocument;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
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 OrientDBUtility {
public class DBUtility {
private static final Logger logger = LoggerFactory.getLogger(OrientDBUtility.class);
private static final Logger logger = LoggerFactory.getLogger(DBUtility.class);
public static final String ORIENTDB_CLASS_PROPERTY = ODocumentHelper.ATTRIBUTE_CLASS;
public static final String DB_TYPE_PROPERTY = "@type";
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JsonNode toJsonNode(OElement element) throws ResourceRegistryException {
ORecord oRecord = element.getRecord();
return OrientDBUtility.toJsonNode(oRecord);
}
public static JsonNode toJsonNode(ORecord oRecord) throws ResourceRegistryException {
public static JsonNode toJsonNode(Document document) throws ResourceRegistryException {
try {
ObjectMapper objectMapper = new ObjectMapper();
String string = toJsonString(oRecord);
String string = toJsonString(document);
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(string);
return objectNode;
} catch(Exception e) {
@ -59,61 +51,52 @@ public class OrientDBUtility {
}
public static String replaceType(String s) {
s = s.replace("\"" + ORIENTDB_CLASS_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\"");
s = s.replace("\"" + DB_TYPE_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\"");
return s;
}
public static String toJsonString(OResult oResult) {
String ret = oResult.toJSON();
public static String toJsonString(Document document) {
String ret = document.toJSON().toString();
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
}
public static String toJsonString(ORecord oRecord) {
String ret = oRecord.toJSON("class");
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
public static String getAsStringForLogging(Document document) {
return document.toJSON().toString();
}
public static String getAsStringForLogging(ORecord oRecord) {
return oRecord.toJSON();
public static String getAsStringForException(Document document) {
return toJsonString(document);
}
public static String getAsStringForException(ORecord oRecord) {
return toJsonString(oRecord);
}
public static <El extends OElement> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
public static <El extends Document> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
Class<? extends El> 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 extends OElement> El getElementByUUID(ODatabaseDocument oDatabaseDocument, String elementType, UUID uuid,
public static <El extends Document> El getElementByUUID(RemoteDatabase database, String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
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 extends PropertyElement> P getPropertyDocument(Class<P> clz, OElement element, String property)
public static <P extends PropertyElement> P getPropertyDocument(Class<P> clz, Document element, String property)
throws ResourceRegistryException {
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));

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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);
}
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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();

View File

@ -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);
}

View File

@ -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<IsRelatedTo> getIncomingIsRelatedTo(Resource r) throws Exception {
return getIsRelatedTo(r, ODirection.OUT);
return getIsRelatedTo(r, DIRECTION.OUT);
}
@SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getOutcomingIsRelatedTo(Resource r) throws Exception {
return getIsRelatedTo(r, ODirection.IN);
return getIsRelatedTo(r, DIRECTION.IN);
}
@SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getIsRelatedTo(Resource r, ODirection oDirection) throws Exception {
protected List<IsRelatedTo> getIsRelatedTo(Resource r, DIRECTION direction) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.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<IsRelatedTo> isRelatedToList = ElementMapper.unmarshalList(IsRelatedTo.class, ret);
return isRelatedToList;

View File

@ -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<Resource> 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};

View File

@ -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));