diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java new file mode 100644 index 0000000..30f8ebd --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java @@ -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()); + + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextManagement.java index 0fd9cb3..848d4c0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextManagement.java @@ -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.er.ERAlreadyPresentException; 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.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.utils.Utility; @@ -39,11 +40,8 @@ public class ContextManagement extends EntityManagement { protected String name; private void init() { - this.forceAdmin = true; - this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY); this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY); - this.erType = Context.NAME; } @@ -52,9 +50,10 @@ public class ContextManagement extends EntityManagement { init(); } - public ContextManagement(OrientGraph orientGraph) { - super(AccessType.CONTEXT, orientGraph); - init(); + public ContextManagement(OrientGraph orientGraph) throws ResourceRegistryException { + this(); + this.orientGraph = orientGraph; + getWorkingContext(); } public String getName() { @@ -70,6 +69,13 @@ public class ContextManagement extends EntityManagement { return name; } + protected SecurityContext getWorkingContext() throws ResourceRegistryException { + if(workingContext == null) { + workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID); + } + return workingContext; + } + @Override protected ContextNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { return new ContextNotFoundException(e.getMessage(), e.getCause()); @@ -190,6 +196,8 @@ public class ContextManagement extends EntityManagement { @Override protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException { + SecurityContext securityContext = null; + try { JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); @@ -203,7 +211,6 @@ public class ContextManagement extends EntityManagement { if(uuid==null){ uuid = UUID.randomUUID(); } - SecurityContext.createSecurityContext(orientGraph, uuid, true); createVertex(); @@ -216,14 +223,18 @@ public class ContextManagement extends EntityManagement { }else { checkContext(null); - SecurityContext.createSecurityContext(orientGraph, uuid, true); createVertex(); } + securityContext = new SecurityContext(uuid); + securityContext.create(orientGraph); + return getElement(); }catch (Exception e) { orientGraph.rollback(); - SecurityContext.deleteSecurityContext(orientGraph, uuid, true); + if(securityContext!=null) { + securityContext.delete(orientGraph); + } throw e; } } @@ -303,7 +314,7 @@ public class ContextManagement extends EntityManagement { element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys); - ContextUtility.invalidContextUUIDCache(uuid); + ContextUtility.getInstace().removeFromCache(uuid); return element; } @@ -351,8 +362,11 @@ public class ContextManagement extends EntityManagement { element.remove(); - ContextUtility.invalidContextUUIDCache(uuid); - SecurityContext.deleteSecurityContext(orientGraph, uuid, false); + ContextUtility contextUtility = ContextUtility.getInstace(); + SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid); + securityContext.delete(orientGraph); + + contextUtility.removeFromCache(uuid); return true; diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java new file mode 100644 index 0000000..92222bf --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java @@ -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()); + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java index 7b4035a..7bb50ce 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java @@ -6,6 +6,7 @@ package org.gcube.informationsystem.resourceregistry.context; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.NoSuchElementException; import java.util.UUID; 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.impl.ScopeBean; 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.context.ContextException; 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.slf4j.Logger; 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.tinkerpop.blueprints.Element; +import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.impls.orient.OrientGraph; -import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; /** * @author Luca Frosini (ISTI - CNR) @@ -36,60 +35,26 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; */ public class ContextUtility { - private static final Logger logger = LoggerFactory - .getLogger(ContextUtility.class); + private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class); - private static Map contextUUIDCache; - - static { - contextUUIDCache = new HashMap<>(); - } - - - protected static void invalidContextUUIDCache(){ - 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; - } + private Map contextUUIDs; + private Map contexts; + + private static ContextUtility contextUtility; + + public static ContextUtility getInstace() { + if (contextUtility == null) { + contextUtility = new ContextUtility(); } - - } - - public static UUID addToActualContext(OrientGraph orientGraph, Element element) - throws ContextException { - UUID contextUUID = ContextUtility.getActualContextUUID(); - SecurityContext.addToSecurityContext(orientGraph, element, contextUUID); - return contextUUID; + return contextUtility; } - public static UUID addToActualContex(OSecurity oSecurity, Element element) - throws ContextException { - UUID contextUUID = ContextUtility.getActualContextUUID(); - SecurityContext.addToSecurityContext(oSecurity, element, contextUUID); - return contextUUID; + private ContextUtility() { + contextUUIDs = new HashMap<>(); + contexts = new HashMap<>(); } - public static UUID removeFromActualContext(OrientGraph orientGraph, Element element) - 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(){ + private static String getCurrentContextFullName() { String token = SecurityTokenProvider.instance.get(); AuthorizationEntry authorizationEntry = null; try { @@ -99,145 +64,138 @@ public class ContextUtility { } 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 { - OrientGraph orientGraph = null; + private synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException { try { - String scope = getCurrentContext(); - if(scope==null){ - throw new ContextException("Null Token and Scope. Please set your token first."); + SecurityContext securityContext = null; + + 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); - - 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; - + + return securityContext; + } catch (ContextException e) { throw e; } catch (Exception e) { - throw new ContextException( - "Unable to restrive Context UUID from current Context", e); - } finally{ - if(orientGraph!=null){ - orientGraph.shutdown(); + throw new ContextException("Unable to restrive Context UUID from current Context", e); + } + } + + 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( - 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 { + private Vertex getContextVertexByFullName(String fullName) throws ResourceRegistryException { logger.trace("Going to get {} {} from full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName); - + ScopeBean scopeBean = new ScopeBean(fullName); String name = scopeBean.name(); // TODO Rewrite the query using Gremlin // Please note that this query works because all the scope parts has a // different name - String select = "SELECT FROM " + Context.class.getSimpleName() - + " WHERE " + Context.NAME_PROPERTY + " = \"" + name + "\""; + String select = "SELECT FROM " + Context.class.getSimpleName() + " WHERE " + Context.NAME_PROPERTY + " = \"" + + name + "\""; ; - OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery( - select); - Iterable vertexes = orientGraph.command(osqlSynchQuery) + OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); + + Iterable vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery) .execute(); if (vertexes == null || !vertexes.iterator().hasNext()) { - throw new ContextNotFoundException( - "Error retrieving context with name " + fullName); + throw new ContextNotFoundException("Error retrieving context with name " + fullName); } Iterator iterator = vertexes.iterator(); Vertex context = iterator.next(); - logger.trace("Context Representing Vertex : {}", - Utility.toJsonString(context, true)); + logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true)); if (iterator.hasNext()) { - throw new ContextNotFoundException( - "Found more than one context with name " + name - + "but required the one with path" + fullName - + ". Please Reimplement the query"); + throw new ContextNotFoundException("Found more than one context with name " + name + + "but required the one with path" + fullName + ". Please Reimplement the query"); } return context; } - public static String getActualSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode permissionMode, - SecurityContextMapper.SecurityType securityType) - throws ContextException { - UUID contextUUID = getActualContextUUID(); - return SecurityContextMapper.getSecurityRoleOrUserName(permissionMode, - securityType, contextUUID); - } - } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java index 199fa68..d95ae54 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java @@ -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.isparentof.IsParentOfAlreadyPresentException; 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.utils.Utility; @@ -34,8 +35,18 @@ public class IsParentOfManagement extends RelationManagement 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; - SecurityContext.allowSecurityContextRoles(oSecurity, - orientElement.getRecord(), context); - orientElement.save(); - } - - public static void removeFromSecurityContext(OrientGraph orientGraph, - Element element, UUID context) { - 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); + ODocument oDocument = orientElement.getRecord(); + OSecurity oSecurity = getAdminOSecurity(orientGraph); + String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false); + String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false); + oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName); + oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); + oDocument.save(); orientElement.save(); } - protected static void disallowSecurityContextRoles(OSecurity oSecurity, - ODocument oDocument, UUID context) { - oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, - SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.ROLE, context)); - - oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, - SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.ROLE, context)); - + public void removeElement(Element element) throws ResourceRegistryException { + removeElement(element, ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER)); + } + + public void removeElement(Element element, OrientGraph orientGraph) { + OrientElement orientElement = (OrientElement) element; + ODocument oDocument = orientElement.getRecord(); + OSecurity oSecurity = getAdminOSecurity(orientGraph); + String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false); + String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false); + oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName); + oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); oDocument.save(); - // oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, - // DEFAULT_WRITER_ROLE); - // oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, - // DEFAULT_READER_ROLE); + orientElement.save(); } - protected static void allowSecurityContextRoles(OSecurity oSecurity, - ODocument oDocument, UUID context) { - oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, - SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.WRITER, - 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 void create() throws ResourceRegistryException { + OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); + create(orientGraph); + orientGraph.commit(); + orientGraph.shutdown(); } - - public static void createSecurityContext(OrientGraph orientGraph, - UUID context, boolean commit) { + + public void create(OrientGraph orientGraph) { + 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 reader = oSecurity.getRole(DEFAULT_READER_ROLE); - String writeRoleName = SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.ROLE, context); - ORole writerRole = oSecurity.createRole(writeRoleName, - writer, ALLOW_MODES.DENY_ALL_BUT); + + 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.save(); logger.trace("{} created", writerRole); - - - String readerRoleName = SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.ROLE, context); - ORole readerRole = oSecurity.createRole(readerRoleName, - reader, ALLOW_MODES.DENY_ALL_BUT); + + ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT); readerRole.save(); logger.trace("{} created", readerRole); - - String writerUserName = SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.USER, context); OUser writerUser = oSecurity.createUser(writerUserName, - DatabaseEnvironment.DEFAULT_PASSWORDS - .get(SecurityContextMapper.PermissionMode.WRITER), - writerRole); + DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole); writerUser.save(); logger.trace("{} created", writerUser); - - - String readerUserName = SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.USER, context); + OUser readerUser = oSecurity.createUser(readerUserName, - DatabaseEnvironment.DEFAULT_PASSWORDS - .get(SecurityContextMapper.PermissionMode.READER), - readerRole); + DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole); readerUser.save(); logger.trace("{} created", readerUser); - - if(commit) { - oDatabaseDocumentTx.commit(); - } - - logger.trace( - "Security Context (roles and users) with UUID {} successfully created", - context.toString()); + + logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); } - public static void deleteSecurityContext(OrientGraph orientGraph, - UUID context, boolean commit) { + private void drop(OSecurity oSecurity, String name, SecurityType securityType) { + boolean dropped = false; + switch (securityType) { + case ROLE: + dropped = oSecurity.dropRole(name); + break; - logger.trace( - "Going to remove Security Context (roles and users) with UUID {}", - context.toString()); - ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph(); - OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity(); + case USER: + dropped = oSecurity.dropUser(name); + break; - String user = SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.USER, context); - boolean dropped = oSecurity.dropUser(user); + default: + break; + } if (dropped) { - logger.trace("{} successfully dropped", user); + logger.trace("{} successfully dropped", name); } else { - logger.error("{} was not dropped successfully", user); + logger.error("{} was not dropped successfully", name); } + } - user = SecurityContextMapper.getSecurityRoleOrUserName( - SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.USER, context); - dropped = oSecurity.dropUser(user); - if (dropped) { - logger.trace("{} successfully dropped", user); - } else { - logger.error("{} was not dropped successfully", user); - } - - 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(); - } + public void delete() throws ResourceRegistryException { + OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); + delete(orientGraph); + orientGraph.commit(); + orientGraph.shutdown(); + } + + public void delete(OrientGraph orientGraph) { + ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph); + OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx); - logger.trace( - "Security Context (roles and users) with UUID {} successfully removed", - context.toString()); + logger.trace("Going to remove Security Context (roles and users) with UUID {}", 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()); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java deleted file mode 100644 index 285a9d6..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java +++ /dev/null @@ -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> 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 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 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(); - } - -} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java index a288fe5..1e7f4cf 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java @@ -7,124 +7,298 @@ import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import java.util.UUID; -import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper; -import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; +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.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.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) * */ 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"; - - protected static final String REMOTE_PROTOCOL; - protected static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL"; - - public static final String DB; - protected static final String DB_VARNAME = "DB"; - - protected static final String ROOT_USERNAME; - protected static final String ROOT_USERNAME_VARNAME = "ROOT_USERNAME"; - - protected static final String ROOT_PASSWORD; - protected static final String ROOT_PASSWORD_VARNAME = "ROOT_PASSWORD"; - - protected static final String DEFAULT_ADMIN_USERNAME; - protected static final String DEFAULT_ADMIN_USERNAME_VARNAME = "DEFAULT_ADMIN_USERNAME"; - - protected static final String DEFAULT_ADMIN_ROLE = "admin"; - - public static final String CHANGED_ADMIN_USERNAME; - protected static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME"; - - protected static final String DEFAULT_ADMIN_PASSWORD; - protected static final String DEFAULT_ADMIN_PASSWORD_VARNAME = "DEFAULT_ADMIN_PASSWORD"; - - public static final String CHANGED_ADMIN_PASSWORD; - protected static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_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"; - - 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 Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class); + + private static final String PROPERTY_FILENAME = "config.properties"; + + private static final String HOST_VARNAME = "HOST"; + + private static final String REMOTE_PROTOCOL; + private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL"; + + private static final String DB; + private static final String DB_VARNAME = "DB"; + + private static final String ROOT_USERNAME; + private static final String ROOT_USERNAME_VARNAME = "ROOT_USERNAME"; + + private static final String ROOT_PASSWORD; + private static final String ROOT_PASSWORD_VARNAME = "ROOT_PASSWORD"; + + private static final String DEFAULT_ADMIN_USERNAME; + private static final String DEFAULT_ADMIN_USERNAME_VARNAME = "DEFAULT_ADMIN_USERNAME"; + + public static final String DEFAULT_ADMIN_ROLE = "admin"; + + private static final String CHANGED_ADMIN_USERNAME; + private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME"; + + private static final String DEFAULT_ADMIN_PASSWORD; + private static final String DEFAULT_ADMIN_PASSWORD_VARNAME = "DEFAULT_ADMIN_PASSWORD"; + + private static final String CHANGED_ADMIN_PASSWORD; + private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD"; + + private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD; + private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_WRITER_USER_PASSWORD"; + + private static final String DEFAULT_CREATED_READER_USER_PASSWORD; + private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD"; + public static final Map DEFAULT_PASSWORDS; - - protected static final String HOSTS; - - public static final String SERVER_URI; + + private static final String HOSTS; + + private static final String SERVER_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 { Properties properties = new Properties(); InputStream input = null; - + try { input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME); // load a properties file properties.load(input); - + HOSTS = properties.getProperty(HOST_VARNAME); - + REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME); DB = properties.getProperty(DB_VARNAME); SERVER_URI = REMOTE_PROTOCOL + HOSTS; DB_URI = SERVER_URI + "/" + DB; - + ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME); ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME); - - + String changedAdminUsername = null; try { changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME); - if(changedAdminUsername==null){ - // To be compliant with old configuration.properties which does not have + if (changedAdminUsername == null) { + // To be compliant with old configuration.properties which does not have // CHANGED_ADMIN_USERNAME property we use the db name as admin username changedAdminUsername = DB; } - }catch (Exception e) { - // To be compliant with old configuration.properties which does not have + } catch (Exception e) { + // To be compliant with old configuration.properties which does not have // CHANGED_ADMIN_USERNAME property we use the db name as admin username changedAdminUsername = DB; } CHANGED_ADMIN_USERNAME = changedAdminUsername; - - + CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_ADMIN_PASSWORD_VARNAME); - - + 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_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME); DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME); - - - DEFAULT_PASSWORDS = new HashMap(); - + + DEFAULT_PASSWORDS = new HashMap(); + DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_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); 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); + } + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java deleted file mode 100644 index 082c48a..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java +++ /dev/null @@ -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); - } - -} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java index e905738..2e6d93a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java @@ -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.ERNotFoundException; 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.IsParentOfManagement; -import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; -import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseIntializator; +import org.gcube.informationsystem.resourceregistry.context.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; @@ -67,7 +66,7 @@ import com.tinkerpop.blueprints.util.StringFactory; public abstract class ERManagement { protected Logger logger = LoggerFactory.getLogger(this.getClass()); - + private static Logger staticLogger = LoggerFactory.getLogger(ERManagement.class); public final String AT = "@"; @@ -75,10 +74,10 @@ public abstract class ERManagement { protected final Set ignoreKeys; protected final Set ignoreStartWithKeys; - + protected Class elementClass; protected final AccessType accessType; - + protected OrientGraph orientGraph; protected UUID uuid; @@ -97,21 +96,21 @@ public abstract class ERManagement { 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() { return accessType; } - public boolean isForceAdmin() { - return forceAdmin; + protected SecurityContext workingContext; + + protected SecurityContext getWorkingContext() throws ResourceRegistryException { + if(workingContext == null) { + workingContext = ContextUtility.getCurrentSecurityContext(); + } + return workingContext; } - - public void setForceAdmin(boolean forceAdmin) { - this.forceAdmin = forceAdmin; + + public void setWorkingContext(SecurityContext workingContext) { + this.workingContext = workingContext; } protected ERManagement(AccessType accessType) { @@ -123,13 +122,9 @@ public abstract class ERManagement { this.ignoreStartWithKeys.add(AT); this.ignoreStartWithKeys.add(UNDERSCORE); - - this.reload = false; - } - protected ERManagement(AccessType accessType, OrientGraph orientGraph) { - this(accessType); - this.orientGraph = orientGraph; + this.reload = false; + } public void setUUID(UUID uuid) throws ResourceRegistryException { @@ -144,8 +139,7 @@ public abstract class ERManagement { checkJSON(); } - public void setJSON(String jsonRepresentation) - throws ResourceRegistryException { + public void setJSON(String jsonRepresentation) throws ResourceRegistryException { ObjectMapper mapper = new ObjectMapper(); try { this.jsonNode = mapper.readTree(jsonRepresentation); @@ -156,20 +150,20 @@ public abstract class ERManagement { } protected OClass getOClass() throws SchemaException, ResourceRegistryException { - if(oClass==null){ - if(element!=null){ + if (oClass == null) { + if (element != null) { OrientElement orientElement = (OrientElement) element; OMetadata oMetadata = orientElement.getGraph().getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); String type = orientElement.getRecord().getClassName(); oClass = oSchema.getClass(type); - }else{ + } else { oClass = SchemaManagementImpl.getTypeSchema(erType, accessType); } } return oClass; } - + public void setElementType(String erType) throws ResourceRegistryException { this.erType = erType; if (erType == null || erType.compareTo("") == 0) { @@ -183,9 +177,9 @@ public abstract class ERManagement { protected void checkJSON() throws ResourceRegistryException { if (uuid == null) { try { - uuid = org.gcube.informationsystem.impl.utils.Utility - .getUUIDFromJsonNode(jsonNode); - } catch (Exception e) {} + uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode); + } catch (Exception e) { + } } else { checkUUIDMatch(); } @@ -199,12 +193,11 @@ public abstract class ERManagement { } protected void checkERMatch() throws ResourceRegistryException { - if(jsonNode!=null){ + if (jsonNode != null) { String type = getClassProperty(jsonNode); if (type != null && type.compareTo(erType) != 0) { - String error = String - .format("Declared resourceType does not match with json representation %s!=%s", - erType, type); + String error = String.format("Declared resourceType does not match with json representation %s!=%s", + erType, type); logger.trace(error); throw new ResourceRegistryException(error); } @@ -223,10 +216,9 @@ public abstract class ERManagement { if (header != null) { UUID resourceUUID = header.getUUID(); if (resourceUUID.compareTo(uuid) != 0) { - String error = String - .format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance", - resourceUUID.toString(), uuid.toString(), - erType); + String error = String.format( + "UUID provided in header (%s) differs from the one (%s) used to identify the %s instance", + resourceUUID.toString(), uuid.toString(), erType); throw new ResourceRegistryException(error); } @@ -236,105 +228,97 @@ public abstract class ERManagement { public JSONObject serializeSelfOnly() throws ResourceRegistryException { try { return toJSONObject(); - }catch(Exception e){ + } catch (Exception e) { throw new ResourceRegistryException(e); } } - + public abstract String serialize() throws ResourceRegistryException; - public abstract JSONObject serializeAsJson() - throws ResourceRegistryException; - - protected abstract El reallyCreate() throws ERAlreadyPresentException, - ResourceRegistryException; + public abstract JSONObject serializeAsJson() throws ResourceRegistryException; + protected abstract El reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException; + public El internalCreate() throws ERAlreadyPresentException, ResourceRegistryException { try { reallyCreate(); - + Header entityHeader = HeaderUtility.getHeader(jsonNode, true); if (entityHeader != null) { element.setProperty(Entity.HEADER_PROPERTY, entityHeader); } else { entityHeader = HeaderUtility.addHeader(element, null); } - - if(!(this instanceof ContextManagement || this instanceof IsParentOfManagement)){ - ContextUtility.addToActualContext(orientGraph, element); - } - + + getWorkingContext().addElement(element, orientGraph); + ((OrientElement) element).save(); - + return element; - }catch (ResourceRegistryException e) { + } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause()); } } - - protected abstract El reallyUpdate() throws ERNotFoundException, - ResourceRegistryException; + + protected abstract El reallyUpdate() throws ERNotFoundException, ResourceRegistryException; public El internalUpdate() throws ERNotFoundException, ResourceRegistryException { try { - + reallyUpdate(); - + HeaderUtility.updateModifiedByAndLastUpdate(element); ((OrientElement) element).save(); - + return element; - }catch (ResourceRegistryException e) { + } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { throw new ResourceRegistryException("Error Updating " + erType + " with " + jsonNode, e.getCause()); } } - + public El internalCreateOrUdate() throws ResourceRegistryException { try { return internalUpdate(); - }catch (ERNotFoundException e) { + } catch (ERNotFoundException e) { return internalCreate(); } } - - protected abstract boolean reallyDelete() throws ERNotFoundException, - ResourceRegistryException; + + protected abstract boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException; public boolean internalDelete() throws ERNotFoundException, ResourceRegistryException { // Added for consistency with create and update addToContext removeFromContext. return reallyDelete(); } - - protected abstract boolean reallyAddToContext() throws ContextException, - ResourceRegistryException; - + + protected abstract boolean reallyAddToContext() throws ContextException, ResourceRegistryException; + public boolean internalAddToContext() throws ContextException, ResourceRegistryException { try { boolean ret = reallyAddToContext(); HeaderUtility.updateModifiedByAndLastUpdate(element); ((OrientElement) element).save(); return ret && true; - }catch (ResourceRegistryException e) { + } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { throw new ResourceRegistryException("Error Adding " + erType + " to Current Context ", e.getCause()); } } - protected abstract boolean reallyRemoveFromContext() throws ContextException, - ResourceRegistryException; - + protected abstract boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException; + public boolean internalRemoveFromContext() throws ContextException, ResourceRegistryException { try { boolean ret = reallyRemoveFromContext(); HeaderUtility.updateModifiedByAndLastUpdate(element); ((OrientElement) element).save(); return ret && true; - }catch (ResourceRegistryException e) { + } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause()); @@ -343,53 +327,55 @@ public abstract class ERManagement { public void setElement(El element) throws ResourceRegistryException { if (element == null) { - throw new ResourceRegistryException("Trying to set null " - + elementClass.getSimpleName() + " in " + this); + throw new ResourceRegistryException("Trying to set null " + elementClass.getSimpleName() + " in " + this); } this.element = element; this.uuid = HeaderUtility.getHeader(element).getUUID(); } protected abstract ERNotFoundException getSpecificElementNotFoundException(ERNotFoundException e); - - protected abstract ERAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message); - + + protected abstract ERAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( + String message); + protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message); - + public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { if (element == null) { try { element = retrieveElement(); - }catch (ERNotFoundException e) { + } catch (ERNotFoundException e) { try { 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) { throw e1; - }catch (Exception e1) { + } catch (Exception e1) { throw e; - } + } } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { throw new ResourceRegistryException(e); } - - }else { - if(reload){ + + } else { + if (reload) { ((OrientElement) element).reload(); } } return element; } - + public El retrieveElement() throws ERNotFoundException, ResourceRegistryException { try { - if(uuid==null){ + if (uuid == null) { throw new ERNotFoundException("null UUID does not allow to retrieve the Element"); } - return Utility.getElementByUUID(orientGraph, - erType == null ? accessType.getName() : erType, uuid, elementClass); + return Utility.getElementByUUID(orientGraph, erType == null ? accessType.getName() : erType, uuid, + elementClass); } catch (ERNotFoundException e) { throw getSpecificElementNotFoundException(e); } catch (ResourceRegistryException e) { @@ -398,26 +384,25 @@ public abstract class ERManagement { throw new ResourceRegistryException(e); } } - + public El retrieveElementFromAnyContext() throws ERNotFoundException, ResourceRegistryException { - try{ + try { return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass); - }catch (ERNotFoundException e) { + } catch (ERNotFoundException e) { throw getSpecificElementNotFoundException(e); } catch (ResourceRegistryException e) { throw e; } catch (Exception e) { throw new ResourceRegistryException(e); } - } - - public abstract String reallyGetAll(boolean polymorphic) - throws ResourceRegistryException; + } + + public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException; public String all(boolean polymorphic) throws ResourceRegistryException { try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); + + orientGraph = getWorkingContext().getGraph(PermissionMode.READER); return reallyGetAll(polymorphic); } catch (ResourceRegistryException e) { @@ -430,11 +415,11 @@ public abstract class ERManagement { } } } - - public boolean exists() throws ERNotFoundException, - ERAvailableInAnotherContextException, ResourceRegistryException { + + public boolean exists() + throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { try { - orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); + orientGraph = getWorkingContext().getGraph(PermissionMode.READER); getElement(); @@ -455,14 +440,14 @@ public abstract class ERManagement { public String create() throws ERAlreadyPresentException, ResourceRegistryException { try { - orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin); + orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); element = internalCreate(); orientGraph.commit(); // TODO Notify to subscriptionNotification - + return serialize(); } catch (ResourceRegistryException e) { @@ -484,11 +469,9 @@ public abstract class ERManagement { } } - public String read() throws ERNotFoundException, - ERAvailableInAnotherContextException, ResourceRegistryException { + public String read() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); + orientGraph = getWorkingContext().getGraph(PermissionMode.READER); getElement(); @@ -506,22 +489,19 @@ public abstract class ERManagement { } } - public String update() throws ERNotFoundException, - ERAvailableInAnotherContextException, ResourceRegistryException { + public String update() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin); - + orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); + element = internalUpdate(); - + orientGraph.commit(); - + setReload(true); // TODO Notify to subscriptionNotification - + return serialize(); - // TODO Serialized resource is the old version. This really strange and should be an orient bug - + } catch (ResourceRegistryException e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); if (orientGraph != null) { @@ -541,27 +521,24 @@ public abstract class ERManagement { } } - public boolean delete() throws ERNotFoundException, - ERAvailableInAnotherContextException, ResourceRegistryException { + public boolean delete() + throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid); try { - - orientGraph = ContextUtility.getActualSecurityContextGraph( - PermissionMode.WRITER, true); - + + orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); + boolean deleted = reallyDelete(); - if(deleted){ + if (deleted) { orientGraph.commit(); - logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), - uuid); - }else{ - logger.info("{} with UUID {} was NOT deleted.", accessType.getName(), - uuid); + logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid); + } else { + logger.info("{} with UUID {} was NOT deleted.", accessType.getName(), uuid); orientGraph.rollback(); } - + return deleted; } catch (ResourceRegistryException e) { @@ -584,30 +561,25 @@ public abstract class ERManagement { } public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException { - logger.debug("Going to add {} with UUID {} to actual Context", - accessType.getName(), uuid); + logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid, getWorkingContext().toString()); try { - orientGraph = ContextUtility.getActualSecurityContextGraph( - PermissionMode.WRITER, true); + orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); boolean added = internalAddToContext(); orientGraph.commit(); - logger.info("{} with UUID {} successfully added to actual Context", - accessType.getName(), uuid); - + logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid); + return added; } catch (ResourceRegistryException e) { - logger.error("Unable to add {} with UUID {} to actual Context", - accessType.getName(), uuid); + logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid); if (orientGraph != null) { orientGraph.rollback(); } throw e; } catch (Exception e) { - logger.error("Unable to add {} with UUID {} to actual Context", - accessType.getName(), uuid, e); + logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e); if (orientGraph != null) { orientGraph.rollback(); } @@ -620,32 +592,26 @@ public abstract class ERManagement { } public boolean removeFromContext() throws ERNotFoundException, ContextException, ResourceRegistryException { - logger.debug("Going to remove {} with UUID {} from actual Context", - accessType.getName(), uuid); + logger.debug("Going to remove {} with UUID {} from actual Context", accessType.getName(), uuid); try { - orientGraph = ContextUtility.getActualSecurityContextGraph( - PermissionMode.WRITER, true); + orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); + boolean removed = internalRemoveFromContext(); orientGraph.commit(); - logger.info( - "{} with UUID {} successfully removed from actual Context", - accessType.getName(), uuid); + logger.info("{} with UUID {} successfully removed from actual Context", accessType.getName(), uuid); return removed; } catch (ResourceRegistryException e) { - logger.error("Unable to remove {} with UUID {} from actual Context", - accessType.getName(), uuid); + logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid); if (orientGraph != null) { orientGraph.rollback(); } throw e; } catch (Exception e) { - logger.error( - "Unable to remove {} with UUID {} from actual Context", - accessType.getName(), uuid, e); + logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid, e); if (orientGraph != null) { orientGraph.rollback(); } @@ -665,69 +631,63 @@ public abstract class ERManagement { } public static Object getObjectFromElement(JsonNode value) - throws UnsupportedDataTypeException, ResourceRegistryException{ + throws UnsupportedDataTypeException, ResourceRegistryException { JsonNodeType jsonNodeType = value.getNodeType(); switch (jsonNodeType) { - case OBJECT: - return EmbeddedMangement.getEmbeddedType(value); - - case ARRAY: - /* - List list = new ArrayList(); - Iterator arrayElement = value.elements(); - while (arrayElement.hasNext()) { - JsonNode arrayNode = arrayElement.next(); - Object objectNode = getObjectFromElement(arrayNode); - if (objectNode != null) { - list.add(objectNode); - } - } - return list; - */ - throw new UnsupportedDataTypeException("List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); - - case BINARY: - break; - - case BOOLEAN: - return value.asBoolean(); - - case NULL: - break; - - case NUMBER: - if (value.isDouble() || value.isFloat()) { - return value.asDouble(); - } - if (value.isBigInteger() || value.isShort() || value.isInt()) { - return value.asInt(); - } - - if (value.isLong()) { - return value.asLong(); - } - break; - - case STRING: - return value.asText(); - - case MISSING: - break; - - case POJO: - break; - - default: - break; + case OBJECT: + return EmbeddedMangement.getEmbeddedType(value); + + case ARRAY: + /* + * List list = new ArrayList(); Iterator arrayElement + * = value.elements(); while (arrayElement.hasNext()) { JsonNode arrayNode = + * arrayElement.next(); Object objectNode = getObjectFromElement(arrayNode); if + * (objectNode != null) { list.add(objectNode); } } return list; + */ + throw new UnsupportedDataTypeException( + "List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); + + case BINARY: + break; + + case BOOLEAN: + return value.asBoolean(); + + case NULL: + break; + + case NUMBER: + if (value.isDouble() || value.isFloat()) { + return value.asDouble(); + } + if (value.isBigInteger() || value.isShort() || value.isInt()) { + return value.asInt(); + } + + if (value.isLong()) { + return value.asLong(); + } + break; + + case STRING: + return value.asText(); + + case MISSING: + break; + + case POJO: + break; + + default: + break; } return null; } - public static Map getPropertyMap(JsonNode jsonNode, - Set ignoreKeys, Set ignoreStartWith) - throws JsonProcessingException, IOException { + public static Map getPropertyMap(JsonNode jsonNode, Set ignoreKeys, + Set ignoreStartWith) throws JsonProcessingException, IOException { Map map = new HashMap<>(); @@ -772,23 +732,20 @@ public abstract class ERManagement { return map; } - public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, - Set ignoreKeys, Set ignoreStartWithKeys) - throws ResourceRegistryException { + public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, Set ignoreKeys, + Set ignoreStartWithKeys) throws ResourceRegistryException { Set oldKeys = element.getPropertyKeys(); Map properties; if (element instanceof Vertex || element instanceof Edge) { try { - properties = getPropertyMap(jsonNode, ignoreKeys, - ignoreStartWithKeys); + properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys); } catch (IOException e) { throw new ResourceRegistryException(e); } } else { - String error = String.format("Error while updating %s properties", - element.toString()); + String error = String.format("Error while updating %s properties", element.toString()); throw new ResourceRegistryException(error); } @@ -796,42 +753,37 @@ public abstract class ERManagement { for (String key : properties.keySet()) { try { - + Object object = properties.get(key); - if(!oClass.existsProperty(key)){ - + if (!oClass.existsProperty(key)) { + boolean set = false; - - if(object instanceof ODocument){ + + if (object instanceof ODocument) { ODocument oDocument = (ODocument) object; ((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED); set = true; } - + /* - if(object instanceof Set){ - ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDSET); - set = true; - } - - if(object instanceof List){ - ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); - set = true; - } - */ - - if(!set){ + * if(object instanceof Set){ ((OrientElement) element).setProperty(key, object, + * OType.EMBEDDEDSET); set = true; } + * + * if(object instanceof List){ ((OrientElement) element).setProperty(key, + * object, OType.EMBEDDEDLIST); set = true; } + */ + + if (!set) { element.setProperty(key, object); } - - } else{ + + } else { element.setProperty(key, object); } - + } catch (Exception e) { - String error = String.format( - "Error while setting property %s : %s (%s)", key, properties - .get(key).toString(), e.getMessage()); + String error = String.format("Error while setting property %s : %s (%s)", key, + properties.get(key).toString(), e.getMessage()); staticLogger.error(error); throw new ResourceRegistryException(error, e); } @@ -856,116 +808,114 @@ public abstract class ERManagement { return element; } - + protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException { try { - if(key.compareTo(ER.HEADER_PROPERTY)==0){ + if (key.compareTo(ER.HEADER_PROPERTY) == 0) { // Keeping the header HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object); JSONObject headerObject = new JSONObject(headerOrient.toJSON("class")); return headerObject; } - + if (ignoreKeys.contains(key)) { return null; } - + for (String prefix : ignoreStartWithKeys) { if (key.startsWith(prefix)) { return null; } } - - if(object instanceof ODocument){ + + if (object instanceof ODocument) { String json = ((ODocument) object).toJSON("class"); JSONObject jsonObject = new JSONObject(json); return jsonObject; } - - if(object instanceof Date){ + + if (object instanceof Date) { OProperty oProperty = getOClass().getProperty(key); OType oType = oProperty.getType(); DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance(); switch (oType) { - case DATE: - dateFormat = ODateHelper.getDateFormatInstance(); - break; - - case DATETIME: - dateFormat = ODateHelper.getDateTimeFormatInstance(); - break; - - default: - break; + case DATE: + dateFormat = ODateHelper.getDateFormatInstance(); + break; + + case DATETIME: + dateFormat = ODateHelper.getDateTimeFormatInstance(); + break; + + default: + break; } - + return dateFormat.format((Date) object); } - if(object instanceof Collection){ + if (object instanceof Collection) { Collection collection = (Collection) object; JSONArray jsonArray = new JSONArray(); - for(Object o : collection){ - Object obj = getPropertyForJson("PLACEHOLDER", o); + for (Object o : collection) { + Object obj = getPropertyForJson("PLACEHOLDER", o); jsonArray.put(obj); } - + return jsonArray; } - - + return object.toString(); - - }catch(Exception e){ - throw new ResourceRegistryException("Error while serializing " - + key + "=" + object.toString() + " in " + getElement().toString(), e); + + } catch (Exception e) { + throw new ResourceRegistryException( + "Error while serializing " + key + "=" + object.toString() + " in " + getElement().toString(), e); } } - + protected Collection getSuperclasses() throws SchemaException, ResourceRegistryException { Collection allSuperClasses = getOClass().getAllSuperClasses(); Collection superClasses = new HashSet<>(); - for(OClass oSuperClass : allSuperClasses){ + for (OClass oSuperClass : allSuperClasses) { String name = oSuperClass.getName(); - if(name.compareTo(StringFactory.V.toUpperCase())==0 || - name.compareTo(StringFactory.E.toUpperCase())==0 || - name.compareTo(DatabaseIntializator.O_RESTRICTED_CLASS)==0){ + if (name.compareTo(StringFactory.V.toUpperCase()) == 0 || name.compareTo(StringFactory.E.toUpperCase()) == 0 + || name.compareTo(DatabaseEnvironment.O_RESTRICTED_CLASS) == 0) { continue; } superClasses.add(name); } - + return superClasses; } - + public JSONObject toJSONObject() throws ResourceRegistryException { try { OrientElement orientElement = (OrientElement) getElement(); - + Map properties = orientElement.getProperties(); - for(String key : orientElement.getPropertyKeys()){ + for (String key : orientElement.getPropertyKeys()) { Object object = properties.get(key); object = getPropertyForJson(key, object); - if(object!=null){ + if (object != null) { properties.put(key, object); - }else{ + } else { properties.remove(key); } } - + JSONObject jsonObject = new JSONObject(properties); - + String type = orientElement.getRecord().getClassName(); jsonObject.put(ISManageable.CLASS_PROPERTY, type); - + Collection superClasses = getSuperclasses(); JSONArray jsonArray = new JSONArray(superClasses); jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray); - + return jsonObject; } catch (ResourceRegistryException e) { throw e; - } catch(Exception e){ + } catch (Exception e) { throw new ResourceRegistryException("Error while serializing " + getElement().toString(), e); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java index 6578c7f..830f542 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java @@ -10,6 +10,7 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo; import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; 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.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; @@ -60,12 +61,12 @@ public class ERManagementUtility { } @SuppressWarnings("rawtypes") - private static ERManagement getERManagement(OrientGraph orientGraph, Element element) + private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element) throws ResourceRegistryException { if (element instanceof Vertex) { - return getEntityManagement(orientGraph, (Vertex) element); + return getEntityManagement(workingContext, orientGraph, (Vertex) element); } 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(), Entity.NAME, Relation.NAME)); @@ -97,12 +98,12 @@ public class ERManagementUtility { } @SuppressWarnings("rawtypes") - public static ERManagement getERManagementFromUUID(OrientGraph orientGraph, UUID uuid) + public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, UUID uuid) throws ResourceRegistryException { Element element; try { element = getAnyElementByUUID(orientGraph, uuid); - return getERManagement(orientGraph, element); + return getERManagement(workingContext, orientGraph, element); } catch (Exception e) { throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s", uuid.toString(), Entity.NAME, Relation.NAME)); @@ -110,7 +111,7 @@ public class ERManagementUtility { } @SuppressWarnings({ "rawtypes", "unchecked" }) - public static EntityManagement getEntityManagement(OrientGraph orientGraph, Vertex vertex) + public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, Vertex vertex) throws ResourceRegistryException { if (orientGraph == null) { @@ -136,9 +137,9 @@ public class ERManagementUtility { EntityManagement entityManagement = null; if (orientVertexType.isSubClassOf(Resource.NAME)) { - entityManagement = new ResourceManagement(orientGraph); + entityManagement = new ResourceManagement(workingContext, orientGraph); } else if (orientVertexType.isSubClassOf(Facet.NAME)) { - entityManagement = new FacetManagement(orientGraph); + entityManagement = new FacetManagement(workingContext, orientGraph); } else { String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); @@ -149,7 +150,7 @@ public class ERManagementUtility { } @SuppressWarnings({ "unchecked", "rawtypes" }) - public static RelationManagement getRelationManagement(OrientGraph orientGraph, Edge edge) + public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, Edge edge) throws ResourceRegistryException { if (orientGraph == null) { @@ -165,9 +166,9 @@ public class ERManagementUtility { OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); RelationManagement relationManagement = null; if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { - relationManagement = new ConsistsOfManagement(orientGraph); + relationManagement = new ConsistsOfManagement(workingContext, orientGraph); } else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { - relationManagement = new IsRelatedToManagement(orientGraph); + relationManagement = new IsRelatedToManagement(workingContext, orientGraph); } else { String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java index 8efb84e..c16f045 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/EntityManagement.java @@ -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.er.ERAvailableInAnotherContextException; 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.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; @@ -61,6 +61,12 @@ public abstract class EntityManagement extends } + protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) { + this(accessType); + this.orientGraph = orientGraph; + setWorkingContext(workingContext); + } + @SuppressWarnings("rawtypes") /* * It works perfectly in case of any kind of update. @@ -71,7 +77,7 @@ public abstract class EntityManagement extends String id = edge.getId().toString(); RelationManagement relationManagement = relationManagements.get(id); if(relationManagement==null) { - relationManagement = ERManagementUtility.getRelationManagement(orientGraph, edge); + relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); relationManagements.put(id, relationManagement); } return relationManagement; @@ -93,11 +99,6 @@ public abstract class EntityManagement extends relationManagements.put(id, relationManagement); } - protected EntityManagement(AccessType accessType, OrientGraph orientGraph) { - this(accessType); - this.orientGraph = orientGraph; - } - protected static JSONObject addRelation(JSONObject sourceResource, JSONObject relation, String arrayKey) throws ResourceRegistryException { @@ -186,7 +187,7 @@ public abstract class EntityManagement extends protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException { - ContextUtility.addToActualContext(orientGraph, getElement()); + getWorkingContext().addElement(getElement(), orientGraph); Iterable edges = getElement().getEdges(Direction.OUT); @@ -211,7 +212,7 @@ public abstract class EntityManagement extends relationManagement.internalRemoveFromContext(); } - ContextUtility.removeFromActualContext(orientGraph, getElement()); + getWorkingContext().removeElement(getElement(), orientGraph); return true; } @@ -224,7 +225,7 @@ public abstract class EntityManagement extends Iterable iterable = orientGraph.getVerticesOfClass(erType, polymorphic); for(Vertex vertex : iterable){ @SuppressWarnings("rawtypes") - EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex); + EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); try { JSONObject jsonObject = entityManagement.serializeAsJson(); jsonArray.put(jsonObject); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java index 6795b5f..eba7dd3 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagement.java @@ -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.FacetNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; +import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import com.tinkerpop.blueprints.Vertex; @@ -26,8 +27,8 @@ public class FacetManagement extends EntityManagement { super(AccessType.FACET); } - public FacetManagement(OrientGraph orientGraph) { - super(AccessType.FACET, orientGraph); + public FacetManagement(SecurityContext workingContext, OrientGraph orientGraph) { + super(AccessType.FACET, workingContext, orientGraph); } @Override diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java index 3a5f72a..7072faf 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagement.java @@ -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.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; -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.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; @@ -45,8 +45,8 @@ public class ResourceManagement extends EntityManagement { super(AccessType.RESOURCE); } - public ResourceManagement(OrientGraph orientGraph) { - super(AccessType.RESOURCE, orientGraph); + public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) { + super(AccessType.RESOURCE, workingContext, orientGraph); } @Override @@ -150,7 +150,7 @@ public class ResourceManagement extends EntityManagement { if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode consistOfJsonNode : jsonNodeArray) { - ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); + ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); com.setJSON(consistOfJsonNode); com.setSourceEntityManagement(this); com.internalCreate(); @@ -162,8 +162,7 @@ public class ResourceManagement extends EntityManagement { if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode relationJsonNode : jsonNodeArray) { - IsRelatedToManagement irtm = new IsRelatedToManagement( - orientGraph); + IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); irtm.setJSON(relationJsonNode); irtm.setSourceEntityManagement(this); irtm.internalCreate(); @@ -183,7 +182,7 @@ public class ResourceManagement extends EntityManagement { if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode relationJsonNode : jsonNodeArray) { - ConsistsOfManagement com = new ConsistsOfManagement(orientGraph); + ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); com.setJSON(relationJsonNode); com.internalCreateOrUdate(); addToRelationManagement(com); @@ -194,8 +193,7 @@ public class ResourceManagement extends EntityManagement { if (jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); for (JsonNode relationJsonNode : jsonNodeArray) { - IsRelatedToManagement irtm = new IsRelatedToManagement( - orientGraph); + IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); irtm.setJSON(relationJsonNode); irtm.internalUpdate(); addToRelationManagement(irtm); @@ -222,9 +220,9 @@ public class ResourceManagement extends EntityManagement { @SuppressWarnings("rawtypes") RelationManagement relationManagement = null; if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { - relationManagement = new IsRelatedToManagement(orientGraph); + relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph); } else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { - relationManagement = new ConsistsOfManagement(orientGraph); + relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph); } else { logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME, @@ -245,8 +243,7 @@ public class ResourceManagement extends EntityManagement { public String all(boolean polymorphic, Map constraint) throws ResourceRegistryException { try { - orientGraph = ContextUtility - .getActualSecurityContextGraph(PermissionMode.READER, forceAdmin); + orientGraph = getWorkingContext().getGraph(PermissionMode.READER); return reallyGetAll(polymorphic, constraint); } catch (ResourceRegistryException e) { @@ -345,7 +342,7 @@ public class ResourceManagement extends EntityManagement { Vertex vertex = (Vertex) element; @SuppressWarnings("rawtypes") - EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex); + EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); try { JSONObject jsonObject = entityManagement.serializeAsJson(); jsonArray.put(jsonObject); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/ConsistsOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/ConsistsOfManagement.java index bc5bfd5..18f5142 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/ConsistsOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/ConsistsOfManagement.java @@ -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.ConsistsOfAvailableInAnotherContextException; 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.ResourceManagement; @@ -25,8 +26,8 @@ public class ConsistsOfManagement extends RelationManagement serializeEdges(Iterable edges, boolean postFilterPolymorphic) throws ResourceRegistryException { @@ -533,7 +504,7 @@ public abstract class RelationManagement osqlSynchQuery = new OSQLSynchQuery<>(query, limit); osqlSynchQuery.setFetchPlan(fetchPlan); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java index a495112..ffd18c1 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; 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.Resource; 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.rest.ERPath; 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.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; @@ -270,8 +270,7 @@ public class ERManager { CalledMethodProvider.instance.set( HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to add {} with UUID {} to current context {}", Resource.NAME, uuid, - ContextUtility.getCurrentContext()); + logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME); ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setUUID(UUID.fromString(uuid)); return resourceManagement.addToContext(); @@ -288,8 +287,7 @@ public class ERManager { CalledMethodProvider.instance.set( HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to add {} with UUID {} to current context {}", Facet.NAME, uuid, - ContextUtility.getCurrentContext()); + logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME); FacetManagement facetManagement = new FacetManagement(); facetManagement.setUUID(UUID.fromString(uuid)); return facetManagement.addToContext(); @@ -306,8 +304,7 @@ public class ERManager { CalledMethodProvider.instance.set( HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to remove {} with UUID {} from current context {}", Resource.NAME, uuid, - ContextUtility.getCurrentContext()); + logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME); ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setUUID(UUID.fromString(uuid)); return resourceManagement.removeFromContext(); @@ -324,8 +321,7 @@ public class ERManager { CalledMethodProvider.instance.set( HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); - logger.info("Requested to remove {} with UUID {} from current context {}", Facet.NAME, uuid, - ContextUtility.getCurrentContext()); + logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME); FacetManagement facetManagement = new FacetManagement(); facetManagement.setUUID(UUID.fromString(uuid)); return facetManagement.removeFromContext(); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java index 25ccbd9..512f5ab 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java @@ -8,8 +8,9 @@ import org.gcube.informationsystem.model.entity.Entity; import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; 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.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +56,8 @@ public class SchemaContextManagement implements SchemaManagement { OrientGraph orientGraph = null; try { - orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, true); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + orientGraph = adminSecurityContext.getGraph(PermissionMode.WRITER); ObjectMapper mapper = new ObjectMapper(); TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java index d6e2301..42af592 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java @@ -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.SchemaException; 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.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.types.TypeBinder; import org.gcube.informationsystem.types.TypeBinder.Property; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; @@ -92,8 +93,8 @@ public class SchemaManagementImpl implements SchemaManagement { logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type); - orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx( - PermissionMode.READER, true); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); return getTypeSchema(orientGraphNoTx, type, accessType); } catch (ResourceRegistryException e) { @@ -178,8 +179,9 @@ public class SchemaManagementImpl implements SchemaManagement { TypeDefinition typeDefinition = mapper.readValue(jsonSchema, TypeDefinition.class); - orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx( - PermissionMode.WRITER, true); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER); + OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); @@ -313,7 +315,7 @@ public class SchemaManagementImpl implements SchemaManagement { baseType.getName(), jsonSchema); return ret; }catch (Exception e) { - oSchema. dropClass(typeDefinition.getName()); + oSchema.dropClass(typeDefinition.getName()); throw e; } } catch (OSchemaException ex) { @@ -336,9 +338,9 @@ public class SchemaManagementImpl implements SchemaManagement { throws SchemaNotFoundException, SchemaException { OrientGraphNoTx orientGraphNoTx = null; try { - orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx( - PermissionMode.WRITER, true); - + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER); + OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); OClass baseOClass = getTypeSchema(oSchema, type, null); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java index 14116b2..34fc4a0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java @@ -17,8 +17,9 @@ import org.gcube.informationsystem.model.entity.Entity; import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; 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.SecurityContextMapper.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.slf4j.Logger; 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.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; +import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientElement; @@ -94,7 +96,8 @@ public class Utility { Class clz) throws ERNotFoundException, ResourceRegistryException { OrientGraphNoTx orientGraphNoTx = null; try { - orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx(PermissionMode.READER, true); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz); } finally { if (orientGraphNoTx != null) { @@ -104,7 +107,7 @@ public class Utility { } public static El getElementByUUID( - OrientBaseGraph orientBaseGraph, String elementType, UUID uuid, + Graph graph, String elementType, UUID uuid, Class clz) throws ERNotFoundException, ResourceRegistryException { if (elementType == null || elementType.compareTo("") == 0) { @@ -123,7 +126,7 @@ public class Utility { OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery<>(select); - Iterable elements = orientBaseGraph.command(osqlSynchQuery).execute(); + Iterable elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute(); if (elements == null || !elements.iterator().hasNext()) { String error = String.format("No %s with UUID %s was found", elementType, uuid.toString()); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java index 51a8e41..265c200 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java @@ -11,10 +11,13 @@ import org.gcube.informationsystem.impl.entity.ContextImpl; import org.gcube.informationsystem.impl.utils.ISMapper; import org.gcube.informationsystem.model.entity.Context; 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.context.ContextAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; 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.junit.Assert; import org.junit.Test; @@ -22,61 +25,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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); - @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 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> children = context.getChildren(); - for (IsParentOf child : children) { - Assert.assertTrue(child.getSource() == context); - Context childContext = child.getTarget(); - Assert.assertTrue(childContext.getParent().getSource() == context); - } - - } - // @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 { Context gcube = new ContextImpl("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_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 (pre.getHeader() != null) { FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create); @@ -125,13 +84,39 @@ public class ContextManagementTest { Context postParent = post.getParent().getSource(); 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 { ContextManagement contextManagement = new ContextManagement(); contextManagement.setUUID(uuid); String contextString = contextManagement.read(); logger.debug("Read {}", contextString); + roleUserAssertions(uuid, false); return ISMapper.unmarshal(Context.class, contextString); } @@ -142,6 +127,7 @@ public class ContextManagementTest { logger.debug("Created {}", contextString); Context c = ISMapper.unmarshal(Context.class, contextString); assertions(context, c, true, true); + roleUserAssertions(c.getHeader().getUUID(), false); return c; } @@ -152,6 +138,7 @@ public class ContextManagementTest { logger.debug("Updated {}", contextString); Context c = ISMapper.unmarshal(Context.class, contextString); assertions(context, c, true, false); + roleUserAssertions(c.getHeader().getUUID(), false); return c; } @@ -160,6 +147,7 @@ public class ContextManagementTest { contextManagement.setUUID(uuid); boolean deleted = contextManagement.delete(); Assert.assertTrue(deleted); + roleUserAssertions(uuid, true); logger.debug("Deleted {} with UUID {}", Context.NAME, uuid); return deleted; } @@ -383,14 +371,27 @@ public class ContextManagementTest { public void testGetAll() throws Exception { ContextManagement contextManagement = new ContextManagement(); String all = contextManagement.all(false); - logger.debug(all); + logger.trace(all); List contexts = ISMapper.unmarshalList(Context.class, all); for(Context context : contexts){ - logger.debug(ISMapper.marshal(context)); + logger.trace(ISMapper.marshal(context)); + List> children = context.getChildren(); + for (IsParentOf 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 { Context gcube = new ContextImpl("gcube"); gcube = create(gcube); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java new file mode 100644 index 0000000..37fb53c --- /dev/null +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java @@ -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); + } +} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializatorTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializatorTest.java deleted file mode 100644 index c632380..0000000 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializatorTest.java +++ /dev/null @@ -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()); - - } -} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java index 9c64081..0ca8dfb 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java @@ -292,8 +292,8 @@ public class ERManagementTest extends ScopedTest { facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); - //boolean deleted = facetManagement.delete(); - //Assert.assertTrue(deleted); + boolean deleted = facetManagement.delete(); + Assert.assertTrue(deleted); } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagementTest.java index 8aff91c..d57ec23 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/FacetManagementTest.java @@ -81,9 +81,6 @@ public class FacetManagementTest extends ScopedTest { checkAssertion(softwareFacet, VERSION, null, true); UUID uuid = softwareFacet.getHeader().getUUID(); - Thread.sleep(1000); - - /* Testing Update */ softwareFacet.setVersion(NEW_VERSION); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java index 061b61a..2edff48 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java @@ -117,6 +117,14 @@ public class RuleTest extends ScopedTest { // TODO continue with checks + + + + eServiceManagement = new ResourceManagement(); + eServiceManagement.setElementType(EService.NAME); + eServiceManagement.setJSON(eServiceString); + boolean deleted = eServiceManagement.delete(); + Assert.assertTrue(deleted); } } diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index 7ac795d..b00fc6b 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -11,6 +11,9 @@ + + +