Refs #10435: Add support for hierarchical roles to support child context overview

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

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@158879 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2017-11-28 16:34:43 +00:00
parent d79b91361e
commit f754bf7dda
29 changed files with 1185 additions and 1239 deletions

View File

@ -0,0 +1,65 @@
package org.gcube.informationsystem.resourceregistry.context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
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.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class AdminSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public AdminSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
}
@Override
public void create() {
throw new RuntimeException("Cannot use this method for Admin Context");
}
@Override
public void create(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
ORole admin = oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
ORole writerRole = oSecurity.createRole(writerRoleName, admin, ALLOW_MODES.DENY_ALL_BUT);
writerRole.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL);
writerRole.save();
logger.trace("{} created", writerRole);
ORole readerRole = oSecurity.createRole(readerRoleName, admin, ALLOW_MODES.DENY_ALL_BUT);
readerRole.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_READ);
readerRole.save();
logger.trace("{} created", readerRole);
OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
writerUser.save();
logger.trace("{} created", writerUser);
OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
readerUser.save();
logger.trace("{} created", readerUser);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
}

View File

@ -18,6 +18,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
@ -39,11 +40,8 @@ public class ContextManagement extends EntityManagement<Context> {
protected String name; protected String name;
private void init() { private void init() {
this.forceAdmin = true;
this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY); this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY);
this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY); this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY);
this.erType = Context.NAME; this.erType = Context.NAME;
} }
@ -52,9 +50,10 @@ public class ContextManagement extends EntityManagement<Context> {
init(); init();
} }
public ContextManagement(OrientGraph orientGraph) { public ContextManagement(OrientGraph orientGraph) throws ResourceRegistryException {
super(AccessType.CONTEXT, orientGraph); this();
init(); this.orientGraph = orientGraph;
getWorkingContext();
} }
public String getName() { public String getName() {
@ -70,6 +69,13 @@ public class ContextManagement extends EntityManagement<Context> {
return name; return name;
} }
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
return workingContext;
}
@Override @Override
protected ContextNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { protected ContextNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) {
return new ContextNotFoundException(e.getMessage(), e.getCause()); return new ContextNotFoundException(e.getMessage(), e.getCause());
@ -190,6 +196,8 @@ public class ContextManagement extends EntityManagement<Context> {
@Override @Override
protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null;
try { try {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
@ -203,7 +211,6 @@ public class ContextManagement extends EntityManagement<Context> {
if(uuid==null){ if(uuid==null){
uuid = UUID.randomUUID(); uuid = UUID.randomUUID();
} }
SecurityContext.createSecurityContext(orientGraph, uuid, true);
createVertex(); createVertex();
@ -216,14 +223,18 @@ public class ContextManagement extends EntityManagement<Context> {
}else { }else {
checkContext(null); checkContext(null);
SecurityContext.createSecurityContext(orientGraph, uuid, true);
createVertex(); createVertex();
} }
securityContext = new SecurityContext(uuid);
securityContext.create(orientGraph);
return getElement(); return getElement();
}catch (Exception e) { }catch (Exception e) {
orientGraph.rollback(); orientGraph.rollback();
SecurityContext.deleteSecurityContext(orientGraph, uuid, true); if(securityContext!=null) {
securityContext.delete(orientGraph);
}
throw e; throw e;
} }
} }
@ -303,7 +314,7 @@ public class ContextManagement extends EntityManagement<Context> {
element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys); element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ContextUtility.invalidContextUUIDCache(uuid); ContextUtility.getInstace().removeFromCache(uuid);
return element; return element;
} }
@ -351,8 +362,11 @@ public class ContextManagement extends EntityManagement<Context> {
element.remove(); element.remove();
ContextUtility.invalidContextUUIDCache(uuid); ContextUtility contextUtility = ContextUtility.getInstace();
SecurityContext.deleteSecurityContext(orientGraph, uuid, false); SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(orientGraph);
contextUtility.removeFromCache(uuid);
return true; return true;

View File

@ -0,0 +1,72 @@
package org.gcube.informationsystem.resourceregistry.context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
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.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class ContextSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public ContextSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
@Override
public void create(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
ORole writer = oSecurity.getRole(DEFAULT_WRITER_ROLE);
ORole reader = oSecurity.getRole(DEFAULT_READER_ROLE);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
/*
String writerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, true);
String readerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, true);
String writerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, true);
String readerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, true);
*/
ORole writerRole = oSecurity.createRole(writerRoleName, writer, ALLOW_MODES.DENY_ALL_BUT);
writerRole.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL);
writerRole.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL);
writerRole.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL);
writerRole.save();
logger.trace("{} created", writerRole);
ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT);
readerRole.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ);
readerRole.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ);
readerRole.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ);
readerRole.save();
logger.trace("{} created", readerRole);
OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
writerUser.save();
logger.trace("{} created", writerUser);
OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
readerUser.save();
logger.trace("{} created", readerUser);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
}

View File

