From 1fcdccd7af5e6cf3182ff47eb770b32af97a6c0e Mon Sep 17 00:00:00 2001 From: "luca.frosini" Date: Thu, 30 Nov 2017 17:06:08 +0000 Subject: [PATCH] Refs #10435: Add support for hierarchical roles to support child context overview Task-Url: https://support.d4science.org/issues/10435 git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@158968 82a268e6-3cf1-43bd-a215-b396298e98cf --- .../resourceregistry/ResourceInitializer.java | 8 +- .../context/AdminSecurityContext.java | 65 -- .../context/ContextManagement.java | 181 +++-- .../context/ContextSecurityContext.java | 72 -- .../context/ContextUtility.java | 134 ++-- .../context/IsParentOfManagement.java | 57 +- .../context/SecurityContext.java | 301 -------- .../security/AdminSecurityContext.java | 50 ++ .../security/ContextSecurityContext.java | 44 ++ .../security/SchemaSecurityContext.java | 44 ++ .../context/security/SecurityContext.java | 457 ++++++++++++ .../dbinitialization/DatabaseEnvironment.java | 177 +++-- .../dbinitialization/SchemaActionImpl.java | 37 +- .../resourceregistry/er/ERManagement.java | 668 +++++++++--------- .../er/ERManagementUtility.java | 140 ++-- .../er/EmbeddedMangement.java | 34 +- .../er/entity/EntityManagement.java | 164 ++--- .../er/entity/FacetManagement.java | 12 +- .../er/entity/ResourceManagement.java | 199 +++--- .../er/relation/ConsistsOfManagement.java | 19 +- .../er/relation/IsRelatedToManagement.java | 23 +- .../er/relation/RelationManagement.java | 497 +++++++------ .../resourceregistry/query/Query.java | 11 +- .../resourceregistry/query/QueryImpl.java | 162 +---- .../resourceregistry/rest/Access.java | 175 ++--- .../resourceregistry/rest/ContextManager.java | 3 - .../resourceregistry/rest/ERManager.java | 135 ++-- .../rest/ResourceRegistryExceptionMapper.java | 19 +- .../resourceregistry/rest/SchemaManager.java | 56 +- .../schema/SchemaContextManagement.java | 36 +- .../schema/SchemaManagement.java | 6 +- .../schema/SchemaManagementImpl.java | 321 ++++----- .../resourceregistry/utils/HeaderOrient.java | 23 +- .../resourceregistry/utils/HeaderUtility.java | 53 +- .../resourceregistry/utils/Utility.java | 106 ++- .../resourceregistry/ScopedTest.java | 11 +- .../context/ContextManagementTest.java | 57 +- .../er/AbstractERManagementTest.java | 15 + .../er/entity/FacetManagementTest.java | 343 ++++++--- .../er/entity/ResourceManagementTest.java | 12 +- .../er/multicontext/BasicTest.java | 41 +- 41 files changed, 2526 insertions(+), 2442 deletions(-) delete mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java delete mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java delete mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContext.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/security/AdminSecurityContext.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/security/ContextSecurityContext.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SchemaSecurityContext.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SecurityContext.java create mode 100644 src/test/java/org/gcube/informationsystem/resourceregistry/er/AbstractERManagementTest.java diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java b/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java index 1c568f8..ff36232 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/ResourceInitializer.java @@ -10,12 +10,12 @@ import org.glassfish.jersey.server.ResourceConfig; * @author Luca Frosini (ISTI - CNR) */ @ApplicationPath("/") -public class ResourceInitializer extends ResourceConfig { - +public class ResourceInitializer extends ResourceConfig { + public static final String APPLICATION_JSON_CHARSET_UTF_8 = MediaType.APPLICATION_JSON + ";charset=UTF-8"; - public ResourceInitializer(){ + public ResourceInitializer() { packages(Access.class.getPackage().toString()); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java deleted file mode 100644 index 30f8ebd..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/AdminSecurityContext.java +++ /dev/null @@ -1,65 +0,0 @@ -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 848d4c0..c0b9082 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.context.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; @@ -33,8 +34,11 @@ import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientGraph; +/** + * @author Luca Frosini (ISTI - CNR) + */ public class ContextManagement extends EntityManagement { - + private static Logger logger = LoggerFactory.getLogger(ContextManagement.class); protected String name; @@ -57,12 +61,12 @@ public class ContextManagement extends EntityManagement { } public String getName() { - if(name==null) { - if(element==null) { - if(jsonNode!=null) { + if(name == null) { + if(element == null) { + if(jsonNode != null) { name = jsonNode.get(Context.NAME_PROPERTY).asText(); } - }else { + } else { name = element.getProperty(Context.NAME_PROPERTY); } } @@ -71,7 +75,8 @@ public class ContextManagement extends EntityManagement { protected SecurityContext getWorkingContext() throws ResourceRegistryException { if(workingContext == null) { - workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID); + workingContext = ContextUtility.getInstace() + .getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID); } return workingContext; } @@ -91,109 +96,99 @@ public class ContextManagement extends EntityManagement { return new ContextAlreadyPresentException(message); } - protected void checkContext(ContextManagement parentContext) throws ContextNotFoundException, - ContextAlreadyPresentException, ResourceRegistryException { - - if (parentContext != null) { + protected void checkContext(ContextManagement parentContext) + throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException { + + if(parentContext != null) { String parentId = parentContext.getElement().getId().toString(); // TODO Rewrite using Gremlin - String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME - + ") FROM " + parentId + " MAXDEPTH 1) WHERE " - + Context.NAME_PROPERTY + "=\"" + getName() + "\" AND " - + Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY - + "<>\"" + parentContext.uuid + "\""; - + String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME + ") FROM " + parentId + + " MAXDEPTH 1) WHERE " + Context.NAME_PROPERTY + "=\"" + getName() + "\" AND " + + Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY + "<>\"" + parentContext.uuid + "\""; + logger.trace(select); - + StringBuilder message = new StringBuilder(); message.append("A context with name ("); message.append(getName()); message.append(") has been already created as child of "); message.append(parentContext.serializeSelfOnly().toString()); - + logger.trace("Checking if {} -> {}", message, select); - - OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery( - select); - Iterable vertexes = orientGraph.command(osqlSynchQuery) - .execute(); - - if (vertexes != null && vertexes.iterator().hasNext()) { + + OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); + Iterable vertexes = orientGraph.command(osqlSynchQuery).execute(); + + if(vertexes != null && vertexes.iterator().hasNext()) { throw new ContextAlreadyPresentException(message.toString()); } - + } else { // TODO Rewrite using Gremlin - String select = "SELECT FROM " - + org.gcube.informationsystem.model.entity.Context.NAME - + " WHERE " + Context.NAME_PROPERTY + " = \"" + getName() - + "\"" + " AND in(\"" + IsParentOf.NAME + "\").size() = 0"; - - OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery( - select); - Iterable vertexes = orientGraph.command(osqlSynchQuery) - .execute(); - - if (vertexes != null && vertexes.iterator().hasNext()) { + String select = "SELECT FROM " + org.gcube.informationsystem.model.entity.Context.NAME + " WHERE " + + Context.NAME_PROPERTY + " = \"" + getName() + "\"" + " AND in(\"" + IsParentOf.NAME + + "\").size() = 0"; + + OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); + Iterable vertexes = orientGraph.command(osqlSynchQuery).execute(); + + if(vertexes != null && vertexes.iterator().hasNext()) { throw new ContextAlreadyPresentException( - "A root context with the same name (" + this.getName() - + ") already exist"); + "A root context with the same name (" + this.getName() + ") already exist"); } - + } - + } - @Override public String serialize() throws ResourceRegistryException { return serializeAsJson().toString(); } - + @Override public JSONObject serializeAsJson() throws ResourceRegistryException { JSONObject context = serializeSelfOnly(); - - int count=0; + + int count = 0; Iterable parents = getElement().getEdges(Direction.IN); - for(Edge edge : parents){ - if(++count>1) { + for(Edge edge : parents) { + if(++count > 1) { throw new ContextException("A " + Context.NAME + " can not have more than one parent"); } try { IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); isParentOfManagement.setElement(edge); - JSONObject isParentOf = isParentOfManagement.serializeAsJson(true,false); + JSONObject isParentOf = isParentOfManagement.serializeAsJson(true, false); context.putOpt(Context.PARENT_PROPERTY, isParentOf); - } catch (JSONException e) { + } catch(JSONException e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ContextException(""); } } - Iterable childrenEdges = getElement().getEdges(Direction.OUT); - for (Edge edge : childrenEdges) { + for(Edge edge : childrenEdges) { IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); isParentOfManagement.setElement(edge); try { JSONObject isParentOf = isParentOfManagement.serializeAsJson(); context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY); - }catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw e; - }catch (Exception e) { + } catch(Exception e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(e); } } - + return context; } - + @Override protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException { SecurityContext securityContext = null; @@ -201,14 +196,14 @@ public class ContextManagement extends EntityManagement { try { JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); - if (isParentOfJsonNode!=null && !(isParentOfJsonNode instanceof NullNode)) { + if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) { JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY); ContextManagement parentContext = new ContextManagement(orientGraph); parentContext.setJSON(parentJsonNode); checkContext(parentContext); - if(uuid==null){ + if(uuid == null) { uuid = UUID.randomUUID(); } @@ -221,7 +216,7 @@ public class ContextManagement extends EntityManagement { isParentOfManagement.internalCreate(); - }else { + } else { checkContext(null); createVertex(); } @@ -230,15 +225,15 @@ public class ContextManagement extends EntityManagement { securityContext.create(orientGraph); return getElement(); - }catch (Exception e) { + } catch(Exception e) { orientGraph.rollback(); - if(securityContext!=null) { + if(securityContext != null) { securityContext.delete(orientGraph); } throw e; } } - + @Override protected Vertex reallyUpdate() throws ERNotFoundException, ResourceRegistryException { @@ -250,8 +245,8 @@ public class ContextManagement extends EntityManagement { Iterable iterable = getElement().getVertices(Direction.IN, IsParentOf.NAME); for(Vertex p : iterable) { - if(found){ - String message = String.format("{} has more than one parent. {}", Context.NAME, + if(found) { + String message = String.format("{} has more than one parent. {}", Context.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(message.toString()); } @@ -259,9 +254,8 @@ public class ContextManagement extends EntityManagement { found = true; } - ContextManagement actualParentContextManagement = null; - if(parent!=null) { + if(parent != null) { actualParentContextManagement = new ContextManagement(orientGraph); actualParentContextManagement.setElement(parent); } @@ -270,27 +264,26 @@ public class ContextManagement extends EntityManagement { JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode parentContextJsonNode = null; - if (isParentOfJsonNode!=null && !(isParentOfJsonNode instanceof NullNode)) { + if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) { parentContextJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY); } - - if(parentContextJsonNode!=null && !(parentContextJsonNode instanceof NullNode)) { + if(parentContextJsonNode != null && !(parentContextJsonNode instanceof NullNode)) { UUID parentUUID = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode); - if(actualParentContextManagement!=null){ - if(parentUUID.compareTo(actualParentContextManagement.uuid)!=0) { + if(actualParentContextManagement != null) { + if(parentUUID.compareTo(actualParentContextManagement.uuid) != 0) { parentChanged = true; } - }else { + } else { parentChanged = true; } - if(parentChanged){ + if(parentChanged) { newParentContextManagement = new ContextManagement(orientGraph); newParentContextManagement.setJSON(parentContextJsonNode); } - }else{ - if(actualParentContextManagement!=null) { + } else { + if(actualParentContextManagement != null) { parentChanged = true; newParentContextManagement = null; } @@ -299,7 +292,7 @@ public class ContextManagement extends EntityManagement { String oldName = getElement().getProperty(Context.NAME_PROPERTY); String newName = jsonNode.get(Context.NAME_PROPERTY).asText(); - if(oldName.compareTo(newName)!=0){ + if(oldName.compareTo(newName) != 0) { nameChanged = true; name = newName; } @@ -312,36 +305,36 @@ public class ContextManagement extends EntityManagement { move(newParentContextManagement, false); } - element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys); - + element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, + ignoreStartWithKeys); + ContextUtility.getInstace().removeFromCache(uuid); return element; } - - - private void move(ContextManagement newParentContextManagement, boolean check) + + private void move(ContextManagement newParentContextManagement, boolean check) throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException { - if(check){ + if(check) { checkContext(newParentContextManagement); } // Removing the old parent relationship if any Iterable edges = getElement().getEdges(Direction.IN, IsParentOf.NAME); - if (edges != null && edges.iterator().hasNext()) { + if(edges != null && edges.iterator().hasNext()) { Iterator edgeIterator = edges.iterator(); Edge edge = edgeIterator.next(); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(); isParentOfManagement.setElement(edge); isParentOfManagement.internalDelete(); - if (edgeIterator.hasNext()) { - throw new ContextException("Seems that the Context has more than one Parent. " - + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + if(edgeIterator.hasNext()) { + throw new ContextException( + "Seems that the Context has more than one Parent. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } } - if(newParentContextManagement!=null){ + if(newParentContextManagement != null) { JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); isParentOfManagement.setJSON(isParentOfJsonNode); @@ -351,17 +344,17 @@ public class ContextManagement extends EntityManagement { } } - + @Override protected boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException { Iterable iterable = getElement().getEdges(Direction.OUT); Iterator iterator = iterable.iterator(); - while (iterator.hasNext()) { + while(iterator.hasNext()) { throw new ContextException("Cannot remove a " + Context.NAME + " having children"); } element.remove(); - + ContextUtility contextUtility = ContextUtility.getInstace(); SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid); securityContext.delete(orientGraph); @@ -376,18 +369,18 @@ public class ContextManagement extends EntityManagement { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { JSONArray jsonArray = new JSONArray(); Iterable iterable = orientGraph.getVerticesOfClass(erType, polymorphic); - for(Vertex vertex : iterable){ + for(Vertex vertex : iterable) { ContextManagement contextManagement = new ContextManagement(); contextManagement.setElement(vertex); try { - JSONObject jsonObject = contextManagement.serializeAsJson(); + JSONObject jsonObject = contextManagement.serializeAsJson(); jsonArray.put(jsonObject); - }catch (ResourceRegistryException e) { - logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", + } catch(ResourceRegistryException e) { + logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } } return jsonArray.toString(); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java deleted file mode 100644 index 92222bf..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextSecurityContext.java +++ /dev/null @@ -1,72 +0,0 @@ -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 7bb50ce..baaef27 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.context; import java.util.HashMap; @@ -19,7 +16,9 @@ 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.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; @@ -31,145 +30,156 @@ import com.tinkerpop.blueprints.Vertex; /** * @author Luca Frosini (ISTI - CNR) - * */ public class ContextUtility { - + private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class); - - private Map contextUUIDs; - private Map contexts; - + + private Map contextUUIDs; + private Map contexts; + private static ContextUtility contextUtility; - + public static ContextUtility getInstace() { - if (contextUtility == null) { + if(contextUtility == null) { contextUtility = new ContextUtility(); } return contextUtility; } - + private ContextUtility() { contextUUIDs = new HashMap<>(); contexts = new HashMap<>(); } - + + private static final InheritableThreadLocal hierarchicMode = new InheritableThreadLocal() { + + @Override + protected Boolean initialValue() { + return false; + } + + }; + + public static InheritableThreadLocal getHierarchicMode() { + return hierarchicMode; + } + private static String getCurrentContextFullName() { String token = SecurityTokenProvider.instance.get(); AuthorizationEntry authorizationEntry = null; try { authorizationEntry = Constants.authorizationService().get(token); - } catch (Exception e) { + } catch(Exception e) { return ScopeProvider.instance.get(); } return authorizationEntry.getContext(); } - + public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException { String fullName = getCurrentContextFullName(); - if (fullName == null) { + 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); + 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()) { + for(String fullName : contextUUIDs.keySet()) { UUID uuidKey = contextUUIDs.get(fullName); - if (uuidKey.compareTo(uuid) == 0) { + 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); } - + private synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException { try { SecurityContext securityContext = null; - + logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName); UUID uuid = contextUUIDs.get(fullName); - - if (uuid == null) { + + 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); } - + return securityContext; - - } catch (ContextException e) { + + } catch(ContextException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { 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) { - + if(securityContext == null) { + securityContext = new SecurityContext(uuid); - + try { - if (contextVertex == null) { + if(contextVertex == null) { contextVertex = getContextVertexByUUID(uuid); } Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next(); - - if (parentVertex != null) { + + if(parentVertex != null) { UUID parentUUID = Utility.getUUID(parentVertex); securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex)); } - - } catch (NoSuchElementException e) { + + } catch(NoSuchElementException e) { // No parent } - + contexts.put(uuid, securityContext); } - + return securityContext; } - + 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 @@ -177,25 +187,25 @@ public class ContextUtility { + name + "\""; ; OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); - + Iterable vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery) .execute(); - - if (vertexes == null || !vertexes.iterator().hasNext()) { + + if(vertexes == null || !vertexes.iterator().hasNext()) { 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)); - - if (iterator.hasNext()) { + + 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"); } - + return context; } - + } 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 d95ae54..9d1ffe1 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.context; import org.codehaus.jettison.json.JSONObject; @@ -16,6 +13,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.context.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.utils.Utility; @@ -29,12 +27,12 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; * @author Luca Frosini (ISTI - CNR) */ @SuppressWarnings("rawtypes") -public class IsParentOfManagement extends RelationManagement { - +public class IsParentOfManagement extends RelationManagement { + public IsParentOfManagement() { super(AccessType.IS_PARENT_OF); } - + public IsParentOfManagement(OrientGraph orientGraph) throws ResourceRegistryException { this(); this.orientGraph = orientGraph; @@ -44,7 +42,8 @@ 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; - 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(); - } - - 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(); - orientElement.save(); - } - - public void create() throws ResourceRegistryException { - OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); - create(orientGraph); - orientGraph.commit(); - orientGraph.shutdown(); - } - - 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.save(); - logger.trace("{} created", writerRole); - - ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT); - 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()); - } - - private void drop(OSecurity oSecurity, String name, SecurityType securityType) { - boolean dropped = false; - switch (securityType) { - case ROLE: - dropped = oSecurity.dropRole(name); - break; - - case USER: - dropped = oSecurity.dropUser(name); - break; - - default: - break; - } - if (dropped) { - logger.trace("{} successfully dropped", name); - } else { - logger.error("{} was not dropped successfully", name); - } - } - - public void delete() throws ResourceRegistryException { - 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("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/security/AdminSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/AdminSecurityContext.java new file mode 100644 index 0000000..b48b1fb --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/AdminSecurityContext.java @@ -0,0 +1,50 @@ +package org.gcube.informationsystem.resourceregistry.context.security; + +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.metadata.security.ORole; +import com.orientechnologies.orient.core.metadata.security.ORule; +import com.orientechnologies.orient.core.metadata.security.OSecurity; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public class AdminSecurityContext extends SecurityContext { + + private static Logger logger = LoggerFactory.getLogger(SecurityContext.class); + + public AdminSecurityContext() throws ResourceRegistryException { + super(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID, false); + } + + @Override + public void create() { + throw new RuntimeException("Cannot use this method for Admin Context"); + } + + protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) { + return oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE); + } + + @Override + protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { + logger.trace("Adding extra rules for {}", role.getName()); + switch(permissionMode) { + case WRITER: + role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL); + break; + + case READER: + role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_READ); + break; + + default: + break; + } + return role; + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/ContextSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/ContextSecurityContext.java new file mode 100644 index 0000000..437b252 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/ContextSecurityContext.java @@ -0,0 +1,44 @@ +package org.gcube.informationsystem.resourceregistry.context.security; + +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.metadata.security.ORole; +import com.orientechnologies.orient.core.metadata.security.ORule; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public class ContextSecurityContext extends SecurityContext { + + private static Logger logger = LoggerFactory.getLogger(SecurityContext.class); + + public ContextSecurityContext() throws ResourceRegistryException { + super(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID, false); + } + + @Override + protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { + logger.trace("Adding extra rules for {}", role.getName()); + switch(permissionMode) { + case WRITER: + role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL); + role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL); + role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL); + break; + + case READER: + role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ); + role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ); + role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ); + break; + + default: + break; + } + return role; + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SchemaSecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SchemaSecurityContext.java new file mode 100644 index 0000000..c3493c7 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SchemaSecurityContext.java @@ -0,0 +1,44 @@ +package org.gcube.informationsystem.resourceregistry.context.security; + +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.metadata.security.ORole; +import com.orientechnologies.orient.core.metadata.security.ORule; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public class SchemaSecurityContext extends SecurityContext { + + private static Logger logger = LoggerFactory.getLogger(SecurityContext.class); + + public SchemaSecurityContext() throws ResourceRegistryException { + super(DatabaseEnvironment.SCHEMA_SECURITY_CONTEXT_UUID, false); + } + + @Override + protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { + logger.trace("Adding extra rules for {}", role.getName()); + switch(permissionMode) { + case WRITER: + role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL); + role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL); + role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL); + break; + + case READER: + role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ); + role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ); + role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ); + break; + + default: + break; + } + return role; + } + +} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SecurityContext.java new file mode 100644 index 0000000..20c48c0 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/security/SecurityContext.java @@ -0,0 +1,457 @@ +/** + * + */ +package org.gcube.informationsystem.resourceregistry.context.security; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.gcube.informationsystem.model.entity.Context; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.resourceregistry.context.ContextUtility; +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.ORestrictedOperation; +import com.orientechnologies.orient.core.metadata.security.ORole; +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.orientechnologies.orient.core.record.impl.ODocument; +import com.tinkerpop.blueprints.Element; +import com.tinkerpop.blueprints.impls.orient.OrientElement; +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 class SecurityContext { + + private static Logger logger = LoggerFactory.getLogger(SecurityContext.class); + + protected static final String DEFAULT_WRITER_ROLE = "writer"; + protected static final String DEFAULT_READER_ROLE = "reader"; + + public static final String H = "H"; + + protected final boolean hierarchic; + + 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; + } + } + + protected final UUID context; + + protected final Map> factoryMap; + + protected SecurityContext parentSecurityContext; + + protected boolean isHierarchicMode() { + return hierarchic && ContextUtility.getHierarchicMode().get(); + } + + public void setParentSecurityContext(SecurityContext parentSecurityContext) { + this.parentSecurityContext = parentSecurityContext; + } + + public SecurityContext getParentSecurityContext() { + return parentSecurityContext; + } + + /** + * Use to change the parent not to set the first time + * + * @param newParentSecurityContext + * @throws ResourceRegistryException + */ + public void changeParentSecurityContext(SecurityContext newParentSecurityContext) throws ResourceRegistryException { + OrientGraph orientGraph = getAdminOrientGraph(); + changeParentSecurityContext(newParentSecurityContext, orientGraph); + } + + protected OrientGraph getAdminOrientGraph() throws ResourceRegistryException { + return ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); + } + + /** + * Use to change the parent not to set the first time + * + * @param newParentSecurityContext + * @param orientGraph + */ + public void changeParentSecurityContext(SecurityContext newParentSecurityContext, OrientGraph orientGraph) { + // TODO Remove from old hierarchy + // TODO Add to new Hierarchy + // In both cases take in account the new and the old parent + setParentSecurityContext(newParentSecurityContext); + } + + protected SecurityContext(UUID context, boolean hierarchic) throws ResourceRegistryException { + this.context = context; + this.factoryMap = new HashMap<>(); + this.hierarchic = hierarchic; + } + + public SecurityContext(UUID context) throws ResourceRegistryException { + this(context, true); + } + + private synchronized OrientGraphFactory getFactory(PermissionMode permissionMode, boolean recreate) { + OrientGraphFactory factory = null; + + Boolean h = hierarchic && isHierarchicMode(); + + Map factories = factoryMap.get(h); + if(factories == null) { + factories = new HashMap<>(); + } else { + if(recreate) { + factories.remove(permissionMode); + } + } + + factory = factories.get(permissionMode); + + if(factory == null) { + + String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h); + 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; + } + + public 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(); + } + + private ODatabaseDocumentTx getAdminODatabaseDocumentTx(OrientGraph orientGraph) { + ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph(); + return oDatabaseDocumentTx; + } + + private 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, getAdminOrientGraph()); + } + + protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) { + String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic); + oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName); + String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic); + oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); + } + + public void addElement(Element element, OrientGraph orientGraph) { + OrientElement orientElement = (OrientElement) element; + ODocument oDocument = orientElement.getRecord(); + OSecurity oSecurity = getAdminOSecurity(orientGraph); + allow(oSecurity, oDocument, false); + if(hierarchic) { + allow(oSecurity, oDocument, true); + if(getParentSecurityContext() != null) { + getParentSecurityContext().addElementToHierarchy(oSecurity, oDocument); + } + } + oDocument.save(); + orientElement.save(); + } + + protected void addElementToHierarchy(OSecurity oSecurity, ODocument oDocument) { + allow(oSecurity, oDocument, true); + if(getParentSecurityContext() != null) { + getParentSecurityContext().addElementToHierarchy(oSecurity, oDocument); + } + } + + public void removeElement(Element element) throws ResourceRegistryException { + removeElement(element, getAdminOrientGraph()); + } + + protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) { + + // The element could be created in such a context so the writerUser for the + // context is allowed by default + // because it was the creator + String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchic); + oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_ALL, writerUserName); + String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchic); + oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName); + + String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic); + oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName); + String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic); + oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName); + + } + + public void removeElement(Element element, OrientGraph orientGraph) { + OrientElement orientElement = (OrientElement) element; + ODocument oDocument = orientElement.getRecord(); + OSecurity oSecurity = getAdminOSecurity(orientGraph); + deny(oSecurity, oDocument, false); + if(hierarchic) { + deny(oSecurity, oDocument, true); + if(getParentSecurityContext() != null) { + getParentSecurityContext().removeElementFromHierarchy(oSecurity, oDocument); + } + } + oDocument.save(); + orientElement.save(); + } + + protected boolean allowed(final ORole role, final ODocument oDocument) { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + + Callable callable = new Callable() { + + @Override + public Boolean call() throws Exception { + ContextUtility.getHierarchicMode().set(false); + OrientGraphNoTx orientGraphNoTx = getGraphNoTx(PermissionMode.READER); + try { + OrientElement element = orientGraphNoTx.getElement(oDocument.getIdentity()); + if(element == null) { + return false; + } + return true; + } catch(Exception e) { + return false; + } finally { + orientGraphNoTx.shutdown(); + } + } + + }; + + Future result = executor.submit(callable); + try { + return result.get(); + } catch(Exception e) { + return false; + } + } + + protected void removeElementFromHierarchy(OSecurity oSecurity, ODocument oDocument) { + // I don't have to deny the Hierarchic role if the element belong to context + String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false); + ORole writerRole = oSecurity.getRole(writerRoleName); + + /* + * This check if the writerRole (not hierarchic) has the right to operate on the + * document. In such a case don't have to deny the hierarchy + */ + boolean allowed = allowed(writerRole, oDocument); + + // If allowed not denying the hierarchy and continuing to parents + if(!allowed) { + deny(oSecurity, oDocument, true); + if(getParentSecurityContext() != null) { + getParentSecurityContext().removeElementFromHierarchy(oSecurity, oDocument); + } + } + } + + public void create() throws ResourceRegistryException { + OrientGraph orientGraph = getAdminOrientGraph(); + create(orientGraph); + orientGraph.commit(); + orientGraph.shutdown(); + } + + protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { + return role; + } + + protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) { + return oSecurity.getRole(permissionMode.name().toLowerCase()); + } + + protected void createRolesAndUsers(OSecurity oSecurity) { + boolean[] booleanArray; + if(hierarchic) { + booleanArray = new boolean[] {false, true}; + } else { + booleanArray = new boolean[] {false}; + } + + for(boolean hierarchic : booleanArray) { + for(PermissionMode permissionMode : PermissionMode.values()) { + ORole superRole = getSuperRole(oSecurity, permissionMode); + + String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic); + ORole role = oSecurity.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT); + addExtraRules(role, permissionMode); + role.save(); + logger.trace("{} created", role); + + String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic); + OUser user = oSecurity.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode), + role); + user.save(); + logger.trace("{} created", user); + } + } + } + + public void create(OrientGraph orientGraph) { + ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph); + OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx); + + createRolesAndUsers(oSecurity); + + logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); + } + + private void drop(OSecurity oSecurity, String name, SecurityType securityType) { + boolean dropped = false; + switch(securityType) { + case ROLE: + dropped = oSecurity.dropRole(name); + break; + + case USER: + dropped = oSecurity.dropUser(name); + break; + + default: + break; + } + if(dropped) { + logger.trace("{} successfully dropped", name); + } else { + logger.error("{} was not dropped successfully", name); + } + } + + public void delete() throws ResourceRegistryException { + OrientGraph orientGraph = getAdminOrientGraph(); + delete(orientGraph); + orientGraph.commit(); + orientGraph.shutdown(); + } + + protected void deleteRolesAndUsers(OSecurity oSecurity) { + boolean[] booleanArray; + if(hierarchic) { + booleanArray = new boolean[] {false, true}; + } else { + booleanArray = new boolean[] {false}; + } + for(boolean hierarchic : booleanArray) { + for(PermissionMode permissionMode : PermissionMode.values()) { + for(SecurityType securityType : SecurityType.values()) { + String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic); + drop(oSecurity, name, securityType); + } + } + } + } + + public void delete(OrientGraph orientGraph) { + ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph); + OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx); + + logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString()); + + deleteRolesAndUsers(oSecurity); + + 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/dbinitialization/DatabaseEnvironment.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java index 1e7f4cf..3570e63 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.dbinitialization; import java.io.InputStream; @@ -14,11 +11,11 @@ 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.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SchemaSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,160 +37,156 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType; /** * @author Luca Frosini (ISTI - CNR) - * */ public class DatabaseEnvironment { - + 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; - + + public static final Map DEFAULT_PASSWORDS; + 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) { + 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) { + } 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); + + SchemaSecurityContext schemaSecurityContext = new SchemaSecurityContext(); contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext); - if (created) { + if(created) { OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD).setupPool(1, 10); OrientGraph orientGraph = factory.getTx(); @@ -205,39 +198,39 @@ public class DatabaseEnvironment { contextSecurityContext.create(); schemaSecurityContext.create(); - + createEntitiesAndRelations(); } - - } catch (Exception e) { + + } 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)) { - + + 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 = @@ -248,51 +241,51 @@ public class DatabaseEnvironment { 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()) { + + 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(); @@ -300,5 +293,5 @@ public class DatabaseEnvironment { entityRegistrationAction.manageEmbeddedClass(ValueSchema.class); erDiscovery.manageDiscoveredERTypes(entityRegistrationAction); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java index 5ddb148..d4bd1d0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.dbinitialization; import org.gcube.informationsystem.impl.utils.discovery.SchemaAction; @@ -18,53 +15,52 @@ import org.gcube.informationsystem.types.TypeBinder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * @author Luca Frosini (ISTI - CNR) */ public class SchemaActionImpl implements SchemaAction { - private static Logger logger = LoggerFactory.getLogger(SchemaActionImpl.class); protected SchemaManagement schemaManagement; - public SchemaActionImpl(){ + public SchemaActionImpl() { this.schemaManagement = new SchemaManagementImpl(); } @Override - public > void manageRelationClass( - Class r) throws Exception { - try{ + public > void manageRelationClass(Class r) + throws Exception { + try { String json = TypeBinder.serializeType(r); logger.trace(json); - if (ConsistsOf.class.isAssignableFrom(r)) { + if(ConsistsOf.class.isAssignableFrom(r)) { schemaManagement.create(json, AccessType.CONSISTS_OF); - } else if(IsRelatedTo.class.isAssignableFrom(r)){ + } else if(IsRelatedTo.class.isAssignableFrom(r)) { schemaManagement.create(json, AccessType.IS_RELATED_TO); } else { schemaManagement.create(json, AccessType.RELATION); } - } catch(Exception ex){ - logger.error("Error creating schema for {} type {} : {}", Relation.NAME, r.getSimpleName(), ex.getMessage()); + } catch(Exception ex) { + logger.error("Error creating schema for {} type {} : {}", Relation.NAME, r.getSimpleName(), + ex.getMessage()); throw ex; } } @Override public void manageEntityClass(Class e) throws Exception { - try{ + try { String json = TypeBinder.serializeType(e); logger.trace(json); - if (Facet.class.isAssignableFrom(e)) { + if(Facet.class.isAssignableFrom(e)) { schemaManagement.create(json, AccessType.FACET); - } else if(Resource.class.isAssignableFrom(e)){ + } else if(Resource.class.isAssignableFrom(e)) { schemaManagement.create(json, AccessType.RESOURCE); } else { schemaManagement.create(json, AccessType.ENTITY); } - } catch(Exception ex){ + } catch(Exception ex) { logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage()); throw ex; } @@ -76,12 +72,11 @@ public class SchemaActionImpl implements SchemaAction { String json = TypeBinder.serializeType(e); logger.trace(json); schemaManagement.create(json, AccessType.EMBEDDED); - } catch (Exception ex) { - logger.error("Error creating schema for {} type {} : {}", - Embedded.NAME, e.getSimpleName(), + } catch(Exception ex) { + logger.error("Error creating schema for {} type {} : {}", Embedded.NAME, e.getSimpleName(), ex.getMessage()); throw ex; } - + } } 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 2e6d93a..b24e838 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.er; import java.io.IOException; @@ -32,8 +29,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailabl import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient; @@ -64,38 +61,38 @@ import com.tinkerpop.blueprints.util.StringFactory; * @author Luca Frosini (ISTI - CNR) */ public abstract class ERManagement { - + protected Logger logger = LoggerFactory.getLogger(this.getClass()); - + private static Logger staticLogger = LoggerFactory.getLogger(ERManagement.class); - + public final String AT = "@"; public final String UNDERSCORE = "_"; - + protected final Set ignoreKeys; protected final Set ignoreStartWithKeys; - + protected Class elementClass; protected final AccessType accessType; - + protected OrientGraph orientGraph; - + protected UUID uuid; protected JsonNode jsonNode; protected OClass oClass; protected String erType; - + protected El element; protected boolean reload; public boolean isReload() { return reload; } - + public void setReload(boolean reload) { this.reload = reload; } - + public AccessType getAccessType() { return accessType; } @@ -112,46 +109,46 @@ public abstract class ERManagement { public void setWorkingContext(SecurityContext workingContext) { this.workingContext = workingContext; } - + protected ERManagement(AccessType accessType) { this.accessType = accessType; - + this.ignoreKeys = new HashSet(); - + this.ignoreStartWithKeys = new HashSet(); - + this.ignoreStartWithKeys.add(AT); this.ignoreStartWithKeys.add(UNDERSCORE); - + this.reload = false; - + } - + public void setUUID(UUID uuid) throws ResourceRegistryException { this.uuid = uuid; - if (jsonNode != null) { + if(jsonNode != null) { checkUUIDMatch(); } } - + public void setJSON(JsonNode jsonNode) throws ResourceRegistryException { this.jsonNode = jsonNode; checkJSON(); } - + public void setJSON(String jsonRepresentation) throws ResourceRegistryException { ObjectMapper mapper = new ObjectMapper(); try { this.jsonNode = mapper.readTree(jsonRepresentation); - } catch (IOException e) { + } catch(IOException e) { throw new ResourceRegistryException(e); } checkJSON(); } - + 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(); @@ -163,39 +160,39 @@ public abstract class ERManagement { } return oClass; } - + public void setElementType(String erType) throws ResourceRegistryException { this.erType = erType; - if (erType == null || erType.compareTo("") == 0) { + if(erType == null || erType.compareTo("") == 0) { erType = accessType.getName(); } - if (jsonNode != null) { + if(jsonNode != null) { checkERMatch(); } } - + protected void checkJSON() throws ResourceRegistryException { - if (uuid == null) { + if(uuid == null) { try { uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode); - } catch (Exception e) { + } catch(Exception e) { } } else { checkUUIDMatch(); } - - if (this.erType == null) { + + if(this.erType == null) { this.erType = getClassProperty(jsonNode); getOClass(); } else { checkERMatch(); } } - + protected void checkERMatch() throws ResourceRegistryException { - if (jsonNode != null) { + if(jsonNode != null) { String type = getClassProperty(jsonNode); - if (type != null && type.compareTo(erType) != 0) { + if(type != null && type.compareTo(erType) != 0) { String error = String.format("Declared resourceType does not match with json representation %s!=%s", erType, type); logger.trace(error); @@ -204,720 +201,727 @@ public abstract class ERManagement { } getOClass(); } - + protected void checkUUIDMatch() throws ResourceRegistryException { Header header = null; try { header = HeaderUtility.getHeader(jsonNode, false); - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } - - if (header != null) { + + if(header != null) { UUID resourceUUID = header.getUUID(); - if (resourceUUID.compareTo(uuid) != 0) { + 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); throw new ResourceRegistryException(error); - + } } } - + 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 El internalCreate() throws ERAlreadyPresentException, ResourceRegistryException { try { reallyCreate(); - + Header entityHeader = HeaderUtility.getHeader(jsonNode, true); - if (entityHeader != null) { + if(entityHeader != null) { element.setProperty(Entity.HEADER_PROPERTY, entityHeader); } else { entityHeader = HeaderUtility.addHeader(element, null); } - + getWorkingContext().addElement(element, orientGraph); - + ((OrientElement) element).save(); - + return element; - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause()); } } - + 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) { + } 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; - + public boolean internalDelete() throws ERNotFoundException, ResourceRegistryException { // Added for consistency with create and update addToContext removeFromContext. return reallyDelete(); } - + 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) { + } catch(Exception e) { throw new ResourceRegistryException("Error Adding " + erType + " to Current Context ", e.getCause()); } } - + 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) { + } catch(Exception e) { throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause()); } } - + public void setElement(El element) throws ResourceRegistryException { - if (element == null) { + if(element == null) { 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 ERAlreadyPresentException getSpecificERAlreadyPresentException(String message); - + public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { - if (element == null) { + 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()); - } catch (ERAvailableInAnotherContextException e1) { + } catch(ERAvailableInAnotherContextException e1) { throw e1; - } catch (Exception e1) { + } catch(Exception e1) { throw e; } - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } - + } else { - if (reload) { + 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); - } catch (ERNotFoundException e) { + } catch(ERNotFoundException e) { throw getSpecificElementNotFoundException(e); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } } - + public El retrieveElementFromAnyContext() throws ERNotFoundException, ResourceRegistryException { try { return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass); - } catch (ERNotFoundException e) { + } catch(ERNotFoundException e) { throw getSpecificElementNotFoundException(e); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } } - + public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException; - + public String all(boolean polymorphic) throws ResourceRegistryException { try { - + orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - + return reallyGetAll(polymorphic); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public boolean exists() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - + getElement(); - + return true; - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid); throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e); throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public String create() throws ERAlreadyPresentException, ResourceRegistryException { - + try { orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); - + element = internalCreate(); - + orientGraph.commit(); - + // TODO Notify to subscriptionNotification - + return serialize(); - - } catch (ResourceRegistryException e) { + + } catch(ResourceRegistryException e) { logger.error("Unable to create {}", accessType.getName()); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to create {}", accessType.getName(), e); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public String read() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - + getElement(); - + return serialize(); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid); throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e); throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public String update() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); - + element = internalUpdate(); - + orientGraph.commit(); - + setReload(true); + // TODO Notify to subscriptionNotification - + return serialize(); - - } catch (ResourceRegistryException e) { + + } catch(ResourceRegistryException e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public boolean delete() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid); - + try { - + 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); orientGraph.rollback(); } - + return deleted; - - } catch (ResourceRegistryException e) { + + } catch(ResourceRegistryException e) { logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException { - logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid, getWorkingContext().toString()); - + logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid, + getWorkingContext().toString()); + try { orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); - + boolean added = internalAddToContext(); - + orientGraph.commit(); logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid); - + return added; - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw new ContextException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public boolean removeFromContext() throws ERNotFoundException, ContextException, ResourceRegistryException { logger.debug("Going to remove {} with UUID {} from actual Context", accessType.getName(), uuid); - + try { - + orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); boolean removed = internalRemoveFromContext(); - + orientGraph.commit(); logger.info("{} with UUID {} successfully removed from actual Context", accessType.getName(), uuid); - + return removed; - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw e; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid, e); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw new ContextException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + public static String getClassProperty(JsonNode jsonNode) { - if (jsonNode.has(ISManageable.CLASS_PROPERTY)) { + if(jsonNode.has(ISManageable.CLASS_PROPERTY)) { return jsonNode.get(ISManageable.CLASS_PROPERTY).asText(); } return null; } - + public static Object getObjectFromElement(JsonNode value) 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; + + 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; } - + return null; } - - public static Map getPropertyMap(JsonNode jsonNode, Set ignoreKeys, + + public static Map getPropertyMap(JsonNode jsonNode, Set ignoreKeys, Set ignoreStartWith) throws JsonProcessingException, IOException { - - Map map = new HashMap<>(); - - if (ignoreKeys == null) { + + Map map = new HashMap<>(); + + if(ignoreKeys == null) { ignoreKeys = new HashSet<>(); } - - if (ignoreStartWith == null) { + + if(ignoreStartWith == null) { ignoreStartWith = new HashSet<>(); } - - Iterator> fields = jsonNode.fields(); - - OUTER_WHILE: while (fields.hasNext()) { - Entry entry = fields.next(); - + + Iterator> fields = jsonNode.fields(); + + OUTER_WHILE: while(fields.hasNext()) { + Entry entry = fields.next(); + String key = entry.getKey(); - - if (ignoreKeys.contains(key)) { + + if(ignoreKeys.contains(key)) { continue; } - - for (String prefix : ignoreStartWith) { - if (key.startsWith(prefix)) { + + for(String prefix : ignoreStartWith) { + if(key.startsWith(prefix)) { continue OUTER_WHILE; } } - + JsonNode value = entry.getValue(); Object object = null; try { object = getObjectFromElement(value); - if (object != null) { + if(object != null) { map.put(key, object); } - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { staticLogger.warn("An invalidy property has been provided. It will be ignored."); } - + } - + return map; } - + 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) { + + Map properties; + if(element instanceof Vertex || element instanceof Edge) { try { properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys); - } catch (IOException e) { + } catch(IOException e) { throw new ResourceRegistryException(e); } } else { String error = String.format("Error while updating %s properties", element.toString()); throw new ResourceRegistryException(error); } - + oldKeys.removeAll(properties.keySet()); - - for (String key : properties.keySet()) { + + 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; } + * OType.EMBEDDEDSET); set = true; } if(object instanceof List){ + * ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); set = + * true; } */ - - if (!set) { + + if(!set) { element.setProperty(key, object); } - + } else { element.setProperty(key, object); } - - } catch (Exception e) { + + } catch(Exception e) { 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); } } - - OUTER_FOR: for (String key : oldKeys) { - - if (ignoreKeys.contains(key)) { + + OUTER_FOR: for(String key : oldKeys) { + + if(ignoreKeys.contains(key)) { continue; } - - for (String prefix : ignoreStartWithKeys) { - if (key.startsWith(prefix)) { + + for(String prefix : ignoreStartWithKeys) { + if(key.startsWith(prefix)) { continue OUTER_FOR; } } - + element.removeProperty(key); } - + ((OrientElement) element).save(); - + 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)) { + + if(ignoreKeys.contains(key)) { return null; } - - for (String prefix : ignoreStartWithKeys) { - if (key.startsWith(prefix)) { + + 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; + switch(oType) { + 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) { + for(Object o : collection) { Object obj = getPropertyForJson("PLACEHOLDER", o); jsonArray.put(obj); } - + return jsonArray; } - + return object.toString(); - - } catch (Exception 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 + 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()) { + + Map properties = orientElement.getProperties(); + 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 { 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) { + } 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 830f542..e69042a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java @@ -10,7 +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.context.security.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; @@ -32,150 +32,152 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientVertex; import com.tinkerpop.blueprints.impls.orient.OrientVertexType; +/** + * @author Luca Frosini (ISTI - CNR) + */ public class ERManagementUtility { - + private static Logger logger = LoggerFactory.getLogger(EntityManagement.class); - + @SuppressWarnings("rawtypes") public static ERManagement getERManagement(String type) throws ResourceRegistryException { - + OClass oClass = SchemaManagementImpl.getTypeSchema(type, null); ERManagement erManagement = null; - - if (oClass.isSubClassOf(Resource.NAME)) { + + if(oClass.isSubClassOf(Resource.NAME)) { erManagement = new ResourceManagement(); - } else if (oClass.isSubClassOf(Facet.NAME)) { + } else if(oClass.isSubClassOf(Facet.NAME)) { erManagement = new FacetManagement(); - } else if (oClass.isSubClassOf(ConsistsOf.NAME)) { + } else if(oClass.isSubClassOf(ConsistsOf.NAME)) { erManagement = new ConsistsOfManagement(); - } else if (oClass.isSubClassOf(IsRelatedTo.NAME)) { + } else if(oClass.isSubClassOf(IsRelatedTo.NAME)) { erManagement = new IsRelatedToManagement(); } - - if (erManagement == null) { + + if(erManagement == null) { throw new ResourceRegistryException(String.format("%s is not querable", type.toString())); } - + erManagement.setElementType(type); return erManagement; } - + @SuppressWarnings("rawtypes") - private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element) - throws ResourceRegistryException { - if (element instanceof Vertex) { + private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, + Element element) throws ResourceRegistryException { + if(element instanceof Vertex) { return getEntityManagement(workingContext, orientGraph, (Vertex) element); - } else if (element instanceof Edge) { + } else if(element instanceof Edge) { 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)); } - + public static Element getAnyElementByUUID(UUID uuid) throws ERNotFoundException, ResourceRegistryException { try { return Utility.getElementByUUIDAsAdmin(null, uuid, Vertex.class); - } catch (ERNotFoundException e) { + } catch(ERNotFoundException e) { return Utility.getElementByUUIDAsAdmin(null, uuid, Edge.class); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } } - + private static Element getAnyElementByUUID(OrientGraph orientGraph, UUID uuid) throws ERNotFoundException, ResourceRegistryException { try { return Utility.getElementByUUID(orientGraph, null, uuid, Vertex.class); - } catch (ERNotFoundException e) { + } catch(ERNotFoundException e) { return Utility.getElementByUUID(orientGraph, null, uuid, Edge.class); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } } - + @SuppressWarnings("rawtypes") - public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, UUID uuid) - throws ResourceRegistryException { + public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, + UUID uuid) throws ResourceRegistryException { Element element; try { element = getAnyElementByUUID(orientGraph, uuid); return getERManagement(workingContext, orientGraph, element); - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s", uuid.toString(), Entity.NAME, Relation.NAME)); } } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, Vertex vertex) - throws ResourceRegistryException { - - if (orientGraph == null) { - throw new ResourceRegistryException(OrientGraph.class.getSimpleName() - + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, + Vertex vertex) throws ResourceRegistryException { + + if(orientGraph == null) { + throw new ResourceRegistryException( + OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - - if (vertex == null) { - throw new ResourceRegistryException(Vertex.class.getSimpleName() - + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + + if(vertex == null) { + throw new ResourceRegistryException( + Vertex.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - + OrientVertexType orientVertexType = null; try { orientVertexType = ((OrientVertex) vertex).getType(); - } catch (Exception e) { - String error = String.format( - "Unable to detect type of %s. %s", - vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + } catch(Exception e) { + String error = String.format("Unable to detect type of %s. %s", vertex.toString(), + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error(error, e); throw new ResourceRegistryException(error); } - + EntityManagement entityManagement = null; - if (orientVertexType.isSubClassOf(Resource.NAME)) { + if(orientVertexType.isSubClassOf(Resource.NAME)) { entityManagement = new ResourceManagement(workingContext, orientGraph); - } else if (orientVertexType.isSubClassOf(Facet.NAME)) { + } else if(orientVertexType.isSubClassOf(Facet.NAME)) { 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); + String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME, + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(error); } entityManagement.setElement(vertex); return entityManagement; } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, Edge edge) - throws ResourceRegistryException { - - if (orientGraph == null) { - throw new ResourceRegistryException(OrientGraph.class.getSimpleName() - + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, + Edge edge) throws ResourceRegistryException { + + if(orientGraph == null) { + throw new ResourceRegistryException( + OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - - if (edge == null) { - throw new ResourceRegistryException(Edge.class.getSimpleName() - + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + + if(edge == null) { + throw new ResourceRegistryException( + Edge.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - + OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); RelationManagement relationManagement = null; - if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { + if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { relationManagement = new ConsistsOfManagement(workingContext, orientGraph); - } else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { + } else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { 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); + String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME, + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(error); } relationManagement.setElement(edge); return relationManagement; } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java index 4fa94e1..b20b10e 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.er; import java.util.HashSet; @@ -23,9 +20,8 @@ import com.orientechnologies.orient.core.record.impl.ODocument; * @author Luca Frosini (ISTI - CNR) */ public class EmbeddedMangement { - - private static Logger logger = LoggerFactory - .getLogger(EmbeddedMangement.class); + + private static Logger logger = LoggerFactory.getLogger(EmbeddedMangement.class); public static final Set EMBEDDED_IGNORE_KEYS; public static final Set EMBEDDED_IGNORE_START_WITH_KEYS; @@ -35,42 +31,40 @@ public class EmbeddedMangement { static { EMBEDDED_IGNORE_KEYS = new HashSet(); - + EMBEDDED_IGNORE_START_WITH_KEYS = new HashSet(); EMBEDDED_IGNORE_START_WITH_KEYS.add(AT); EMBEDDED_IGNORE_START_WITH_KEYS.add(UNDERSCORE); - + } - - public static ODocument getEmbeddedType(JsonNode jsonNode) - throws ResourceRegistryException { - if (jsonNode.has(ISManageable.CLASS_PROPERTY)) { + public static ODocument getEmbeddedType(JsonNode jsonNode) throws ResourceRegistryException { + if(jsonNode.has(ISManageable.CLASS_PROPERTY)) { // Complex type String type = ERManagement.getClassProperty(jsonNode); - + try { SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED); - } catch (SchemaNotFoundException e) { + } catch(SchemaNotFoundException e) { throw e; } - + Header header = null; try { header = HeaderUtility.getHeader(jsonNode, false); - } catch (Exception e) { + } catch(Exception e) { logger.warn("An invalid Header has been provided. Anyway embedded object cannot have an Header."); throw new ResourceRegistryException("An embedded object cannot have an Header"); } - - if (header != null) { + + if(header != null) { throw new ResourceRegistryException("An embedded object cannot have an Header"); } - + ODocument oDocument = new ODocument(type); return oDocument.fromJSON(jsonNode.toString()); - + } ODocument oDocument = new ODocument(); 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 c16f045..be30424 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 @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.er.entity; import java.util.HashMap; @@ -16,7 +13,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.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; @@ -32,33 +29,27 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertex; /** * @author Luca Frosini (ISTI - CNR) */ -public abstract class EntityManagement extends - ERManagement { - +public abstract class EntityManagement extends ERManagement { + /** - * Provide a cache edge-internal-id -> RelationManagement - * this avoid to recreate the relationManagement of already visited - * edges + * Provide a cache edge-internal-id -> RelationManagement + * this avoid to recreate the relationManagement of already visited edges */ @SuppressWarnings("rawtypes") - protected Map relationManagements; + protected Map relationManagements; protected EntityManagement(AccessType accessType) { super(accessType); - + this.ignoreKeys.add(Entity.HEADER_PROPERTY); - - this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX - .toLowerCase()); - this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX - .toLowerCase()); - this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX - .toUpperCase()); - this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX - .toUpperCase()); + + this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toLowerCase()); + this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase()); + this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toUpperCase()); + this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase()); this.relationManagements = new HashMap<>(); - + } protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) { @@ -69,24 +60,26 @@ public abstract class EntityManagement extends @SuppressWarnings("rawtypes") /* - * It works perfectly in case of any kind of update. - * In case of use from create the cache does not work by using the ID because until commit the edge has a fake id - * starting with - (minus) sign. This not imply any collateral effect but a better solution is a desiderata. + * It works perfectly in case of any kind of update. In case of use from create + * the cache does not work by using the ID because until commit the edge has a + * fake id starting with - (minus) sign. This not imply any collateral effect + * but a better solution is a desiderata. */ protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException { String id = edge.getId().toString(); RelationManagement relationManagement = relationManagements.get(id); - if(relationManagement==null) { + if(relationManagement == null) { relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); relationManagements.put(id, relationManagement); } return relationManagement; } - - protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement) throws ResourceRegistryException { + + protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement) + throws ResourceRegistryException { Element elem = relationManagement.getElement(); String id = elem.getId().toString(); - if(relationManagements.get(id)!=null && relationManagements.get(id)!=relationManagement) { + if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Two different instance of "); errorMessage.append(relationManagement.getClass().getSimpleName()); @@ -99,142 +92,133 @@ public abstract class EntityManagement extends relationManagements.put(id, relationManagement); } - protected static JSONObject addRelation(JSONObject sourceResource, - JSONObject relation, String arrayKey) + protected static JSONObject addRelation(JSONObject sourceResource, JSONObject relation, String arrayKey) throws ResourceRegistryException { JSONArray relationArray = null; try { - if (sourceResource.has(arrayKey)) { + if(sourceResource.has(arrayKey)) { relationArray = sourceResource.getJSONArray(arrayKey); } else { relationArray = new JSONArray(); } - + relationArray.put(relation); sourceResource.putOpt(arrayKey, relationArray); - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } return sourceResource; } - protected Vertex createVertex() throws EntityAlreadyPresentException, - ResourceRegistryException { - - logger.trace("Going to create {} for {} ({}) using {}", - Vertex.class.getSimpleName(), accessType.getName(), erType, jsonNode); - + protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException { + + logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(), + erType, jsonNode); + try { - - if(oClass.isAbstract()){ - String error = String.format("Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", + + if(oClass.isAbstract()) { + String error = String.format( + "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", accessType.getName(), erType); throw new ResourceRegistryException(error); } Vertex vertexEntity = orientGraph.addVertex("class:" + erType); - + try { - if(uuid!=null){ + if(uuid != null) { Vertex v = getElement(); - if (v != null) { - String error = String.format( - "A %s with UUID %s already exist", erType, - uuid.toString()); + if(v != null) { + String error = String.format("A %s with UUID %s already exist", erType, uuid.toString()); throw getSpecificERAlreadyPresentException(error); } } - } catch (ERNotFoundException e) { + } catch(ERNotFoundException e) { try { Element el = ERManagementUtility.getAnyElementByUUID(uuid); - String error = String.format( - "UUID %s is already used by another %s. This is not allowed.", + String error = String.format("UUID %s is already used by another %s. This is not allowed.", uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME); throw getSpecificERAvailableInAnotherContextException(error); - }catch (ERNotFoundException e1) { + } catch(ERNotFoundException e1) { // OK the UUID is not already used. } - } catch (ERAvailableInAnotherContextException e) { + } catch(ERAvailableInAnotherContextException e) { throw e; - } + } this.element = vertexEntity; - - if (accessType==AccessType.RESOURCE) { + + if(accessType == AccessType.RESOURCE) { // Facet and relation are created in calling method } else { - ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, - ignoreStartWithKeys); + ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); } - + logger.info("Created {} is {}", Vertex.class.getSimpleName(), Utility.toJsonString((OrientVertex) element, true)); - + return element; - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { - logger.trace("Error while creating {} for {} ({}) using {}", - Vertex.class.getSimpleName(), accessType.getName(), erType, jsonNode, e); - throw new ResourceRegistryException("Error Creating " + erType - + " with " + jsonNode, e.getCause()); + } catch(Exception e) { + logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(), + accessType.getName(), erType, jsonNode, e); + throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause()); } } - + @Override - protected boolean reallyAddToContext() throws ContextException, - ResourceRegistryException { - + protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException { + getWorkingContext().addElement(getElement(), orientGraph); - + Iterable edges = getElement().getEdges(Direction.OUT); - - for (Edge edge : edges) { + + for(Edge edge : edges) { @SuppressWarnings("rawtypes") RelationManagement relationManagement = getRelationManagement(edge); relationManagement.internalAddToContext(); } - + return true; } - + @Override - protected boolean reallyRemoveFromContext() throws ContextException, - ResourceRegistryException { - + protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException { + Iterable edges = getElement().getEdges(Direction.OUT); - - for (Edge edge : edges) { + + for(Edge edge : edges) { @SuppressWarnings("rawtypes") RelationManagement relationManagement = getRelationManagement(edge); relationManagement.internalRemoveFromContext(); } getWorkingContext().removeElement(getElement(), orientGraph); - + return true; } - - @Override public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { JSONArray jsonArray = new JSONArray(); Iterable iterable = orientGraph.getVerticesOfClass(erType, polymorphic); - for(Vertex vertex : iterable){ + for(Vertex vertex : iterable) { @SuppressWarnings("rawtypes") - EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); + EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), + orientGraph, vertex); try { - JSONObject jsonObject = entityManagement.serializeAsJson(); + JSONObject jsonObject = entityManagement.serializeAsJson(); jsonArray.put(jsonObject); - }catch (ResourceRegistryException e) { - logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", + } catch(ResourceRegistryException e) { + logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } } return jsonArray.toString(); } - + } 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 eba7dd3..e92748d 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 @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.er.entity; import org.codehaus.jettison.json.JSONObject; @@ -11,7 +8,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.context.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import com.tinkerpop.blueprints.Vertex; @@ -19,10 +16,9 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; /** * @author Luca Frosini (ISTI - CNR) - * */ public class FacetManagement extends EntityManagement { - + public FacetManagement() { super(AccessType.FACET); } @@ -60,7 +56,7 @@ public class FacetManagement extends EntityManagement { protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { return createVertex(); } - + @Override protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException { Vertex facet = getElement(); @@ -73,5 +69,5 @@ public class FacetManagement extends EntityManagement { getElement().remove(); return true; } - + } 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 7072faf..cd9525b 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.SecurityContext; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.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; @@ -40,13 +40,13 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType; * @author Luca Frosini (ISTI - CNR) */ public class ResourceManagement extends EntityManagement { - + public ResourceManagement() { super(AccessType.RESOURCE); } - + public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) { - super(AccessType.RESOURCE, workingContext, orientGraph); + super(AccessType.RESOURCE, workingContext, orientGraph); } @Override @@ -55,7 +55,8 @@ public class ResourceManagement extends EntityManagement { } @Override - protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message) { + protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( + String message) { return new ResourceAvailableInAnotherContextException(message); } @@ -68,33 +69,31 @@ public class ResourceManagement extends EntityManagement { public String serialize() throws ResourceRegistryException { return serializeAsJson().toString(); } - + @SuppressWarnings("unchecked") @Override public JSONObject serializeAsJson() throws ResourceRegistryException { JSONObject sourceResource = serializeSelfOnly(); - + /* - * Cannot get ConsistsOf edge only because is not polymorphic for a - * com.tinkerpop.blueprints.Vertex - * vertex.getEdges(Direction.OUT, ConsistsOf.NAME); - * TODO Looks for a different query + * Cannot get ConsistsOf edge only because is not polymorphic for a + * com.tinkerpop.blueprints.Vertex vertex.getEdges(Direction.OUT, + * ConsistsOf.NAME); TODO Looks for a different query */ Iterable edges = getElement().getEdges(Direction.OUT); - for (Edge edge : edges) { + for(Edge edge : edges) { @SuppressWarnings("rawtypes") RelationManagement relationManagement = getRelationManagement(edge); relationManagement.setReload(reload); - if(relationManagement.giveMeSourceEntityManagementAsIs()==null) { + if(relationManagement.giveMeSourceEntityManagementAsIs() == null) { relationManagement.setSourceEntityManagement(this); } - - if(relationManagement.giveMeSourceEntityManagementAsIs()!=this) { + if(relationManagement.giveMeSourceEntityManagementAsIs() != this) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("SourceEntityManagement for "); errorMessage.append(relationManagement.getClass().getSimpleName()); @@ -103,53 +102,51 @@ public class ResourceManagement extends EntityManagement { throw new ResourceRegistryException(errorMessage.toString()); } - if (relationManagement instanceof ConsistsOfManagement) { + if(relationManagement instanceof ConsistsOfManagement) { try { JSONObject consistsOf = relationManagement.serializeAsJson(true, true); sourceResource = addConsistsOf(sourceResource, consistsOf); - }catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw e; - }catch (Exception e) { + } catch(Exception e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(e); } } /* - * This comment is just to show that IsRelatedTo is not serialized - * by default as design choice and not because forget + * This comment is just to show that IsRelatedTo is not serialized by default as + * design choice and not because forget * - * else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ - * JSONObject isRelatedTo = relationManagement.serializeAsJson(true, true); - * sourceResource = addIsRelatedTo(sourceResource, isRelatedTo); - * } + * else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ JSONObject + * isRelatedTo = relationManagement.serializeAsJson(true, true); sourceResource + * = addIsRelatedTo(sourceResource, isRelatedTo); } */ } - + return sourceResource; } - - public static JSONObject addConsistsOf(JSONObject sourceResource, - JSONObject consistsOf) throws ResourceRegistryException { + + public static JSONObject addConsistsOf(JSONObject sourceResource, JSONObject consistsOf) + throws ResourceRegistryException { return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter()); } - - public static JSONObject addIsRelatedTo(JSONObject sourceResource, - JSONObject isRelatedTo) throws ResourceRegistryException { + + public static JSONObject addIsRelatedTo(JSONObject sourceResource, JSONObject isRelatedTo) + throws ResourceRegistryException { return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter()); } - + @Override - protected Vertex reallyCreate() throws ResourceAlreadyPresentException, - ResourceRegistryException { + protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException { createVertex(); - + String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter(); - if (jsonNode.has(property)) { + if(jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); - for (JsonNode consistOfJsonNode : jsonNodeArray) { + for(JsonNode consistOfJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); com.setJSON(consistOfJsonNode); com.setSourceEntityManagement(this); @@ -157,11 +154,11 @@ public class ResourceManagement extends EntityManagement { addToRelationManagement(com); } } - + property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter(); - if (jsonNode.has(property)) { + if(jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); - for (JsonNode relationJsonNode : jsonNodeArray) { + for(JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); irtm.setJSON(relationJsonNode); irtm.setSourceEntityManagement(this); @@ -169,95 +166,92 @@ public class ResourceManagement extends EntityManagement { addToRelationManagement(irtm); } } - + return element; } - + @Override protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException { - + getElement(); - + String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter(); - if (jsonNode.has(property)) { + if(jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); - for (JsonNode relationJsonNode : jsonNodeArray) { + for(JsonNode relationJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); com.setJSON(relationJsonNode); com.internalCreateOrUdate(); addToRelationManagement(com); } } - + property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter(); - if (jsonNode.has(property)) { + if(jsonNode.has(property)) { JsonNode jsonNodeArray = jsonNode.get(property); - for (JsonNode relationJsonNode : jsonNodeArray) { + for(JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); irtm.setJSON(relationJsonNode); irtm.internalUpdate(); addToRelationManagement(irtm); } } - + return element; } - + @SuppressWarnings("unchecked") @Override - protected boolean reallyDelete() throws ResourceNotFoundException, - ResourceRegistryException { + protected boolean reallyDelete() throws ResourceNotFoundException, ResourceRegistryException { // internalDeleteResource(orientGraph, uuid, null); - + getElement(); - + Iterable iterable = element.getEdges(Direction.OUT); Iterator iterator = iterable.iterator(); - while (iterator.hasNext()) { + while(iterator.hasNext()) { Edge edge = iterator.next(); OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); @SuppressWarnings("rawtypes") RelationManagement relationManagement = null; - if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { + if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph); - } else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { + } else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph); } else { - logger.warn("{} is not a {} nor a {}. {}", - Utility.toJsonString(edge, true), IsRelatedTo.NAME, + logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME, ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - if (relationManagement != null) { + if(relationManagement != null) { relationManagement.setElement(edge); relationManagement.internalDelete(); } - + } - + element.remove(); - + return true; } - - public String all(boolean polymorphic, Map constraint) throws ResourceRegistryException { + public String all(boolean polymorphic, Map constraint) throws ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - + return reallyGetAll(polymorphic, constraint); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - - public String reallyGetAll(boolean polymorphic, Map constraint) throws ResourceRegistryException{ + + public String reallyGetAll(boolean polymorphic, Map constraint) throws ResourceRegistryException { JSONArray jsonArray = new JSONArray(); String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART); @@ -267,11 +261,11 @@ public class ResourceManagement extends EntityManagement { // TODO check types - /* - * SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') - * FROM (SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor')) + /* + * SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT + * FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor')) * - * WHERE @class='EService' // Only is not polymorphic + * WHERE @class='EService' // Only is not polymorphic */ boolean first = true; @@ -282,11 +276,11 @@ public class ResourceManagement extends EntityManagement { selectStringBuilder.append(erType); selectStringBuilder.append("') FROM (SELECT FROM "); selectStringBuilder.append(facetType); - for(String key : constraint.keySet()){ - if(first){ + for(String key : constraint.keySet()) { + if(first) { selectStringBuilder.append(" WHERE "); first = false; - }else{ + } else { selectStringBuilder.append(" AND "); } selectStringBuilder.append(key); @@ -297,64 +291,59 @@ public class ResourceManagement extends EntityManagement { selectStringBuilder.append("'"); } selectStringBuilder.append(" ))"); - - if(!polymorphic){ + + if(!polymorphic) { selectStringBuilder.append(" WHERE @class='"); selectStringBuilder.append(erType); selectStringBuilder.append("'"); } - + String select = selectStringBuilder.toString(); logger.trace(select); - - OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery( - select); - Iterable elements = orientGraph.command(osqlSynchQuery) - .execute(); + OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); + Iterable elements = orientGraph.command(osqlSynchQuery).execute(); - for(Element element : elements){ + for(Element element : elements) { - if(polymorphic){ + if(polymorphic) { OrientVertexType orientVertexType = null; try { OrientElement orientElement = ((OrientElement) element); - if(orientElement instanceof OrientEdge){ + if(orientElement instanceof OrientEdge) { continue; } orientVertexType = ((OrientVertex) orientElement).getType(); - }catch (Exception e) { - String error = String.format("Unable to detect type of %s. %s", - element.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + } catch(Exception e) { + String error = String.format("Unable to detect type of %s. %s", element.toString(), + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error(error, e); throw new ResourceRegistryException(error); } - - if(orientVertexType.getName().compareTo(erType)!=0){ - if(!orientVertexType.isSubClassOf(erType) ) { + + if(orientVertexType.getName().compareTo(erType) != 0) { + if(!orientVertexType.isSubClassOf(erType)) { continue; } } - } Vertex vertex = (Vertex) element; @SuppressWarnings("rawtypes") - EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); + EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), + orientGraph, vertex); try { - JSONObject jsonObject = entityManagement.serializeAsJson(); + JSONObject jsonObject = entityManagement.serializeAsJson(); jsonArray.put(jsonObject); - }catch (ResourceRegistryException e) { - logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", + } catch(ResourceRegistryException e) { + logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } } - return jsonArray.toString(); } - - + } 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 18f5142..10a61dc 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 @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.er.relation; import org.gcube.informationsystem.model.AccessType; @@ -10,7 +7,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.context.security.SecurityContext; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; @@ -20,21 +17,21 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; * @author Luca Frosini (ISTI - CNR) */ @SuppressWarnings("rawtypes") -public class ConsistsOfManagement extends RelationManagement { - +public class ConsistsOfManagement extends RelationManagement { + public ConsistsOfManagement() { super(AccessType.CONSISTS_OF); } - + public ConsistsOfManagement(SecurityContext workingContext, OrientGraph orientGraph) { super(AccessType.CONSISTS_OF, workingContext, orientGraph); } - + @Override protected ConsistsOfNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { return new ConsistsOfNotFoundException(e.getMessage(), e.getCause()); } - + @Override protected ConsistsOfAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( String message) { @@ -50,10 +47,10 @@ public class ConsistsOfManagement extends RelationManagement { - +public class IsRelatedToManagement extends RelationManagement { + public IsRelatedToManagement() { super(AccessType.IS_RELATED_TO); } - + public IsRelatedToManagement(SecurityContext workingContext, OrientGraph orientGraph) { super(AccessType.IS_RELATED_TO, workingContext, orientGraph); } - + @Override protected IsRelatedToNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { return new IsRelatedToNotFoundException(e.getMessage(), e.getCause()); } - + @Override protected IsRelatedToAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( String message) { return new IsRelatedToAvailableInAnotherContextException(message); } - + @Override protected IsRelatedToAlreadyPresentException getSpecificERAlreadyPresentException(String message) { return new IsRelatedToAlreadyPresentException(message); } - + @Override protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { return new ResourceManagement(getWorkingContext(), orientGraph); } - + @Override protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException { return new ResourceManagement(getWorkingContext(), orientGraph); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java index e8a2299..addc9c5 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/RelationManagement.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.er.relation; import java.util.ArrayList; @@ -27,8 +24,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; @@ -49,16 +46,16 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; */ @SuppressWarnings("rawtypes") public abstract class RelationManagement - extends ERManagement { - + extends ERManagement { + protected final Class targetEntityClass; - + protected S sourceEntityManagement; protected T targetEntityManagement; - + protected RelationManagement(AccessType accessType) { super(accessType); - + this.ignoreKeys.add(Relation.HEADER_PROPERTY); this.ignoreKeys.add(Relation.TARGET_PROPERTY); this.ignoreKeys.add(Relation.SOURCE_PROPERTY); @@ -66,35 +63,36 @@ public abstract class RelationManagement fullSerialize(Map visitedSourceResources) + + protected Map fullSerialize(Map visitedSourceResources) throws ResourceRegistryException { Vertex source = getElement().getVertex(Direction.OUT); - + String id = source.getId().toString(); - + JSONObject sourceResource = visitedSourceResources.get(id); ResourceManagement resourceManagement = null; - if (sourceResource == null) { - resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, source); - if (this instanceof IsRelatedToManagement) { + if(sourceResource == null) { + resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), + orientGraph, source); + if(this instanceof IsRelatedToManagement) { sourceResource = resourceManagement.serializeAsJson(); - } else if (this instanceof ConsistsOfManagement) { + } else if(this instanceof ConsistsOfManagement) { sourceResource = resourceManagement.serializeSelfOnly(); } else { - String error = String.format( - "{%s is not a %s nor a %s. %s", - this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(), + String error = String.format("{%s is not a %s nor a %s. %s", this, + IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(error); } } - - if (this instanceof IsRelatedToManagement) { + if(this instanceof IsRelatedToManagement) { sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson()); - } else if (this instanceof ConsistsOfManagement) { + } else if(this instanceof ConsistsOfManagement) { sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson()); } else { - String error = String.format( - "{%s is not a %s nor a %s. %s", - this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(), + String error = String.format("{%s is not a %s nor a %s. %s", this, + IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ResourceRegistryException(error); } - + visitedSourceResources.put(id, sourceResource); - + return visitedSourceResources; } - + @Override protected Edge reallyCreate() throws ResourceRegistryException { - - if (sourceEntityManagement == null) { - - if (!jsonNode.has(Relation.SOURCE_PROPERTY)) { + + if(sourceEntityManagement == null) { + + if(!jsonNode.has(Relation.SOURCE_PROPERTY)) { throw new ResourceRegistryException("Error while creating relation. No source definition found"); } - + UUID sourceUUID = org.gcube.informationsystem.impl.utils.Utility .getUUIDFromJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY)); - + sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement.setUUID(sourceUUID); } - - if (targetEntityManagement == null) { + + if(targetEntityManagement == null) { targetEntityManagement = newTargetEntityManagement(); - - if (!jsonNode.has(Relation.TARGET_PROPERTY)) { + + if(!jsonNode.has(Relation.TARGET_PROPERTY)) { throw new ResourceRegistryException("Error while creating " + erType + ". No target definition found"); } - + try { targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY)); - } catch (SchemaException e) { + } catch(SchemaException e) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("A "); errorMessage.append(erType); @@ -243,347 +239,342 @@ public abstract class RelationManagement {}", erType, getSourceEntityManagement().serialize(), getTargetEntityManagement().serialize()); - + Vertex source = (Vertex) getSourceEntityManagement().getElement(); Vertex target = (Vertex) getTargetEntityManagement().getElement(); - + element = orientGraph.addEdge(null, source, target, erType); - + ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); - + logger.info("{} successfully created", erType); - + return element; } - + protected abstract S newSourceEntityManagement() throws ResourceRegistryException; - + protected abstract T newTargetEntityManagement() throws ResourceRegistryException; - + @Override protected Edge reallyUpdate() throws ResourceRegistryException { - + logger.debug("Trying to update {} : {}", erType, jsonNode); - + Edge edge = getElement(); ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys); - - if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) { + + if(accessType.compareTo(AccessType.CONSISTS_OF) == 0) { JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); - if (target != null) { + if(target != null) { FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph); fm.setJSON(target); fm.internalUpdate(); } } - + logger.info("{} {} successfully updated", erType, jsonNode); - + return edge; - + } - + @Override protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException { getElement(); - + AddConstraint addConstraint = AddConstraint.unpropagate; - + try { PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element, Relation.PROPAGATION_CONSTRAINT); - if (propagationConstraint.getAddConstraint() != null) { + if(propagationConstraint.getAddConstraint() != null) { addConstraint = propagationConstraint.getAddConstraint(); } else { - String error = String.format( - "%s.%s in %s is null. %s", - Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.ADD_PROPERTY, - Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT, + PropagationConstraint.ADD_PROPERTY, Utility.toJsonString(element, true), + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error(error); throw new ResourceRegistryException(error); } - } catch (Exception e) { - String error = String.format( - "Error while getting %s from %s while performing AddToContext. %s", - Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), + } catch(Exception e) { + String error = String.format("Error while getting %s from %s while performing AddToContext. %s", + Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.warn(error); throw new ResourceRegistryException(error, e); } - - switch (addConstraint) { - case propagate: - /* - * The relation must be added only in the case the target vertex must be added. - * Otherwise we have a relation which point to an entity outside of the context. - */ - getTargetEntityManagement().internalAddToContext(); - - getWorkingContext().addElement(getElement(), orientGraph); - - break; - - case unpropagate: - break; - - default: - break; + + switch(addConstraint) { + case propagate: + /* + * The relation must be added only in the case the target vertex must be added. + * Otherwise we have a relation which point to an entity outside of the context. + */ + getTargetEntityManagement().internalAddToContext(); + + getWorkingContext().addElement(getElement(), orientGraph); + + break; + + case unpropagate: + break; + + default: + break; } - + return true; } - + public boolean forcedAddToContext() throws ContextException, ResourceRegistryException { - + getElement(); - + /* Adding source to Context */ getSourceEntityManagement().internalAddToContext(); - + /* Adding target to Context */ getTargetEntityManagement().internalAddToContext(); - + getWorkingContext().addElement(getElement(), orientGraph); return true; } - + @Override protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException { getElement(); - + RemoveConstraint removeConstraint = RemoveConstraint.keep; - + try { PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element, Relation.PROPAGATION_CONSTRAINT); - if (propagationConstraint.getRemoveConstraint() != null) { + if(propagationConstraint.getRemoveConstraint() != null) { removeConstraint = propagationConstraint.getRemoveConstraint(); } else { - String error = String.format( - "%s.%s in %s is null. %s", - Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY, - Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT, + PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true), + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error(error); throw new ResourceRegistryException(error); } - } catch (Exception e) { - String error = String.format( - "Error while getting %s from %s while performing RemoveFromContext. %s", - Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), + } catch(Exception e) { + String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s", + Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error(error); throw new ResourceRegistryException(error, e); - + } - + /* * In any removeConstraint value the relation MUST be removed from context to * avoid to have edge having a source outside of the context. */ getWorkingContext().removeElement(getElement(), orientGraph); - - switch (removeConstraint) { - case cascade: - getTargetEntityManagement().internalRemoveFromContext(); - break; - - case cascadeWhenOrphan: - Vertex target = (Vertex) getTargetEntityManagement().getElement(); - - Iterable iterable = target.getEdges(Direction.IN); - Iterator iterator = iterable.iterator(); - int count = 0; - OrientEdge edge = null; - while (iterator.hasNext()) { - edge = (OrientEdge) iterator.next(); - OrientEdge thisOrientEdge = (OrientEdge) getElement(); - if (edge.compareTo(thisOrientEdge) != 0) { - if (thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) { - count++; - break; - } - /* - * else{ ContextUtility.removeFromActualContext(orientGraph, edge); } - */ - } - } - - if (count > 0) { - logger.trace( - "{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.", - element, target, edge, removeConstraint); - } else { + + switch(removeConstraint) { + case cascade: getTargetEntityManagement().internalRemoveFromContext(); - } - break; - - case keep: - break; - - default: - break; + break; + + case cascadeWhenOrphan: + Vertex target = (Vertex) getTargetEntityManagement().getElement(); + + Iterable iterable = target.getEdges(Direction.IN); + Iterator iterator = iterable.iterator(); + int count = 0; + OrientEdge edge = null; + while(iterator.hasNext()) { + edge = (OrientEdge) iterator.next(); + OrientEdge thisOrientEdge = (OrientEdge) getElement(); + if(edge.compareTo(thisOrientEdge) != 0) { + if(thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) { + count++; + break; + } + /* + * else{ ContextUtility.removeFromActualContext(orientGraph, edge); } + */ + } + } + + if(count > 0) { + logger.trace( + "{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.", + element, target, edge, removeConstraint); + } else { + getTargetEntityManagement().internalRemoveFromContext(); + } + break; + + case keep: + break; + + default: + break; } - + return true; } - + @Override protected boolean reallyDelete() throws RelationNotFoundException, ResourceRegistryException { logger.debug("Going to remove {} with UUID {}. Related {}s will be detached.", accessType.getName(), uuid, targetEntityClass.getSimpleName()); - + getElement(); - + RemoveConstraint removeConstraint = RemoveConstraint.keep; - + try { PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element, Relation.PROPAGATION_CONSTRAINT); - if (propagationConstraint.getRemoveConstraint() != null) { + if(propagationConstraint.getRemoveConstraint() != null) { removeConstraint = propagationConstraint.getRemoveConstraint(); } else { - String error = String.format( - "%s.%s in %s is null. %s", - Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY, - Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT, + PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true), + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error(error); throw new ResourceRegistryException(error); } - } catch (Exception e) { - logger.warn( - "Error while getting {} from {}. Assuming {}. {}", - Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), removeConstraint, - Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); + } catch(Exception e) { + logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT, + Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } - + Vertex target = (Vertex) getTargetEntityManagement().getElement(); element.remove(); - - switch (removeConstraint) { - case cascade: - getTargetEntityManagement().internalDelete(); - break; - - case cascadeWhenOrphan: - Iterable iterable = target.getEdges(Direction.IN); - Iterator iterator = iterable.iterator(); - if (iterator.hasNext()) { - logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element, - target, removeConstraint); - } else { + + switch(removeConstraint) { + case cascade: getTargetEntityManagement().internalDelete(); - } - break; - - case keep: - break; - - default: - break; + break; + + case cascadeWhenOrphan: + Iterable iterable = target.getEdges(Direction.IN); + Iterator iterator = iterable.iterator(); + if(iterator.hasNext()) { + logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element, + target, removeConstraint); + } else { + getTargetEntityManagement().internalDelete(); + } + break; + + case keep: + break; + + default: + break; } - + return true; } - + @SuppressWarnings("unchecked") protected Collection serializeEdges(Iterable edges, boolean postFilterPolymorphic) throws ResourceRegistryException { - Map visitedSourceResources = new HashMap<>(); - for (Edge edge : edges) { - if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) { + Map visitedSourceResources = new HashMap<>(); + for(Edge edge : edges) { + if(postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) { continue; } - RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); + RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), + orientGraph, edge); visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); } return visitedSourceResources.values(); } - + protected String serializeJSONObjectList(Collection list) { JSONArray jsonArray = new JSONArray(list); return jsonArray.toString(); } - + @Override public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { Iterable edges = orientGraph.getEdgesOfClass(erType, polymorphic); Collection collection = serializeEdges(edges, false); return serializeJSONObjectList(collection); } - + public String reallyGetAllFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException { EntityManagement entityManagement = null; try { - entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), orientGraph, uuid); - } catch (ResourceRegistryException e) { + entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), + orientGraph, uuid); + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException( String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME)); } - + Vertex vertex = (Vertex) entityManagement.getElement(); - + List list = new ArrayList<>(); Iterable edges = vertex.getEdges(direction, erType); list.addAll(serializeEdges(edges, !polymorphic)); - + return serializeJSONObjectList(list); - + } - + public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - + return reallyGetAllFrom(uuid, direction, polymorphic); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + @Override public boolean addToContext() throws ERNotFoundException, ContextException { logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid); - + try { orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); - + boolean added = forcedAddToContext(); - + orientGraph.commit(); logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid); - + return added; - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e); - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.rollback(); } throw new ContextException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/query/Query.java b/src/main/java/org/gcube/informationsystem/resourceregistry/query/Query.java index 628d84b..5d1f63f 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/query/Query.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/query/Query.java @@ -1,26 +1,21 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.query; import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; /** * @author Luca Frosini (ISTI - CNR) - * */ public interface Query { - + /** * @param query * @param limit * @param fetchPlan * @return * @throws InvalidQueryException - * http://orientdb.com/docs/last/OrientDB-REST.html#query + * http://orientdb.com/docs/last/OrientDB-REST.html#query */ - public String query(String query, Integer limit, String fetchPlan) - throws InvalidQueryException; + public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException; public String gremlinQuery(String query) throws InvalidQueryException; diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/query/QueryImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/query/QueryImpl.java index 3970bc2..c3f3262 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/query/QueryImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/query/QueryImpl.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.query; import java.io.StringWriter; @@ -10,8 +7,8 @@ import java.util.List; import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext; -import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,116 +19,20 @@ import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; /** * @author Luca Frosini (ISTI - CNR) - * */ public class QueryImpl implements Query { - + private static Logger logger = LoggerFactory.getLogger(QueryImpl.class); - - /* - private static final String QUERY = "query/"; - private static final String SQL = "sql/"; - - private static final String DEFAULT_LIMIT = DEFAULT_LIMIT_INT + "/"; - - private static final URL BASE_QUERY_URL; - - static { - try { - URL url = new URL(DatabaseEnvironment.HTTP_URL_STRINGS[0]); - URL urlQuery = new URL(url, QUERY); - URL urlDB = new URL(urlQuery, DatabaseEnvironment.DB + "/"); - BASE_QUERY_URL = new URL(urlDB, SQL); - } catch (Exception e) { - throw new RuntimeException(e); - } - - } - - private void checkStatus(HttpURLConnection connection) throws Exception { - int statusCode = connection.getResponseCode(); - switch (statusCode) { - case 200: - case 201: - return; - default: - throw new Exception(connection.getResponseMessage()); - } - } - - @Override - public String execute(String query, String fetchPlan) - throws InvalidQueryException { - - - String readerUsername; - try { - readerUsername = ContextUtility.getActualSecurityRoleOrUserName(SecurityContextMapper.PermissionMode.READER, SecurityContextMapper.SecurityType.USER); - } catch (ContextException e1) { - throw new RuntimeException(e1); - } - logger.trace("Reader Username : {}", readerUsername); - - try { - URL queryURL = new URL(BASE_QUERY_URL, URLEncoder.encode(query, - "UTF-8") + "/"); - - / * - if (limit != null && limit > 0) { - queryURL = new URL(queryURL, limit.toString() + "/"); - } else { - queryURL = new URL(queryURL, DEFAULT_LIMIT); - } - * / - queryURL = new URL(queryURL, DEFAULT_LIMIT); - - - if (fetchPlan != null && fetchPlan.compareTo("") != 0) { - queryURL = new URL(queryURL, fetchPlan + "/"); - } - - logger.debug("Connecting to {}", queryURL.toString()); - HttpURLConnection connection = (HttpURLConnection) queryURL - .openConnection(); - - String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER); - String authString = String.format("%s:%s", readerUsername, password); - - byte[] authEncBytes = Base64.encode(authString.getBytes()); - String authStringEnc = new String(authEncBytes); - connection.setRequestProperty("Authorization", "Basic " - + authStringEnc); - connection.setRequestMethod(HTTPMethods.GET.toString()); - connection.connect(); - - checkStatus(connection); - - InputStream inputStream = connection.getInputStream(); - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int length; - while ((length = inputStream.read(buffer)) != -1) { - result.write(buffer, 0, length); - } - return result.toString("UTF-8"); - - } catch (Exception e) { - throw new InvalidQueryException(e.getMessage(), e); - } - - } - */ @Override - public String query(String query, Integer limit, String fetchPlan) - throws InvalidQueryException { - if(limit == null){ + public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException { + if(limit == null) { limit = AccessPath.DEFAULT_LIMIT; } limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit; ODatabaseDocumentTx oDatabaseDocumentTx = null; - + try { SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); @@ -140,47 +41,45 @@ public class QueryImpl implements Query { OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery<>(query, limit); osqlSynchQuery.setFetchPlan(fetchPlan); osqlSynchQuery.setCacheableResult(true); - - logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", - osqlSynchQuery.getText(), osqlSynchQuery.getFetchPlan(), - osqlSynchQuery.getLimit()); + + logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(), + osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit()); List records = oDatabaseDocumentTx.query(osqlSynchQuery); - - Writer writer = new StringWriter(); - writer.append("{\"result\":["); - for(int i=0; i + * It includeSubtypes to query Entities and Relations in the current Context.
* It accepts idempotent query only..
*
* For query syntax please refer to
+ * * * https://orientdb.com/docs/last/SQL-Syntax.html
*
+ * * e.g. GET /resource-registry/access?query=SELECT FROM V * - * @param query - * Defines the query to send to the backend. - * @param limit - * Defines the number of results you want returned, defaults to - * includeSubtypes results. + * @param query + * Defines the query to send to the backend. + * @param limit + * Defines the number of results you want returned, defaults to includeSubtypes results. * @param fetchPlan - * Defines the fetching strategy you want to use. See - * https://orientdb.com/docs/last/Fetching-Strategies.html + * Defines the fetching strategy you want to use. See + * + * https://orientdb.com/docs/last/Fetching-Strategies.html + * * @return The JSON representation of the result * @throws InvalidQueryException * if the query is invalid or no idempotent @@ -85,23 +85,18 @@ public class Access { @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String query(@QueryParam(AccessPath.QUERY_PARAM) String query, @QueryParam(AccessPath.LIMIT_PARAM) Integer limit, - @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) - throws InvalidQueryException { - logger.info("Requested query (fetch plan {}, limit : {}):\n{}", - fetchPlan, limit, query); + @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) throws InvalidQueryException { + logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query); Query queryManager = new QueryImpl(); return queryManager.query(query, limit, fetchPlan); } @HEAD - @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" - + "/{" + ID_PATH_PARAM + "}") - public Response exists(@PathParam(TYPE_PATH_PARAM) String type, - @PathParam(ID_PATH_PARAM) String id) throws ERNotFoundException, - ERAvailableInAnotherContextException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.HEAD.name() + " /" + AccessPath.ACCESS_PATH_PART + - "/" + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}"); + @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/{" + ID_PATH_PARAM + "}") + public Response exists(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(ID_PATH_PARAM) String id) + throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException { + CalledMethodProvider.instance.set(HTTPMETHOD.HEAD.name() + " /" + AccessPath.ACCESS_PATH_PART + "/" + + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to check if {} with id {} exists", type, id); @SuppressWarnings("rawtypes") @@ -109,152 +104,137 @@ public class Access { UUID uuid = null; try { uuid = UUID.fromString(id); - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } erManagement.setUUID(uuid); try { boolean found = erManagement.exists(); - if(found){ + if(found) { return Response.status(Status.NO_CONTENT).build(); - }else{ + } else { // This code should never be reached due to exception management // anyway adding it for safety reason return Response.status(Status.NOT_FOUND).build(); } - } catch (ERNotFoundException e) { + } catch(ERNotFoundException e) { return Response.status(Status.NOT_FOUND).build(); - } catch (ERAvailableInAnotherContextException e) { + } catch(ERAvailableInAnotherContextException e) { return Response.status(Status.FORBIDDEN).build(); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; } } /* * e.g. GET - * /resource-registry/access/instance/ContactFacet/4d28077b-566d-4132-b073- - * f4edaf61dcb9 + * /resource-registry/access/instance/ContactFacet/4d28077b-566d-4132-b073-f4edaf61dcb9 */ @GET - @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" - + "/{" + ID_PATH_PARAM + "}") + @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/{" + ID_PATH_PARAM + "}") @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getInstance(@PathParam(TYPE_PATH_PARAM) String type, - @PathParam(ID_PATH_PARAM) String id) + public String getInstance(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(ID_PATH_PARAM) String id) throws ERNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.GET.name() + " /" + AccessPath.ACCESS_PATH_PART + - "/" + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.GET.name() + " /" + AccessPath.ACCESS_PATH_PART + "/" + + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested {} with id {}", type, id); - + @SuppressWarnings("rawtypes") ERManagement erManagement = ERManagementUtility.getERManagement(type); UUID uuid = null; try { uuid = UUID.fromString(id); - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException(e); } erManagement.setUUID(uuid); return erManagement.read(); } - + /* - * e.g. GET /resource-registry/access/instances/EService?polymorphic=true - * - * &reference=4d28077b-566d-4132-b073-f4edaf61dcb9 &direction=(in|out|both) + * e.g. + * GET /resource-registry/access/instances/EService?polymorphic=true + * &reference=4d28077b-566d-4132-b073-f4edaf61dcb9 &direction=(in|out|both) */ - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings({"rawtypes"}) @GET @Path(AccessPath.INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}") @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String getInstances(@PathParam(TYPE_PATH_PARAM) String type, @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic, @QueryParam(AccessPath.REFERENCE) String reference, - @QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction) - throws ResourceRegistryException { - logger.info("Requested {} ({}={}) instances", type, - AccessPath.POLYMORPHIC_PARAM, polymorphic); - + @QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction) throws ResourceRegistryException { + logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic); + ERManagement erManagement = ERManagementUtility.getERManagement(type); - - if (erManagement instanceof EntityManagement) { + + if(erManagement instanceof EntityManagement) { return erManagement.all(polymorphic); } - - if (erManagement instanceof RelationManagement) { - if (reference != null) { + + if(erManagement instanceof RelationManagement) { + if(reference != null) { UUID uuid = null; try { uuid = UUID.fromString(reference); - } catch (Exception e) { - String errror = String.format( - "Provided %s (%s) is not a valid %s", - AccessPath.REFERENCE, reference, + } catch(Exception e) { + String errror = String.format("Provided %s (%s) is not a valid %s", AccessPath.REFERENCE, reference, UUID.class.getSimpleName()); throw new ResourceRegistryException(errror); } - + Direction directionEnum; - if (direction == null) { + if(direction == null) { directionEnum = Direction.BOTH; } else { try { - directionEnum = Enum.valueOf(Direction.class, direction - .trim().toUpperCase()); - } catch (Exception e) { - String errror = String - .format("Provided %s (%s) is not valid. Allowed values are %s", - AccessPath.DIRECTION, direction, - Arrays.toString(Direction.values()).toLowerCase()); + directionEnum = Enum.valueOf(Direction.class, direction.trim().toUpperCase()); + } catch(Exception e) { + String errror = String.format("Provided %s (%s) is not valid. Allowed values are %s", + AccessPath.DIRECTION, direction, Arrays.toString(Direction.values()).toLowerCase()); throw new ResourceRegistryException(errror); } } - - return ((RelationManagement) erManagement).allFrom(uuid, - directionEnum, polymorphic); - + + return ((RelationManagement) erManagement).allFrom(uuid, directionEnum, polymorphic); + } else { return erManagement.all(polymorphic); } } - + throw new ResourceRegistryException("Invalid Request"); } - /* - * e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet?polymorphic=true + * e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet + * ?polymorphic=true */ - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings({"rawtypes"}) @GET - @Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + - "/" + "{" + AccessPath.RELATION_TYPE_PATH_PART + "}"+ "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}") + @Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/" + "{" + + AccessPath.RELATION_TYPE_PATH_PART + "}" + "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}") @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) - public String getFilteredInstances( - @PathParam(TYPE_PATH_PARAM) String type, + public String getFilteredInstances(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(AccessPath.RELATION_TYPE_PATH_PART) @DefaultValue(ConsistsOf.NAME) String relationType, @PathParam(AccessPath.FACET_TYPE_PATH_PART) @DefaultValue(Facet.NAME) String facetType, @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic, - @Context UriInfo uriInfo) - throws ResourceRegistryException { - logger.info("Requested {} ({}={}) instances", type, - AccessPath.POLYMORPHIC_PARAM, polymorphic); + @Context UriInfo uriInfo) throws ResourceRegistryException { + logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic); - MultivaluedMap multivaluedMap = uriInfo.getQueryParameters(); + MultivaluedMap multivaluedMap = uriInfo.getQueryParameters(); - Map constraint = new HashMap<>(); - for(String key : multivaluedMap.keySet()){ - if(key.compareTo(AccessPath.POLYMORPHIC_PARAM)==0){ + Map constraint = new HashMap<>(); + for(String key : multivaluedMap.keySet()) { + if(key.compareTo(AccessPath.POLYMORPHIC_PARAM) == 0) { continue; } - if(key.compareTo("gcube-token")==0){ + if(key.compareTo("gcube-token") == 0) { continue; } - if(key.compareTo("gcube-scope")==0){ + if(key.compareTo("gcube-scope") == 0) { continue; } constraint.put(key, multivaluedMap.getFirst(key)); @@ -263,16 +243,14 @@ public class Access { constraint.put(AccessPath.FACET_TYPE_PATH_PART, facetType); ERManagement erManagement = ERManagementUtility.getERManagement(type); - - if (erManagement instanceof ResourceManagement) { + + if(erManagement instanceof ResourceManagement) { return ((ResourceManagement) erManagement).all(polymorphic, constraint); } - + throw new ResourceRegistryException("Invalid Request"); } - - /* * e.g. GET /resource-registry/access/schema/ContactFacet?polymorphic=true */ @@ -286,7 +264,6 @@ public class Access { SchemaManagement schemaManagement = new SchemaManagementImpl(); return schemaManagement.read(type, polymorphic); } - /* * e.g. GET /resource-registry/access/context/c0f314e7-2807-4241-a792-2a6c79ed4fd0 diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ContextManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ContextManager.java index 43d0e46..e898aa0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ContextManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ContextManager.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.rest; import java.util.UUID; 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 ffd18c1..c138c3b 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ERManager.java @@ -40,12 +40,12 @@ import org.slf4j.LoggerFactory; */ @Path(ERPath.ER_PATH_PART) public class ERManager { - + private static Logger logger = LoggerFactory.getLogger(ERManager.class); - + public static final String ID_PATH_PARAM = "id"; public static final String TYPE_PATH_PARAM = "type"; - + /** * e.g. PUT /resource-registry/er/facet/ContactFacet * @@ -54,13 +54,12 @@ public class ERManager { */ @PUT @Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json) throws FacetAlreadyPresentException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.FACET_PATH_PART + "/" + type); + CalledMethodProvider.instance + .set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/" + type); logger.info("Requested to create {} of type {}", Facet.NAME, type); logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json); FacetManagement facetManagement = new FacetManagement(); @@ -70,7 +69,7 @@ public class ERManager { return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) .build(); } - + /** * e.g. POST /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 * @@ -79,13 +78,12 @@ public class ERManager { */ @POST @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json) throws FacetNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" + + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to update {} with id {}", Facet.NAME, uuid); logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json); FacetManagement facetManagement = new FacetManagement(); @@ -93,26 +91,25 @@ public class ERManager { facetManagement.setJSON(json); return facetManagement.update(); } - + /** - * e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 + * e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 * */ @DELETE @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" + + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to delete {} with id {}", Facet.NAME, uuid); FacetManagement facetManagement = new FacetManagement(); facetManagement.setUUID(UUID.fromString(uuid)); return facetManagement.delete(); } - + /* Resources Methods */ - + /** * e.g. PUT /resource-registry/er/resource/HostingNode * @@ -121,13 +118,12 @@ public class ERManager { */ @PUT @Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json) throws ResourceAlreadyPresentException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.RESOURCE_PATH_PART + "/" + type); + CalledMethodProvider.instance + .set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/" + type); logger.info("Requested to create {} of type {}", Resource.NAME, type); logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json); ResourceManagement resourceManagement = new ResourceManagement(); @@ -137,7 +133,7 @@ public class ERManager { return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) .build(); } - + /** * e.g. POST /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * @@ -146,13 +142,12 @@ public class ERManager { */ @POST @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json) throws ResourceNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/" + + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to update {} with id {}", Resource.NAME, uuid); logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json); ResourceManagement resourceManagement = new ResourceManagement(); @@ -160,24 +155,23 @@ public class ERManager { resourceManagement.setJSON(json); return resourceManagement.update(); } - + /** - * e.g. DELETE /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 + * e.g. DELETE + * /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * */ @DELETE @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception { - CalledMethodProvider.instance.set( - HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" + + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to delete {} with id {}", Resource.NAME, uuid); ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setUUID(UUID.fromString(uuid)); return resourceManagement.delete(); } - - + /** * e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy * @@ -186,13 +180,12 @@ public class ERManager { */ @PUT @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json) throws ResourceAlreadyPresentException, ResourceRegistryException { CalledMethodProvider.instance.set( - HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type); + HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type); logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type); logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); @@ -202,23 +195,23 @@ public class ERManager { return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) .build(); } - + /** - * e.g. DELETE /resource-registry/er/consistsOf/9bff49c8-c0a7-45de-827c-accb71defbd3 + * e.g. DELETE + * /resource-registry/er/consistsOf/9bff49c8-c0a7-45de-827c-accb71defbd3 * */ @DELETE @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" + + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); consistsOfManagement.setUUID(UUID.fromString(consistOfUUID)); return consistsOfManagement.delete(); } - + /** * e.g. PUT /resource-registry/er/isRelatedTo/Hosts * @@ -227,13 +220,12 @@ public class ERManager { */ @PUT @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json) throws ResourceAlreadyPresentException, ResourceRegistryException { CalledMethodProvider.instance.set( - HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type); + HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type); logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json); IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); isRelatedToManagement.setElementType(type); @@ -242,40 +234,40 @@ public class ERManager { return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) .build(); } - + /** - * e.g. DELETE /resource-registry/er/isRelatedTo/b3982715-a7aa-4530-9a5f-2f60008d256e + * e.g. DELETE + * /resource-registry/er/isRelatedTo/b3982715-a7aa-4530-9a5f-2f60008d256e * */ @DELETE @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/" + + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}"); logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID); IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID)); return isRelatedToManagement.delete(); } - + /** - * e.g POST /resource-registry/er/add/resource/67062c11-9c3a-4906-870d-7df6a43408b0 + * e.g POST + * /resource-registry/er/add/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * */ @POST @Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + 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 {}", Resource.NAME, uuid, Context.NAME); ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setUUID(UUID.fromString(uuid)); return resourceManagement.addToContext(); } - + /** * e.g POST /resource-registry/er/add/facet/f6931232-c034-4979-9b2f-7193d3fba7df * @@ -284,47 +276,46 @@ public class ERManager { @Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + 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 {}", Facet.NAME, uuid, Context.NAME); FacetManagement facetManagement = new FacetManagement(); facetManagement.setUUID(UUID.fromString(uuid)); return facetManagement.addToContext(); } - + /** - * e.g POST /resource-registry/er/remove/resource/67062c11-9c3a-4906-870d-7df6a43408b0 + * e.g POST + * /resource-registry/er/remove/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * */ @POST @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + 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 {}", Resource.NAME, uuid, Context.NAME); ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setUUID(UUID.fromString(uuid)); return resourceManagement.removeFromContext(); } - + /** - * e.g POST /resource-registry/er/remove/facet/f6931232-c034-4979-9b2f-7193d3fba7df + * e.g POST + * /resource-registry/er/remove/facet/f6931232-c034-4979-9b2f-7193d3fba7df * */ @POST @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException { - CalledMethodProvider.instance.set( - HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + - "/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}"); + 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 {}", 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/rest/ResourceRegistryExceptionMapper.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ResourceRegistryExceptionMapper.java index aed7258..71a3200 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ResourceRegistryExceptionMapper.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ResourceRegistryExceptionMapper.java @@ -15,28 +15,29 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound * @author Luca Frosini (ISTI - CNR) */ @Provider -public class ResourceRegistryExceptionMapper implements ExceptionMapper{ - +public class ResourceRegistryExceptionMapper implements ExceptionMapper { + @Override public Response toResponse(ResourceRegistryException exception) { Status status = Status.BAD_REQUEST; - if(ERNotFoundException.class.isAssignableFrom(exception.getClass())){ + if(ERNotFoundException.class.isAssignableFrom(exception.getClass())) { status = Status.NOT_FOUND; - } else if(ERAlreadyPresentException.class.isAssignableFrom(exception.getClass())){ + } else if(ERAlreadyPresentException.class.isAssignableFrom(exception.getClass())) { status = Status.CONFLICT; - } else if(ERAvailableInAnotherContextException.class.isAssignableFrom(exception.getClass())){ + } else if(ERAvailableInAnotherContextException.class.isAssignableFrom(exception.getClass())) { status = Status.FORBIDDEN; - } else if(exception.getClass() == ResourceRegistryException.class){ + } else if(exception.getClass() == ResourceRegistryException.class) { status = Status.INTERNAL_SERVER_ERROR; - } + } try { - String entity = org.gcube.informationsystem.resourceregistry.api.exceptions.ExceptionMapper.marshal(exception); + String entity = org.gcube.informationsystem.resourceregistry.api.exceptions.ExceptionMapper + .marshal(exception); MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; return Response.status(status).entity(entity).type(mediaType).build(); - }catch (Exception e) { + } catch(Exception e) { String entity = exception.getMessage(); MediaType mediaType = MediaType.TEXT_PLAIN_TYPE; return Response.status(status).entity(entity).type(mediaType).build(); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java index 2a03273..ef8d811 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SchemaManager.java @@ -30,10 +30,10 @@ import org.slf4j.LoggerFactory; */ @ApplicationPath(SchemaPath.SCHEMA_PATH_PART) public class SchemaManager { - + private static Logger logger = LoggerFactory.getLogger(SchemaManager.class); public static final String TYPE_PATH_PARAM = "type"; - + /** * e.g. PUT /resource-registry/schema/{E-R} * @@ -46,52 +46,52 @@ public class SchemaManager { */ @PUT @Path("{" + TYPE_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public Response create(@PathParam(TYPE_PATH_PARAM) String type, String json) throws SchemaException, ResourceRegistryException { logger.info("Requested {} registration with schema {}", type, json); - + AccessType accessType = null; try { accessType = AccessType.valueOf(type); - switch (accessType) { - case EMBEDDED: - break; - - case FACET: - break; - - case RESOURCE: - break; - - case IS_RELATED_TO: - break; - - case CONSISTS_OF: - break; - - default: - throw new Exception(); - + switch(accessType) { + case EMBEDDED: + break; + + case FACET: + break; + + case RESOURCE: + break; + + case IS_RELATED_TO: + break; + + case CONSISTS_OF: + break; + + default: + throw new Exception(); + } - } catch (Exception e) { + } catch(Exception e) { String error = String.format("Cannot register %s schema", type); throw new ResourceRegistryException(error); } - + SchemaManagement schemaManagement = new SchemaManagementImpl(); String ret = schemaManagement.create(json, accessType); return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) .build(); } - + /* * e.g. GET /resource-registry/schema/ContactFacet?polymorphic=true */ @GET @Path("{" + TYPE_PATH_PARAM + "}") - @Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String read(@PathParam(TYPE_PATH_PARAM) String type, @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic) @@ -100,5 +100,5 @@ public class SchemaManager { SchemaManagement schemaManagement = new SchemaManagementImpl(); return schemaManagement.read(type, polymorphic); } - + } 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 512f5ab..17e86e2 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java @@ -8,9 +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.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,17 +23,17 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientVertex; public class SchemaContextManagement implements SchemaManagement { - + private static Logger logger = LoggerFactory.getLogger(SchemaContextManagement.class); public static final String SCHEMA = "__SCHEMA"; - protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception{ + protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception { Iterable iterable = orientGraph.getVerticesOfClass(vertexType, false); Iterator iterator = iterable.iterator(); Vertex vertex = null; - if(iterator.hasNext()){ + if(iterator.hasNext()) { vertex = iterator.next(); } else { String error = String.format("%s is not a registered type", vertexType); @@ -41,8 +41,10 @@ public class SchemaContextManagement implements SchemaManagement { throw new Exception(error); } - if(iterator.hasNext()){ - String error = String.format("More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.", vertexType); + if(iterator.hasNext()) { + String error = String.format( + "More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.", + vertexType); logger.error(error); throw new Exception(error); } @@ -52,7 +54,7 @@ public class SchemaContextManagement implements SchemaManagement { @Override public String create(String json, AccessType baseType) throws SchemaException { - + OrientGraph orientGraph = null; try { @@ -62,11 +64,11 @@ public class SchemaContextManagement implements SchemaManagement { ObjectMapper mapper = new ObjectMapper(); TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class); - if (Entity.class.isAssignableFrom(baseType.getTypeClass())) { + if(Entity.class.isAssignableFrom(baseType.getTypeClass())) { OrientVertex orientVertex = orientGraph.addVertex("class:" + typeDefinition.getName()); orientVertex.setProperty(SCHEMA, json); orientVertex.save(); - } else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) { + } else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) { String sourceClass = typeDefinition.getSourceType(); Vertex source = getVertex(orientGraph, sourceClass); @@ -77,7 +79,7 @@ public class SchemaContextManagement implements SchemaManagement { orientEdge.setProperty(SCHEMA, json); orientEdge.save(); - } else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) { + } else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) { ODocument doc = new ODocument(typeDefinition.getName()); doc.field(SCHEMA, json); doc.save(); @@ -86,31 +88,31 @@ public class SchemaContextManagement implements SchemaManagement { orientGraph.commit(); return json; - }catch (Exception e) { - if (orientGraph != null) { + } catch(Exception e) { + if(orientGraph != null) { orientGraph.rollback(); } throw new SchemaException(e); } finally { - if (orientGraph != null) { + if(orientGraph != null) { orientGraph.shutdown(); } } } - + @Override public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { // TODO Auto-generated method stub return null; } - + @Override public String update(String type, AccessType accessType, String json) throws SchemaNotFoundException, SchemaException { throw new UnsupportedOperationException("Not Yet implemented"); } - + @Override public String delete(String type, AccessType accessType) throws SchemaNotFoundException { throw new UnsupportedOperationException("Not Yet implemented"); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java index 417e716..c33dd79 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagement.java @@ -7,8 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema /** * @author Luca Frosini (ISTI - CNR) * - * For JSON schema see - * http://orientdb.com/docs/last/OrientDB-REST.html#class + * For JSON schema see http://orientdb.com/docs/last/OrientDB-REST.html#class * */ public interface SchemaManagement { @@ -17,7 +16,8 @@ public interface SchemaManagement { public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException; - public String update(String type, AccessType accessType, String json) throws SchemaNotFoundException, SchemaException; + public String update(String type, AccessType accessType, String json) + throws SchemaNotFoundException, SchemaException; public String delete(String type, AccessType accessType) throws SchemaNotFoundException; 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 42af592..e60b1c3 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java @@ -19,9 +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.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.gcube.informationsystem.types.TypeBinder; import org.gcube.informationsystem.types.TypeBinder.Property; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; @@ -44,298 +44,271 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; /** * @author Luca Frosini (ISTI - CNR) * - * TODO Create an instance for each Registered Type in a management - * SecurityContext so that that management context can be used to see - * Entity and Relations as graph. + * TODO Create an instance for each Registered Type in a management SecurityContext so that that management context + * can be used to see Entity and Relations as graph. * */ public class SchemaManagementImpl implements SchemaManagement { - - private static Logger logger = LoggerFactory - .getLogger(SchemaManagementImpl.class); - - protected static OClass getOClass(OSchema oSchema, String type) - throws SchemaException { + + private static Logger logger = LoggerFactory.getLogger(SchemaManagementImpl.class); + + protected static OClass getOClass(OSchema oSchema, String type) throws SchemaException { return oSchema.getClass(type); } - - public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, - String type, AccessType accessType) throws SchemaException { + + public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, String type, AccessType accessType) + throws SchemaException { OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); return getTypeSchema(oSchema, type, accessType); } - - public static OClass getTypeSchema(OSchema oSchema, String type, - AccessType accessType) throws SchemaException { + + public static OClass getTypeSchema(OSchema oSchema, String type, AccessType accessType) throws SchemaException { try { OClass oClass = oSchema.getClass(type); - if (oClass == null) { + if(oClass == null) { throw new SchemaNotFoundException(type + " was not registered"); } - if(accessType!=null && type.compareTo(accessType.getName())!= 0) { - if (!oClass.isSubClassOf(accessType.getName())) { + if(accessType != null && type.compareTo(accessType.getName()) != 0) { + if(!oClass.isSubClassOf(accessType.getName())) { throw new SchemaException(type + " is not a " + accessType.getName()); } } return oClass; - } catch (SchemaNotFoundException snfe) { + } catch(SchemaNotFoundException snfe) { throw snfe; - } catch (Exception e) { + } catch(Exception e) { throw new SchemaException(e.getMessage()); } } - + public static OClass getTypeSchema(String type, AccessType accessType) throws SchemaException, ResourceRegistryException { OrientGraphNoTx orientGraphNoTx = null; try { - logger.debug("Getting {} Type {} schema", - accessType != null ? accessType.getName() : "", type); - + logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); - + return getTypeSchema(orientGraphNoTx, type, accessType); - } catch (ResourceRegistryException e) { + } catch(ResourceRegistryException e) { throw e; } finally { - if (orientGraphNoTx != null) { + if(orientGraphNoTx != null) { orientGraphNoTx.shutdown(); } } } - - protected static TypeDefinition getTypeDefinition(OClass oClass) - throws SchemaException { + + protected static TypeDefinition getTypeDefinition(OClass oClass) throws SchemaException { ODocument oDocument = ((OClassImpl) oClass).toStream(); String json = oDocument.toJSON(); try { return TypeBinder.deserializeTypeDefinition(json); - } catch (Exception e) { + } catch(Exception e) { throw new SchemaException(e); } } - - protected static String getTypeDefinitionAsString(OClass oClass) - throws SchemaException { - + + protected static String getTypeDefinitionAsString(OClass oClass) throws SchemaException { + try { TypeDefinition typeDefinition = getTypeDefinition(oClass); return TypeBinder.serializeTypeDefinition(typeDefinition); - } catch (Exception e) { + } catch(Exception e) { throw new SchemaException(e); } } - - protected List getSuperclassesAndCheckCompliancy( - OrientGraphNoTx orientGraphNoTx, TypeDefinition typeDefinition, - String baseType) throws SchemaException { - + + protected List getSuperclassesAndCheckCompliancy(OrientGraphNoTx orientGraphNoTx, + TypeDefinition typeDefinition, String baseType) throws SchemaException { + Set superClasses = typeDefinition.getSuperClasses(); - if (baseType != null) { - if (superClasses == null || superClasses.size() == 0) { + if(baseType != null) { + if(superClasses == null || superClasses.size() == 0) { throw new RuntimeException( - String.format( - "No Superclass found in schema %s. The Type Definition must extend %s", + String.format("No Superclass found in schema %s. The Type Definition must extend %s", typeDefinition, baseType)); } } - + OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); - + List oSuperclasses = new ArrayList<>(); - for (String superClass : superClasses) { + for(String superClass : superClasses) { OClass oSuperClass = getOClass(oSchema, superClass); - if(oSuperClass==null){ - throw new SchemaNotFoundException("Superclass "+ superClass + " does not exists"); + if(oSuperClass == null) { + throw new SchemaNotFoundException("Superclass " + superClass + " does not exists"); } - if (baseType != null) { - if (typeDefinition.getName().compareTo(baseType) != 0) { - if (!oSuperClass.isSubClassOf(baseType)) { - throw new RuntimeException(superClass - + " is not a subsclass of " + baseType - + ". Each Superclass MUST be a subclass of " - + baseType); + if(baseType != null) { + if(typeDefinition.getName().compareTo(baseType) != 0) { + if(!oSuperClass.isSubClassOf(baseType)) { + throw new RuntimeException(superClass + " is not a subsclass of " + baseType + + ". Each Superclass MUST be a subclass of " + baseType); } } } oSuperclasses.add(oSuperClass); } - + return oSuperclasses; } - protected String registerTypeSchema(String jsonSchema, AccessType baseType) - throws SchemaException { - + protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException { + OrientGraphNoTx orientGraphNoTx = null; try { - logger.info("Trying to register {} {}", baseType.getName(), - jsonSchema); - + logger.info("Trying to register {} {}", baseType.getName(), jsonSchema); + ObjectMapper mapper = new ObjectMapper(); - TypeDefinition typeDefinition = mapper.readValue(jsonSchema, - TypeDefinition.class); - + TypeDefinition typeDefinition = mapper.readValue(jsonSchema, TypeDefinition.class); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); - + OClass oClass = null; - if (Entity.class.isAssignableFrom(baseType.getTypeClass())) { - oClass = orientGraphNoTx.createVertexType(typeDefinition - .getName()); - } else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) { - oClass = orientGraphNoTx.createEdgeType(typeDefinition - .getName()); + if(Entity.class.isAssignableFrom(baseType.getTypeClass())) { + oClass = orientGraphNoTx.createVertexType(typeDefinition.getName()); + } else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) { + oClass = orientGraphNoTx.createEdgeType(typeDefinition.getName()); /* - * This information are persisted in Management Context - * - * String outBaseType = typeDefinition.getOutBaseType(); - * String inBaseType = typeDefinition.getInBaseType(); - * + * This information are persisted in Management Context String outBaseType = + * typeDefinition.getOutBaseType(); String inBaseType = + * typeDefinition.getInBaseType(); */ - } else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) { + } else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) { oClass = oSchema.createClass(typeDefinition.getName()); } else { - String error = String - .format("Allowed superclass are %s, %s, %s, or any subclasses of them.", - Entity.NAME, Relation.NAME, Embedded.NAME); + String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.", + Entity.NAME, Relation.NAME, Embedded.NAME); throw new ResourceRegistryException(error); } try { - - if (typeDefinition.getDescription() != null) { + + if(typeDefinition.getDescription() != null) { try { oClass.setDescription(typeDefinition.getDescription()); - }catch (Exception e) { - logger.warn("Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065"); + } catch(Exception e) { + logger.warn( + "Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065"); } } - + try { - // oClass.setAbstract(false); // Used to allow to persist Schema in Context Management + // oClass.setAbstract(false); // Used to allow to persist Schema in Context + // Management oClass.setAbstract(typeDefinition.isAbstract()); - } catch (Exception e) { + } catch(Exception e) { logger.error( "Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.", typeDefinition.getName()); } - - if (typeDefinition.getName().compareTo(Embedded.NAME) != 0) { - List oSuperclasses = getSuperclassesAndCheckCompliancy( - orientGraphNoTx, typeDefinition, baseType.getName()); + + if(typeDefinition.getName().compareTo(Embedded.NAME) != 0) { + List oSuperclasses = getSuperclassesAndCheckCompliancy(orientGraphNoTx, typeDefinition, + baseType.getName()); oClass.setSuperClasses(oSuperclasses); } - - if (Resource.class.isAssignableFrom(baseType.getTypeClass())) { + + if(Resource.class.isAssignableFrom(baseType.getTypeClass())) { Set properties = typeDefinition.getProperties(); - if (properties != null && properties.size() > 0) { - throw new Exception( - "A Resource cannot contains any properties."); + if(properties != null && properties.size() > 0) { + throw new Exception("A Resource cannot contains any properties."); } } else { - for (Property property : typeDefinition.getProperties()) { + for(Property property : typeDefinition.getProperties()) { OType oType = OType.getById(property.getType().byteValue()); - switch (oType) { + switch(oType) { case EMBEDDEDLIST: - throw new UnsupportedDataTypeException(oType.name() + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); + throw new UnsupportedDataTypeException(oType.name() + + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); case EMBEDDEDSET: - throw new UnsupportedDataTypeException(oType.name() + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); + throw new UnsupportedDataTypeException(oType.name() + + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); default: break; } OProperty op = oClass.createProperty(property.getName(), oType); op.setDescription(property.getDescription()); - + /* - * Mandatory and notNull does not work in distributed mode: - * so that on Type declaration they are forced to false + * Mandatory and notNull does not work in distributed mode: so that on Type + * declaration they are forced to false * ovp.setMandatory(property.isMandatory()); - * ovp.setNotNull(property.isNotnull()); - * - * This information are persisted in Management Context + * ovp.setNotNull(property.isNotnull()); This information are persisted in + * Management Context */ op.setMandatory(false); op.setNotNull(false); - + op.setReadonly(property.isReadonly()); op.setRegexp(property.getRegexp()); - - if (property.getLinkedClass() != null) { - OClass linkedClass = getOClass(oSchema, - property.getLinkedClass()); - if (linkedClass == null) { - logger.trace("class {} not found in schema", - property.getLinkedClass()); - throw new Exception("class " - + property.getLinkedClass() - + " not found in schema"); + + if(property.getLinkedClass() != null) { + OClass linkedClass = getOClass(oSchema, property.getLinkedClass()); + if(linkedClass == null) { + logger.trace("class {} not found in schema", property.getLinkedClass()); + throw new Exception("class " + property.getLinkedClass() + " not found in schema"); } - - if (linkedClass.isEdgeType() - || linkedClass.isVertexType()) { - throw new Exception( - "An Embedded Field cannot be an Entity or a Relation"); + + if(linkedClass.isEdgeType() || linkedClass.isVertexType()) { + throw new Exception("An Embedded Field cannot be an Entity or a Relation"); } - + op.setLinkedClass(linkedClass); - } else if (property.getLinkedType() != null) { - op.setLinkedType(OType.getById(property.getLinkedType() - .byteValue())); + } else if(property.getLinkedType() != null) { + op.setLinkedType(OType.getById(property.getLinkedType().byteValue())); } } } - + OClass toBeSerializedOClass = oClass; - if (oClass instanceof OrientElementType) { - toBeSerializedOClass = getOClass(oSchema, - typeDefinition.getName()); + if(oClass instanceof OrientElementType) { + toBeSerializedOClass = getOClass(oSchema, typeDefinition.getName()); } /* - SchemaContextManagement managementUtility = new SchemaContextManagement(); - String ret = managementUtility.create(jsonSchema, baseType); - */ + * SchemaContextManagement managementUtility = new SchemaContextManagement(); + * String ret = managementUtility.create(jsonSchema, baseType); + */ // TODO Remove when the previous has been implemented String ret = getTypeDefinitionAsString(toBeSerializedOClass); - logger.info("{} type registered successfully: {}", - baseType.getName(), jsonSchema); + logger.info("{} type registered successfully: {}", baseType.getName(), jsonSchema); return ret; - }catch (Exception e) { + } catch(Exception e) { oSchema.dropClass(typeDefinition.getName()); throw e; } - } catch (OSchemaException ex) { - if(ex.getMessage().contains("already exists")){ + } catch(OSchemaException ex) { + if(ex.getMessage().contains("already exists")) { throw new SchemaAlreadyPresentException(ex); } throw new SchemaException(ex); - } catch (SchemaException e) { + } catch(SchemaException e) { throw e; - } catch (Exception ex) { + } catch(Exception ex) { throw new SchemaException(ex); } finally { - if (orientGraphNoTx != null) { + if(orientGraphNoTx != null) { orientGraphNoTx.shutdown(); } } } - - protected String getSchema(String type, boolean includeSubtypes) - throws SchemaNotFoundException, SchemaException { + + protected String getSchema(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { OrientGraphNoTx orientGraphNoTx = null; try { AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); @@ -344,61 +317,55 @@ public class SchemaManagementImpl implements SchemaManagement { OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); OClass baseOClass = getTypeSchema(oSchema, type, null); - + List typeDefinitions = new ArrayList<>(); typeDefinitions.add(getTypeDefinition(baseOClass)); - if(includeSubtypes){ + if(includeSubtypes) { Collection subClasses = baseOClass.getAllSubclasses(); - for (OClass oClass : subClasses) { + for(OClass oClass : subClasses) { typeDefinitions.add(getTypeDefinition(oClass)); } } /* - Collection oClasses = oSchema.getClasses(); - for (OClass oClass : oClasses) { - if (oClass.isSubClassOf(baseOClass)) { - typeDefinitions.add(getTypeDefinition(oClass)); - } - } - */ - + * Collection oClasses = oSchema.getClasses(); for (OClass oClass : + * oClasses) { if (oClass.isSubClassOf(baseOClass)) { + * typeDefinitions.add(getTypeDefinition(oClass)); } } + */ + return TypeBinder.serializeTypeDefinitions(typeDefinitions); - } catch (SchemaException e) { + } catch(SchemaException e) { throw e; - } catch (Exception e) { + } catch(Exception e) { throw new SchemaException(e); } finally { - if (orientGraphNoTx != null) { + if(orientGraphNoTx != null) { orientGraphNoTx.shutdown(); } } - + } - + @Override - public String create(String jsonSchema, AccessType accessType) - throws SchemaException { + public String create(String jsonSchema, AccessType accessType) throws SchemaException { return registerTypeSchema(jsonSchema, accessType); } - + @Override - public String read(String entityType, boolean includeSubtypes) - throws SchemaNotFoundException, SchemaException { + public String read(String entityType, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { return getSchema(entityType, includeSubtypes); } - + @Override - public String update(String entityType, AccessType accessType, - String jsonSchema) throws SchemaNotFoundException, SchemaException { + public String update(String entityType, AccessType accessType, String jsonSchema) + throws SchemaNotFoundException, SchemaException { throw new UnsupportedOperationException("Not Yet implemented"); } - + @Override - public String delete(String entityType, AccessType accessType) - throws SchemaNotFoundException { + public String delete(String entityType, AccessType accessType) throws SchemaNotFoundException { throw new UnsupportedOperationException("Not Yet implemented"); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderOrient.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderOrient.java index e9379e9..1c22492 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderOrient.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderOrient.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.utils; import java.util.Date; @@ -14,12 +11,12 @@ import com.orientechnologies.orient.core.record.impl.ODocument; * @author Luca Frosini (ISTI - CNR) */ public class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.embedded.Header { - - public HeaderOrient(){ + + public HeaderOrient() { super(Header.NAME); } - protected HeaderOrient(String iClassName){ + protected HeaderOrient(String iClassName) { super(iClassName); } @@ -29,16 +26,16 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst } @Override - public void setUUID(UUID uuid){ + public void setUUID(UUID uuid) { this.field(Header.UUID_PROPERTY, uuid.toString()); } - + @Override public String getCreator() { return this.field(Header.CREATOR_PROPERTY); } - public void setCreator(String creator){ + public void setCreator(String creator) { this.field(Header.CREATOR_PROPERTY, creator); } @@ -47,7 +44,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst return this.field(Header.CREATION_TIME_PROPERTY); } - public void setCreationTime(Date creationTime){ + public void setCreationTime(Date creationTime) { this.field(Header.CREATION_TIME_PROPERTY, creationTime); } @@ -56,7 +53,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst return this.field(Header.MODIFIED_BY_PROPERTY); } - public void setModifiedBy(String modifiedBy){ + public void setModifiedBy(String modifiedBy) { this.field(Header.MODIFIED_BY_PROPERTY, modifiedBy); } @@ -65,8 +62,8 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst return this.field(Header.LAST_UPDATE_TIME_PROPERTY); } - public void setLastUpdateTime(Date lastUpdateTime){ + public void setLastUpdateTime(Date lastUpdateTime) { this.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderUtility.java index 7ec8a7b..2baf888 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderUtility.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.utils; import java.io.IOException; @@ -31,60 +28,60 @@ import com.tinkerpop.blueprints.Element; * @author Luca Frosini (ISTI - CNR) */ public class HeaderUtility { - + private static final Logger logger = LoggerFactory.getLogger(HeaderUtility.class); - + public static String getUser() { String user = org.gcube.informationsystem.model.embedded.Header.UNKNOWN_USER; try { Caller caller = AuthorizationProvider.instance.get(); - if (caller != null) { + if(caller != null) { ClientInfo clientInfo = caller.getClient(); String clientId = clientInfo.getId(); - if (clientId != null && clientId.compareTo("") != 0) { + if(clientId != null && clientId.compareTo("") != 0) { user = clientId; } else { throw new Exception("Username null or empty"); } } - } catch (Exception e) { + } catch(Exception e) { logger.error("Unable to retrieve user. {} will be used", user); } return user; } - + public static Header createHeader(UUID uuid) { HeaderOrient header = new HeaderOrient(); - - if (uuid == null) { + + if(uuid == null) { uuid = UUID.randomUUID(); } - + header.setUUID(uuid); - + String creator = getUser(); header.setCreator(creator); header.setModifiedBy(creator); - + Date date = Calendar.getInstance().getTime(); SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); logger.trace("Setting Last Update and Creation Time to " + ft.format(date)); - + header.setCreationTime(date); header.setLastUpdateTime(date); - + return header; } - + public static Header getHeader(JsonNode jsonNode, boolean creation) throws JsonParseException, JsonMappingException, IOException { - if (jsonNode.has(Resource.HEADER_PROPERTY)) { + if(jsonNode.has(Resource.HEADER_PROPERTY)) { JsonNode headerNode = jsonNode.get(Resource.HEADER_PROPERTY); - if (headerNode.isNull()) { + if(headerNode.isNull()) { return null; } HeaderOrient header = null; - if (creation) { + if(creation) { // If an header is provided MUST contains and UUID otherwise is // an invalid request so that let that an exception is raised UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText()); @@ -97,9 +94,9 @@ public class HeaderUtility { } return null; } - + public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException { - if (oDocument instanceof HeaderOrient) { + if(oDocument instanceof HeaderOrient) { return (HeaderOrient) oDocument; } else { try { @@ -111,29 +108,29 @@ public class HeaderUtility { headerOrient.setModifiedBy(header.getModifiedBy()); headerOrient.setLastUpdateTime(header.getLastUpdateTime()); return headerOrient; - } catch (Exception e) { + } catch(Exception e) { throw new ResourceRegistryException( "Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } } } - + public static Header addHeader(Element element, UUID uuid) { Header header = createHeader(uuid); element.setProperty(Entity.HEADER_PROPERTY, header); return header; } - + public static Header addHeader(Edge edge, UUID uuid) { Header header = createHeader(uuid); edge.setProperty(Entity.HEADER_PROPERTY, header); return header; } - + public static Header getHeader(Element element) throws ResourceRegistryException { return Utility.getEmbedded(Header.class, element, Entity.HEADER_PROPERTY); } - + public static void updateModifiedByAndLastUpdate(Element element) throws ResourceRegistryException { ODocument oDocument = element.getProperty(Entity.HEADER_PROPERTY); String modifiedBy = getUser(); @@ -142,5 +139,5 @@ public class HeaderUtility { oDocument.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); element.setProperty(Entity.HEADER_PROPERTY, oDocument); } - + } 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 34fc4a0..100a3ca 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java @@ -1,6 +1,3 @@ -/** - * - */ package org.gcube.informationsystem.resourceregistry.utils; import java.util.HashSet; @@ -17,9 +14,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.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,115 +37,104 @@ import com.tinkerpop.blueprints.util.io.graphson.GraphSONUtility; * @author Luca Frosini (ISTI - CNR) */ public class Utility { - + private static final Logger logger = LoggerFactory.getLogger(Utility.class); - + public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator."; - public static JSONObject toJsonObject(OrientElement element, boolean raw) - throws ResourceRegistryException { + public static JSONObject toJsonObject(OrientElement element, boolean raw) throws ResourceRegistryException { try { return new JSONObject(toJsonString(element, raw)); - }catch(Exception e){ + } catch(Exception e) { throw new ResourceRegistryException(e); } } - + public static String toJsonString(OrientElement element, boolean raw) { ORecord oRecord = element.getRecord(); return toJsonString(oRecord, raw); } - + public static String toJsonString(ORecord oRecord, boolean raw) { - if (raw) { + if(raw) { return oRecord.toJSON(); } return oRecord.toJSON("class"); } - - public static JSONObject toJsonObject(Element element, boolean raw) - throws JSONException { - if (raw) { - return GraphSONUtility.jsonFromElement(element, - element.getPropertyKeys(), GraphSONMode.EXTENDED); + + public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException { + if(raw) { + return GraphSONUtility.jsonFromElement(element, element.getPropertyKeys(), GraphSONMode.EXTENDED); } else { Set keys = new HashSet<>(element.getPropertyKeys()); - for (String key : element.getPropertyKeys()) { - if (key.startsWith("_")) { + for(String key : element.getPropertyKeys()) { + if(key.startsWith("_")) { keys.remove(key); } } - return GraphSONUtility.jsonFromElement(element, keys, - GraphSONMode.EXTENDED); + return GraphSONUtility.jsonFromElement(element, keys, GraphSONMode.EXTENDED); } } - + public static String toJsonString(Element element, boolean raw) { try { return toJsonObject(element, true).toString(); - } catch (Exception e) { + } catch(Exception e) { return String.valueOf(element); } } - public static El getElementByUUIDAsAdmin(String elementType, UUID uuid, Class clz) throws ERNotFoundException, ResourceRegistryException { OrientGraphNoTx orientGraphNoTx = null; try { - AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz); } finally { - if (orientGraphNoTx != null) { + if(orientGraphNoTx != null) { orientGraphNoTx.shutdown(); } } } - - public static El getElementByUUID( - Graph graph, String elementType, UUID uuid, + + public static El getElementByUUID(Graph graph, String elementType, UUID uuid, Class clz) throws ERNotFoundException, ResourceRegistryException { - - if (elementType == null || elementType.compareTo("") == 0) { - if (Vertex.class.isAssignableFrom(clz)) { + + if(elementType == null || elementType.compareTo("") == 0) { + if(Vertex.class.isAssignableFrom(clz)) { elementType = Entity.NAME; } - if (Edge.class.isAssignableFrom(clz)) { + if(Edge.class.isAssignableFrom(clz)) { elementType = Relation.NAME; } } - + // TODO Rewrite using Gremlin - String select = "SELECT FROM " + elementType + " WHERE " - + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY + String select = "SELECT FROM " + elementType + " WHERE " + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY + " = \"" + uuid.toString() + "\""; - + OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery<>(select); - + 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()); + if(elements == null || !elements.iterator().hasNext()) { + String error = String.format("No %s with UUID %s was found", elementType, uuid.toString()); logger.info(error); throw new ERNotFoundException(error); } - + Iterator iterator = elements.iterator(); El element = iterator.next(); - - logger.trace("{} with {} is : {}", elementType, uuid.toString(), - Utility.toJsonString(element, true)); - - if (iterator.hasNext()) { - throw new ResourceRegistryException("Found more than one " - + elementType + " with uuid " + uuid.toString() + + logger.trace("{} with {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true)); + + if(iterator.hasNext()) { + throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString() + ". This is a fatal error please contact Admnistrator"); } - + return element; } - public static E getEmbedded(Class clz, Element element, String property) throws ResourceRegistryException { @@ -156,22 +142,20 @@ public class Utility { ODocument oDocument = element.getProperty(property); E e = ISMapper.unmarshal(clz, oDocument.toJSON()); return e; - } catch (Exception ex) { - String error = String.format("Error while getting %s from %s", - property, toJsonString(element, true)); + } catch(Exception ex) { + String error = String.format("Error while getting %s from %s", property, toJsonString(element, true)); throw new ResourceRegistryException(error, ex); } } - public static UUID getUUID(Element element) - throws ResourceRegistryException { + public static UUID getUUID(Element element) throws ResourceRegistryException { /* - * ODocument header = element.getProperty(Entity.HEADER_PROPERTY); - * String contextID = header.field(Header.UUID_PROPERTY); return + * ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String + * contextID = header.field(Header.UUID_PROPERTY); return * UUID.fromString(contextID); */ Header header = HeaderUtility.getHeader(element); return header.getUUID(); } - + } \ No newline at end of file diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java index 1ac216c..49ff4f9 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/ScopedTest.java @@ -30,6 +30,9 @@ public class ScopedTest { protected static final String PROPERTIES_FILENAME = "token.properties"; + private static final String GCUBE_VARNAME = "GCUBE"; + public static final String GCUBE; + private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT"; public static final String GCUBE_DEVNEXT; @@ -47,6 +50,7 @@ public class ScopedTest { public static final String GCUBE_DEVNEXT_ANOTHER_USER; public static final String DEFAULT_TEST_SCOPE; + public static final String PARENT_DEFAULT_TEST_SCOPE; public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER; public static final String ALTERNATIVE_TEST_SCOPE; @@ -60,7 +64,9 @@ public class ScopedTest { } catch (IOException e) { throw new RuntimeException(e); } - + + GCUBE = properties.getProperty(GCUBE_VARNAME); + GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME); GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME); @@ -71,8 +77,11 @@ public class ScopedTest { DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT; + PARENT_DEFAULT_TEST_SCOPE = GCUBE; + DEFAULT_TEST_SCOPE_ANOTHER_USER = GCUBE_DEVNEXT_ANOTHER_USER; ALTERNATIVE_TEST_SCOPE = GCUBE_DEVNEXT_NEXTNEXT; + } public static String getCurrentScope(String token) throws ObjectNotFound, Exception{ 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 eed20f7..2b22afb 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java @@ -16,8 +16,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis 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.context.security.ContextSecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; +import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.SecurityType; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest; import org.junit.Assert; import org.junit.Test; @@ -69,7 +71,8 @@ public class ContextManagementTest extends ScopedTest { 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) throws ResourceRegistryException { + 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); @@ -84,32 +87,34 @@ public class ContextManagementTest extends ScopedTest { 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); - + 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); - + + boolean[] booleanArray = new boolean[] { false, true }; + for (boolean hierarchic : booleanArray) { + for (PermissionMode permissionMode : PermissionMode.values()) { + String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic); + ORole oRole = oSecurity.getRole(role); + Assert.assertEquals(oRole == null, deleted); + + String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic); + OUser oUser = oSecurity.getUser(user); + Assert.assertEquals(oUser == null, deleted); + + } } - - } - protected Context read(UUID uuid) throws ResourceRegistryException, IOException { ContextManagement contextManagement = new ContextManagement(); @@ -366,15 +371,15 @@ public class ContextManagementTest extends ScopedTest { delete(contextA1); logger.debug("The DB should be now clean"); } - + @Test public void testGetAll() throws Exception { ContextManagement contextManagement = new ContextManagement(); String all = contextManagement.all(false); logger.trace(all); List contexts = ISMapper.unmarshalList(Context.class, all); - for(Context context : contexts){ - logger.trace(ISMapper.marshal(context)); + for (Context context : contexts) { + logger.trace(ISMapper.marshal(context)); List> children = context.getChildren(); for (IsParentOf child : children) { Assert.assertTrue(child.getSource() == context); @@ -384,7 +389,7 @@ public class ContextManagementTest extends ScopedTest { roleUserAssertions(context.getHeader().getUUID(), false); } } - + // @Test public void deleteContext() throws ResourceRegistryException, IOException { Context context = read(UUID.fromString("")); @@ -435,14 +440,14 @@ public class ContextManagementTest extends ScopedTest { Context parthenosRegistry = new ContextImpl("PARTHENOS_Registry"); parthenosRegistry.setParent(parthenosVO); create(parthenosRegistry); - + } // @Test public void createProductionMissingContext() throws Exception { UUID d4ResearchUUID = UUID.fromString("8b926d1c-4460-4d7a-adab-c75ad2770a21"); UUID farmUUID = UUID.fromString("dbafdb3e-f7f9-4039-ad1c-3432c041f53c"); - + Map contexts = new HashMap<>(); contexts.put("ICES_FIACO2017", d4ResearchUUID); contexts.put("D4STeam", farmUUID); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/AbstractERManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/AbstractERManagementTest.java new file mode 100644 index 0000000..8e4b312 --- /dev/null +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/AbstractERManagementTest.java @@ -0,0 +1,15 @@ +package org.gcube.informationsystem.resourceregistry.er; + +import org.gcube.informationsystem.model.ER; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; + +public abstract class AbstractERManagementTest { + + public abstract Er create(Er er) throws ResourceRegistryException; + + public abstract Er update(Er er) throws ResourceRegistryException; + + public abstract Er read(Er er) throws ResourceRegistryException; + + public abstract boolean delete(Er er) throws ResourceRegistryException; +} 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 d57ec23..5335d28 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 @@ -5,10 +5,14 @@ import java.util.UUID; import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl; import org.gcube.informationsystem.impl.utils.ISMapper; import org.gcube.informationsystem.model.ER; +import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.facet.SoftwareFacet; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException; +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.utils.Utility; +import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementTest; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.junit.Assert; @@ -16,8 +20,11 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * @author Luca Frosini (ISTI - CNR) + */ public class FacetManagementTest extends ScopedTest { - + private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class); public static final String GROUP = "InformationSystem"; @@ -33,134 +40,276 @@ public class FacetManagementTest extends ScopedTest { return softwareFacet; } + public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, String version) { + Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP) == 0); + Assert.assertTrue(softwareFacet.getName().compareTo(NAME) == 0); + Assert.assertTrue(softwareFacet.getVersion().compareTo(version) == 0); + } + public static void checkHeader(ER er, UUID uuid, boolean create) { - Assert.assertTrue(er.getHeader()!=null); - Assert.assertTrue(er.getHeader().getUUID()!=null); + Assert.assertTrue(er.getHeader() != null); + Assert.assertTrue(er.getHeader().getUUID() != null); - if(uuid!=null) { - Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid)==0); + if(uuid != null) { + Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0); } - String user = HeaderUtility.getUser(); - Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user)==0); + String user = HeaderUtility.getUser(); + Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user) == 0); - if(create){ - Assert.assertTrue(er.getHeader().getCreator().compareTo(user)==0); - Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime())==0); - }else { + if(create) { + Assert.assertTrue(er.getHeader().getCreator().compareTo(user) == 0); + Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0); + } else { Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime())); } - } - public static void checkAssertion(SoftwareFacet softwareFacet, String version, UUID uuid, boolean create) { - checkHeader(softwareFacet, uuid, create); - - Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP)==0); - Assert.assertTrue(softwareFacet.getName().compareTo(NAME)==0); - Assert.assertTrue(softwareFacet.getVersion().compareTo(version)==0); + public static void checkAssertion(Facet facet, UUID uuid, boolean create) { + checkHeader(facet, uuid, create); } + protected F create(F facet) throws Exception { + FacetManagement facetManagement = new FacetManagement(); + String facetType = Utility.getType(facet); + facetManagement.setElementType(facetType); + facetManagement.setJSON(ISMapper.marshal(facet)); + + String json = facetManagement.create(); + logger.debug("Created : {}", json); + @SuppressWarnings("unchecked") + F createdFacet = (F) ISMapper.unmarshal(facet.getClass(), json); + logger.debug("Unmarshalled {}", createdFacet); + + UUID uuid = null; + if(facet.getHeader() != null) { + uuid = facet.getHeader().getUUID(); + } + checkAssertion(createdFacet, uuid, true); + return createdFacet; + } + protected F update(F facet) throws Exception { + FacetManagement facetManagement = new FacetManagement(); + String facetType = Utility.getType(facet); + facetManagement.setElementType(facetType); + facetManagement.setJSON(ISMapper.marshal(facet)); + + String json = facetManagement.update(); + logger.debug("Updated : {}", json); + @SuppressWarnings("unchecked") + F updatedFacet = (F) ISMapper.unmarshal(facet.getClass(), json); + logger.debug("Unmarshalled {}", updatedFacet); + + UUID uuid = facet.getHeader().getUUID(); + checkAssertion(updatedFacet, uuid, false); + + return updatedFacet; + } + + protected F read(F facet) throws Exception { + UUID uuid = facet.getHeader().getUUID(); + + FacetManagement facetManagement = new FacetManagement(); + String facetType = Utility.getType(facet); + facetManagement.setElementType(facetType); + facetManagement.setUUID(uuid); + + String json = facetManagement.read(); + logger.debug("Read : {}", json); + @SuppressWarnings("unchecked") + F readFacet = (F) ISMapper.unmarshal(facet.getClass(), json); + logger.debug("Unmarshalled {}", readFacet); + + checkAssertion(readFacet, uuid, false); + + return readFacet; + } + + protected boolean delete(F facet) throws Exception { + FacetManagement facetManagement = new FacetManagement(); + String facetType = Utility.getType(facet); + facetManagement.setElementType(facetType); + facetManagement.setUUID(facet.getHeader().getUUID()); + + boolean deleted = facetManagement.delete(); + Assert.assertTrue(deleted); + + try { + read(facet); + } catch(FacetNotFoundException e) { + logger.info("Facet not found as expected"); + } + + return deleted; + } + + protected boolean addToContext(F facet) throws Exception { + FacetManagement facetManagement = new FacetManagement(); + String facetType = Utility.getType(facet); + facetManagement.setElementType(facetType); + facetManagement.setUUID(facet.getHeader().getUUID()); + + boolean added = facetManagement.addToContext(); + Assert.assertTrue(added); + + return added; + } + + protected boolean removeFromContext(F facet) throws Exception { + FacetManagement facetManagement = new FacetManagement(); + String facetType = Utility.getType(facet); + facetManagement.setElementType(facetType); + facetManagement.setUUID(facet.getHeader().getUUID()); + + boolean added = facetManagement.removeFromContext(); + Assert.assertTrue(added); + + return added; + } + + interface ActionFunction { + void call(F facet) throws Exception; + } + + protected void assertThrow(F facet, Class c, + ActionFunction action) throws Exception { + try { + action.call(facet); + throw new RuntimeException("Expected " + c.getName()); + } catch(Exception e) { + if(c.isAssignableFrom(e.getClass())) { + logger.debug("As expected {} has been thrown", c.getName()); + return; + } + throw e; + } + } @Test public void createUpdateReadDelete() throws Exception { SoftwareFacet softwareFacet = getSoftwareFacet(); - /* Testing Create */ - FacetManagement facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setJSON(ISMapper.marshal(softwareFacet)); - - String json = facetManagement.create(); - logger.debug("Created : {}", json); - softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json); - logger.debug("Unmarshalled {}", softwareFacet); - - checkAssertion(softwareFacet, VERSION, null, true); - UUID uuid = softwareFacet.getHeader().getUUID(); + softwareFacet = create(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); /* Testing Update */ softwareFacet.setVersion(NEW_VERSION); + softwareFacet = update(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); - facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setJSON(ISMapper.marshal(softwareFacet)); - - json = facetManagement.update(); - logger.debug("Updated : {}", json); - softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json); - logger.debug("Unmarshalled {}", softwareFacet); - - checkAssertion(softwareFacet, NEW_VERSION, uuid, false); - - /* Testing Read */ - facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setUUID(uuid); + softwareFacet = read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); - json = facetManagement.read(); - logger.debug("Read : {}", json); - softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json); - logger.debug("Unmarshalled {}", softwareFacet); - - checkAssertion(softwareFacet, NEW_VERSION, uuid, false); - - - /* Testing Create the facet with the same UUID */ - facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setJSON(ISMapper.marshal(softwareFacet)); - - try { - facetManagement.create(); - }catch (FacetAlreadyPresentException e) { - logger.info("Facet already present as expected"); - } - - /* Testing Delete */ - boolean deleted = facetManagement.delete(); - Assert.assertTrue(deleted); - - facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setUUID(uuid); - - try { - facetManagement.read(); - }catch (FacetNotFoundException e) { - logger.info("Facet not found as expected"); - } + assertThrow(softwareFacet, FacetAlreadyPresentException.class, (SoftwareFacet s) -> { + create(s); + }); + /* Testing Delete */ + delete(softwareFacet); /* Testing new Create to check creation with provided UUID */ - facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setJSON(ISMapper.marshal(softwareFacet)); - - json = facetManagement.create(); - logger.debug("Created : {}", json); - softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json); - logger.debug("Unmarshalled {}", softwareFacet); + softwareFacet = create(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); - checkAssertion(softwareFacet, NEW_VERSION, uuid, true); + delete(softwareFacet); + } + + @Test + public void testHierarchy() throws Exception { + /* Setting scope /gcube/devNext/NextNext */ + ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT); - /* Testing Delete */ - deleted = facetManagement.delete(); - Assert.assertTrue(deleted); + SoftwareFacet softwareFacet = getSoftwareFacet(); - facetManagement = new FacetManagement(); - facetManagement.setElementType(SoftwareFacet.NAME); - facetManagement.setUUID(uuid); + /* Testing Create */ + softwareFacet = create(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); - try { - facetManagement.read(); - }catch (FacetNotFoundException e) { - logger.info("Facet not found as expected"); - } + softwareFacet = update(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); + + /* Testing Read */ + softwareFacet = read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); + + /* Setting (parent) scope /gcube/devNext */ + ScopedTest.setContext(GCUBE_DEVNEXT); + + assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> { + read(s); + }); + + /* Entering hierarchic mode */ + ContextUtility.getHierarchicMode().set(true); + + softwareFacet = read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); + + /* Setting (parent of parent) scope /gcube */ + ScopedTest.setContext(GCUBE); + + softwareFacet = read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); + + /* Leaving hierarchic mode */ + ContextUtility.getHierarchicMode().set(false); + + assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> { + read(s); + }); + + /* Adding to /gcube. The context are now /gcube and /gcube/devNext/NextNext */ + addToContext(softwareFacet); + softwareFacet = read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, VERSION); + + softwareFacet.setVersion(NEW_VERSION); + softwareFacet = update(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); + + /* Restoring scope /gcube/devNext/NextNext */ + ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT); + read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); + + /* Removing from /gcube/devNext/NextNext. The context is now /gcube */ + removeFromContext(softwareFacet); + + assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> { + read(s); + }); + + /* Setting (parent) scope /gcube/devNext */ + ScopedTest.setContext(GCUBE_DEVNEXT); + assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> { + read(s); + }); + + /* Entering hierarchic mode */ + ContextUtility.getHierarchicMode().set(true); + + assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> { + read(s); + }); + + /* Setting (parent of parent) scope /gcube */ + ScopedTest.setContext(GCUBE); + // The facet must be readable in hierarchic mode in /gcube because the context + // has been explicitly added + read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); + + /* Leaving hierarchic mode */ + ContextUtility.getHierarchicMode().set(false); + + read(softwareFacet); + checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION); + + delete(softwareFacet); } } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java index 7cd66c9..77a0c45 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/entity/ResourceManagementTest.java @@ -27,12 +27,11 @@ public class ResourceManagementTest extends ScopedTest { private static Logger logger = LoggerFactory.getLogger(ResourceManagementTest.class); - public static void checkAssertion(EService eService, String version, UUID eServiceUUID, boolean create) { + public static void checkAssertion(EService eService, UUID eServiceUUID, boolean create) { FacetManagementTest.checkHeader(eService, eServiceUUID, create); SoftwareFacet softwareFacet = eService.getFacets(SoftwareFacet.class).get(0); - FacetManagementTest.checkAssertion(softwareFacet, version, null, create); - + FacetManagementTest.checkAssertion(softwareFacet, null, create); } @@ -55,7 +54,8 @@ public class ResourceManagementTest extends ScopedTest { logger.trace("Created {}", json); eService = ISMapper.unmarshal(EService.class, json); - checkAssertion(eService, FacetManagementTest.VERSION, null, true); + checkAssertion(eService, null, true); + FacetManagementTest.checkSoftwareFacetAssertion(softwareFacet, FacetManagementTest.VERSION); UUID uuid = eService.getHeader().getUUID(); softwareFacet = eService.getFacets(SoftwareFacet.class).get(0); @@ -72,7 +72,9 @@ public class ResourceManagementTest extends ScopedTest { logger.trace("Updated {}", json); eService = ISMapper.unmarshal(EService.class, json); - checkAssertion(eService, FacetManagementTest.NEW_VERSION, uuid, false); + checkAssertion(eService, uuid, false); + softwareFacet = eService.getFacets(SoftwareFacet.class).get(0); + FacetManagementTest.checkSoftwareFacetAssertion(softwareFacet, FacetManagementTest.NEW_VERSION); resourceManagement = new ResourceManagement(); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/BasicTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/BasicTest.java index 69a0539..d0c0d78 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/BasicTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/BasicTest.java @@ -8,7 +8,6 @@ import java.net.URL; import java.util.Calendar; import java.util.UUID; -import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.impl.embedded.PropagationConstraintImpl; import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl; import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl; @@ -25,11 +24,9 @@ import org.gcube.informationsystem.impl.relation.consistsof.HasPersistentMemoryI import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl; import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl; import org.gcube.informationsystem.impl.utils.ISMapper; -import org.gcube.informationsystem.model.embedded.Header; import org.gcube.informationsystem.model.embedded.PropagationConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.entity.Entity; import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.facet.AccessPointFacet; import org.gcube.informationsystem.model.entity.facet.CPUFacet; @@ -53,6 +50,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet. import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException; +import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.er.SmartgearResourcesTest; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; @@ -85,10 +83,9 @@ public class BasicTest extends ScopedTest { String json = facetManagement.create(); logger.debug("Created : {}", json); - JSONObject jsonObject = new JSONObject(json); - JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY); - UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY)); - + CPUFacet createdCPUFacet = ISMapper.unmarshal(CPUFacet.class, json); + UUID uuid = createdCPUFacet.getHeader().getUUID(); + facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); @@ -98,7 +95,7 @@ public class BasicTest extends ScopedTest { /* ------------------------------------------------------------------ */ logger.debug("Switching to another scope"); - ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE); + ScopedTest.setContext(ScopedTest.PARENT_DEFAULT_TEST_SCOPE); try { facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); @@ -111,6 +108,19 @@ public class BasicTest extends ScopedTest { logger.debug("Good the facet created in the default context is not visible in an alternative context"); } + /* ---------------- entering hierarchic mode */ + + ContextUtility.getHierarchicMode().set(true); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + readJson = facetManagement.read(); + logger.debug("You should be able to read it {}", readJson); + + ContextUtility.getHierarchicMode().set(false); + + /* ---------------- leaving hierarchic mode */ + cpuFacet.setAdditionalProperty("My", "Test"); try { @@ -126,20 +136,6 @@ public class BasicTest extends ScopedTest { logger.debug("Good the Facet created in the default context cannot be updated in an alternative context"); } - /* Commented because the behavior has been changed - try { - facetManagement = new FacetManagement(); - facetManagement.setUUID(uuid); - facetManagement.delete(); - logger.debug("You should not be able to delete Facet with UUID {}", - uuid); - throw new Exception( - "You should not be able to delete Facet with UUID " + uuid); - } catch (FacetAvailableInAnotherContextException e) { - logger.debug("Good the Facet created in the default context cannot be deleted in an alternative context"); - } - */ - /* ------------------------------------------------------------------ */ logger.debug("Setting back default scope"); @@ -158,6 +154,7 @@ public class BasicTest extends ScopedTest { facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); + boolean deleted = facetManagement.delete(); Assert.assertTrue(deleted); }