@ -6,6 +6,7 @@ package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID; import java.util.UUID;
import org.gcube.common.authorization.client.Constants; import org.gcube.common.authorization.client.Constants;
@ -14,21 +15,19 @@ import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean; import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.informationsystem.model.entity.Context; import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -36,60 +35,26 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
*/ */
public class ContextUtility { public class ContextUtility {
private static final Logger logger = LoggerFactory private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
.getLogger(ContextUtility.class);
private static Map<String, UUID> contextUUIDCache; private Map<String, UUID> contextUUIDs;
private Map<UUID, SecurityContext> contexts;
static {
contextUUIDCache = new HashMap<>(); private static ContextUtility contextUtility;
}
public static ContextUtility getInstace() {
if (contextUtility == null) {
protected static void invalidContextUUIDCache(){ contextUtility = new ContextUtility();
contextUUIDCache = new HashMap<>();
}
protected static void invalidContextUUIDCache(UUID uuid){
for(String scope : contextUUIDCache.keySet()){
UUID gotUUID = contextUUIDCache.get(scope);
if(gotUUID.compareTo(uuid)==0){
contextUUIDCache.remove(scope);
return;
}
} }
return contextUtility;
}
public static UUID addToActualContext(OrientGraph orientGraph, Element element)
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.addToSecurityContext(orientGraph, element, contextUUID);
return contextUUID;
} }
public static UUID addToActualContex(OSecurity oSecurity, Element element) private ContextUtility() {
throws ContextException { contextUUIDs = new HashMap<>();
UUID contextUUID = ContextUtility.getActualContextUUID(); contexts = new HashMap<>();
SecurityContext.addToSecurityContext(oSecurity, element, contextUUID);
return contextUUID;
} }
public static UUID removeFromActualContext(OrientGraph orientGraph, Element element) private static String getCurrentContextFullName() {
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.removeFromSecurityContext(orientGraph, element, contextUUID);
return contextUUID;
}
public static UUID removeFromActualContext(OSecurity oSecurity, Element element)
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.removeFromSecurityContext(oSecurity, element, contextUUID);
return contextUUID;
}
public static String getCurrentContext(){
String token = SecurityTokenProvider.instance.get(); String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null; AuthorizationEntry authorizationEntry = null;
try { try {
@ -99,145 +64,138 @@ public class ContextUtility {
} }
return authorizationEntry.getContext(); return authorizationEntry.getContext();
} }
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
String fullName = getCurrentContextFullName();
if (fullName == null) {
throw new ContextException("Null Token and Scope. Please set your token first.");
}
return ContextUtility.getInstace().getSecurityContextByFullName(fullName);
}
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace().
getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
return adminSecurityContext;
}
public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException {
for (String fullName : contextUUIDs.keySet()) {
UUID uuidKey = contextUUIDs.get(fullName);
if (uuidKey.compareTo(uuid) == 0) {
contextUUIDs.remove(fullName);
contexts.remove(uuid);
return;
}
}
}
public synchronized void addSecurityContext(String fullname, SecurityContext securityContext) {
contextUUIDs.put(fullname, securityContext.getUUID());
contexts.put(securityContext.getUUID(), securityContext);
}
public static UUID getActualContextUUID() throws ContextException { private synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException {
OrientGraph orientGraph = null;
try { try {
String scope = getCurrentContext(); SecurityContext securityContext = null;
if(scope==null){
throw new ContextException("Null Token and Scope. Please set your token first."); logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
UUID uuid = contextUUIDs.get(fullName);
if (uuid == null) {
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
fullName);
Vertex contextVertex = getContextVertexByFullName(fullName);
uuid = Utility.getUUID(contextVertex);
securityContext = getSecurityContextByUUID(uuid, contextVertex);
addSecurityContext(fullName, securityContext);
} else {
securityContext = contexts.get(uuid);
} }
logger.trace("Trying to get context UUID for scope {}", scope);
return securityContext;
UUID uuid = contextUUIDCache.get(scope);
if(uuid == null){
logger.trace("UUID for scope {} is not in cache. Going to query it", scope);
orientGraph = SecurityContextMapper
.getSecurityContextGraph(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.READER);
Vertex context = ContextUtility.getContextVertexByFullName(
orientGraph, scope);
uuid = Utility.getUUID(context);
contextUUIDCache.put(scope, uuid);
}
return uuid;
} catch (ContextException e) { } catch (ContextException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ContextException( throw new ContextException("Unable to restrive Context UUID from current Context", e);
"Unable to restrive Context UUID from current Context", e); }
} finally{ }
if(orientGraph!=null){
orientGraph.shutdown(); protected SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException {
return getSecurityContextByUUID(uuid, null);
}
private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
return Utility.getElementByUUID(getAdminSecurityContext().getGraph(PermissionMode.READER), Context.NAME, uuid,
Vertex.class);
}
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid);
if (securityContext == null) {
securityContext = new SecurityContext(uuid);
try {
if (contextVertex == null) {
contextVertex = getContextVertexByUUID(uuid);
}
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next();
if (parentVertex != null) {
UUID parentUUID = Utility.getUUID(parentVertex);
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
}
} catch (NoSuchElementException e) {
// No parent
} }
contexts.put(uuid, securityContext);
} }
return securityContext;
} }
public static OrientGraph getActualSecurityContextGraph( private Vertex getContextVertexByFullName(String fullName) throws ResourceRegistryException {
PermissionMode permissionMode, boolean forceAdmin) throws ResourceRegistryException {
try {
UUID contextUUID = null;
if(forceAdmin) {
contextUUID = SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID;
}else {
contextUUID = getActualContextUUID();
}
return SecurityContextMapper.getSecurityContextGraph(contextUUID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
}
public static OrientGraphNoTx getActualSecurityContextGraphNoTx(
PermissionMode permissionMode, boolean forceAdmin) throws ResourceRegistryException {
try {
UUID contextUUID = null;
if(forceAdmin) {
contextUUID = SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID;
}else {
contextUUID = getActualContextUUID();
}
return SecurityContextMapper.getSecurityContextGraphNoTx(contextUUID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
}
public static ODatabaseDocumentTx getActualSecurityContextDatabaseTx(
PermissionMode permissionMode) throws ResourceRegistryException {
try {
UUID contextUUID = getActualContextUUID();
return SecurityContextMapper.getSecurityContextDatabaseDocumentTx(contextUUID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
}
public static Vertex getContextVertexByFullName(OrientGraph orientGraph,
String fullName) throws ContextNotFoundException {
logger.trace("Going to get {} {} from full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName); logger.trace("Going to get {} {} from full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName);
ScopeBean scopeBean = new ScopeBean(fullName); ScopeBean scopeBean = new ScopeBean(fullName);
String name = scopeBean.name(); String name = scopeBean.name();
// TODO Rewrite the query using Gremlin // TODO Rewrite the query using Gremlin
// Please note that this query works because all the scope parts has a // Please note that this query works because all the scope parts has a
// different name // different name
String select = "SELECT FROM " + Context.class.getSimpleName() String select = "SELECT FROM " + Context.class.getSimpleName() + " WHERE " + Context.NAME_PROPERTY + " = \""
+ " WHERE " + Context.NAME_PROPERTY + " = \"" + name + "\""; + name + "\"";
; ;
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>( OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery) Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
.execute(); .execute();
if (vertexes == null || !vertexes.iterator().hasNext()) { if (vertexes == null || !vertexes.iterator().hasNext()) {
throw new ContextNotFoundException( throw new ContextNotFoundException("Error retrieving context with name " + fullName);
"Error retrieving context with name " + fullName);
} }
Iterator<Vertex> iterator = vertexes.iterator(); Iterator<Vertex> iterator = vertexes.iterator();
Vertex context = iterator.next(); Vertex context = iterator.next();
logger.trace("Context Representing Vertex : {}", logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
Utility.toJsonString(context, true));
if (iterator.hasNext()) { if (iterator.hasNext()) {
throw new ContextNotFoundException( throw new ContextNotFoundException("Found more than one context with name " + name
"Found more than one context with name " + name + "but required the one with path" + fullName + ". Please Reimplement the query");
+ "but required the one with path" + fullName
+ ". Please Reimplement the query");
} }
return context; return context;
} }
public static String getActualSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode permissionMode,
SecurityContextMapper.SecurityType securityType)
throws ContextException {
UUID contextUUID = getActualContextUUID();
return SecurityContextMapper.getSecurityRoleOrUserName(permissionMode,
securityType, contextUUID);
}
} }

View File

@ -16,6 +16,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
@ -34,8 +35,18 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
super(AccessType.IS_PARENT_OF); super(AccessType.IS_PARENT_OF);
} }
public IsParentOfManagement(OrientGraph orientGraph) { public IsParentOfManagement(OrientGraph orientGraph) throws ResourceRegistryException {
super(AccessType.IS_PARENT_OF, orientGraph); this();
this.orientGraph = orientGraph;
getWorkingContext();
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
return workingContext;
} }
@Override @Override

View File

@ -3,8 +3,12 @@
*/ */
package org.gcube.informationsystem.resourceregistry.context; package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -19,6 +23,8 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
@ -26,194 +32,270 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
*/ */
public class SecurityContext { public class SecurityContext {
private static Logger logger = LoggerFactory private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
.getLogger(SecurityContext.class);
public static final String DEFAULT_WRITER_ROLE = "writer"; public static final String DEFAULT_WRITER_ROLE = "writer";
public static final String DEFAULT_READER_ROLE = "reader"; public static final String DEFAULT_READER_ROLE = "reader";
public static final String H = "H";
public static void addToSecurityContext(OrientGraph orientGraph, public enum SecurityType {
Element element, UUID context) { ROLE("Role"), USER("User");
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity(); private final String name;
SecurityContext.addToSecurityContext(oSecurity, element, context);
private SecurityType(String name) {
this.name = name;
}
public String toString() {
return name;
}
} }
public static void addToSecurityContext(OSecurity oSecurity, Element element, public enum PermissionMode {
UUID context) { READER("Reader"), WRITER("Writer");
private final String name;
private PermissionMode(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
protected final UUID context;
protected final Map<PermissionMode, OrientGraphFactory> factories;
protected SecurityContext parentSecurityContext;
public void setParentSecurityContext(SecurityContext parentSecurityContext) {
this.parentSecurityContext = parentSecurityContext;
}
public SecurityContext(UUID context) throws ResourceRegistryException {
this.context = context;
this.factories = new HashMap<>();
}
private synchronized OrientGraphFactory getFactory(PermissionMode permissionMode, boolean recreate) {
OrientGraphFactory factory = null;
if (recreate) {
factories.remove(permissionMode);
} else {
factory = factories.get(permissionMode);
}
if (factory == null) {
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI, username, password).setupPool(1, 10);
factory.setConnectionStrategy(DatabaseEnvironment.CONNECTION_STRATEGY_PARAMETER.toString());
factories.put(permissionMode, factory);
}
return factory;
}
public UUID getUUID() {
return context;
}
protected String getSecurityRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
boolean hierarchic) {
StringBuilder stringBuilder = new StringBuilder();
if (hierarchic) {
stringBuilder.append(H);
}
stringBuilder.append(permissionMode);
stringBuilder.append(securityType);
stringBuilder.append("_");
stringBuilder.append(context.toString());
return stringBuilder.toString();
}
protected ODatabaseDocumentTx getAdminODatabaseDocumentTx(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
return oDatabaseDocumentTx;
}
protected OSecurity getAdminOSecurity(ODatabaseDocumentTx oDatabaseDocumentTx) {
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
return oSecurity;
}
private OSecurity getAdminOSecurity(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
return getAdminOSecurity(oDatabaseDocumentTx);
}
public void addElement(Element element) throws ResourceRegistryException {
addElement(element, ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER));
}
public void addElement(Element element, OrientGraph orientGraph) {
OrientElement orientElement = (OrientElement) element; OrientElement orientElement = (OrientElement) element;
SecurityContext.allowSecurityContextRoles(oSecurity, ODocument oDocument = orientElement.getRecord();
orientElement.getRecord(), context); OSecurity oSecurity = getAdminOSecurity(orientGraph);
orientElement.save(); String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
} String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
public static void removeFromSecurityContext(OrientGraph orientGraph, oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
Element element, UUID context) { oDocument.save();
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
SecurityContext.removeFromSecurityContext(oSecurity, element, context);
}
public static void removeFromSecurityContext(OSecurity oSecurity, Element element,
UUID context) {
OrientElement orientElement = (OrientElement) element;
SecurityContext.disallowSecurityContextRoles(oSecurity,
orientElement.getRecord(), context);
orientElement.save(); orientElement.save();
} }
protected static void disallowSecurityContextRoles(OSecurity oSecurity, public void removeElement(Element element) throws ResourceRegistryException {
ODocument oDocument, UUID context) { removeElement(element, ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER));
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, }
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER, public void removeElement(Element element, OrientGraph orientGraph) {
SecurityContextMapper.SecurityType.ROLE, context)); OrientElement orientElement = (OrientElement) element;
ODocument oDocument = orientElement.getRecord();
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, OSecurity oSecurity = getAdminOSecurity(orientGraph);
SecurityContextMapper.getSecurityRoleOrUserName( String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
SecurityContextMapper.PermissionMode.READER, String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
SecurityContextMapper.SecurityType.ROLE, context)); oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
oDocument.save(); oDocument.save();
// oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, orientElement.save();
// DEFAULT_WRITER_ROLE);
// oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ,
// DEFAULT_READER_ROLE);
} }
protected static void allowSecurityContextRoles(OSecurity oSecurity, public void create() throws ResourceRegistryException {
ODocument oDocument, UUID context) { OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, create(orientGraph);
SecurityContextMapper.getSecurityRoleOrUserName( orientGraph.commit();
SecurityContextMapper.PermissionMode.WRITER, orientGraph.shutdown();
SecurityContextMapper.SecurityType.ROLE, context));
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context));
oDocument.save();
// oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL,
// DEFAULT_WRITER_ROLE);
// oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
// DEFAULT_READER_ROLE);
} }
public static void createSecurityContext(OrientGraph orientGraph, public void create(OrientGraph orientGraph) {
UUID context, boolean commit) { ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
ORole writer = oSecurity.getRole(DEFAULT_WRITER_ROLE); ORole writer = oSecurity.getRole(DEFAULT_WRITER_ROLE);
ORole reader = oSecurity.getRole(DEFAULT_READER_ROLE); ORole reader = oSecurity.getRole(DEFAULT_READER_ROLE);
String writeRoleName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER, String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
SecurityContextMapper.SecurityType.ROLE, context); String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
ORole writerRole = oSecurity.createRole(writeRoleName, String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
writer, ALLOW_MODES.DENY_ALL_BUT); String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
/*
String writerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, true);
String readerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, true);
String writerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, true);
String readerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, true);
*/
ORole writerRole = oSecurity.createRole(writerRoleName, writer, ALLOW_MODES.DENY_ALL_BUT);
writerRole.save(); writerRole.save();
logger.trace("{} created", writerRole); logger.trace("{} created", writerRole);
ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT);
String readerRoleName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context);
ORole readerRole = oSecurity.createRole(readerRoleName,
reader, ALLOW_MODES.DENY_ALL_BUT);
readerRole.save(); readerRole.save();
logger.trace("{} created", readerRole); logger.trace("{} created", readerRole);
String writerUserName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.USER, context);
OUser writerUser = oSecurity.createUser(writerUserName, OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
.get(SecurityContextMapper.PermissionMode.WRITER),
writerRole);
writerUser.save(); writerUser.save();
logger.trace("{} created", writerUser); logger.trace("{} created", writerUser);
String readerUserName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.USER, context);
OUser readerUser = oSecurity.createUser(readerUserName, OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
.get(SecurityContextMapper.PermissionMode.READER),
readerRole);
readerUser.save(); readerUser.save();
logger.trace("{} created", readerUser); logger.trace("{} created", readerUser);
if(commit) { logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
oDatabaseDocumentTx.commit();
}
logger.trace(
"Security Context (roles and users) with UUID {} successfully created",
context.toString());
} }
public static void deleteSecurityContext(OrientGraph orientGraph, private void drop(OSecurity oSecurity, String name, SecurityType securityType) {
UUID context, boolean commit) { boolean dropped = false;
switch (securityType) {
case ROLE:
dropped = oSecurity.dropRole(name);
break;
logger.trace( case USER:
"Going to remove Security Context (roles and users) with UUID {}", dropped = oSecurity.dropUser(name);
context.toString()); break;
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
String user = SecurityContextMapper.getSecurityRoleOrUserName( default:
SecurityContextMapper.PermissionMode.READER, break;
SecurityContextMapper.SecurityType.USER, context); }
boolean dropped = oSecurity.dropUser(user);
if (dropped) { if (dropped) {
logger.trace("{} successfully dropped", user); logger.trace("{} successfully dropped", name);
} else { } else {
logger.error("{} was not dropped successfully", user); logger.error("{} was not dropped successfully", name);
} }
}
user = SecurityContextMapper.getSecurityRoleOrUserName( public void delete() throws ResourceRegistryException {
SecurityContextMapper.PermissionMode.WRITER, OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
SecurityContextMapper.SecurityType.USER, context); delete(orientGraph);
dropped = oSecurity.dropUser(user); orientGraph.commit();
if (dropped) { orientGraph.shutdown();
logger.trace("{} successfully dropped", user); }
} else {
logger.error("{} was not dropped successfully", user); public void delete(OrientGraph orientGraph) {
} ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
String role = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context);
dropped = oSecurity.dropRole(role);
if (dropped) {
logger.trace("{} successfully dropped", role);
} else {
logger.error("{} was not dropped successfully", role);
}
role = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, context);
dropped = oSecurity.dropRole(role);
if (dropped) {
logger.trace("{} successfully dropped", role);
} else {
logger.error("{} was not dropped successfully", role);
}
if(commit) {
oDatabaseDocumentTx.commit();
}
logger.trace( logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString());
"Security Context (roles and users) with UUID {} successfully removed",
context.toString()); String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
drop(oSecurity, readerUserName, SecurityType.USER);
drop(oSecurity, writerUserName, SecurityType.USER);
drop(oSecurity, readerRoleName, SecurityType.ROLE);
drop(oSecurity, writerRoleName, SecurityType.ROLE);
logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString());
}
public OrientGraph getGraph(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraph orientGraph = factory.getTx();
if (orientGraph.isClosed()) {
factory = getFactory(permissionMode, true);
orientGraph = factory.getTx();
}
return orientGraph;
}
public OrientGraphNoTx getGraphNoTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
if (orientGraphNoTx.isClosed()) {
factory = getFactory(permissionMode, true);
orientGraphNoTx = factory.getNoTx();
}
return orientGraphNoTx;
}
public ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if (databaseDocumentTx.isClosed()) {
factory = getFactory(permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
@Override
public String toString() {
return String.format("%s %s", Context.NAME, getUUID().toString());
} }
} }

View File

@ -1,193 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseIntializator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public abstract class SecurityContextMapper {
private static Logger logger = LoggerFactory
.getLogger(SecurityContextMapper.class);
// Used to persist Schemas
protected static final String ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
protected static final UUID ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
// Used to Persist Context and their relations
public static final String MANAGEMENT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
public static final UUID MANAGEMENT_SECURITY_CONTEXT_UUID = UUID.fromString(MANAGEMENT_SECURITY_CONTEXT);
private static final Map<PermissionMode, Map<UUID, OrientGraphFactory>> securityContextFactories;
static {
try {
boolean created = DatabaseIntializator.initGraphDB();
logger.trace("Creating factory for {} connecting as {}",
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.CHANGED_ADMIN_USERNAME);
securityContextFactories = new HashMap<>();
OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.CHANGED_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD)
.setupPool(1, 10);
factory.setConnectionStrategy(DatabaseIntializator.CONNECTION_STRATEGY_PARAMETER.toString());
OrientGraph orientGraph = factory.getTx();
if (created) {
SecurityContext.createSecurityContext(orientGraph, ADMIN_SECURITY_CONTEXT_UUID, true);
SecurityContext.createSecurityContext(orientGraph, MANAGEMENT_SECURITY_CONTEXT_UUID, true);
}
for (PermissionMode p : PermissionMode.values()) {
Map<UUID, OrientGraphFactory> map = new HashMap<>();
securityContextFactories.put(p, map);
getSecurityContextFactory(ADMIN_SECURITY_CONTEXT_UUID, p, false);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT_UUID, p, false);
}
if(created) {
DatabaseIntializator.createEntitiesAndRelations();
}
} catch (Exception e) {
logger.error("Error initializing database connection", e);
throw new RuntimeException(
"Error initializing database connection", e);
}
}
public enum SecurityType {
ROLE("Role"), USER("User");
private final String name;
private SecurityType(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
public enum PermissionMode {
READER("Reader"), WRITER("Writer");
private final String name;
private PermissionMode(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
/**
* @param context Context UUID. For ADMIN operation uses SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID
* @return
*/
private static OrientGraphFactory getSecurityContextFactory(
UUID context, PermissionMode permissionMode, boolean recreate) {
OrientGraphFactory factory = null;
Map<UUID, OrientGraphFactory> permissionSecurityContextFactories = securityContextFactories.get(permissionMode);
if(recreate) {
permissionSecurityContextFactories.remove(context);
}else {
factory = permissionSecurityContextFactories.get(context);
}
if (factory == null) {
String username = null;
String password = null;
if(context.compareTo(ADMIN_SECURITY_CONTEXT_UUID)==0){
username = DatabaseEnvironment.CHANGED_ADMIN_USERNAME;
password = DatabaseEnvironment.CHANGED_ADMIN_PASSWORD;
}else {
username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, context);
password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
}
factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI,
username, password).setupPool(1, 10);
factory.setConnectionStrategy(DatabaseIntializator.CONNECTION_STRATEGY_PARAMETER.toString());
permissionSecurityContextFactories.put(context, factory);
}
return factory;
}
protected static OrientGraph getSecurityContextGraph(
UUID context, PermissionMode permissionMode) {
OrientGraphFactory factory = getSecurityContextFactory(context, permissionMode, false);
OrientGraph orientGraph = factory.getTx();
if(orientGraph.isClosed()) {
factory = getSecurityContextFactory(context, permissionMode, true);
orientGraph = factory.getTx();
}
return orientGraph;
}
protected static OrientGraphNoTx getSecurityContextGraphNoTx(
UUID context, PermissionMode permissionMode) {
OrientGraphFactory factory = getSecurityContextFactory(context, permissionMode, false);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
if(orientGraphNoTx.isClosed()) {
factory = getSecurityContextFactory(context, permissionMode, true);
orientGraphNoTx = factory.getNoTx();
}
return orientGraphNoTx;
}
public static ODatabaseDocumentTx getSecurityContextDatabaseDocumentTx(
UUID context, PermissionMode permissionMode) {
OrientGraphFactory factory = getSecurityContextFactory(context, permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if(databaseDocumentTx.isClosed()) {
factory = getSecurityContextFactory(context, permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
public static String getSecurityRoleOrUserName(
PermissionMode permissionMode, SecurityType securityType,
UUID context) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(permissionMode);
stringBuilder.append(securityType);
stringBuilder.append("_");
stringBuilder.append(context.toString());
return stringBuilder.toString();
}
}

View File

@ -7,124 +7,298 @@ import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.impl.utils.discovery.ERDiscovery;
import org.gcube.informationsystem.model.ISConstants;
import org.gcube.informationsystem.model.embedded.Embedded;
import org.gcube.informationsystem.model.embedded.ValueSchema;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY;
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.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
* *
*/ */
public class DatabaseEnvironment { public class DatabaseEnvironment {
private static Logger logger = LoggerFactory.getLogger(DatabaseIntializator.class);
protected static final String PROPERTY_FILENAME = "config.properties";
protected static final String HOST_VARNAME = "HOST"; private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class);
protected static final String REMOTE_PROTOCOL; private static final String PROPERTY_FILENAME = "config.properties";
protected static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL";
private static final String HOST_VARNAME = "HOST";
public static final String DB;
protected static final String DB_VARNAME = "DB"; private static final String REMOTE_PROTOCOL;
private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL";
protected static final String ROOT_USERNAME;
protected static final String ROOT_USERNAME_VARNAME = "ROOT_USERNAME"; private static final String DB;
private static final String DB_VARNAME = "DB";
protected static final String ROOT_PASSWORD;
protected static final String ROOT_PASSWORD_VARNAME = "ROOT_PASSWORD"; private static final String ROOT_USERNAME;
private static final String ROOT_USERNAME_VARNAME = "ROOT_USERNAME";
protected static final String DEFAULT_ADMIN_USERNAME;
protected static final String DEFAULT_ADMIN_USERNAME_VARNAME = "DEFAULT_ADMIN_USERNAME"; private static final String ROOT_PASSWORD;
private static final String ROOT_PASSWORD_VARNAME = "ROOT_PASSWORD";
protected static final String DEFAULT_ADMIN_ROLE = "admin";
private static final String DEFAULT_ADMIN_USERNAME;
public static final String CHANGED_ADMIN_USERNAME; private static final String DEFAULT_ADMIN_USERNAME_VARNAME = "DEFAULT_ADMIN_USERNAME";
protected static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME";
public static final String DEFAULT_ADMIN_ROLE = "admin";
protected static final String DEFAULT_ADMIN_PASSWORD;
protected static final String DEFAULT_ADMIN_PASSWORD_VARNAME = "DEFAULT_ADMIN_PASSWORD"; private static final String CHANGED_ADMIN_USERNAME;
private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME";
public static final String CHANGED_ADMIN_PASSWORD;
protected static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD"; private static final String DEFAULT_ADMIN_PASSWORD;
private static final String DEFAULT_ADMIN_PASSWORD_VARNAME = "DEFAULT_ADMIN_PASSWORD";
protected static final String DEFAULT_CREATED_WRITER_USER_PASSWORD;
protected static final String DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_WRITER_USER_PASSWORD"; private static final String CHANGED_ADMIN_PASSWORD;
private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD";
protected static final String DEFAULT_CREATED_READER_USER_PASSWORD;
protected static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_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 DEFAULT_CREATED_READER_USER_PASSWORD;
private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD";
public static final Map<PermissionMode, String> DEFAULT_PASSWORDS; public static final Map<PermissionMode, String> DEFAULT_PASSWORDS;
protected static final String HOSTS; private static final String HOSTS;
public static final String SERVER_URI; private static final String SERVER_URI;
public static final String DB_URI; public static final String DB_URI;
private static final String DATABASE_TYPE = "graph";
private static final String STORAGE_MODE = "plocal";
public static final String O_RESTRICTED_CLASS = "ORestricted";
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT \"%s\"";
// Used to indicate virtual admin security context
private static final String ADMIN_SECURITY_CONTEXT;
public static final UUID ADMIN_SECURITY_CONTEXT_UUID;
// Used to persist Schemas
private static final String SCHEMA_SECURITY_CONTEXT;
public static final UUID SCHEMA_SECURITY_CONTEXT_UUID;
// Used to Persist Context and their relations
private static final String CONTEXT_SECURITY_CONTEXT;
public static final UUID CONTEXT_SECURITY_CONTEXT_UUID;
static { static {
Properties properties = new Properties(); Properties properties = new Properties();
InputStream input = null; InputStream input = null;
try { try {
input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME); input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME);
// load a properties file // load a properties file
properties.load(input); properties.load(input);
HOSTS = properties.getProperty(HOST_VARNAME); HOSTS = properties.getProperty(HOST_VARNAME);
REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME); REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME);
DB = properties.getProperty(DB_VARNAME); DB = properties.getProperty(DB_VARNAME);
SERVER_URI = REMOTE_PROTOCOL + HOSTS; SERVER_URI = REMOTE_PROTOCOL + HOSTS;
DB_URI = SERVER_URI + "/" + DB; DB_URI = SERVER_URI + "/" + DB;
ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME); ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME);
ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME); ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME);
String changedAdminUsername = null; String changedAdminUsername = null;
try { try {
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME); changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
if(changedAdminUsername==null){ if (changedAdminUsername == null) {
// To be compliant with old configuration.properties which does not have // To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username // CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB; changedAdminUsername = DB;
} }
}catch (Exception e) { } catch (Exception e) {
// To be compliant with old configuration.properties which does not have // To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username // CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB; changedAdminUsername = DB;
} }
CHANGED_ADMIN_USERNAME = changedAdminUsername; CHANGED_ADMIN_USERNAME = changedAdminUsername;
CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_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_WRITER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME);
DEFAULT_CREATED_READER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME); DEFAULT_CREATED_READER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME);
DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME); DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME);
DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME); DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME);
DEFAULT_PASSWORDS = new HashMap<PermissionMode, String>();
DEFAULT_PASSWORDS = new HashMap<SecurityContextMapper.PermissionMode, String>();
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD);
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
} catch (Exception e) {
} catch(Exception e){
logger.error("Unable to load properties from {}", PROPERTY_FILENAME); logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
throw new RuntimeException("Unable to load properties", e); throw new RuntimeException("Unable to load properties", e);
} }
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
// Used to persist Schemas
SCHEMA_SECURITY_CONTEXT = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
SCHEMA_SECURITY_CONTEXT_UUID = UUID.fromString(SCHEMA_SECURITY_CONTEXT);
// Used to Persist Context and their relations
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
try {
boolean created = initGraphDB();
ContextUtility contextUtility = ContextUtility.getInstace();
AdminSecurityContext adminSecurityContext = new AdminSecurityContext();
contextUtility.addSecurityContext(adminSecurityContext.getUUID().toString(), adminSecurityContext);
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
contextUtility.addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
SecurityContext schemaSecurityContext = new SecurityContext(SCHEMA_SECURITY_CONTEXT_UUID);
contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext);
if (created) {
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD).setupPool(1, 10);
OrientGraph orientGraph = factory.getTx();
adminSecurityContext.create(orientGraph);
orientGraph.commit();
orientGraph.shutdown();
factory.close();
contextSecurityContext.create();
schemaSecurityContext.create();
createEntitiesAndRelations();
}
} catch (Exception e) {
logger.error("Error initializing database connection", e);
throw new RuntimeException("Error initializing database connection", e);
}
} }
private static boolean initGraphDB() throws Exception {
OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false);
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD);
if (!serverAdmin.existsDatabase(DB, STORAGE_MODE)) {
logger.info("The database {} does not exist. Going to create it.", DB_URI);
serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE);
logger.trace("Connecting to newly created database {} as {} with default password", DB_URI,
DEFAULT_ADMIN_USERNAME);
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD)
.setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
/* Updating DateTimeFormat to be aligned with IS model definition */
/*
* This solution does not work OStorageConfiguration configuration =
* orientGraphNoTx.getRawGraph().getStorage().getConfiguration();
* configuration.dateTimeFormat = ISConstants.DATETIME_PATTERN;
* configuration.update();
*/
String query = String.format(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, ISConstants.DATETIME_PATTERN);
OCommandSQL preparedQuery = new OCommandSQL(query);
orientGraphNoTx.getRawGraph().command(preparedQuery).execute();
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSecurity oSecurity = oMetadata.getSecurity();
logger.trace("Changing {} password", DEFAULT_ADMIN_USERNAME);
OUser admin = oSecurity.getUser(DEFAULT_ADMIN_USERNAME);
admin.setPassword(CHANGED_ADMIN_PASSWORD);
admin.save();
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();
for (PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
oUser.save();
logger.trace("Updating password for user {}", permissionMode.toString());
}
logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)");
OSchema oSchema = oMetadata.getSchema();
OClass oRestricted = oSchema.getClass(O_RESTRICTED_CLASS);
OrientVertexType v = orientGraphNoTx.getVertexBaseType();
v.addSuperClass(oRestricted);
OrientEdgeType e = orientGraphNoTx.getEdgeBaseType();
e.addSuperClass(oRestricted);
// orientGraphNoTx.commit();
orientGraphNoTx.shutdown();
factory.close();
return true;
}
serverAdmin.close();
return false;
}
private static void createEntitiesAndRelations() throws Exception {
ERDiscovery erDiscovery = ISMapper.getErdiscovery();
SchemaActionImpl entityRegistrationAction = new SchemaActionImpl();
entityRegistrationAction.manageEmbeddedClass(Embedded.class);
entityRegistrationAction.manageEmbeddedClass(ValueSchema.class);
erDiscovery.manageDiscoveredERTypes(entityRegistrationAction);
}
} }

View File

@ -1,157 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.impl.utils.discovery.ERDiscovery;
import org.gcube.informationsystem.model.ISConstants;
import org.gcube.informationsystem.model.embedded.Embedded;
import org.gcube.informationsystem.model.embedded.ValueSchema;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY;
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.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class DatabaseIntializator {
private static Logger logger = LoggerFactory
.getLogger(DatabaseIntializator.class);
private static final String DATABASE_TYPE = "graph";
private static final String STORAGE_MODE = "plocal";
public static final String O_RESTRICTED_CLASS = "ORestricted";
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT \"%s\"";
public static boolean initGraphDB() throws Exception {
OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false);
logger.trace("Connecting to {} as {} to create new DB",
DatabaseEnvironment.SERVER_URI, DatabaseEnvironment.ROOT_USERNAME);
OServerAdmin serverAdmin = new OServerAdmin(DatabaseEnvironment.SERVER_URI)
.connect(DatabaseEnvironment.ROOT_USERNAME,
DatabaseEnvironment.ROOT_PASSWORD);
if (!serverAdmin.existsDatabase(DatabaseEnvironment.DB, STORAGE_MODE)) {
logger.trace("Creating Database {}", DatabaseEnvironment.DB_URI);
serverAdmin.createDatabase(DatabaseEnvironment.DB, DATABASE_TYPE,
STORAGE_MODE);
logger.trace(
"Connecting to newly created database {} as {} with default password",
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME,
DatabaseEnvironment.DEFAULT_ADMIN_PASSWORD)
.setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
/* Updating DateTimeFormat to be aligned with IS model definition */
/*
* This solution does not work
* OStorageConfiguration configuration = orientGraphNoTx.getRawGraph().getStorage().getConfiguration();
* configuration.dateTimeFormat = ISConstants.DATETIME_PATTERN;
* configuration.update();
*/
String query = String.format(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, ISConstants.DATETIME_PATTERN);
OCommandSQL preparedQuery = new OCommandSQL( query );
orientGraphNoTx.getRawGraph().command( preparedQuery ).execute();
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSecurity oSecurity = oMetadata.getSecurity();
logger.trace("Changing {} password",
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
OUser admin = oSecurity
.getUser(DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
admin.setPassword(DatabaseEnvironment.CHANGED_ADMIN_PASSWORD);
admin.save();
logger.trace("Creating new admin named '{}'",
DatabaseEnvironment.CHANGED_ADMIN_USERNAME);
ORole adminRole = oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
OUser newAdminUser = oSecurity.createUser(DatabaseEnvironment.CHANGED_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD, adminRole);
newAdminUser.save();
for (PermissionMode permissionMode : DatabaseEnvironment.DEFAULT_PASSWORDS
.keySet()) {
OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DatabaseEnvironment.DEFAULT_PASSWORDS
.get(permissionMode));
oUser.save();
logger.trace("Updating password for user {}",
permissionMode.toString());
}
logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)");
OSchema oSchema = oMetadata.getSchema();
OClass oRestricted = oSchema.getClass(O_RESTRICTED_CLASS);
OrientVertexType v = orientGraphNoTx.getVertexBaseType();
v.addSuperClass(oRestricted);
OrientEdgeType e = orientGraphNoTx.getEdgeBaseType();
e.addSuperClass(oRestricted);
//orientGraphNoTx.commit();
orientGraphNoTx.shutdown();
factory.close();
return true;
}
serverAdmin.close();
return false;
}
public static void createEntitiesAndRelations() throws Exception {
ERDiscovery erDiscovery = ISMapper.getErdiscovery();
SchemaActionImpl entityRegistrationAction = new SchemaActionImpl();
entityRegistrationAction.manageEmbeddedClass(Embedded.class);
entityRegistrationAction.manageEmbeddedClass(ValueSchema.class);
erDiscovery.manageDiscoveredERTypes(entityRegistrationAction);
}
}

View File

@ -31,11 +31,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyP
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextManagement;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.IsParentOfManagement; import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseIntializator; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient; import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
@ -67,7 +66,7 @@ import com.tinkerpop.blueprints.util.StringFactory;
public abstract class ERManagement<ERType extends ER, El extends Element> { public abstract class ERManagement<ERType extends ER, El extends Element> {
protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Logger logger = LoggerFactory.getLogger(this.getClass());
private static Logger staticLogger = LoggerFactory.getLogger(ERManagement.class); private static Logger staticLogger = LoggerFactory.getLogger(ERManagement.class);
public final String AT = "@"; public final String AT = "@";
@ -75,10 +74,10 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected final Set<String> ignoreKeys; protected final Set<String> ignoreKeys;
protected final Set<String> ignoreStartWithKeys; protected final Set<String> ignoreStartWithKeys;
protected Class<El> elementClass; protected Class<El> elementClass;
protected final AccessType accessType; protected final AccessType accessType;
protected OrientGraph orientGraph; protected OrientGraph orientGraph;
protected UUID uuid; protected UUID uuid;
@ -97,21 +96,21 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
this.reload = reload; this.reload = reload;
} }
/**
* This boolean is used to force the use of ADMIN user instead of the user of the context
*/
protected boolean forceAdmin;
public AccessType getAccessType() { public AccessType getAccessType() {
return accessType; return accessType;
} }
public boolean isForceAdmin() { protected SecurityContext workingContext;
return forceAdmin;
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getCurrentSecurityContext();
}
return workingContext;
} }
public void setForceAdmin(boolean forceAdmin) { public void setWorkingContext(SecurityContext workingContext) {
this.forceAdmin = forceAdmin; this.workingContext = workingContext;
} }
protected ERManagement(AccessType accessType) { protected ERManagement(AccessType accessType) {
@ -123,13 +122,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
this.ignoreStartWithKeys.add(AT); this.ignoreStartWithKeys.add(AT);
this.ignoreStartWithKeys.add(UNDERSCORE); this.ignoreStartWithKeys.add(UNDERSCORE);
this.reload = false;
}
protected ERManagement(AccessType accessType, OrientGraph orientGraph) { this.reload = false;
this(accessType);
this.orientGraph = orientGraph;
} }
public void setUUID(UUID uuid) throws ResourceRegistryException { public void setUUID(UUID uuid) throws ResourceRegistryException {
@ -144,8 +139,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
checkJSON(); checkJSON();
} }
public void setJSON(String jsonRepresentation) public void setJSON(String jsonRepresentation) throws ResourceRegistryException {
throws ResourceRegistryException {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
try { try {
this.jsonNode = mapper.readTree(jsonRepresentation); this.jsonNode = mapper.readTree(jsonRepresentation);
@ -156,20 +150,20 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
protected OClass getOClass() throws SchemaException, ResourceRegistryException { protected OClass getOClass() throws SchemaException, ResourceRegistryException {
if(oClass==null){ if (oClass == null) {
if(element!=null){ if (element != null) {
OrientElement orientElement = (OrientElement) element; OrientElement orientElement = (OrientElement) element;
OMetadata oMetadata = orientElement.getGraph().getRawGraph().getMetadata(); OMetadata oMetadata = orientElement.getGraph().getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
String type = orientElement.getRecord().getClassName(); String type = orientElement.getRecord().getClassName();
oClass = oSchema.getClass(type); oClass = oSchema.getClass(type);
}else{ } else {
oClass = SchemaManagementImpl.getTypeSchema(erType, accessType); oClass = SchemaManagementImpl.getTypeSchema(erType, accessType);
} }
} }
return oClass; return oClass;
} }
public void setElementType(String erType) throws ResourceRegistryException { public void setElementType(String erType) throws ResourceRegistryException {
this.erType = erType; this.erType = erType;
if (erType == null || erType.compareTo("") == 0) { if (erType == null || erType.compareTo("") == 0) {
@ -183,9 +177,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected void checkJSON() throws ResourceRegistryException { protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) { if (uuid == null) {
try { try {
uuid = org.gcube.informationsystem.impl.utils.Utility uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode);
.getUUIDFromJsonNode(jsonNode); } catch (Exception e) {
} catch (Exception e) {} }
} else { } else {
checkUUIDMatch(); checkUUIDMatch();
} }
@ -199,12 +193,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
protected void checkERMatch() throws ResourceRegistryException { protected void checkERMatch() throws ResourceRegistryException {
if(jsonNode!=null){ if (jsonNode != null) {
String type = getClassProperty(jsonNode); String type = getClassProperty(jsonNode);
if (type != null && type.compareTo(erType) != 0) { if (type != null && type.compareTo(erType) != 0) {
String error = String String error = String.format("Declared resourceType does not match with json representation %s!=%s",
.format("Declared resourceType does not match with json representation %s!=%s", erType, type);
erType, type);
logger.trace(error); logger.trace(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
@ -223,10 +216,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
if (header != null) { if (header != null) {
UUID resourceUUID = header.getUUID(); UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) { if (resourceUUID.compareTo(uuid) != 0) {
String error = String String error = String.format(
.format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance", "UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(), resourceUUID.toString(), uuid.toString(), erType);
erType);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
@ -236,105 +228,97 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public JSONObject serializeSelfOnly() throws ResourceRegistryException { public JSONObject serializeSelfOnly() throws ResourceRegistryException {
try { try {
return toJSONObject(); return toJSONObject();
}catch(Exception e){ } catch (Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
public abstract String serialize() throws ResourceRegistryException; public abstract String serialize() throws ResourceRegistryException;
public abstract JSONObject serializeAsJson() public abstract JSONObject serializeAsJson() throws ResourceRegistryException;
throws ResourceRegistryException;
protected abstract El reallyCreate() throws ERAlreadyPresentException,
ResourceRegistryException;
protected abstract El reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException;
public El internalCreate() throws ERAlreadyPresentException, ResourceRegistryException { public El internalCreate() throws ERAlreadyPresentException, ResourceRegistryException {
try { try {
reallyCreate(); reallyCreate();
Header entityHeader = HeaderUtility.getHeader(jsonNode, true); Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
if (entityHeader != null) { if (entityHeader != null) {
element.setProperty(Entity.HEADER_PROPERTY, entityHeader); element.setProperty(Entity.HEADER_PROPERTY, entityHeader);
} else { } else {
entityHeader = HeaderUtility.addHeader(element, null); entityHeader = HeaderUtility.addHeader(element, null);
} }
if(!(this instanceof ContextManagement || this instanceof IsParentOfManagement)){ getWorkingContext().addElement(element, orientGraph);
ContextUtility.addToActualContext(orientGraph, element);
}
((OrientElement) element).save(); ((OrientElement) element).save();
return element; return element;
}catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause());
} }
} }
protected abstract El reallyUpdate() throws ERNotFoundException, protected abstract El reallyUpdate() throws ERNotFoundException, ResourceRegistryException;
ResourceRegistryException;
public El internalUpdate() throws ERNotFoundException, ResourceRegistryException { public El internalUpdate() throws ERNotFoundException, ResourceRegistryException {
try { try {
reallyUpdate(); reallyUpdate();
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save(); ((OrientElement) element).save();
return element; return element;
}catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException("Error Updating " + erType + " with " + jsonNode, e.getCause()); throw new ResourceRegistryException("Error Updating " + erType + " with " + jsonNode, e.getCause());
} }
} }
public El internalCreateOrUdate() throws ResourceRegistryException { public El internalCreateOrUdate() throws ResourceRegistryException {
try { try {
return internalUpdate(); return internalUpdate();
}catch (ERNotFoundException e) { } catch (ERNotFoundException e) {
return internalCreate(); return internalCreate();
} }
} }
protected abstract boolean reallyDelete() throws ERNotFoundException, protected abstract boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException;
ResourceRegistryException;
public boolean internalDelete() throws ERNotFoundException, ResourceRegistryException { public boolean internalDelete() throws ERNotFoundException, ResourceRegistryException {
// Added for consistency with create and update addToContext removeFromContext. // Added for consistency with create and update addToContext removeFromContext.
return reallyDelete(); return reallyDelete();
} }
protected abstract boolean reallyAddToContext() throws ContextException, protected abstract boolean reallyAddToContext() throws ContextException, ResourceRegistryException;
ResourceRegistryException;
public boolean internalAddToContext() throws ContextException, ResourceRegistryException { public boolean internalAddToContext() throws ContextException, ResourceRegistryException {
try { try {
boolean ret = reallyAddToContext(); boolean ret = reallyAddToContext();
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save(); ((OrientElement) element).save();
return ret && true; return ret && true;
}catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException("Error Adding " + erType + " to Current Context ", e.getCause()); throw new ResourceRegistryException("Error Adding " + erType + " to Current Context ", e.getCause());
} }
} }
protected abstract boolean reallyRemoveFromContext() throws ContextException, protected abstract boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException;
ResourceRegistryException;
public boolean internalRemoveFromContext() throws ContextException, ResourceRegistryException { public boolean internalRemoveFromContext() throws ContextException, ResourceRegistryException {
try { try {
boolean ret = reallyRemoveFromContext(); boolean ret = reallyRemoveFromContext();
HeaderUtility.updateModifiedByAndLastUpdate(element); HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save(); ((OrientElement) element).save();
return ret && true; return ret && true;
}catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause()); throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause());
@ -343,53 +327,55 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public void setElement(El element) throws ResourceRegistryException { public void setElement(El element) throws ResourceRegistryException {
if (element == null) { if (element == null) {
throw new ResourceRegistryException("Trying to set null " throw new ResourceRegistryException("Trying to set null " + elementClass.getSimpleName() + " in " + this);
+ elementClass.getSimpleName() + " in " + this);
} }
this.element = element; this.element = element;
this.uuid = HeaderUtility.getHeader(element).getUUID(); this.uuid = HeaderUtility.getHeader(element).getUUID();
} }
protected abstract ERNotFoundException getSpecificElementNotFoundException(ERNotFoundException e); protected abstract ERNotFoundException getSpecificElementNotFoundException(ERNotFoundException e);
protected abstract ERAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message); protected abstract ERAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message);
protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message); protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message);
public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
if (element == null) { if (element == null) {
try { try {
element = retrieveElement(); element = retrieveElement();
}catch (ERNotFoundException e) { } catch (ERNotFoundException e) {
try { try {
retrieveElementFromAnyContext(); retrieveElementFromAnyContext();
throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName() : erType + " with UUID " + uuid + " is available in another " + Context.class.getSimpleName()); throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName()
: erType + " with UUID " + uuid + " is available in another "
+ Context.class.getSimpleName());
} catch (ERAvailableInAnotherContextException e1) { } catch (ERAvailableInAnotherContextException e1) {
throw e1; throw e1;
}catch (Exception e1) { } catch (Exception e1) {
throw e; throw e;
} }
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
}else { } else {
if(reload){ if (reload) {
((OrientElement) element).reload(); ((OrientElement) element).reload();
} }
} }
return element; return element;
} }
public El retrieveElement() throws ERNotFoundException, ResourceRegistryException { public El retrieveElement() throws ERNotFoundException, ResourceRegistryException {
try { try {
if(uuid==null){ if (uuid == null) {
throw new ERNotFoundException("null UUID does not allow to retrieve the Element"); throw new ERNotFoundException("null UUID does not allow to retrieve the Element");
} }
return Utility.getElementByUUID(orientGraph, return Utility.getElementByUUID(orientGraph, erType == null ? accessType.getName() : erType, uuid,
erType == null ? accessType.getName() : erType, uuid, elementClass); elementClass);
} catch (ERNotFoundException e) { } catch (ERNotFoundException e) {
throw getSpecificElementNotFoundException(e); throw getSpecificElementNotFoundException(e);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -398,26 +384,25 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
public El retrieveElementFromAnyContext() throws ERNotFoundException, ResourceRegistryException { public El retrieveElementFromAnyContext() throws ERNotFoundException, ResourceRegistryException {
try{ try {
return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass); return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass);
}catch (ERNotFoundException e) { } catch (ERNotFoundException e) {
throw getSpecificElementNotFoundException(e); throw getSpecificElementNotFoundException(e);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
public abstract String reallyGetAll(boolean polymorphic) public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException;
throws ResourceRegistryException;
public String all(boolean polymorphic) throws ResourceRegistryException { public String all(boolean polymorphic) throws ResourceRegistryException {
try { try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAll(polymorphic); return reallyGetAll(polymorphic);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -430,11 +415,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
} }
} }
public boolean exists() throws ERNotFoundException, public boolean exists()
ERAvailableInAnotherContextException, ResourceRegistryException { throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
getElement(); getElement();
@ -455,14 +440,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public String create() throws ERAlreadyPresentException, ResourceRegistryException { public String create() throws ERAlreadyPresentException, ResourceRegistryException {
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin); orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER);
element = internalCreate(); element = internalCreate();
orientGraph.commit(); orientGraph.commit();
// TODO Notify to subscriptionNotification // TODO Notify to subscriptionNotification
return serialize(); return serialize();
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -484,11 +469,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
} }
public String read() throws ERNotFoundException, public String read() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
ERAvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = ContextUtility orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
getElement(); getElement();
@ -506,22 +489,19 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
} }
public String update() throws ERNotFoundException, public String update() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
ERAvailableInAnotherContextException, ResourceRegistryException {
try { try {
orientGraph = ContextUtility orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER);
.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
element = internalUpdate(); element = internalUpdate();
orientGraph.commit(); orientGraph.commit();
setReload(true); setReload(true);
// TODO Notify to subscriptionNotification // TODO Notify to subscriptionNotification
return serialize(); return serialize();
// TODO Serialized resource is the old version. This really strange and should be an orient bug
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
if (orientGraph != null) { if (orientGraph != null) {
@ -541,27 +521,24 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
} }
public boolean delete() throws ERNotFoundException, public boolean delete()
ERAvailableInAnotherContextException, ResourceRegistryException { throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid); logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid);
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph( orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
PermissionMode.WRITER, true);
boolean deleted = reallyDelete(); boolean deleted = reallyDelete();
if(deleted){ if (deleted) {
orientGraph.commit(); orientGraph.commit();
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
uuid); } else {
}else{ logger.info("{} with UUID {} was NOT deleted.", accessType.getName(), uuid);
logger.info("{} with UUID {} was NOT deleted.", accessType.getName(),
uuid);
orientGraph.rollback(); orientGraph.rollback();
} }
return deleted; return deleted;
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -584,30 +561,25 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException { public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to add {} with UUID {} to actual Context", logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid, getWorkingContext().toString());
accessType.getName(), uuid);
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph( orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
PermissionMode.WRITER, true);
boolean added = internalAddToContext(); boolean added = internalAddToContext();
orientGraph.commit(); orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context", logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
accessType.getName(), uuid);
return added; return added;
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to add {} with UUID {} to actual Context", logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid);
accessType.getName(), uuid);
if (orientGraph != null) { if (orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context", logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
accessType.getName(), uuid, e);
if (orientGraph != null) { if (orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }
@ -620,32 +592,26 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
public boolean removeFromContext() throws ERNotFoundException, ContextException, ResourceRegistryException { public boolean removeFromContext() throws ERNotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {} from actual Context", logger.debug("Going to remove {} with UUID {} from actual Context", accessType.getName(), uuid);
accessType.getName(), uuid);
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph(
PermissionMode.WRITER, true);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean removed = internalRemoveFromContext(); boolean removed = internalRemoveFromContext();
orientGraph.commit(); orientGraph.commit();
logger.info( logger.info("{} with UUID {} successfully removed from actual Context", accessType.getName(), uuid);
"{} with UUID {} successfully removed from actual Context",
accessType.getName(), uuid);
return removed; return removed;
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from actual Context", logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid);
accessType.getName(), uuid);
if (orientGraph != null) { if (orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
logger.error( logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid, e);
"Unable to remove {} with UUID {} from actual Context",
accessType.getName(), uuid, e);
if (orientGraph != null) { if (orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }
@ -665,69 +631,63 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} }
public static Object getObjectFromElement(JsonNode value) public static Object getObjectFromElement(JsonNode value)
throws UnsupportedDataTypeException, ResourceRegistryException{ throws UnsupportedDataTypeException, ResourceRegistryException {
JsonNodeType jsonNodeType = value.getNodeType(); JsonNodeType jsonNodeType = value.getNodeType();
switch (jsonNodeType) { switch (jsonNodeType) {
case OBJECT: case OBJECT:
return EmbeddedMangement.getEmbeddedType(value); return EmbeddedMangement.getEmbeddedType(value);
case ARRAY: case ARRAY:
/* /*
List<Object> list = new ArrayList<Object>(); * List<Object> list = new ArrayList<Object>(); Iterator<JsonNode> arrayElement
Iterator<JsonNode> arrayElement = value.elements(); * = value.elements(); while (arrayElement.hasNext()) { JsonNode arrayNode =
while (arrayElement.hasNext()) { * arrayElement.next(); Object objectNode = getObjectFromElement(arrayNode); if
JsonNode arrayNode = arrayElement.next(); * (objectNode != null) { list.add(objectNode); } } return list;
Object objectNode = getObjectFromElement(arrayNode); */
if (objectNode != null) { throw new UnsupportedDataTypeException(
list.add(objectNode); "List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
}
} case BINARY:
return list; break;
*/
throw new UnsupportedDataTypeException("List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); case BOOLEAN:
return value.asBoolean();
case BINARY:
break; case NULL:
break;
case BOOLEAN:
return value.asBoolean(); case NUMBER:
if (value.isDouble() || value.isFloat()) {
case NULL: return value.asDouble();
break; }
if (value.isBigInteger() || value.isShort() || value.isInt()) {
case NUMBER: return value.asInt();
if (value.isDouble() || value.isFloat()) { }
return value.asDouble();
} if (value.isLong()) {
if (value.isBigInteger() || value.isShort() || value.isInt()) { return value.asLong();
return value.asInt(); }
} break;
if (value.isLong()) { case STRING:
return value.asLong(); return value.asText();
}
break; case MISSING:
break;
case STRING:
return value.asText(); case POJO:
break;
case MISSING:
break; default:
break;
case POJO:
break;
default:
break;
} }
return null; return null;
} }
public static Map<String, Object> getPropertyMap(JsonNode jsonNode, public static Map<String, Object> getPropertyMap(JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreKeys, Set<String> ignoreStartWith) Set<String> ignoreStartWith) throws JsonProcessingException, IOException {
throws JsonProcessingException, IOException {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
@ -772,23 +732,20 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return map; return map;
} }
public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreKeys, Set<String> ignoreStartWithKeys) Set<String> ignoreStartWithKeys) throws ResourceRegistryException {
throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyKeys(); Set<String> oldKeys = element.getPropertyKeys();
Map<String, Object> properties; Map<String, Object> properties;
if (element instanceof Vertex || element instanceof Edge) { if (element instanceof Vertex || element instanceof Edge) {
try { try {
properties = getPropertyMap(jsonNode, ignoreKeys, properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
ignoreStartWithKeys);
} catch (IOException e) { } catch (IOException e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} else { } else {
String error = String.format("Error while updating %s properties", String error = String.format("Error while updating %s properties", element.toString());
element.toString());
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
@ -796,42 +753,37 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
for (String key : properties.keySet()) { for (String key : properties.keySet()) {
try { try {
Object object = properties.get(key); Object object = properties.get(key);
if(!oClass.existsProperty(key)){ if (!oClass.existsProperty(key)) {
boolean set = false; boolean set = false;
if(object instanceof ODocument){ if (object instanceof ODocument) {
ODocument oDocument = (ODocument) object; ODocument oDocument = (ODocument) object;
((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED); ((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED);
set = true; set = true;
} }
/* /*
if(object instanceof Set){ * if(object instanceof Set){ ((OrientElement) element).setProperty(key, object,
((OrientElement) element).setProperty(key, object, OType.EMBEDDEDSET); * OType.EMBEDDEDSET); set = true; }
set = true; *
} * if(object instanceof List){ ((OrientElement) element).setProperty(key,
* object, OType.EMBEDDEDLIST); set = true; }
if(object instanceof List){ */
((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST);
set = true; if (!set) {
}
*/
if(!set){
element.setProperty(key, object); element.setProperty(key, object);
} }
} else{ } else {
element.setProperty(key, object); element.setProperty(key, object);
} }
} catch (Exception e) { } catch (Exception e) {
String error = String.format( String error = String.format("Error while setting property %s : %s (%s)", key,
"Error while setting property %s : %s (%s)", key, properties properties.get(key).toString(), e.getMessage());
.get(key).toString(), e.getMessage());
staticLogger.error(error); staticLogger.error(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
} }
@ -856,116 +808,114 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return element; return element;
} }
protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException { protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException {
try { try {
if(key.compareTo(ER.HEADER_PROPERTY)==0){ if (key.compareTo(ER.HEADER_PROPERTY) == 0) {
// Keeping the header // Keeping the header
HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object); HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object);
JSONObject headerObject = new JSONObject(headerOrient.toJSON("class")); JSONObject headerObject = new JSONObject(headerOrient.toJSON("class"));
return headerObject; return headerObject;
} }
if (ignoreKeys.contains(key)) { if (ignoreKeys.contains(key)) {
return null; return null;
} }
for (String prefix : ignoreStartWithKeys) { for (String prefix : ignoreStartWithKeys) {
if (key.startsWith(prefix)) { if (key.startsWith(prefix)) {
return null; return null;
} }
} }
if(object instanceof ODocument){ if (object instanceof ODocument) {
String json = ((ODocument) object).toJSON("class"); String json = ((ODocument) object).toJSON("class");
JSONObject jsonObject = new JSONObject(json); JSONObject jsonObject = new JSONObject(json);
return jsonObject; return jsonObject;
} }
if(object instanceof Date){ if (object instanceof Date) {
OProperty oProperty = getOClass().getProperty(key); OProperty oProperty = getOClass().getProperty(key);
OType oType = oProperty.getType(); OType oType = oProperty.getType();
DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance(); DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance();
switch (oType) { switch (oType) {
case DATE: case DATE:
dateFormat = ODateHelper.getDateFormatInstance(); dateFormat = ODateHelper.getDateFormatInstance();
break; break;
case DATETIME: case DATETIME:
dateFormat = ODateHelper.getDateTimeFormatInstance(); dateFormat = ODateHelper.getDateTimeFormatInstance();
break; break;
default: default:
break; break;
} }
return dateFormat.format((Date) object); return dateFormat.format((Date) object);
} }
if(object instanceof Collection){ if (object instanceof Collection) {
Collection<?> collection = (Collection<?>) object; Collection<?> collection = (Collection<?>) object;
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
for(Object o : collection){ for (Object o : collection) {
Object obj = getPropertyForJson("PLACEHOLDER", o); Object obj = getPropertyForJson("PLACEHOLDER", o);
jsonArray.put(obj); jsonArray.put(obj);
} }
return jsonArray; return jsonArray;
} }
return object.toString(); return object.toString();
}catch(Exception e){ } catch (Exception e) {
throw new ResourceRegistryException("Error while serializing " throw new ResourceRegistryException(
+ key + "=" + object.toString() + " in " + getElement().toString(), e); "Error while serializing " + key + "=" + object.toString() + " in " + getElement().toString(), e);
} }
} }
protected Collection<String> getSuperclasses() throws SchemaException, ResourceRegistryException { protected Collection<String> getSuperclasses() throws SchemaException, ResourceRegistryException {
Collection<OClass> allSuperClasses = getOClass().getAllSuperClasses(); Collection<OClass> allSuperClasses = getOClass().getAllSuperClasses();
Collection<String> superClasses = new HashSet<>(); Collection<String> superClasses = new HashSet<>();
for(OClass oSuperClass : allSuperClasses){ for (OClass oSuperClass : allSuperClasses) {
String name = oSuperClass.getName(); String name = oSuperClass.getName();
if(name.compareTo(StringFactory.V.toUpperCase())==0 || if (name.compareTo(StringFactory.V.toUpperCase()) == 0 || name.compareTo(StringFactory.E.toUpperCase()) == 0
name.compareTo(StringFactory.E.toUpperCase())==0 || || name.compareTo(DatabaseEnvironment.O_RESTRICTED_CLASS) == 0) {
name.compareTo(DatabaseIntializator.O_RESTRICTED_CLASS)==0){
continue; continue;
} }
superClasses.add(name); superClasses.add(name);
} }
return superClasses; return superClasses;
} }
public JSONObject toJSONObject() throws ResourceRegistryException { public JSONObject toJSONObject() throws ResourceRegistryException {
try { try {
OrientElement orientElement = (OrientElement) getElement(); OrientElement orientElement = (OrientElement) getElement();
Map<String, Object> properties = orientElement.getProperties(); Map<String, Object> properties = orientElement.getProperties();
for(String key : orientElement.getPropertyKeys()){ for (String key : orientElement.getPropertyKeys()) {
Object object = properties.get(key); Object object = properties.get(key);
object = getPropertyForJson(key, object); object = getPropertyForJson(key, object);
if(object!=null){ if (object != null) {
properties.put(key, object); properties.put(key, object);
}else{ } else {
properties.remove(key); properties.remove(key);
} }
} }
JSONObject jsonObject = new JSONObject(properties); JSONObject jsonObject = new JSONObject(properties);
String type = orientElement.getRecord().getClassName(); String type = orientElement.getRecord().getClassName();
jsonObject.put(ISManageable.CLASS_PROPERTY, type); jsonObject.put(ISManageable.CLASS_PROPERTY, type);
Collection<String> superClasses = getSuperclasses(); Collection<String> superClasses = getSuperclasses();
JSONArray jsonArray = new JSONArray(superClasses); JSONArray jsonArray = new JSONArray(superClasses);
jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray); jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray);
return jsonObject; return jsonObject;
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch(Exception e){ } catch (Exception e) {
throw new ResourceRegistryException("Error while serializing " + getElement().toString(), e); throw new ResourceRegistryException("Error while serializing " + getElement().toString(), e);
} }
} }

View File

@ -10,6 +10,7 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -60,12 +61,12 @@ public class ERManagementUtility {
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static ERManagement getERManagement(OrientGraph orientGraph, Element element) private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element)
throws ResourceRegistryException { throws ResourceRegistryException {
if (element instanceof Vertex) { if (element instanceof Vertex) {
return getEntityManagement(orientGraph, (Vertex) element); return getEntityManagement(workingContext, orientGraph, (Vertex) element);
} else if (element instanceof Edge) { } else if (element instanceof Edge) {
return getRelationManagement(orientGraph, (Edge) element); return getRelationManagement(workingContext, orientGraph, (Edge) element);
} }
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(), throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
Entity.NAME, Relation.NAME)); Entity.NAME, Relation.NAME));
@ -97,12 +98,12 @@ public class ERManagementUtility {
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static ERManagement getERManagementFromUUID(OrientGraph orientGraph, UUID uuid) public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, UUID uuid)
throws ResourceRegistryException { throws ResourceRegistryException {
Element element; Element element;
try { try {
element = getAnyElementByUUID(orientGraph, uuid); element = getAnyElementByUUID(orientGraph, uuid);
return getERManagement(orientGraph, element); return getERManagement(workingContext, orientGraph, element);
} catch (Exception e) { } catch (Exception e) {
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s", throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
uuid.toString(), Entity.NAME, Relation.NAME)); uuid.toString(), Entity.NAME, Relation.NAME));
@ -110,7 +111,7 @@ public class ERManagementUtility {
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public static EntityManagement getEntityManagement(OrientGraph orientGraph, Vertex vertex) public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, Vertex vertex)
throws ResourceRegistryException { throws ResourceRegistryException {
if (orientGraph == null) { if (orientGraph == null) {
@ -136,9 +137,9 @@ public class ERManagementUtility {
EntityManagement entityManagement = null; EntityManagement entityManagement = null;
if (orientVertexType.isSubClassOf(Resource.NAME)) { if (orientVertexType.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(orientGraph); entityManagement = new ResourceManagement(workingContext, orientGraph);
} else if (orientVertexType.isSubClassOf(Facet.NAME)) { } else if (orientVertexType.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(orientGraph); entityManagement = new FacetManagement(workingContext, orientGraph);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", String error = String.format("{%s is not a %s nor a %s. %s",
vertex, Resource.NAME, Facet.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex, Resource.NAME, Facet.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -149,7 +150,7 @@ public class ERManagementUtility {
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public static RelationManagement getRelationManagement(OrientGraph orientGraph, Edge edge) public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, Edge edge)
throws ResourceRegistryException { throws ResourceRegistryException {
if (orientGraph == null) { if (orientGraph == null) {
@ -165,9 +166,9 @@ public class ERManagementUtility {
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
RelationManagement relationManagement = null; RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(orientGraph); relationManagement = new ConsistsOfManagement(workingContext, orientGraph);
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { } else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph); relationManagement = new IsRelatedToManagement(workingContext, orientGraph);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", String error = String.format("{%s is not a %s nor a %s. %s",
edge, ConsistsOf.NAME, IsRelatedTo.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); edge, ConsistsOf.NAME, IsRelatedTo.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);

View File

@ -16,7 +16,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
@ -61,6 +61,12 @@ public abstract class EntityManagement<E extends Entity> extends
} }
protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) {
this(accessType);
this.orientGraph = orientGraph;
setWorkingContext(workingContext);
}
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
/* /*
* It works perfectly in case of any kind of update. * It works perfectly in case of any kind of update.
@ -71,7 +77,7 @@ public abstract class EntityManagement<E extends Entity> extends
String id = edge.getId().toString(); String id = edge.getId().toString();
RelationManagement relationManagement = relationManagements.get(id); RelationManagement relationManagement = relationManagements.get(id);
if(relationManagement==null) { if(relationManagement==null) {
relationManagement = ERManagementUtility.getRelationManagement(orientGraph, edge); relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
return relationManagement; return relationManagement;
@ -93,11 +99,6 @@ public abstract class EntityManagement<E extends Entity> extends
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
protected EntityManagement(AccessType accessType, OrientGraph orientGraph) {
this(accessType);
this.orientGraph = orientGraph;
}
protected static JSONObject addRelation(JSONObject sourceResource, protected static JSONObject addRelation(JSONObject sourceResource,
JSONObject relation, String arrayKey) JSONObject relation, String arrayKey)
throws ResourceRegistryException { throws ResourceRegistryException {
@ -186,7 +187,7 @@ public abstract class EntityManagement<E extends Entity> extends
protected boolean reallyAddToContext() throws ContextException, protected boolean reallyAddToContext() throws ContextException,
ResourceRegistryException { ResourceRegistryException {
ContextUtility.addToActualContext(orientGraph, getElement()); getWorkingContext().addElement(getElement(), orientGraph);
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
@ -211,7 +212,7 @@ public abstract class EntityManagement<E extends Entity> extends
relationManagement.internalRemoveFromContext(); relationManagement.internalRemoveFromContext();
} }
ContextUtility.removeFromActualContext(orientGraph, getElement()); getWorkingContext().removeElement(getElement(), orientGraph);
return true; return true;
} }
@ -224,7 +225,7 @@ public abstract class EntityManagement<E extends Entity> extends
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic); Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
for(Vertex vertex : iterable){ for(Vertex vertex : iterable){
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex); EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
try { try {
JSONObject jsonObject = entityManagement.serializeAsJson(); JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);

View File

@ -11,6 +11,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
@ -26,8 +27,8 @@ public class FacetManagement extends EntityManagement<Facet> {
super(AccessType.FACET); super(AccessType.FACET);
} }
public FacetManagement(OrientGraph orientGraph) { public FacetManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.FACET, orientGraph); super(AccessType.FACET, workingContext, orientGraph);
} }
@Override @Override

View File

@ -15,8 +15,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
@ -45,8 +45,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
super(AccessType.RESOURCE); super(AccessType.RESOURCE);
} }
public ResourceManagement(OrientGraph orientGraph) { public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.RESOURCE, orientGraph); super(AccessType.RESOURCE, workingContext, orientGraph);
} }
@Override @Override
@ -150,7 +150,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode consistOfJsonNode : jsonNodeArray) { for (JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(consistOfJsonNode); com.setJSON(consistOfJsonNode);
com.setSourceEntityManagement(this); com.setSourceEntityManagement(this);
com.internalCreate(); com.internalCreate();
@ -162,8 +162,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement( IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
orientGraph);
irtm.setJSON(relationJsonNode); irtm.setJSON(relationJsonNode);
irtm.setSourceEntityManagement(this); irtm.setSourceEntityManagement(this);
irtm.internalCreate(); irtm.internalCreate();
@ -183,7 +182,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for (JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(relationJsonNode); com.setJSON(relationJsonNode);
com.internalCreateOrUdate(); com.internalCreateOrUdate();
addToRelationManagement(com); addToRelationManagement(com);
@ -194,8 +193,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) { if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement( IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
orientGraph);
irtm.setJSON(relationJsonNode); irtm.setJSON(relationJsonNode);
irtm.internalUpdate(); irtm.internalUpdate();
addToRelationManagement(irtm); addToRelationManagement(irtm);
@ -222,9 +220,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = null; RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph); relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph);
} else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { } else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(orientGraph); relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph);
} else { } else {
logger.warn("{} is not a {} nor a {}. {}", logger.warn("{} is not a {} nor a {}. {}",
Utility.toJsonString(edge, true), IsRelatedTo.NAME, Utility.toJsonString(edge, true), IsRelatedTo.NAME,
@ -245,8 +243,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
public String all(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException { public String all(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException {
try { try {
orientGraph = ContextUtility orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
return reallyGetAll(polymorphic, constraint); return reallyGetAll(polymorphic, constraint);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -345,7 +342,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
Vertex vertex = (Vertex) element; Vertex vertex = (Vertex) element;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex); EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
try { try {
JSONObject jsonObject = entityManagement.serializeAsJson(); JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);

View File

@ -10,6 +10,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -25,8 +26,8 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf, Resourc
super(AccessType.CONSISTS_OF); super(AccessType.CONSISTS_OF);
} }
public ConsistsOfManagement(OrientGraph orientGraph) { public ConsistsOfManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.CONSISTS_OF, orientGraph); super(AccessType.CONSISTS_OF, workingContext, orientGraph);
} }
@Override @Override
@ -47,12 +48,12 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf, Resourc
@Override @Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(orientGraph); return new ResourceManagement(getWorkingContext(), orientGraph);
} }
@Override @Override
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException { protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
return new FacetManagement(orientGraph); return new FacetManagement(getWorkingContext(), orientGraph);
} }
} }

View File

@ -10,6 +10,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
@ -24,8 +25,8 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, Resou
super(AccessType.IS_RELATED_TO); super(AccessType.IS_RELATED_TO);
} }
public IsRelatedToManagement(OrientGraph orientGraph) { public IsRelatedToManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.IS_RELATED_TO, orientGraph); super(AccessType.IS_RELATED_TO, workingContext, orientGraph);
} }
@Override @Override
@ -46,12 +47,12 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, Resou
@Override @Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(orientGraph); return new ResourceManagement(getWorkingContext(), orientGraph);
} }
@Override @Override
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException { protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(orientGraph); return new ResourceManagement(getWorkingContext(), orientGraph);
} }
} }

View File

@ -27,7 +27,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
@ -85,9 +86,10 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
} }
protected RelationManagement(AccessType accessType, OrientGraph orientGraph) { protected RelationManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) {
this(accessType); this(accessType);
this.orientGraph = orientGraph; this.orientGraph = orientGraph;
setWorkingContext(workingContext);
} }
/* /*
@ -174,7 +176,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
ResourceManagement resourceManagement = null; ResourceManagement resourceManagement = null;
if (sourceResource == null) { if (sourceResource == null) {
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(orientGraph, source); resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, source);
if (this instanceof IsRelatedToManagement) { if (this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.serializeAsJson(); sourceResource = resourceManagement.serializeAsJson();
} else if (this instanceof ConsistsOfManagement) { } else if (this instanceof ConsistsOfManagement) {
@ -279,7 +281,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) { if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if (target != null) { if (target != null) {
FacetManagement fm = new FacetManagement(orientGraph); FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph);
fm.setJSON(target); fm.setJSON(target);
fm.internalUpdate(); fm.internalUpdate();
} }
@ -327,7 +329,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
*/ */
getTargetEntityManagement().internalAddToContext(); getTargetEntityManagement().internalAddToContext();
ContextUtility.addToActualContext(orientGraph, getElement()); getWorkingContext().addElement(getElement(), orientGraph);
break; break;
@ -351,8 +353,8 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
/* Adding target to Context */ /* Adding target to Context */
getTargetEntityManagement().internalAddToContext(); getTargetEntityManagement().internalAddToContext();
ContextUtility.addToActualContext(orientGraph, getElement()); getWorkingContext().addElement(getElement(), orientGraph);
return true; return true;
} }
@ -389,7 +391,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
* In any removeConstraint value the relation MUST be removed from context to * In any removeConstraint value the relation MUST be removed from context to
* avoid to have edge having a source outside of the context. * avoid to have edge having a source outside of the context.
*/ */
ContextUtility.removeFromActualContext(orientGraph, element); getWorkingContext().removeElement(getElement(), orientGraph);
switch (removeConstraint) { switch (removeConstraint) {
case cascade: case cascade:
@ -494,37 +496,6 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return true; return true;
} }
@SuppressWarnings("unused")
private String create(UUID sourceUUID, UUID targetUUID) throws ResourceRegistryException {
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
getSourceEntityManagement().setUUID(sourceUUID);
getTargetEntityManagement().setUUID(targetUUID);
element = reallyCreate();
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic) protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException { throws ResourceRegistryException {
@ -533,7 +504,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) { if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
continue; continue;
} }
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(orientGraph, edge); RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
} }
return visitedSourceResources.values(); return visitedSourceResources.values();
@ -555,7 +526,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
throws ResourceRegistryException { throws ResourceRegistryException {
EntityManagement entityManagement = null; EntityManagement entityManagement = null;
try { try {
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(orientGraph, uuid); entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), orientGraph, uuid);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
@ -575,7 +546,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException { public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException {
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAllFrom(uuid, direction, polymorphic); return reallyGetAllFrom(uuid, direction, polymorphic);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -594,7 +565,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid); logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid);
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, true); orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean added = forcedAddToContext(); boolean added = forcedAddToContext();

View File

@ -10,7 +10,8 @@ import java.util.List;
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -132,9 +133,9 @@ public class QueryImpl implements Query {
ODatabaseDocumentTx oDatabaseDocumentTx = null; ODatabaseDocumentTx oDatabaseDocumentTx = null;
try { try {
oDatabaseDocumentTx = ContextUtility SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
.getActualSecurityContextDatabaseTx(PermissionMode.READER);
oDatabaseDocumentTx = securityContext.getDatabaseDocumentTx(PermissionMode.READER);
OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit); OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit);
osqlSynchQuery.setFetchPlan(fetchPlan); osqlSynchQuery.setFetchPlan(fetchPlan);

View File

@ -14,6 +14,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.CalledMethodProvider; import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource; import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.ConsistsOf;
@ -27,7 +28,6 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.ERPath; import org.gcube.informationsystem.resourceregistry.api.rest.ERPath;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall.HTTPMETHOD; import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall.HTTPMETHOD;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
@ -270,8 +270,7 @@ public class ERManager {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); "/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to add {} with UUID {} to current context {}", Resource.NAME, uuid, logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME);
ContextUtility.getCurrentContext());
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid)); resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.addToContext(); return resourceManagement.addToContext();
@ -288,8 +287,7 @@ public class ERManager {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); "/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to add {} with UUID {} to current context {}", Facet.NAME, uuid, logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME);
ContextUtility.getCurrentContext());
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid)); facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.addToContext(); return facetManagement.addToContext();
@ -306,8 +304,7 @@ public class ERManager {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); "/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to remove {} with UUID {} from current context {}", Resource.NAME, uuid, logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME);
ContextUtility.getCurrentContext());
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid)); resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.removeFromContext(); return resourceManagement.removeFromContext();
@ -324,8 +321,7 @@ public class ERManager {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); "/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to remove {} with UUID {} from current context {}", Facet.NAME, uuid, logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME);
ContextUtility.getCurrentContext());
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid)); facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.removeFromContext(); return facetManagement.removeFromContext();

View File

@ -8,8 +8,9 @@ import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -55,7 +56,8 @@ public class SchemaContextManagement implements SchemaManagement {
OrientGraph orientGraph = null; OrientGraph orientGraph = null;
try { try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, true); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraph = adminSecurityContext.getGraph(PermissionMode.WRITER);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class); TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class);

View File

@ -19,8 +19,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder; import org.gcube.informationsystem.types.TypeBinder;
import org.gcube.informationsystem.types.TypeBinder.Property; import org.gcube.informationsystem.types.TypeBinder.Property;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
@ -92,8 +93,8 @@ public class SchemaManagementImpl implements SchemaManagement {
logger.debug("Getting {} Type {} schema", logger.debug("Getting {} Type {} schema",
accessType != null ? accessType.getName() : "", type); accessType != null ? accessType.getName() : "", type);
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx( AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
PermissionMode.READER, true); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return getTypeSchema(orientGraphNoTx, type, accessType); return getTypeSchema(orientGraphNoTx, type, accessType);
} catch (ResourceRegistryException e) { } catch (ResourceRegistryException e) {
@ -178,8 +179,9 @@ public class SchemaManagementImpl implements SchemaManagement {
TypeDefinition typeDefinition = mapper.readValue(jsonSchema, TypeDefinition typeDefinition = mapper.readValue(jsonSchema,
TypeDefinition.class); TypeDefinition.class);
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx( AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
PermissionMode.WRITER, true); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
@ -313,7 +315,7 @@ public class SchemaManagementImpl implements SchemaManagement {
baseType.getName(), jsonSchema); baseType.getName(), jsonSchema);
return ret; return ret;
}catch (Exception e) { }catch (Exception e) {
oSchema. dropClass(typeDefinition.getName()); oSchema.dropClass(typeDefinition.getName());
throw e; throw e;
} }
} catch (OSchemaException ex) { } catch (OSchemaException ex) {
@ -336,9 +338,9 @@ public class SchemaManagementImpl implements SchemaManagement {
throws SchemaNotFoundException, SchemaException { throws SchemaNotFoundException, SchemaException {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx( AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
PermissionMode.WRITER, true); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass baseOClass = getTypeSchema(oSchema, type, null); OClass baseOClass = getTypeSchema(oSchema, type, null);

View File

@ -17,8 +17,9 @@ import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +28,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientElement;
@ -94,7 +96,8 @@ public class Utility {
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException { Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx(PermissionMode.READER, true); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz); return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz);
} finally { } finally {
if (orientGraphNoTx != null) { if (orientGraphNoTx != null) {
@ -104,7 +107,7 @@ public class Utility {
} }
public static <El extends Element> El getElementByUUID( public static <El extends Element> El getElementByUUID(
OrientBaseGraph orientBaseGraph, String elementType, UUID uuid, Graph graph, String elementType, UUID uuid,
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException { Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
if (elementType == null || elementType.compareTo("") == 0) { if (elementType == null || elementType.compareTo("") == 0) {
@ -123,7 +126,7 @@ public class Utility {
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select); OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
Iterable<El> elements = orientBaseGraph.command(osqlSynchQuery).execute(); Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute();
if (elements == null || !elements.iterator().hasNext()) { if (elements == null || !elements.iterator().hasNext()) {
String error = String.format("No %s with UUID %s was found", String error = String.format("No %s with UUID %s was found",
elementType, uuid.toString()); elementType, uuid.toString());

View File

@ -11,10 +11,13 @@ import org.gcube.informationsystem.impl.entity.ContextImpl;
import org.gcube.informationsystem.impl.utils.ISMapper; import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.model.entity.Context; import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.relation.IsParentOf; import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.resourceregistry.ScopedTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -22,61 +25,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
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.tinkerpop.blueprints.impls.orient.OrientGraph;
public class ContextManagementTest { public class ContextManagementTest extends ScopedTest {
private static Logger logger = LoggerFactory.getLogger(ContextManagementTest.class); private static Logger logger = LoggerFactory.getLogger(ContextManagementTest.class);
@Test
public void get() throws Exception {
// UUID uuid = UUID.fromString("602ce5ea-b263-452a-93e5-ab33db7af979");
UUID uuid = UUID.fromString("4e2b121e-ba5a-41e1-bbed-be9b60370aa3");
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(uuid);
String string = contextManagement.read();
logger.debug(string);
Context context = ISMapper.unmarshal(Context.class, string);
logger.debug("{}", ISMapper.marshal(context));
logger.debug("Parent : {}", ISMapper.marshal(context.getParent().getSource()));
for (IsParentOf<Context, Context> isParentOf : context.getChildren()) {
logger.debug("Children : {}", ISMapper.marshal(isParentOf.getTarget()));
}
Context parent = context.getParent().getSource();
Context sameOfContext = parent.getChildren().get(0).getTarget();
Assert.assertTrue(context == sameOfContext);
List<IsParentOf<Context, Context>> children = context.getChildren();
for (IsParentOf<Context, Context> child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
Assert.assertTrue(childContext.getParent().getSource() == context);
}
}
// @Test // @Test
public void test() throws Exception {
UUID uuid = UUID.fromString("4e2b121e-ba5a-41e1-bbed-be9b60370aa3");
Context myTest = new ContextImpl("myTest");
myTest.setParent(uuid);
String contextJsonString = ISMapper.marshal(myTest);
logger.debug("myTest : {}", contextJsonString);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setJSON(contextJsonString);
contextManagement.create();
}
@Test
public void testJava() throws Exception { public void testJava() throws Exception {
Context gcube = new ContextImpl("gcube"); Context gcube = new ContextImpl("gcube");
logger.debug("gcube : {}", ISMapper.marshal(gcube)); logger.debug("gcube : {}", ISMapper.marshal(gcube));
@ -110,7 +69,7 @@ public class ContextManagementTest {
public static final String CTX_NAME_B = "B"; public static final String CTX_NAME_B = "B";
public static final String CTX_NAME_C = "C"; public static final String CTX_NAME_C = "C";
protected void assertions(Context pre, Context post, boolean checkParent, boolean create) { protected void assertions(Context pre, Context post, boolean checkParent, boolean create) throws ResourceRegistryException {
if (checkParent) { if (checkParent) {
if (pre.getHeader() != null) { if (pre.getHeader() != null) {
FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create); FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create);
@ -125,13 +84,39 @@ public class ContextManagementTest {
Context postParent = post.getParent().getSource(); Context postParent = post.getParent().getSource();
assertions(preParent, postParent, false, false); assertions(preParent, postParent, false, false);
} }
} }
protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException {
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER);
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
SecurityContext securityContext = new SecurityContext(uuid);
for(PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, false);
ORole oRole = oSecurity.getRole(role);
Assert.assertEquals(oRole==null, deleted);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false);
OUser oUser = oSecurity.getUser(user);
Assert.assertEquals(oUser==null, deleted);
}
}
protected Context read(UUID uuid) throws ResourceRegistryException, IOException { protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(uuid); contextManagement.setUUID(uuid);
String contextString = contextManagement.read(); String contextString = contextManagement.read();
logger.debug("Read {}", contextString); logger.debug("Read {}", contextString);
roleUserAssertions(uuid, false);
return ISMapper.unmarshal(Context.class, contextString); return ISMapper.unmarshal(Context.class, contextString);
} }
@ -142,6 +127,7 @@ public class ContextManagementTest {
logger.debug("Created {}", contextString); logger.debug("Created {}", contextString);
Context c = ISMapper.unmarshal(Context.class, contextString); Context c = ISMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, true); assertions(context, c, true, true);
roleUserAssertions(c.getHeader().getUUID(), false);
return c; return c;
} }
@ -152,6 +138,7 @@ public class ContextManagementTest {
logger.debug("Updated {}", contextString); logger.debug("Updated {}", contextString);
Context c = ISMapper.unmarshal(Context.class, contextString); Context c = ISMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, false); assertions(context, c, true, false);
roleUserAssertions(c.getHeader().getUUID(), false);
return c; return c;
} }
@ -160,6 +147,7 @@ public class ContextManagementTest {
contextManagement.setUUID(uuid); contextManagement.setUUID(uuid);
boolean deleted = contextManagement.delete(); boolean deleted = contextManagement.delete();
Assert.assertTrue(deleted); Assert.assertTrue(deleted);
roleUserAssertions(uuid, true);
logger.debug("Deleted {} with UUID {}", Context.NAME, uuid); logger.debug("Deleted {} with UUID {}", Context.NAME, uuid);
return deleted; return deleted;
} }
@ -383,14 +371,27 @@ public class ContextManagementTest {
public void testGetAll() throws Exception { public void testGetAll() throws Exception {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
String all = contextManagement.all(false); String all = contextManagement.all(false);
logger.debug(all); logger.trace(all);
List<Context> contexts = ISMapper.unmarshalList(Context.class, all); List<Context> contexts = ISMapper.unmarshalList(Context.class, all);
for(Context context : contexts){ for(Context context : contexts){
logger.debug(ISMapper.marshal(context)); logger.trace(ISMapper.marshal(context));
List<IsParentOf<Context, Context>> children = context.getChildren();
for (IsParentOf<Context, Context> child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
Assert.assertTrue(childContext.getParent().getSource() == context);
}
roleUserAssertions(context.getHeader().getUUID(), false);
} }
} }
// @Test
public void deleteContext() throws ResourceRegistryException, IOException {
Context context = read(UUID.fromString(""));
delete(context);
}
@Test // @Test
public void createDevContext() throws Exception { public void createDevContext() throws Exception {
Context gcube = new ContextImpl("gcube"); Context gcube = new ContextImpl("gcube");
gcube = create(gcube); gcube = create(gcube);

View File

@ -0,0 +1,16 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatabaseEnvironmentTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironmentTest.class);
@Test
public void createDB() throws Exception{
String db = DatabaseEnvironment.DB_URI;
logger.trace("Created DB is {}", db);
}
}

View File

@ -1,32 +0,0 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
public class DatabaseIntializatorTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseIntializatorTest.class);
//@Test
public void testInitDB() throws Exception{
DatabaseIntializator.initGraphDB();
OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.CHANGED_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD)
.setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
/* Updating Datetime Format to be aligned with IS model definition */
OStorageConfiguration configuration = orientGraphNoTx.getRawGraph().getStorage().getConfiguration();
logger.debug("Got DateTimeFormat {}", configuration.getDateTimeFormat());
}
}

View File

@ -292,8 +292,8 @@ public class ERManagementTest extends ScopedTest {
facetManagement = new FacetManagement(); facetManagement = new FacetManagement();
facetManagement.setUUID(uuid); facetManagement.setUUID(uuid);
//boolean deleted = facetManagement.delete(); boolean deleted = facetManagement.delete();
//Assert.assertTrue(deleted); Assert.assertTrue(deleted);
} }

View File

@ -81,9 +81,6 @@ public class FacetManagementTest extends ScopedTest {
checkAssertion(softwareFacet, VERSION, null, true); checkAssertion(softwareFacet, VERSION, null, true);
UUID uuid = softwareFacet.getHeader().getUUID(); UUID uuid = softwareFacet.getHeader().getUUID();
Thread.sleep(1000);
/* Testing Update */ /* Testing Update */
softwareFacet.setVersion(NEW_VERSION); softwareFacet.setVersion(NEW_VERSION);

View File

@ -117,6 +117,14 @@ public class RuleTest extends ScopedTest {
// TODO continue with checks // TODO continue with checks
eServiceManagement = new ResourceManagement();
eServiceManagement.setElementType(EService.NAME);
eServiceManagement.setJSON(eServiceString);
boolean deleted = eServiceManagement.delete();
Assert.assertTrue(deleted);
} }
} }

View File

@ -11,6 +11,9 @@
<logger name="org.gcube" level="INFO" /> <logger name="org.gcube" level="INFO" />
<logger name="org.gcube.informationsystem" level="TRACE" /> <logger name="org.gcube.informationsystem" level="TRACE" />
<logger name="org.gcube.informationsystem.types" level="INFO" />
<logger name="org.gcube.informationsystem.resourceregistry.dbinitialization" level="INFO" />
<logger name=" org.gcube.informationsystem.impl.utils.discovery" level="INFO" />
<root level="WARN"> <root level="WARN">
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT" />