From 1e14003aa8e1d116ae67f7d9e322bf06d87821ae Mon Sep 17 00:00:00 2001 From: "luca.frosini" Date: Wed, 13 Feb 2019 11:33:29 +0000 Subject: [PATCH] Merged from private branch used to refactor and add features git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@177107 82a268e6-3cf1-43bd-a215-b396298e98cf --- distro/changelog.xml | 8 +- pom.xml | 4 +- .../context/ContextManagement.java | 57 +++-- .../context/ContextUtility.java | 4 +- .../context/IsParentOfManagement.java | 28 +-- .../context/security/SecurityContext.java | 192 +++++++++++++--- .../dbinitialization/DatabaseEnvironment.java | 107 +++++++-- .../dbinitialization/SchemaActionImpl.java | 22 +- .../resourceregistry/er/ERManagement.java | 154 +++++++------ .../er/ERManagementUtility.java | 20 +- .../er/EmbeddedMangement.java | 73 ------- .../er/PropertyManagement.java | 180 +++++++++++++++ .../er/entity/EntityManagement.java | 73 ++++--- .../er/entity/FacetManagement.java | 6 +- .../er/entity/ResourceManagement.java | 123 ++--------- .../er/relation/ConsistsOfManagement.java | 10 +- .../er/relation/IsRelatedToManagement.java | 10 +- .../er/relation/RelationManagement.java | 108 ++++----- .../resourceregistry/query/Query.java | 2 +- .../resourceregistry/query/QueryImpl.java | 57 +++-- .../resourceregistry/rest/Access.java | 13 +- .../resourceregistry/rest/ContextManager.java | 13 +- .../rest/InstancesManager.java | 8 +- .../rest/SharingManagement.java | 14 +- .../schema/SchemaContextManagement.java | 8 +- .../schema/SchemaManagementImpl.java | 140 ++++++------ .../utils/EncryptedOrient.java | 74 +++++++ .../resourceregistry/utils/HeaderOrient.java | 4 +- .../resourceregistry/utils/HeaderUtility.java | 8 +- .../utils/PropagationConstraintOrient.java | 4 +- .../resourceregistry/utils/Utility.java | 63 ++---- src/main/resources/config.properties.example | 3 + src/main/resources/db.key.README | 2 + .../access/QueryImplTest.java | 4 +- .../context/ContextManagementTest.java | 86 +------- .../DatabaseEnvironmentTest.java | 31 +++ .../resourceregistry/er/ERManagementTest.java | 206 +++++++++++++----- .../resourceregistry/er/EncryptionTest.java | 46 ++++ .../er/SmartgearResourcesTest.java | 72 +++--- .../er/entity/FacetManagementTest.java | 12 +- .../er/entity/ResourceManagementTest.java | 22 +- .../er/multicontext/BasicTest.java | 86 ++++---- .../er/multicontext/RuleTest.java | 24 +- .../schema/SchemaManagementImplTest.java | 36 +-- 44 files changed, 1316 insertions(+), 901 deletions(-) delete mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/er/PropertyManagement.java create mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java create mode 100644 src/main/resources/db.key.README create mode 100644 src/test/java/org/gcube/informationsystem/resourceregistry/er/EncryptionTest.java diff --git a/distro/changelog.xml b/distro/changelog.xml index a7c3925..36465da 100644 --- a/distro/changelog.xml +++ b/distro/changelog.xml @@ -1,8 +1,12 @@ - - + + Migrated Code from OrientDB 2.2.X APIs OrientDB 3.0.X APIs #13180 + Using gxREST defined Methdos in place of the ones defined in resource-regsitry APIs #11455 + Added support for Encrypted property #12812 + Refactored code to support renaming of Embedded class to Property #13274 + Refactored code to avoid to use jettison library Removed unneeded dependency (common-smartgears-app) diff --git a/pom.xml b/pom.xml index 9cc2a56..f9fa3e3 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ org.gcube.information-system resource-registry - 2.0.1-SNAPSHOT + 2.1.0-SNAPSHOT Resource Registry Resource Registry war @@ -90,12 +90,10 @@ javax.ws.rs javax.ws.rs-api - 2.0.1 org.glassfish.jersey.containers jersey-container-servlet - 2.13 javax.servlet 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 bbd0a4f..368d9eb 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextManagement.java @@ -3,14 +3,11 @@ package org.gcube.informationsystem.resourceregistry.context; import java.util.Iterator; import java.util.UUID; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.model.reference.entity.Context; -import org.gcube.informationsystem.model.reference.relation.IsParentOf; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Context; +import org.gcube.informationsystem.model.reference.properties.Header; +import org.gcube.informationsystem.model.reference.relations.IsParentOf; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; @@ -26,8 +23,12 @@ import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; @@ -73,6 +74,7 @@ public class ContextManagement extends EntityManagement { return name; } + @Override protected SecurityContext getWorkingContext() throws ResourceRegistryException { if(workingContext == null) { workingContext = ContextUtility.getInstance() @@ -126,7 +128,7 @@ public class ContextManagement extends EntityManagement { } else { // TODO Rewrite using Gremlin - String select = "SELECT FROM " + org.gcube.informationsystem.model.reference.entity.Context.NAME + " WHERE " + String select = "SELECT FROM " + org.gcube.informationsystem.model.reference.entities.Context.NAME + " WHERE " + Context.NAME_PROPERTY + " = \"" + getName() + "\"" + " AND in(\"" + IsParentOf.NAME + "\").size() = 0"; @@ -148,9 +150,9 @@ public class ContextManagement extends EntityManagement { } @Override - public JSONObject serializeAsJson() throws ResourceRegistryException { + public JsonNode serializeAsJson() throws ResourceRegistryException { - JSONObject context = serializeSelfOnly(); + JsonNode context = serializeSelfOnly(); int count = 0; Iterable parents = getElement().getEdges(Direction.IN); @@ -161,9 +163,11 @@ public class ContextManagement extends EntityManagement { try { IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); isParentOfManagement.setElement(edge); - JSONObject isParentOf = isParentOfManagement.serializeAsJson(true, false); - context.putOpt(Context.PARENT_PROPERTY, isParentOf); - } catch(JSONException e) { + JsonNode isParentOf = isParentOfManagement.serializeAsJson(true, false); + if(isParentOf!=null) { + ((ObjectNode) context).replace(Context.PARENT_PROPERTY, isParentOf); + } + } catch(Exception e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); throw new ContextException(""); } @@ -175,7 +179,7 @@ public class ContextManagement extends EntityManagement { IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); isParentOfManagement.setElement(edge); try { - JSONObject isParentOf = isParentOfManagement.serializeAsJson(); + JsonNode isParentOf = isParentOfManagement.serializeAsJson(); context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY); } catch(ResourceRegistryException e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); @@ -201,7 +205,7 @@ public class ContextManagement extends EntityManagement { JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY); ContextManagement parentContextManagement = new ContextManagement(orientGraph); - parentContextManagement.setJSON(parentJsonNode); + parentContextManagement.setJsonNode(parentJsonNode); UUID parentUUID = parentContextManagement.uuid; parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID); @@ -214,7 +218,7 @@ public class ContextManagement extends EntityManagement { createVertex(); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); - isParentOfManagement.setJSON(isParentOfJsonNode); + isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setSourceEntityManagement(parentContextManagement); isParentOfManagement.setTargetEntityManagement(this); @@ -280,7 +284,7 @@ public class ContextManagement extends EntityManagement { } if(parentContextJsonNode != null && !(parentContextJsonNode instanceof NullNode)) { - UUID parentUUID = org.gcube.informationsystem.model.impl.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode); + UUID parentUUID = org.gcube.informationsystem.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode); if(actualParentContextManagement != null) { if(parentUUID.compareTo(actualParentContextManagement.uuid) != 0) { parentChanged = true; @@ -291,7 +295,7 @@ public class ContextManagement extends EntityManagement { if(parentChanged) { newParentContextManagement = new ContextManagement(orientGraph); - newParentContextManagement.setJSON(parentContextJsonNode); + newParentContextManagement.setJsonNode(parentContextJsonNode); } } else { if(actualParentContextManagement != null) { @@ -319,7 +323,7 @@ public class ContextManagement extends EntityManagement { element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys); - ContextUtility.getInstance().removeFromCache(uuid, true); + ContextUtility.getInstance().removeFromCache(uuid, (nameChanged && !parentChanged)); return element; } @@ -350,7 +354,7 @@ public class ContextManagement extends EntityManagement { if(newParentContextManagement != null) { JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); - isParentOfManagement.setJSON(isParentOfJsonNode); + isParentOfManagement.setJsonNode(isParentOfJsonNode); isParentOfManagement.setSourceEntityManagement(newParentContextManagement); isParentOfManagement.setTargetEntityManagement(this); isParentOfManagement.internalCreate(); @@ -383,20 +387,25 @@ public class ContextManagement extends EntityManagement { @Override public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { - JSONArray jsonArray = new JSONArray(); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode arrayNode = objectMapper.createArrayNode(); Iterable iterable = orientGraph.getVerticesOfClass(elementType, polymorphic); for(Vertex vertex : iterable) { ContextManagement contextManagement = new ContextManagement(); contextManagement.setElement(vertex); try { - JSONObject jsonObject = contextManagement.serializeAsJson(); - jsonArray.put(jsonObject); + JsonNode jsonObject = contextManagement.serializeAsJson(); + arrayNode.add(jsonObject); } 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(); + try { + return objectMapper.writeValueAsString(arrayNode); + } catch(JsonProcessingException e) { + throw new ResourceRegistryException(e); + } } } 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 ae72008..5b8ae42 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/ContextUtility.java @@ -11,8 +11,8 @@ import org.gcube.common.authorization.library.AuthorizationEntry; import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.informationsystem.model.reference.entity.Context; -import org.gcube.informationsystem.model.reference.relation.IsParentOf; +import org.gcube.informationsystem.model.reference.entities.Context; +import org.gcube.informationsystem.model.reference.relations.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; 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 3c02892..a79f441 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/IsParentOfManagement.java @@ -2,14 +2,13 @@ package org.gcube.informationsystem.resourceregistry.context; import java.util.UUID; -import org.codehaus.jettison.json.JSONObject; -import org.gcube.informationsystem.model.impl.embedded.PropagationConstraintImpl; +import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.AddConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.relation.IsParentOf; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.IsParentOf; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; @@ -22,6 +21,7 @@ import org.gcube.informationsystem.resourceregistry.er.relation.RelationManageme import org.gcube.informationsystem.resourceregistry.utils.Utility; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientGraph; @@ -60,8 +60,8 @@ public class IsParentOfManagement extends RelationManagement> factoryMap; + protected final Map> poolMap; protected SecurityContext parentSecurityContext; @@ -115,6 +119,10 @@ public class SecurityContext { return ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); } + protected ODatabaseSession getAdminDatabaseSession() throws ResourceRegistryException { + return ContextUtility.getAdminSecurityContext().getDatabaseSession(PermissionMode.WRITER); + } + /** * @return a set containing all children and recursively * all children. @@ -188,11 +196,13 @@ public class SecurityContext { if(newParentSecurityContext!=null){ for(PermissionMode permissionMode : PermissionMode.values()) { + List roles = new ArrayList<>(); for(SecurityContext child : allChildren) { String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true); ORole role = oSecurity.getRole(roleName); - getParentSecurityContext().addHierarchicRoleToParent(oSecurity, permissionMode, role); + roles.add(role); } + newParentSecurityContext.addHierarchicRoleToParent(oSecurity, permissionMode, roles.toArray(new ORole[allChildren.size()])); } } @@ -201,6 +211,7 @@ public class SecurityContext { protected SecurityContext(UUID context, boolean hierarchic) throws ResourceRegistryException { this.context = context; this.factoryMap = new HashMap<>(); + this.poolMap = new HashMap<>(); this.hierarchic = hierarchic; this.children = new HashSet<>(); } @@ -209,6 +220,41 @@ public class SecurityContext { this(context, true); } + private synchronized ODatabasePool getPool(PermissionMode permissionMode, boolean recreate) { + ODatabasePool pool = null; + + Boolean h = isHierarchicMode(); + + Map pools = poolMap.get(h); + if(pools == null) { + pools = new HashMap<>(); + poolMap.put(h, pools); + } else { + if(recreate) { + pool = pools.get(permissionMode); + if(pool!=null) { + pool.close(); + pools.remove(permissionMode); + } + } + } + + pool = pools.get(permissionMode); + + if(pool == null) { + + String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h); + String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode); + + pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password); + //pool.setConnectionStrategy(DatabaseEnvironment.CONNECTION_STRATEGY_PARAMETER.toString()); + + pools.put(permissionMode, pool); + } + + return pool; + } + private synchronized OrientGraphFactory getFactory(PermissionMode permissionMode, boolean recreate) { OrientGraphFactory factory = null; @@ -217,9 +263,14 @@ public class SecurityContext { Map factories = factoryMap.get(h); if(factories == null) { factories = new HashMap<>(); + factoryMap.put(h, factories); } else { if(recreate) { - factories.remove(permissionMode); + factory = factories.get(permissionMode); + if(factory!=null) { + factory.close(); + factories.remove(permissionMode); + } } } @@ -256,9 +307,13 @@ public class SecurityContext { return stringBuilder.toString(); } + @Deprecated private OSecurity getOSecurity(OrientGraph orientGraph) { - ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph(); - return oDatabaseDocumentTx.getMetadata().getSecurity(); + return orientGraph.getRawGraph().getMetadata().getSecurity(); + } + + private OSecurity getOSecurity(ODatabaseSession oDatabaseSession) { + return oDatabaseSession.getMetadata().getSecurity(); } public void addElement(Element element) throws ResourceRegistryException { @@ -324,9 +379,9 @@ public class SecurityContext { @Override public Boolean call() throws Exception { ContextUtility.getHierarchicMode().set(false); - OrientGraphNoTx orientGraphNoTx = getGraphNoTx(PermissionMode.READER); + ODatabaseSession oDatabaseSession = getDatabaseSession(PermissionMode.READER); try { - OrientElement element = orientGraphNoTx.getElement(oDocument.getIdentity()); + OrientElement element = oDatabaseSession.getRecord(oDocument.getIdentity()); if(element == null) { return false; } @@ -334,7 +389,7 @@ public class SecurityContext { } catch(Exception e) { return false; } finally { - orientGraphNoTx.shutdown(); + oDatabaseSession.close(); } } @@ -349,10 +404,16 @@ public class SecurityContext { } public void create() throws ResourceRegistryException { + /* OrientGraph orientGraph = getAdminOrientGraph(); create(orientGraph); orientGraph.commit(); orientGraph.shutdown(); + */ + ODatabaseSession oDatabaseSession = getAdminDatabaseSession(); + create(oDatabaseSession); + oDatabaseSession.commit(); + oDatabaseSession.close(); } protected ORole addExtraRules(ORole role, PermissionMode permissionMode) { @@ -364,14 +425,16 @@ public class SecurityContext { return oSecurity.getRole(superRoleName); } - protected void addHierarchicRoleToParent(OSecurity oSecurity, PermissionMode permissionMode, ORole role) { + protected void addHierarchicRoleToParent(OSecurity oSecurity, PermissionMode permissionMode, ORole... roles) { String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true); OUser user = oSecurity.getUser(userName); - user.addRole(role); + for(ORole role : roles) { + user.addRole(role); + } user.save(); if(getParentSecurityContext() != null) { - getParentSecurityContext().addHierarchicRoleToParent(oSecurity, permissionMode, role); + getParentSecurityContext().addHierarchicRoleToParent(oSecurity, permissionMode, roles); } } @@ -407,11 +470,15 @@ public class SecurityContext { } + public void create(ODatabaseSession oDatabaseSession) { + OSecurity oSecurity = getOSecurity(oDatabaseSession); + createRolesAndUsers(oSecurity); + logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); + } + public void create(OrientGraph orientGraph) { OSecurity oSecurity = getOSecurity(orientGraph); - createRolesAndUsers(oSecurity); - logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString()); } @@ -437,10 +504,16 @@ public class SecurityContext { } public void delete() throws ResourceRegistryException { + /* OrientGraph orientGraph = getAdminOrientGraph(); delete(orientGraph); orientGraph.commit(); orientGraph.shutdown(); + */ + ODatabaseSession oDatabaseSession = getAdminDatabaseSession(); + create(oDatabaseSession); + oDatabaseSession.commit(); + oDatabaseSession.close(); } protected void removeChildrenHRolesFromParents(OSecurity oSecurity) { @@ -501,38 +574,86 @@ public class SecurityContext { public void delete(OrientGraph orientGraph) { OSecurity oSecurity = getOSecurity(orientGraph); - + delete(oSecurity); + } + + public void delete(ODatabaseSession oDatabaseSession) { + OSecurity oSecurity = getOSecurity(oDatabaseSession); + delete(oSecurity); + } + + + private void delete(OSecurity oSecurity) { 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.close(); - factory = getFactory(permissionMode, true); - orientGraph = factory.getTx(); + public OrientGraph getGraph(PermissionMode permissionMode) throws ResourceRegistryException { + try { + OrientGraphFactory factory = getFactory(permissionMode, false); + OrientGraph orientGraph = null; + try { + orientGraph = factory.getTx(); + if(orientGraph.isClosed()) { + // Enforcing factory recreation + throw new Exception(); + } + }catch (Exception e) { + factory = getFactory(permissionMode, true); + orientGraph = factory.getTx(); + } + return orientGraph; + }catch (Exception e) { + throw new ResourceRegistryException(e); } - return orientGraph; } - public OrientGraphNoTx getGraphNoTx(PermissionMode permissionMode) { - OrientGraphFactory factory = getFactory(permissionMode, false); - OrientGraphNoTx orientGraphNoTx = factory.getNoTx(); - if(orientGraphNoTx.isClosed()) { - factory.close(); - factory = getFactory(permissionMode, true); - orientGraphNoTx = factory.getNoTx(); + public OrientGraphNoTx getGraphNoTx(PermissionMode permissionMode) throws ResourceRegistryException { + try { + OrientGraphFactory factory = getFactory(permissionMode, false); + OrientGraphNoTx orientGraphNoTx = null; + try { + orientGraphNoTx = factory.getNoTx(); + if(orientGraphNoTx.isClosed()) { + // Enforcing factory recreation + throw new Exception(); + } + }catch (Exception e) { + factory = getFactory(permissionMode, true); + orientGraphNoTx = factory.getNoTx(); + } + return orientGraphNoTx; + }catch (Exception e) { + throw new ResourceRegistryException(e); } - return orientGraphNoTx; } - public ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) { + public ODatabaseSession getDatabaseSession(PermissionMode permissionMode) throws ResourceRegistryException { + try { + ODatabasePool oDatabasePool = getPool(permissionMode, false); + ODatabaseSession oDatabaseSession = null; + try { + oDatabaseSession = oDatabasePool.acquire(); + if(oDatabaseSession.isClosed()) { + // Enforcing pool recreation + throw new Exception(); + } + }catch (Exception e) { + oDatabasePool = getPool(permissionMode, true); + oDatabaseSession = oDatabasePool.acquire(); + } + return oDatabaseSession; + }catch (Exception e) { + throw new ResourceRegistryException(e); + } + } + + /* * + * Use {@link #getDatabaseSession(PermissionMode)} instead + * / + @Deprecated + private ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) { OrientGraphFactory factory = getFactory(permissionMode, false); ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase(); if(databaseDocumentTx.isClosed()) { @@ -542,6 +663,7 @@ public class SecurityContext { } return databaseDocumentTx; } + */ @Override public String 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 84ac48b..26f0381 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java @@ -1,37 +1,41 @@ package org.gcube.informationsystem.resourceregistry.dbinitialization; +import java.io.File; import java.io.InputStream; +import java.net.URL; +import java.security.Key; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.UUID; -import org.gcube.informationsystem.model.impl.utils.discovery.ISMDiscovery; -import org.gcube.informationsystem.model.impl.utils.discovery.SchemaAction; +import org.gcube.common.encryption.SymmetricKey; import org.gcube.informationsystem.model.reference.ISConstants; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; 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.gcube.informationsystem.utils.discovery.ISMDiscovery; +import org.gcube.informationsystem.utils.discovery.SchemaAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.orient.client.remote.OServerAdmin; import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY; +import com.orientechnologies.orient.core.db.ODatabasePool; +import com.orientechnologies.orient.core.db.ODatabaseSession; +import com.orientechnologies.orient.core.db.ODatabaseType; +import com.orientechnologies.orient.core.db.OrientDB; +import com.orientechnologies.orient.core.db.OrientDBConfig; import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.security.ORole; import com.orientechnologies.orient.core.metadata.security.OSecurity; import com.orientechnologies.orient.core.metadata.security.OUser; -import com.orientechnologies.orient.core.sql.OCommandSQL; -import com.tinkerpop.blueprints.impls.orient.OrientEdgeType; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; -import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; -import com.tinkerpop.blueprints.impls.orient.OrientVertexType; /** * @author Luca Frosini (ISTI - CNR) @@ -40,7 +44,7 @@ public class DatabaseEnvironment { private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class); - private static final String PROPERTY_FILENAME = "config.properties"; + protected static final String PROPERTY_FILENAME = "config.properties"; private static final String HOST_VARNAME = "HOST"; @@ -83,14 +87,19 @@ public class DatabaseEnvironment { 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\""; + + //private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT \"%s\""; + private static final String DATE_FORMAT_NAME = "dateformat"; + private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT :" + DATE_FORMAT_NAME; // Used to indicate virtual admin security context private static final String ADMIN_SECURITY_CONTEXT; @@ -104,6 +113,12 @@ public class DatabaseEnvironment { private static final String CONTEXT_SECURITY_CONTEXT; public static final UUID CONTEXT_SECURITY_CONTEXT_UUID; + + protected static final String DB_KEY_FILENAME_VARNAME = "DB_KEY_FILENAME"; + protected static final String DB_KEY_ALGORITHM_VARNAME = "DB_KEY_ALGORITHM"; + + private static final Key KEY; + static { Properties properties = new Properties(); InputStream input = null; @@ -202,10 +217,28 @@ public class DatabaseEnvironment { } - } catch(Exception e) { + } catch(Throwable e) { logger.error("Error initializing database connection", e); throw new RuntimeException("Error initializing database connection", e); } + + logger.info("Database Connection has been properly initialized"); + + try { + logger.trace("Going to get properties required to load DB key"); + String keyFileName = properties.getProperty(DB_KEY_FILENAME_VARNAME); + String keyAlgorithm = properties.getProperty(DB_KEY_ALGORITHM_VARNAME); + logger.debug("Trying to load DB key from file with name {} created for algorithm {}", keyFileName, keyAlgorithm); + URL keyFileURL = DatabaseEnvironment.class.getClassLoader().getResource(keyFileName); + File keyFile = new File(keyFileURL.toURI()); + logger.debug("Trying to load DB key from file {} created for algorithm {}", keyFile.getAbsolutePath(), keyAlgorithm); + KEY = SymmetricKey.loadKeyFromFile(keyFile, keyAlgorithm); + } catch(Throwable e) { + logger.error("Error loading DB Key", e); + throw new RuntimeException("Error loading DB Key. Unable to continue", e); + } + + logger.info("DB Key has been properly initialized"); } private static boolean initGraphDB() throws Exception { @@ -216,33 +249,48 @@ public class DatabaseEnvironment { OLogManager.instance().setDebugEnabled(false); logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI); - OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD); + OrientDB orientDB = new OrientDB(SERVER_URI, ROOT_USERNAME, ROOT_PASSWORD, OrientDBConfig.defaultConfig()); + /* + OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD); if(!serverAdmin.existsDatabase(DB, STORAGE_MODE)) { - + */ + + if(!orientDB.exists(DB)) { + + logger.info("The database {} does not exist. Going to create it.", DB_URI); - serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE); + //serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE); + orientDB.create(DB, ODatabaseType.PLOCAL); 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(); + */ + + ODatabasePool pool = new ODatabasePool(orientDB,DB, DEFAULT_ADMIN_USERNAME,DEFAULT_ADMIN_PASSWORD); + ODatabaseSession oDatabaseSession = pool.acquire(); + /* Updating DateTimeFormat to be aligned with IS model definition */ /* - * This solution does not work OStorageConfiguration configuration = - * orientGraphNoTx.getRawGraph().getStorage().getConfiguration(); - * configuration.dateTimeFormat = ISConstants.DATETIME_PATTERN; - * configuration.update(); - */ String query = String.format(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, ISConstants.DATETIME_PATTERN); OCommandSQL preparedQuery = new OCommandSQL(query); orientGraphNoTx.getRawGraph().command(preparedQuery).execute(); + */ + Map map = new HashMap<>(); + map.put(DATE_FORMAT_NAME, ISConstants.DATETIME_PATTERN); + oDatabaseSession.command(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, map); - OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); + + //OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); + OMetadata oMetadata = oDatabaseSession.getMetadata(); OSecurity oSecurity = oMetadata.getSecurity(); logger.trace("Changing {} password", DEFAULT_ADMIN_USERNAME); @@ -267,23 +315,38 @@ public class DatabaseEnvironment { OSchema oSchema = oMetadata.getSchema(); OClass oRestricted = oSchema.getClass(O_RESTRICTED_CLASS); + /* OrientVertexType v = orientGraphNoTx.getVertexBaseType(); v.addSuperClass(oRestricted); + */ + OClass v = oSchema.getClass("V"); + v.addSuperClass(oRestricted); + /* OrientEdgeType e = orientGraphNoTx.getEdgeBaseType(); e.addSuperClass(oRestricted); + */ + OClass e = oSchema.getClass("E"); + e.addSuperClass(oRestricted); // orientGraphNoTx.commit(); - orientGraphNoTx.shutdown(); + // orientGraphNoTx.shutdown(); + oDatabaseSession.close(); - factory.close(); + // factory.close(); + pool.close(); return true; } - serverAdmin.close(); + // serverAdmin.close(); + orientDB.close(); return false; } + + public static Key getDatabaseKey() { + return KEY; + } } 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 0c8a30c..c162c2f 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/SchemaActionImpl.java @@ -1,18 +1,18 @@ package org.gcube.informationsystem.resourceregistry.dbinitialization; -import org.gcube.informationsystem.model.impl.utils.discovery.SchemaAction; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.Embedded; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsRelatedTo; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagement; import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; import org.gcube.informationsystem.types.TypeBinder; +import org.gcube.informationsystem.utils.discovery.SchemaAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,16 +74,16 @@ public class SchemaActionImpl implements SchemaAction { } @Override - public void manageEmbeddedClass(Class e) throws Exception { + public

void managePropertyClass(Class

e) throws Exception { try { ((SchemaManagementImpl) schemaManagement).setTypeName(TypeBinder.getType(e)); String json = TypeBinder.serializeType(e); logger.trace(json); - schemaManagement.create(json, AccessType.EMBEDDED); + schemaManagement.create(json, AccessType.PROPERTY); } catch (SchemaAlreadyPresentException sape) { logger.warn("{} already exists. It will be ignored", TypeBinder.getType(e)); } catch(Exception ex) { - logger.error("Error creating schema for {} type {} : {}", Embedded.NAME, e.getSimpleName(), + logger.error("Error creating schema for {} type {} : {}", Property.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 f185966..7e4fd18 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagement.java @@ -14,13 +14,11 @@ import java.util.UUID; import javax.activation.UnsupportedDataTypeException; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.reference.AccessType; import org.gcube.informationsystem.model.reference.ER; import org.gcube.informationsystem.model.reference.ISManageable; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.model.reference.entity.Context; +import org.gcube.informationsystem.model.reference.entities.Context; +import org.gcube.informationsystem.model.reference.properties.Header; import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; @@ -41,7 +39,10 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeType; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; @@ -68,6 +69,8 @@ public abstract class ERManagement { public final String AT = "@"; public final String UNDERSCORE = "_"; + public final static String DELETED = "deleted"; + protected final Set ignoreKeys; protected final Set ignoreStartWithKeys; @@ -134,19 +137,19 @@ public abstract class ERManagement { } } - public void setJSON(JsonNode jsonNode) throws ResourceRegistryException { + public void setJsonNode(JsonNode jsonNode) throws ResourceRegistryException { this.jsonNode = jsonNode; - checkJSON(); + checkJsonNode(); } - public void setJSON(String jsonRepresentation) throws ResourceRegistryException { + public void setJson(String jsonRepresentation) throws ResourceRegistryException { ObjectMapper mapper = new ObjectMapper(); try { this.jsonNode = mapper.readTree(jsonRepresentation); } catch(IOException e) { throw new ResourceRegistryException(e); } - checkJSON(); + checkJsonNode(); } protected OClass getOClass() throws SchemaException, ResourceRegistryException { @@ -186,10 +189,10 @@ public abstract class ERManagement { return elementType; } - protected void checkJSON() throws ResourceRegistryException { + protected void checkJsonNode() throws ResourceRegistryException { if(uuid == null) { try { - uuid = org.gcube.informationsystem.model.impl.utils.Utility.getUUIDFromJsonNode(jsonNode); + uuid = org.gcube.informationsystem.utils.Utility.getUUIDFromJsonNode(jsonNode); } catch(Exception e) { } } else { @@ -237,9 +240,9 @@ public abstract class ERManagement { } } - public JSONObject serializeSelfOnly() throws ResourceRegistryException { + public JsonNode serializeSelfOnly() throws ResourceRegistryException { try { - return toJSONObject(); + return toJsonNode(); } catch(Exception e) { throw new ResourceRegistryException(e); } @@ -247,7 +250,7 @@ public abstract class ERManagement { public abstract String serialize() throws ResourceRegistryException; - public abstract JSONObject serializeAsJson() throws ResourceRegistryException; + public abstract JsonNode serializeAsJson() throws ResourceRegistryException; protected abstract El reallyCreate() throws AlreadyPresentException, ResourceRegistryException; @@ -456,7 +459,8 @@ public abstract class ERManagement { } } - public String createOrUpdate() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { + public String createOrUpdate() + throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { try { orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER); orientGraph.setAutoStartTx(false); @@ -467,7 +471,7 @@ public abstract class ERManagement { getElement(); update = true; element = internalUpdate(); - }catch (NotFoundException e) { + } catch(NotFoundException e) { element = internalCreate(); } @@ -500,8 +504,6 @@ public abstract class ERManagement { } } - - public String create() throws AlreadyPresentException, ResourceRegistryException { try { @@ -606,10 +608,10 @@ public abstract class ERManagement { 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(); + throw new ResourceRegistryException("Error while deleting " + accessType.getName() + " with UUID " + uuid); } + return deleted; } catch(ResourceRegistryException e) { @@ -719,9 +721,12 @@ public abstract class ERManagement { switch(jsonNodeType) { case OBJECT: - return EmbeddedMangement.getEmbeddedType(value); + return PropertyManagement.getPropertyDocument(value); case ARRAY: + /* + * List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354 + */ /* List list = new ArrayList(); Iterator arrayElement = value.elements(); @@ -821,6 +826,15 @@ public abstract class ERManagement { return map; } + /** + * @param oClass + * @param element + * @param jsonNode + * @param ignoreKeys + * @param ignoreStartWithKeys + * @return + * @throws ResourceRegistryException + */ public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, Set ignoreKeys, Set ignoreStartWithKeys) throws ResourceRegistryException { @@ -844,31 +858,33 @@ public abstract class ERManagement { try { Object object = properties.get(key); - if(!oClass.existsProperty(key)) { - - boolean set = false; - - if(object instanceof ODocument) { - ODocument oDocument = (ODocument) object; - ((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED); - set = true; - } - - /* - * if(object instanceof Set){ ((OrientElement) element).setProperty(key, object, - * OType.EMBEDDEDSET); set = true; } if(object instanceof List){ - * ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); set = - * true; } - */ - - if(!set) { - element.setProperty(key, object); - } - - } else { - element.setProperty(key, object); + + boolean set = false; + + if(object instanceof ODocument) { + ODocument oDocument = (ODocument) object; + ((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED); + set = true; } + /* + * List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354 + */ + /* + if(object instanceof Set) { + ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDSET); + set = true; + } + if(object instanceof List) { + ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); + set = true; + } + */ + + if(!set) { + element.setProperty(key, object); + } + } catch(Exception e) { String error = String.format("Error while setting property %s : %s (%s)", key, properties.get(key).toString(), e.getMessage()); @@ -897,13 +913,17 @@ public abstract class ERManagement { return element; } - protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException { + protected JsonNode getPropertyForJson(String key, Object object) throws ResourceRegistryException { try { + if(object instanceof JsonNode) { + return (JsonNode) object; + } + + ObjectMapper objectMapper = new ObjectMapper(); 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; + return Utility.toJsonNode(headerOrient, false); } if(ignoreKeys.contains(key)) { @@ -917,9 +937,8 @@ public abstract class ERManagement { } if(object instanceof ODocument) { - String json = ((ODocument) object).toJSON("class"); - JSONObject jsonObject = new JSONObject(json); - return jsonObject; + ODocument oDocument = (ODocument) object; + return PropertyManagement.getJsonNode(oDocument); } if(object instanceof Date) { @@ -939,21 +958,25 @@ public abstract class ERManagement { break; } - return dateFormat.format((Date) object); + return new TextNode(dateFormat.format((Date) object)); } if(object instanceof Collection) { Collection collection = (Collection) object; - JSONArray jsonArray = new JSONArray(); + ArrayNode arrayNode = objectMapper.createArrayNode(); + for(Object o : collection) { Object obj = getPropertyForJson("PLACEHOLDER", o); - jsonArray.put(obj); + + if(obj!=null) { + arrayNode.add((JsonNode) obj); + } } - return jsonArray; + return arrayNode; } - return object.toString(); + return new TextNode(object.toString()); } catch(Exception e) { throw new ResourceRegistryException( @@ -976,31 +999,30 @@ public abstract class ERManagement { return superClasses; } - public JSONObject toJSONObject() throws ResourceRegistryException { + public JsonNode toJsonNode() throws ResourceRegistryException { try { OrientElement orientElement = (OrientElement) getElement(); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode objectNode = objectMapper.createObjectNode(); Map properties = orientElement.getProperties(); for(String key : orientElement.getPropertyKeys()) { Object object = properties.get(key); - object = getPropertyForJson(key, object); - if(object != null) { - properties.put(key, object); - } else { - properties.remove(key); + JsonNode jsonNode = getPropertyForJson(key, object); + if(jsonNode != null) { + objectNode.replace(key, jsonNode); } } - JSONObject jsonObject = new JSONObject(properties); - String type = orientElement.getRecord().getClassName(); - jsonObject.put(ISManageable.CLASS_PROPERTY, type); + objectNode.put(ISManageable.CLASS_PROPERTY, type); Collection superClasses = getSuperclasses(); - JSONArray jsonArray = new JSONArray(superClasses); - jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray); + ArrayNode arrayNode = objectMapper.valueToTree(superClasses); - return jsonObject; + objectNode.replace(ISManageable.SUPERCLASSES_PROPERTY, arrayNode); + + return objectNode; } catch(ResourceRegistryException e) { throw e; } catch(Exception 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 8586f91..1c4a88a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/ERManagementUtility.java @@ -3,13 +3,13 @@ package org.gcube.informationsystem.resourceregistry.er; import java.util.UUID; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.Embedded; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsRelatedTo; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext; @@ -52,8 +52,8 @@ public class ERManagementUtility { return AccessType.CONSISTS_OF; } else if(oClass.isSubClassOf(IsRelatedTo.NAME)) { return AccessType.IS_RELATED_TO; - } else if(oClass.isSubClassOf(Embedded.NAME)) { - return AccessType.EMBEDDED; + } else if(oClass.isSubClassOf(Property.NAME)) { + return AccessType.PROPERTY; } throw new ResourceRegistryException(type + "is not a base type"); @@ -86,7 +86,7 @@ public class ERManagementUtility { } @SuppressWarnings("rawtypes") - private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, + public static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element) throws ResourceRegistryException { if(element instanceof Vertex) { return getEntityManagement(workingContext, orientGraph, (Vertex) element); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java deleted file mode 100644 index e10b3d7..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/EmbeddedMangement.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.gcube.informationsystem.resourceregistry.er; - -import java.util.HashSet; -import java.util.Set; - -import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.ISManageable; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; -import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; -import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; -import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.JsonNode; -import com.orientechnologies.orient.core.record.impl.ODocument; - -/** - * @author Luca Frosini (ISTI - CNR) - */ -public class EmbeddedMangement { - - private static Logger logger = LoggerFactory.getLogger(EmbeddedMangement.class); - - public static final Set EMBEDDED_IGNORE_KEYS; - public static final Set EMBEDDED_IGNORE_START_WITH_KEYS; - - public static final String AT = "@"; - public static final String UNDERSCORE = "_"; - - 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)) { - // Complex type - String type = ERManagement.getClassProperty(jsonNode); - - try { - SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED); - } catch(SchemaNotFoundException e) { - throw e; - } - - Header header = null; - try { - header = HeaderUtility.getHeader(jsonNode, false); - - } 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) { - throw new ResourceRegistryException("An embedded object cannot have an Header"); - } - - ODocument oDocument = new ODocument(type); - return oDocument.fromJSON(jsonNode.toString()); - - } - - ODocument oDocument = new ODocument(); - return oDocument.fromJSON(jsonNode.toString()); - } -} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/PropertyManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/PropertyManagement.java new file mode 100644 index 0000000..9d26bb6 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/PropertyManagement.java @@ -0,0 +1,180 @@ +package org.gcube.informationsystem.resourceregistry.er; + +import java.security.Key; +import java.util.HashSet; +import java.util.Set; + +import org.gcube.informationsystem.model.impl.properties.EncryptedImpl; +import org.gcube.informationsystem.model.reference.AccessType; +import org.gcube.informationsystem.model.reference.ISManageable; +import org.gcube.informationsystem.model.reference.properties.Encrypted; +import org.gcube.informationsystem.model.reference.properties.Header; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; +import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; +import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl; +import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient; +import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.orientechnologies.orient.core.metadata.schema.OClass; +import com.orientechnologies.orient.core.record.impl.ODocument; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public class PropertyManagement { + + private static Logger logger = LoggerFactory.getLogger(PropertyManagement.class); + + public static final Set PROPERTY_IGNORE_KEYS; + public static final Set PROPERTY_IGNORE_START_WITH_KEYS; + + public static final String AT = "@"; + public static final String UNDERSCORE = "_"; + + static { + PROPERTY_IGNORE_KEYS = new HashSet(); + + PROPERTY_IGNORE_START_WITH_KEYS = new HashSet(); + PROPERTY_IGNORE_START_WITH_KEYS.add(AT); + PROPERTY_IGNORE_START_WITH_KEYS.add(UNDERSCORE); + + } + + public static ODocument getPropertyDocument(JsonNode jsonNode) throws ResourceRegistryException { + ODocument oDocument = null; + if(jsonNode.has(ISManageable.CLASS_PROPERTY)) { + // Complex type + String type = ERManagement.getClassProperty(jsonNode); + OClass oClass = null; + + try { + oClass = SchemaManagementImpl.getTypeSchema(type, AccessType.PROPERTY); + } catch(SchemaNotFoundException e) { + throw e; + } + + try { + Header header = HeaderUtility.getHeader(jsonNode, false); + if(header != null) { + throw new ResourceRegistryException("A property object cannot have an Header"); + } + } catch(Exception e) { + logger.warn("An invalid Header has been provided. Anyway property object cannot have an Header."); + throw new ResourceRegistryException("An property object cannot have an Header"); + } + + + /* + * In case it is an Encrypted type the Value received arrives encrypted with the Context Key + * Resource Registry must decrypt the value with the Context Key and Encrypt it with DB key. + * The opposite operation is done when the value is read by clients. + */ + if(oClass.isSubClassOf(Encrypted.NAME)) { + EncryptedOrient encrypted = new EncryptedOrient(); + oDocument = encrypted; + oDocument.fromJSON(jsonNode.toString()); + try { + String contextEncryptedValue = encrypted.getEncryptedValue(); + + // Decrypting with Context Key (default key) + String decryptedValue = EncryptedImpl.decrypt(contextEncryptedValue); + + + + encrypted.setDecryptedValue(decryptedValue, false); + + /* + // Encrypting with DB Key + Key databaseKey = DatabaseEnvironment.getDatabaseKey(); + String dbEncryptedValue = EncryptedImpl.encrypt(decryptedValue, databaseKey); + + // Setting the value encrypted with DB key + encrypted.setEncryptedValue(dbEncryptedValue); + */ + + } catch(Exception e) { + throw new ResourceRegistryException("Unable to manage "+Encrypted.NAME+" "+org.gcube.informationsystem.model.reference.properties.Property.NAME); + } + return oDocument; + } + + oDocument = new ODocument(type); + } else { + oDocument = new ODocument(); + } + return oDocument.fromJSON(jsonNode.toString()); + } + + + public static JsonNode getJsonNode(ODocument oDocument) throws ResourceRegistryException { + try { + String type = oDocument.getClassName(); + String json = oDocument.toJSON("class"); + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(json); + + + if(type==null) { + return jsonNode; + } + + OClass oClass = SchemaManagementImpl.getTypeSchema(type, AccessType.PROPERTY); + + /* + * In case it is an Encrypted type the value is encrypted with the DB Key + * Resource Registry must decrypt the value with the DB Key and Encrypt it with Context key. + * The opposite operation is done when the value is set from clients. + * see {@link PropertyManagement#getPropertyDocument(JsonNode) getPropertyDocument()} + */ + if(oClass.isSubClassOf(Encrypted.NAME)) { + try { + + EncryptedOrient encrypted = null; + String encryptedValue = (String) oDocument.getProperty(Encrypted.VALUE); + + if(oDocument instanceof EncryptedOrient) { + encrypted = (EncryptedOrient) oDocument; + if(encrypted.getDbEncryptedValue().compareTo(encryptedValue)==0) { + // encrypted.setEncryptedValue(encrypted.getContextEncryptedValue()); + ((ObjectNode) jsonNode).put(Encrypted.VALUE, encrypted.getContextEncryptedValue()); + } + }else { + encrypted = new EncryptedOrient(); + oDocument = (ODocument) encrypted; + + // Decrypting with DB Key + Key databaseKey = DatabaseEnvironment.getDatabaseKey(); + String decryptedValue = EncryptedImpl.decrypt(encryptedValue, databaseKey); + + // encrypted.setDecryptedValue(decryptedValue, true); + + // Encrypting with Context Key (default key) + String contextEncryptedValue = EncryptedImpl.encrypt(decryptedValue); + + // Setting the value encrypted with DB key + //encrypted.setEncryptedValue(contextEncryptedValue); + ((ObjectNode) jsonNode).put(Encrypted.VALUE, contextEncryptedValue); + } + + }catch (Exception e) { + throw new ResourceRegistryException("Errror while managing " + Encrypted.NAME+ " "+ Property.NAME, e); + } + } + + return jsonNode; + + } catch (ResourceRegistryException e) { + throw e; + } catch (Exception e) { + throw new ResourceRegistryException(e); + } + } +} 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 dff45c2..eb4a6de 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 @@ -6,15 +6,13 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Header; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; @@ -28,6 +26,11 @@ import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.utils.Utility; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; @@ -105,18 +108,17 @@ public abstract class EntityManagement extends ERManagement extends ERManagement iterable = orientGraph.getVerticesOfClass(elementType, polymorphic); for(Vertex vertex : iterable) { @SuppressWarnings("rawtypes") EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); try { - JSONObject jsonObject = entityManagement.serializeAsJson(); - jsonArray.put(jsonObject); + JsonNode jsonNode = entityManagement.serializeAsJson(); + arrayNode.add(jsonNode); } 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(); + try { + return objectMapper.writeValueAsString(arrayNode); + } catch(JsonProcessingException e) { + throw new ResourceRegistryException(e); + } } public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, Direction direction, boolean polymorphic, Map constraint) throws ResourceRegistryException { - JSONArray jsonArray = new JSONArray(); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode arrayNode = objectMapper.createArrayNode(); Iterable references = null; @@ -313,8 +322,8 @@ public abstract class EntityManagement extends ERManagement extends ERManagement constraint) throws ResourceRegistryException { - JSONArray jsonArray = new JSONArray(); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode arrayNode = objectMapper.createArrayNode(); if(referenceUUID != null) { constraint.put(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY, referenceUUID.toString()); @@ -418,15 +433,19 @@ public abstract class EntityManagement extends ERManagement { } @Override - public JSONObject serializeAsJson() throws ResourceRegistryException { + public JsonNode serializeAsJson() throws ResourceRegistryException { return serializeSelfOnly(); } 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 2ec3181..5825740 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 @@ -2,11 +2,10 @@ package org.gcube.informationsystem.resourceregistry.er.entity; import java.util.Iterator; -import org.codehaus.jettison.json.JSONObject; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsRelatedTo; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAlreadyPresentException; @@ -63,9 +62,9 @@ public class ResourceManagement extends EntityManagement { @SuppressWarnings("unchecked") @Override - public JSONObject serializeAsJson() throws ResourceRegistryException { + public JsonNode serializeAsJson() throws ResourceRegistryException { - JSONObject sourceResource = serializeSelfOnly(); + JsonNode sourceResource = serializeSelfOnly(); /* * Cannot get ConsistsOf edge only because is not polymorphic for a @@ -95,7 +94,7 @@ public class ResourceManagement extends EntityManagement { if(relationManagement instanceof ConsistsOfManagement) { try { - JSONObject consistsOf = relationManagement.serializeAsJson(true, true); + JsonNode consistsOf = relationManagement.serializeAsJson(true, true); sourceResource = addConsistsOf(sourceResource, consistsOf); } catch(ResourceRegistryException e) { logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); @@ -110,7 +109,7 @@ public class ResourceManagement extends EntityManagement { * 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 + * else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ JsonNode * isRelatedTo = relationManagement.serializeAsJson(true, true); sourceResource * = addIsRelatedTo(sourceResource, isRelatedTo); } */ @@ -119,12 +118,12 @@ public class ResourceManagement extends EntityManagement { return sourceResource; } - public static JSONObject addConsistsOf(JSONObject sourceResource, JSONObject consistsOf) + public static JsonNode addConsistsOf(JsonNode sourceResource, JsonNode consistsOf) throws ResourceRegistryException { return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter()); } - public static JSONObject addIsRelatedTo(JSONObject sourceResource, JSONObject isRelatedTo) + public static JsonNode addIsRelatedTo(JsonNode sourceResource, JsonNode isRelatedTo) throws ResourceRegistryException { return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter()); } @@ -139,7 +138,7 @@ public class ResourceManagement extends EntityManagement { JsonNode jsonNodeArray = jsonNode.get(property); for(JsonNode consistOfJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); - com.setJSON(consistOfJsonNode); + com.setJsonNode(consistOfJsonNode); com.setSourceEntityManagement(this); com.internalCreate(); addToRelationManagement(com); @@ -151,7 +150,7 @@ public class ResourceManagement extends EntityManagement { JsonNode jsonNodeArray = jsonNode.get(property); for(JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); - irtm.setJSON(relationJsonNode); + irtm.setJsonNode(relationJsonNode); irtm.setSourceEntityManagement(this); irtm.internalCreate(); addToRelationManagement(irtm); @@ -171,7 +170,7 @@ public class ResourceManagement extends EntityManagement { JsonNode jsonNodeArray = jsonNode.get(property); for(JsonNode relationJsonNode : jsonNodeArray) { ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); - com.setJSON(relationJsonNode); + com.setJsonNode(relationJsonNode); com.internalCreateOrUdate(); addToRelationManagement(com); } @@ -182,7 +181,7 @@ public class ResourceManagement extends EntityManagement { JsonNode jsonNodeArray = jsonNode.get(property); for(JsonNode relationJsonNode : jsonNodeArray) { IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); - irtm.setJSON(relationJsonNode); + irtm.setJsonNode(relationJsonNode); irtm.internalUpdate(); addToRelationManagement(irtm); } @@ -242,100 +241,4 @@ public class ResourceManagement extends EntityManagement { } } - /* - public String reallyGetAll(boolean polymorphic, Map constraint) throws ResourceRegistryException { - JSONArray jsonArray = new JSONArray(); - - String consistsOfType = constraint.get(ConsistsOf.NAME); - constraint.remove(ConsistsOf.NAME); - String facetType = constraint.get(Facet.NAME); - constraint.remove(Facet.NAME); - - // TODO check types - - /* - * SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT - * FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor')) - * - * WHERE @class='EService' // Only is not polymorphic - * / - - boolean first = true; - - StringBuilder selectStringBuilder = new StringBuilder("SELECT FROM (TRAVERSE inE('"); - selectStringBuilder.append(consistsOfType); - selectStringBuilder.append("'), outV('"); - selectStringBuilder.append(erType); - selectStringBuilder.append("') FROM (SELECT FROM "); - selectStringBuilder.append(facetType); - for(String key : constraint.keySet()) { - if(first) { - selectStringBuilder.append(" WHERE "); - first = false; - } else { - selectStringBuilder.append(" AND "); - } - selectStringBuilder.append(key); - selectStringBuilder.append("="); - String value = constraint.get(key).trim(); - selectStringBuilder.append("'"); - selectStringBuilder.append(value); - selectStringBuilder.append("'"); - } - selectStringBuilder.append(" ))"); - - 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(); - - for(Element element : elements) { - - if(polymorphic) { - OrientVertexType orientVertexType = null; - try { - OrientElement orientElement = ((OrientElement) element); - 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); - logger.error(error, e); - throw new ResourceRegistryException(error); - } - - if(orientVertexType.getName().compareTo(erType) != 0) { - if(!orientVertexType.isSubClassOf(erType)) { - continue; - } - } - - } - - Vertex vertex = (Vertex) element; - - @SuppressWarnings("rawtypes") - EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), - orientGraph, vertex); - try { - JSONObject jsonObject = entityManagement.serializeAsJson(); - jsonArray.put(jsonObject); - } 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 3c3e331..8a180e7 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,11 +1,11 @@ package org.gcube.informationsystem.resourceregistry.er.relation; -import org.gcube.informationsystem.model.impl.embedded.PropagationConstraintImpl; +import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.AddConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException; diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/IsRelatedToManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/IsRelatedToManagement.java index 19d418a..b147061 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/IsRelatedToManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/er/relation/IsRelatedToManagement.java @@ -1,11 +1,11 @@ package org.gcube.informationsystem.resourceregistry.er.relation; -import org.gcube.informationsystem.model.impl.embedded.PropagationConstraintImpl; +import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.AddConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.relation.IsRelatedTo; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException; 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 e8adb41..745dfea 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 @@ -6,17 +6,14 @@ import java.util.Iterator; import java.util.Map; import java.util.UUID; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONObject; -import org.gcube.informationsystem.model.impl.utils.ISMapper; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.AddConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; @@ -32,8 +29,13 @@ import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.utils.PropagationConstraintOrient; import org.gcube.informationsystem.resourceregistry.utils.Utility; +import org.gcube.informationsystem.utils.ISMapper; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.tinkerpop.blueprints.Direction; @@ -140,22 +142,22 @@ 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); + JsonNode sourceResource = visitedSourceResources.get(id); ResourceManagement resourceManagement = null; if(sourceResource == null) { @@ -265,7 +267,7 @@ public abstract class RelationManagement serializeEdges(Iterable edges, boolean postFilterPolymorphic) + protected Collection serializeEdges(Iterable edges, boolean postFilterPolymorphic) throws ResourceRegistryException { - Map visitedSourceResources = new HashMap<>(); + Map visitedSourceResources = new HashMap<>(); for(Edge edge : edges) { if(postFilterPolymorphic && edge.getLabel().compareTo(elementType) != 0) { continue; @@ -559,59 +561,23 @@ public abstract class RelationManagement list) { - JSONArray jsonArray = new JSONArray(list); - return jsonArray.toString(); + protected String serializeJsonNodeCollectionAsString(Collection collection) throws ResourceRegistryException { + try { + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode arrayNode = objectMapper.valueToTree(collection); + return objectMapper.writeValueAsString(arrayNode); + } catch(Exception e) { + throw new ResourceRegistryException(e); + } } @Override public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { Iterable edges = orientGraph.getEdgesOfClass(elementType, polymorphic); - Collection collection = serializeEdges(edges, false); - return serializeJSONObjectList(collection); + Collection collection = serializeEdges(edges, false); + return serializeJsonNodeCollectionAsString(collection); } - /* - public String reallyGetAllFrom(UUID uuid, String type, Direction direction, boolean polymorphic) - throws ResourceRegistryException { - EntityManagement entityManagement = null; - try { - entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), - orientGraph, uuid); - } catch(ResourceRegistryException e) { - throw 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, String type, Direction direction, boolean polymorphic) throws ResourceRegistryException { - try { - orientGraph = getWorkingContext().getGraph(PermissionMode.READER); - - return reallyGetAllFrom(uuid,type, direction, polymorphic); - } catch(ResourceRegistryException e) { - throw e; - } catch(Exception e) { - throw new ResourceRegistryException(e); - } finally { - if(orientGraph != null) { - orientGraph.shutdown(); - } - } - } - */ - @Override public boolean addToContext(UUID contextUUID) throws NotFoundException, ContextException { logger.debug("Going to add {} with UUID {} to Context with UUID {}", accessType.getName(), uuid, contextUUID); 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 5d1f63f..f5b232e 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/query/Query.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/query/Query.java @@ -15,7 +15,7 @@ public interface Query { * @throws InvalidQueryException * 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, boolean raw) 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 c3f3262..e64ff6d 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/query/QueryImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/query/QueryImpl.java @@ -1,21 +1,24 @@ package org.gcube.informationsystem.resourceregistry.query; -import java.io.StringWriter; -import java.io.Writer; -import java.util.List; - +import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; 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.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.utils.Utility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +import com.tinkerpop.blueprints.Element; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; /** * @author Luca Frosini (ISTI - CNR) @@ -25,18 +28,20 @@ public class QueryImpl implements Query { private static Logger logger = LoggerFactory.getLogger(QueryImpl.class); @Override - public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException { + public String query(String query, Integer limit, String fetchPlan, boolean raw) throws InvalidQueryException { if(limit == null) { limit = AccessPath.DEFAULT_LIMIT; } limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit; - ODatabaseDocumentTx oDatabaseDocumentTx = null; + OrientGraph orientGraph = null; try { SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); - oDatabaseDocumentTx = securityContext.getDatabaseDocumentTx(PermissionMode.READER); + orientGraph = securityContext.getGraph(PermissionMode.READER); + orientGraph.setAutoStartTx(false); + orientGraph.begin(); OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery<>(query, limit); osqlSynchQuery.setFetchPlan(fetchPlan); @@ -45,26 +50,38 @@ public class QueryImpl implements Query { logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(), osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit()); - List records = oDatabaseDocumentTx.query(osqlSynchQuery); + Iterable elements = orientGraph.command(osqlSynchQuery).execute(); - Writer writer = new StringWriter(); - writer.append("{\"result\":["); - for(int i = 0; i < records.size(); i++) { - ODocument oDocument = (ODocument) records.get(i); - writer.append(Utility.toJsonString(oDocument, false)); - if(i < (records.size() - 1)) { - writer.append(","); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode arrayNode = objectMapper.createArrayNode(); + + + for(Element element : elements) { + try { + JsonNode jsonNode = null; + if(raw) { + jsonNode = Utility.toJsonNode(element, false); + } else { + @SuppressWarnings("rawtypes") + ERManagement erManagement = ERManagementUtility.getERManagement(securityContext, orientGraph, + element); + jsonNode = erManagement.serializeAsJson(); + } + arrayNode.add(jsonNode); + + } catch(ResourceRegistryException e) { + logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", + element.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); } } - writer.append("]}"); - return writer.toString(); + return objectMapper.writeValueAsString(arrayNode); } catch(Exception e) { throw new InvalidQueryException(e.getMessage()); } finally { - if(oDatabaseDocumentTx != null) { - oDatabaseDocumentTx.close(); + if(orientGraph != null) { + orientGraph.shutdown(); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java index 48e5888..2511b0b 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/Access.java @@ -24,7 +24,7 @@ import javax.ws.rs.core.UriInfo; import org.gcube.common.authorization.library.provider.CalledMethodProvider; import org.gcube.common.gxhttp.reference.GXConnection.HTTPMETHOD; -import org.gcube.informationsystem.model.reference.entity.Resource; +import org.gcube.informationsystem.model.reference.entities.Resource; import org.gcube.informationsystem.resourceregistry.ResourceInitializer; import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; @@ -104,7 +104,7 @@ public class Access { @Path(AccessPath.CONTEXTS_PATH_PART) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) public String getAllContexts() throws ResourceRegistryException { - logger.info("Requested to read all {}s", org.gcube.informationsystem.model.reference.entity.Context.NAME); + logger.info("Requested to read all {}s", org.gcube.informationsystem.model.reference.entities.Context.NAME); setCalledMethodLocal(HTTPMETHOD.GET, AccessPath.CONTEXTS_PATH_PART); ContextManagement contextManagement = new ContextManagement(); return contextManagement.all(false); @@ -123,7 +123,7 @@ public class Access { if(uuid.compareTo(AccessPath.CURRENT_CONTEXT)==0){ uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString(); } - logger.info("Requested to read {} with id {} ", org.gcube.informationsystem.model.reference.entity.Context.NAME, uuid); + logger.info("Requested to read {} with id {} ", org.gcube.informationsystem.model.reference.entities.Context.NAME, uuid); List pathValues = new ArrayList<>(); pathValues.add(AccessPath.CONTEXTS_PATH_PART); @@ -279,13 +279,14 @@ 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) @DefaultValue(AccessPath.DEFAULT_FETCH_PLAN) String fetchPlan) + @QueryParam(AccessPath.FETCH_PLAN_PARAM) @DefaultValue(AccessPath.DEFAULT_FETCH_PLAN_PARAM) String fetchPlan, + @QueryParam(AccessPath.RAW_PARAM) @DefaultValue(AccessPath.DEFAULT_RAW_PARAM) Boolean raw) throws InvalidQueryException { - logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query); + logger.info("Requested query (fetch plan {}, limit : {}, Raw : raw):\n{}", fetchPlan, limit, query, raw); setCalledMethodLocal(HTTPMETHOD.GET, AccessPath.QUERY_PATH_PART); Query queryManager = new QueryImpl(); - return queryManager.query(query, limit, fetchPlan); + return queryManager.query(query, limit, fetchPlan, raw); } /* 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 c600eb5..faf2cc5 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ContextManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/ContextManager.java @@ -12,9 +12,11 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; import org.gcube.common.gxhttp.reference.GXConnection.HTTPMETHOD; -import org.gcube.informationsystem.model.reference.entity.Context; +import org.gcube.informationsystem.model.reference.entities.Context; import org.gcube.informationsystem.resourceregistry.ResourceInitializer; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; @@ -104,26 +106,27 @@ public class ContextManager { ContextManagement contextManagement = new ContextManagement(); contextManagement.setUUID(UUID.fromString(uuid)); - contextManagement.setJSON(json); + contextManagement.setJson(json); return contextManagement.createOrUpdate(); } /* * DELETE /contexts/{UUID} * e.g. DELETE /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0 - * */ @DELETE @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8}) @Path("{" + AccessPath.CONTEXT_UUID_PATH_PARAM + "}") - public boolean delete(@PathParam(AccessPath.CONTEXT_UUID_PATH_PARAM) String uuid) + public Response delete(@PathParam(AccessPath.CONTEXT_UUID_PATH_PARAM) String uuid) throws ContextNotFoundException, ResourceRegistryException { logger.info("Requested to delete {} with id {} ", Context.NAME, uuid); setCalledMethod(HTTPMETHOD.DELETE, uuid); ContextManagement contextManagement = new ContextManagement(); contextManagement.setUUID(UUID.fromString(uuid)); - return contextManagement.delete(); + contextManagement.delete(); + + return Response.status(Status.NO_CONTENT).build(); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/InstancesManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/InstancesManager.java index bdc4cb9..02fa89e 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/InstancesManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/InstancesManager.java @@ -159,7 +159,7 @@ public class InstancesManager { ERManagement erManagement = ERManagementUtility.getERManagement(type); erManagement.setUUID(UUID.fromString(uuid)); erManagement.setElementType(type); - erManagement.setJSON(json); + erManagement.setJson(json); return erManagement.createOrUpdate(); } @@ -171,7 +171,7 @@ public class InstancesManager { */ @DELETE @Path("/{" + AccessPath.TYPE_PATH_PARAM + "}" + "/{" + AccessPath.UUID_PATH_PARAM + "}") - public boolean delete(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, + public Response delete(@PathParam(AccessPath.TYPE_PATH_PARAM) String type, @PathParam(AccessPath.UUID_PATH_PARAM) String uuid) throws ResourceRegistryException { logger.info("Requested to delete {} with id {}", type, uuid); setCalledMethod(HTTPMETHOD.DELETE, type, true); @@ -179,7 +179,9 @@ public class InstancesManager { @SuppressWarnings("rawtypes") ERManagement erManagement = ERManagementUtility.getERManagement(type); erManagement.setUUID(UUID.fromString(uuid)); - return erManagement.delete(); + erManagement.delete(); + + return Response.status(Status.NO_CONTENT).build(); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SharingManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SharingManagement.java index bcb1129..f365456 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SharingManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/rest/SharingManagement.java @@ -8,9 +8,11 @@ import javax.ws.rs.DELETE; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; import org.gcube.common.gxhttp.reference.GXConnection.HTTPMETHOD; -import org.gcube.informationsystem.model.reference.entity.Context; +import org.gcube.informationsystem.model.reference.entities.Context; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; @@ -77,15 +79,15 @@ public class SharingManagement { /* * DELETE /sharing/{CONTEXT_UUID}/{TYPE_NAME}/{UUID} * e.g DELETE - * /resource-registry/sharing/67062c11-9c3a-4906-870d-7df6a43408b0/HostingNode/16032d09-3823-444e-a1ff-a67de4f350a8 - * Where 67062c11-9c3a-4906-870d-7df6a43408b0/ is the Context UUID + * /resource-registry/sharing/contexts/67062c11-9c3a-4906-870d-7df6a43408b0/HostingNode/16032d09-3823-444e-a1ff-a67de4f350a8 + * Where 67062c11-9c3a-4906-870d-7df6a43408b0 is the Context UUID * and 16032d09-3823-444e-a1ff-a67de4f350a8 is the HostingNode UUID * */ @DELETE @Path(SharingPath.CONTEXTS_PATH_PART + "/{" + AccessPath.CONTEXT_UUID_PATH_PARAM + "}" + "/{" + AccessPath.TYPE_PATH_PARAM + "}" + "/{" + AccessPath.UUID_PATH_PARAM + "}") - public boolean remove(@PathParam(AccessPath.CONTEXT_UUID_PATH_PARAM) String contextId, + public Response remove(@PathParam(AccessPath.CONTEXT_UUID_PATH_PARAM) String contextId, @PathParam(AccessPath.TYPE_PATH_PARAM) String type, @PathParam(AccessPath.UUID_PATH_PARAM) String id) throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { logger.info("Requested to remove {} with UUID {} to {} with UUID {}", type, id, Context.NAME, contextId); @@ -108,7 +110,9 @@ public class SharingManagement { throw new ResourceRegistryException(e); } - return erManagement.removeFromContext(contextUUID); + erManagement.removeFromContext(contextUUID); + + return Response.status(Status.NO_CONTENT).build(); } } 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 b9de0b6..d763f25 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaContextManagement.java @@ -3,9 +3,9 @@ package org.gcube.informationsystem.resourceregistry.schema; import java.util.Iterator; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.Embedded; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.model.reference.relations.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.ContextUtility; @@ -79,7 +79,7 @@ public class SchemaContextManagement implements SchemaManagement { orientEdge.setProperty(SCHEMA, json); orientEdge.save(); - } else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) { + } else if(Property.class.isAssignableFrom(baseType.getTypeClass())) { ODocument doc = new ODocument(typeDefinition.getName()); doc.field(SCHEMA, json); doc.save(); 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 fcb7981..95f549b 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImpl.java @@ -7,14 +7,18 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import javax.activation.UnsupportedDataTypeException; import org.gcube.informationsystem.model.reference.AccessType; -import org.gcube.informationsystem.model.reference.embedded.Embedded; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaCreationException; @@ -24,12 +28,13 @@ import org.gcube.informationsystem.resourceregistry.context.ContextUtility; 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.PropertyDefinition; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; +import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.exception.OSchemaException; import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.schema.OClass; @@ -38,9 +43,7 @@ import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; -import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientElementType; -import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; /** * @author Luca Frosini (ISTI - CNR) @@ -63,9 +66,9 @@ public class SchemaManagementImpl implements SchemaManagement { this.typeName = typeName; } - public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, String type, AccessType accessType) + public static OClass getTypeSchema(ODatabaseSession oDatabaseSession, String type, AccessType accessType) throws SchemaException { - OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata(); + OMetadata oMetadata = oDatabaseSession.getMetadata(); OSchema oSchema = oMetadata.getSchema(); return getTypeSchema(oSchema, type, accessType); } @@ -89,22 +92,38 @@ public class SchemaManagementImpl implements SchemaManagement { } } + + + public static OClass getTypeSchema(String type, AccessType accessType) throws SchemaException, ResourceRegistryException { - OrientGraphNoTx orientGraphNoTx = null; + // TODO Add a Type cache try { - 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) { - throw e; - } finally { - if(orientGraphNoTx != null) { - orientGraphNoTx.shutdown(); - } + ExecutorService es = Executors.newSingleThreadExecutor(); + Future result = es.submit(new Callable() { + public OClass call() throws Exception { + ODatabaseSession oDatabaseSession = null; + try { + logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type); + + AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); + oDatabaseSession = adminSecurityContext.getDatabaseSession(PermissionMode.READER); + + return getTypeSchema(oDatabaseSession, type, accessType); + } catch(ResourceRegistryException e) { + throw e; + }catch(Exception e) { + throw new ResourceRegistryException(e); + } finally { + if(oDatabaseSession != null) { + oDatabaseSession.close(); + } + } + } + }); + return result.get(); + } catch(Exception e) { + throw new ResourceRegistryException(e); } } @@ -128,7 +147,7 @@ public class SchemaManagementImpl implements SchemaManagement { } } - protected List getSuperclassesAndCheckCompliancy(OrientGraphNoTx orientGraphNoTx, + protected List getSuperclassesAndCheckCompliancy(ODatabaseSession oDatabaseSession, TypeDefinition typeDefinition, String baseType) throws SchemaException { Set superClasses = typeDefinition.getSuperClasses(); @@ -140,7 +159,7 @@ public class SchemaManagementImpl implements SchemaManagement { } } - OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); + OMetadata oMetadata = oDatabaseSession.getMetadata(); OSchema oSchema = oMetadata.getSchema(); List oSuperclasses = new ArrayList<>(); @@ -165,7 +184,7 @@ public class SchemaManagementImpl implements SchemaManagement { protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException { - OrientGraphNoTx orientGraphNoTx = null; + ODatabaseSession oDatabaseSession = null; try { logger.info("Trying to register {} {}", baseType.getName(), jsonSchema); @@ -179,17 +198,17 @@ public class SchemaManagementImpl implements SchemaManagement { AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER); + oDatabaseSession = adminSecurityContext.getDatabaseSession(PermissionMode.WRITER); - OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); + OMetadata oMetadata = oDatabaseSession.getMetadata(); OSchema oSchema = oMetadata.getSchema(); OClass oClass = null; if(Entity.class.isAssignableFrom(baseType.getTypeClass())) { - oClass = orientGraphNoTx.createVertexType(typeDefinition.getName()); + oClass = oDatabaseSession.createVertexClass(typeDefinition.getName()); } else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) { - oClass = orientGraphNoTx.createEdgeType(typeDefinition.getName()); + oClass = oDatabaseSession.createEdgeClass(typeDefinition.getName()); /* * This information are persisted in Management Context String outBaseType = @@ -197,19 +216,20 @@ public class SchemaManagementImpl implements SchemaManagement { * typeDefinition.getInBaseType(); */ - } else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) { + } else if(Property.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); + Entity.NAME, Relation.NAME, Property.NAME); throw new SchemaCreationException(error); } try { - if(typeDefinition.getDescription() != null) { + String description = typeDefinition.getDescription(); + if(description!=null && description.compareTo("")!=0) { try { - oClass.setDescription(typeDefinition.getDescription()); + oClass.setDescription(description); } catch(Exception e) { logger.warn( "Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065"); @@ -226,21 +246,21 @@ public class SchemaManagementImpl implements SchemaManagement { typeDefinition.getName()); } - if(typeDefinition.getName().compareTo(Embedded.NAME) != 0) { - List oSuperclasses = getSuperclassesAndCheckCompliancy(orientGraphNoTx, typeDefinition, + if(typeDefinition.getName().compareTo(Property.NAME) != 0) { + List oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseSession, typeDefinition, baseType.getName()); oClass.setSuperClasses(oSuperclasses); } if(Resource.class.isAssignableFrom(baseType.getTypeClass())) { - Set properties = typeDefinition.getProperties(); - if(properties != null && properties.size() > 0) { + Set propertyDefinitions = typeDefinition.getProperties(); + if(propertyDefinitions != null && propertyDefinitions.size() > 0) { throw new SchemaCreationException("A Resource cannot contains any properties."); } } else { - for(Property property : typeDefinition.getProperties()) { + for(PropertyDefinition propertyDefinition : typeDefinition.getProperties()) { - OType oType = OType.getById(property.getType().byteValue()); + OType oType = OType.getById(propertyDefinition.getType().byteValue()); switch(oType) { case EMBEDDEDLIST: throw new UnsupportedDataTypeException(oType.name() @@ -252,8 +272,8 @@ public class SchemaManagementImpl implements SchemaManagement { break; } - OProperty op = oClass.createProperty(property.getName(), oType); - op.setDescription(property.getDescription()); + OProperty op = oClass.createProperty(propertyDefinition.getName(), oType); + op.setDescription(propertyDefinition.getDescription()); /* * Mandatory and notNull does not work in distributed mode: so that on Type @@ -265,23 +285,23 @@ public class SchemaManagementImpl implements SchemaManagement { op.setMandatory(false); op.setNotNull(false); - op.setReadonly(property.isReadonly()); - op.setRegexp(property.getRegexp()); + op.setReadonly(propertyDefinition.isReadonly()); + op.setRegexp(propertyDefinition.getRegexp()); - if(property.getLinkedClass() != null) { - OClass linkedClass = getOClass(oSchema, property.getLinkedClass()); + if(propertyDefinition.getLinkedClass() != null) { + OClass linkedClass = getOClass(oSchema, propertyDefinition.getLinkedClass()); if(linkedClass == null) { - logger.trace("class {} not found in schema", property.getLinkedClass()); - throw new Exception("class " + property.getLinkedClass() + " not found in schema"); + logger.trace("class {} not found in schema", propertyDefinition.getLinkedClass()); + throw new Exception("class " + propertyDefinition.getLinkedClass() + " not found in schema"); } if(linkedClass.isEdgeType() || linkedClass.isVertexType()) { - throw new Exception("An Embedded Field cannot be an Entity or a Relation"); + throw new Exception("A Property 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(propertyDefinition.getLinkedType() != null) { + op.setLinkedType(OType.getById(propertyDefinition.getLinkedType().byteValue())); } } } @@ -315,19 +335,19 @@ public class SchemaManagementImpl implements SchemaManagement { } catch(Exception ex) { throw new SchemaCreationException(ex); } finally { - if(orientGraphNoTx != null) { - orientGraphNoTx.shutdown(); + if(oDatabaseSession != null) { + oDatabaseSession.close(); } } } protected String getSchema(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { - OrientGraphNoTx orientGraphNoTx = null; + ODatabaseSession oDatabaseSession = null; try { AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); - orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER); + oDatabaseSession = adminSecurityContext.getDatabaseSession(PermissionMode.WRITER); - OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); + OMetadata oMetadata = oDatabaseSession.getMetadata(); OSchema oSchema = oMetadata.getSchema(); OClass baseOClass = getTypeSchema(oSchema, type, null); @@ -341,20 +361,14 @@ public class SchemaManagementImpl implements SchemaManagement { } } - /* - * Collection oClasses = oSchema.getClasses(); for (OClass oClass : - * oClasses) { if (oClass.isSubClassOf(baseOClass)) { - * typeDefinitions.add(getTypeDefinition(oClass)); } } - */ - return TypeBinder.serializeTypeDefinitions(typeDefinitions); } catch(SchemaException e) { throw e; } catch(Exception e) { throw new SchemaException(e); } finally { - if(orientGraphNoTx != null) { - orientGraphNoTx.shutdown(); + if(oDatabaseSession != null) { + oDatabaseSession.close(); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java new file mode 100644 index 0000000..6ed35b6 --- /dev/null +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/EncryptedOrient.java @@ -0,0 +1,74 @@ +package org.gcube.informationsystem.resourceregistry.utils; + +import java.security.Key; + +import org.gcube.informationsystem.model.impl.properties.EncryptedImpl; +import org.gcube.informationsystem.model.reference.properties.Encrypted; +import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; + +import com.orientechnologies.orient.core.record.impl.ODocument; + +/** + * @author Luca Frosini (ISTI - CNR) + */ +public class EncryptedOrient extends ODocument implements org.gcube.informationsystem.model.reference.properties.Encrypted { + + protected String decryptedValue; + protected String dbEncryptedValue; + protected String contextEncryptedValue; + + public EncryptedOrient() { + super(Encrypted.NAME); + } + + protected EncryptedOrient(String iClassName) { + super(iClassName); + } + + @Override + public String getEncryptedValue() { + return this.field(Encrypted.VALUE); + } + + @Override + public void setEncryptedValue(String encryptedValue) { + this.field(Encrypted.VALUE, encryptedValue); + } + + @Override + public String toJSON(String iFormat) { + return super.toJSON(iFormat); + } + + + public String getDecryptedValue() { + return decryptedValue; + } + + public String getDbEncryptedValue() { + return dbEncryptedValue; + } + + public String getContextEncryptedValue() { + return contextEncryptedValue; + } + + public void setDecryptedValue(String decryptedValue, boolean setEncryptedForContext) throws Exception { + this.decryptedValue = decryptedValue; + + // Encrypting with DB Key + Key databaseKey = DatabaseEnvironment.getDatabaseKey(); + this.dbEncryptedValue = EncryptedImpl.encrypt(decryptedValue, databaseKey); + + // Encrypting with Context Key (default key) + this.contextEncryptedValue = EncryptedImpl.encrypt(decryptedValue); + + + if(setEncryptedForContext) { + setEncryptedValue(contextEncryptedValue); + }else { + setEncryptedValue(dbEncryptedValue); + } + + } +} 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 fc9e5d6..b593c37 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderOrient.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderOrient.java @@ -3,14 +3,14 @@ package org.gcube.informationsystem.resourceregistry.utils; import java.util.Date; import java.util.UUID; -import org.gcube.informationsystem.model.reference.embedded.Header; +import org.gcube.informationsystem.model.reference.properties.Header; import com.orientechnologies.orient.core.record.impl.ODocument; /** * @author Luca Frosini (ISTI - CNR) */ -public class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.reference.embedded.Header { +public class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.reference.properties.Header { public HeaderOrient() { super(Header.NAME); 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 20d84a8..3902e7f 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/HeaderUtility.java @@ -9,10 +9,10 @@ import java.util.UUID; import org.gcube.common.authorization.library.provider.AuthorizationProvider; import org.gcube.common.authorization.library.provider.ClientInfo; import org.gcube.common.authorization.library.utils.Caller; -import org.gcube.informationsystem.model.impl.utils.ISMapper; import org.gcube.informationsystem.model.reference.ER; -import org.gcube.informationsystem.model.reference.embedded.Header; +import org.gcube.informationsystem.model.reference.properties.Header; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; +import org.gcube.informationsystem.utils.ISMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +31,7 @@ public class HeaderUtility { private static final Logger logger = LoggerFactory.getLogger(HeaderUtility.class); public static String getUser() { - String user = org.gcube.informationsystem.model.reference.embedded.Header.UNKNOWN_USER; + String user = org.gcube.informationsystem.model.reference.properties.Header.UNKNOWN_USER; try { Caller caller = AuthorizationProvider.instance.get(); if(caller != null) { @@ -127,7 +127,7 @@ public class HeaderUtility { } public static Header getHeader(Element element) throws ResourceRegistryException { - return Utility.getEmbedded(Header.class, element, ER.HEADER_PROPERTY); + return Utility.getPropertyDocument(Header.class, element, ER.HEADER_PROPERTY); } public static void updateModifiedByAndLastUpdate(Element element) throws ResourceRegistryException { diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java index b8c7bc9..9871d84 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/PropagationConstraintOrient.java @@ -1,13 +1,13 @@ package org.gcube.informationsystem.resourceregistry.utils; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; import com.orientechnologies.orient.core.record.impl.ODocument; /** * @author Luca Frosini (ISTI - CNR) */ -public class PropagationConstraintOrient extends ODocument implements org.gcube.informationsystem.model.reference.embedded.PropagationConstraint { +public class PropagationConstraintOrient extends ODocument implements org.gcube.informationsystem.model.reference.properties.PropagationConstraint { public PropagationConstraintOrient() { super(PropagationConstraint.NAME); 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 43d95e6..90d6f00 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java @@ -1,25 +1,23 @@ package org.gcube.informationsystem.resourceregistry.utils; -import java.util.HashSet; import java.util.Iterator; -import java.util.Set; import java.util.UUID; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.reference.embedded.Embedded; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.properties.Header; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode; +import org.gcube.informationsystem.utils.ISMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; @@ -30,8 +28,6 @@ import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONUtility; /** * @author Luca Frosini (ISTI - CNR) @@ -42,19 +38,26 @@ public class Utility { 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 JsonNode toJsonNode(Element element, boolean raw) throws ResourceRegistryException { + ORecord oRecord = ((OrientElement) element).getRecord(); + return Utility.toJsonNode(oRecord, raw); + } + + public static JsonNode toJsonNode(ORecord oRecord, boolean raw) throws ResourceRegistryException { try { - return new JSONObject(toJsonString(element, raw)); + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.readTree(toJsonString(oRecord, raw)); } 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(Element element, boolean raw) { + ORecord oRecord = ((OrientElement) element).getRecord(); + return Utility.toJsonString(oRecord, raw); } + public static String toJsonString(ORecord oRecord, boolean raw) { if(raw) { return oRecord.toJSON(); @@ -62,28 +65,6 @@ public class Utility { return oRecord.toJSON("class"); } - 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("_")) { - keys.remove(key); - } - } - return GraphSONUtility.jsonFromElement(element, keys, GraphSONMode.EXTENDED); - } - } - - public static String toJsonString(Element element, boolean raw) { - try { - return toJsonObject(element, true).toString(); - } catch(Exception e) { - return String.valueOf(element); - } - } - public static El getElementByUUIDAsAdmin(String elementType, UUID uuid, Class clz) throws NotFoundException, ResourceRegistryException { OrientGraphNoTx orientGraphNoTx = null; @@ -126,7 +107,7 @@ public class Utility { Iterator iterator = elements.iterator(); El element = iterator.next(); - logger.trace("{} with {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true)); + logger.trace("{} with id {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true)); if(iterator.hasNext()) { throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString() @@ -136,11 +117,11 @@ public class Utility { return element; } - public static E getEmbedded(Class clz, Element element, String property) + public static

P getPropertyDocument(Class

clz, Element element, String property) throws ResourceRegistryException { try { ODocument oDocument = element.getProperty(property); - E e = ISMapper.unmarshal(clz, oDocument.toJSON()); + P 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)); diff --git a/src/main/resources/config.properties.example b/src/main/resources/config.properties.example index 68345d6..c7480b1 100644 --- a/src/main/resources/config.properties.example +++ b/src/main/resources/config.properties.example @@ -17,3 +17,6 @@ CHANGED_ADMIN_PASSWORD=CHANGE_ME DEFAULT_CREATED_WRITER_USER_PASSWORD=CHANGE_ME DEFAULT_CREATED_READER_USER_PASSWORD=CHANGE_ME + +DB_KEY_FILENAME=db.key +DB_KEY_ALGORITHM=AES \ No newline at end of file diff --git a/src/main/resources/db.key.README b/src/main/resources/db.key.README new file mode 100644 index 0000000..c3a5d28 --- /dev/null +++ b/src/main/resources/db.key.README @@ -0,0 +1,2 @@ +The Database Key file which name is indicated in the config.properties +must be copied in the location of this README file. \ No newline at end of file diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/access/QueryImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/access/QueryImplTest.java index 2d10eaa..847dc23 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/access/QueryImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/access/QueryImplTest.java @@ -22,8 +22,8 @@ public class QueryImplTest extends ScopedTest { public void testQuery() throws InvalidQueryException{ QueryImpl queryImpl = new QueryImpl(); - String query = "select * from CPUFacet"; - String ret = queryImpl.query(query, -7, null); + String query = "select * from SoftwareFacet"; + String ret = queryImpl.query(query, -7, null, false); logger.debug(ret); } 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 8f33891..5de9c61 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/context/ContextManagementTest.java @@ -4,11 +4,10 @@ import java.io.IOException; import java.util.List; import java.util.UUID; -import org.gcube.informationsystem.model.impl.embedded.HeaderImpl; -import org.gcube.informationsystem.model.impl.entity.ContextImpl; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.reference.entity.Context; -import org.gcube.informationsystem.model.reference.relation.IsParentOf; +import org.gcube.informationsystem.model.impl.entities.ContextImpl; +import org.gcube.informationsystem.model.impl.properties.HeaderImpl; +import org.gcube.informationsystem.model.reference.entities.Context; +import org.gcube.informationsystem.model.reference.relations.IsParentOf; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException; @@ -19,13 +18,13 @@ import org.gcube.informationsystem.resourceregistry.context.security.SecurityCon 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.gcube.informationsystem.utils.ISMapper; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.metadata.security.ORole; import com.orientechnologies.orient.core.metadata.security.OSecurity; import com.orientechnologies.orient.core.metadata.security.OUser; @@ -35,36 +34,6 @@ public class ContextManagementTest extends ScopedTest { private static Logger logger = LoggerFactory.getLogger(ContextManagementTest.class); - @Test - public void testJava() throws Exception { - Context gcube = new ContextImpl("gcube"); - logger.debug("gcube : {}", ISMapper.marshal(ISMapper.unmarshal(Context.class, ISMapper.marshal(gcube)))); - - Context devsec = new ContextImpl("devsec"); - gcube.addChild(devsec); - logger.debug("devsec : {}", ISMapper.marshal(ISMapper.unmarshal(Context.class, ISMapper.marshal(devsec)))); - - Context devVRE = new ContextImpl("devVRE"); - devsec.addChild(devVRE); - logger.debug("devVRE : {}", ISMapper.marshal(ISMapper.unmarshal(Context.class, ISMapper.marshal(devVRE)))); - - Context devNext = new ContextImpl("devNext"); - gcube.addChild(devNext); - logger.debug("devNext : {}", ISMapper.marshal(ISMapper.unmarshal(Context.class, ISMapper.marshal(devNext)))); - - Context NextNext = new ContextImpl("NextNext"); - devNext.addChild(NextNext); - logger.debug("NextNext : {}", ISMapper.marshal(ISMapper.unmarshal(Context.class, ISMapper.marshal(NextNext)))); - - logger.debug("------------------------------------"); - - logger.debug("gcube : {}", ISMapper.marshal(gcube)); - logger.debug("devsec : {}", ISMapper.marshal(devsec)); - logger.debug("devVRE : {}", ISMapper.marshal(devVRE)); - logger.debug("devNext : {}", ISMapper.marshal(devNext)); - logger.debug("NextNext : {}", ISMapper.marshal(NextNext)); - } - public static final String CTX_NAME_A = "A"; public static final String CTX_NAME_B = "B"; public static final String CTX_NAME_C = "C"; @@ -94,8 +63,7 @@ public class ContextManagementTest extends ScopedTest { contextSecurityContext); OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER); - ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph(); - OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity(); + OSecurity oSecurity = orientGraph.getRawGraph().getMetadata().getSecurity(); SecurityContext securityContext = null; if(deleted) { @@ -150,7 +118,7 @@ public class ContextManagementTest extends ScopedTest { protected Context create(Context context) throws ResourceRegistryException, IOException { ContextManagement contextManagement = new ContextManagement(); - contextManagement.setJSON(ISMapper.marshal(context)); + contextManagement.setJson(ISMapper.marshal(context)); String contextString = contextManagement.create(); logger.debug("Created {}", contextString); Context c = ISMapper.unmarshal(Context.class, contextString); @@ -161,7 +129,7 @@ public class ContextManagementTest extends ScopedTest { protected Context update(Context context) throws ResourceRegistryException, IOException { ContextManagement contextManagement = new ContextManagement(); - contextManagement.setJSON(ISMapper.marshal(context)); + contextManagement.setJson(ISMapper.marshal(context)); String contextString = contextManagement.update(); logger.debug("Updated {}", contextString); Context c = ISMapper.unmarshal(Context.class, contextString); @@ -258,16 +226,16 @@ public class ContextManagementTest extends ScopedTest { invalidCreate(contextB3); // Trying to recreate B3. Fails invalidCreate(contextB4); // Trying to recreate B4. Fails invalidCreate(contextA5); // Trying to recreate A5. Fails - - // Trying to move A5 as child of A1. It fails due to A2. + Context nullContext = null; + // Trying to move A5 as root. It fails due to A1. contextA5.setParent(nullContext); invalidUpdate(contextA5); contextA5.setParent(contextB4); // ________A1________ // ___A2_______B4____ // B3______________A5 - + nullContext = null; contextB4.setParent(nullContext); update(contextB4); @@ -461,7 +429,7 @@ public class ContextManagementTest extends ScopedTest { // delete(context); } } - // all = getAll(); + all = getAll(); } } */ @@ -494,34 +462,4 @@ public class ContextManagementTest extends ScopedTest { delete(context); } - // @Test - public void createDevContext() throws Exception { - Context gcube = new ContextImpl("gcube"); - gcube = create(gcube); - - Context devsec = new ContextImpl("devsec"); - devsec.setParent(gcube); - devsec = create(devsec); - - Context devVRE = new ContextImpl("devVRE"); - devVRE.setParent(devsec); - devVRE = create(devVRE); - - Context devNext = new ContextImpl("devNext"); - devNext.setParent(gcube); - devNext = create(devNext); - - Context nextNext = new ContextImpl("NextNext"); - nextNext.setParent(devNext); - nextNext = create(nextNext); - - Context preprod = new ContextImpl("preprod"); - preprod.setParent(gcube); - preprod = create(preprod); - - Context preVRE = new ContextImpl("preVRE"); - preVRE.setParent(preprod); - preVRE = create(preVRE); - } - } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java index 37fb53c..4ccc4d2 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironmentTest.java @@ -13,4 +13,35 @@ public class DatabaseEnvironmentTest { String db = DatabaseEnvironment.DB_URI; logger.trace("Created DB is {}", db); } + + /* + @Test + public void generateDBKey() throws Exception { + Properties properties = new Properties(); + InputStream input = DatabaseEnvironmentTest.class.getClassLoader().getResourceAsStream("config.properties"); + + // load a properties file + properties.load(input); + + String keyFileName = properties.getProperty("DB_KEY_FILENAME"); + String keyAlgorithm = properties.getProperty("DB_KEY_ALGORITHM_VARNAME"); + + URL url = SymmetricKey.class.getResource(keyFileName); + Key key = null; + if(url!=null) { + try { + key = SymmetricKey.loadKeyFromFile(keyFileName, keyAlgorithm); + } catch(Exception e) { + + } + } + + if(key==null){ + key = KeyFactory.newAESKey(); + File file = new File("src/test/resources", keyFileName); + KeySerialization.store(key, file); + } + } + */ + } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java index 9ecae6e..55a509d 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/ERManagementTest.java @@ -16,20 +16,20 @@ import java.util.Map; import java.util.UUID; import org.gcube.common.authorization.library.provider.AuthorizationProvider; -import org.gcube.informationsystem.model.impl.embedded.HeaderImpl; -import org.gcube.informationsystem.model.impl.embedded.PropagationConstraintImpl; -import org.gcube.informationsystem.model.impl.relation.ConsistsOfImpl; -import org.gcube.informationsystem.model.impl.relation.IsIdentifiedByImpl; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.impl.utils.Utility; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsIdentifiedBy; -import org.gcube.informationsystem.model.reference.relation.IsRelatedTo; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.impl.properties.EncryptedImpl; +import org.gcube.informationsystem.model.impl.properties.HeaderImpl; +import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl; +import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl; +import org.gcube.informationsystem.model.impl.relations.IsIdentifiedByImpl; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Encrypted; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsIdentifiedBy; +import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; @@ -38,33 +38,37 @@ import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; -import org.gcube.resourcemanagement.model.impl.entity.facet.AccessPointFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.CPUFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.EventFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.LicenseFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.NetworkingFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.ServiceStateFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.SimpleFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.SoftwareFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.StateFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.resource.EServiceImpl; -import org.gcube.resourcemanagement.model.impl.entity.resource.HostingNodeImpl; -import org.gcube.resourcemanagement.model.impl.relation.isrelatedto.ActivatesImpl; -import org.gcube.resourcemanagement.model.reference.entity.facet.AccessPointFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.CPUFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.ContactFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.EventFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.LicenseFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.NetworkingFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.ServiceStateFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.SimpleFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.SoftwareFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.StateFacet; -import org.gcube.resourcemanagement.model.reference.entity.resource.Configuration; -import org.gcube.resourcemanagement.model.reference.entity.resource.EService; -import org.gcube.resourcemanagement.model.reference.entity.resource.HostingNode; -import org.gcube.resourcemanagement.model.reference.entity.resource.Service; -import org.gcube.resourcemanagement.model.reference.relation.isrelatedto.Activates; +import org.gcube.informationsystem.utils.ISMapper; +import org.gcube.informationsystem.utils.Utility; +import org.gcube.resourcemanagement.model.impl.entities.facets.AccessPointFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.LicenseFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.NetworkingFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.ServiceStateFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.SimpleFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.StateFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.resources.EServiceImpl; +import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl; +import org.gcube.resourcemanagement.model.impl.properties.ValueSchemaImpl; +import org.gcube.resourcemanagement.model.impl.relations.isrelatedto.ActivatesImpl; +import org.gcube.resourcemanagement.model.reference.entities.facets.AccessPointFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.CPUFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.ContactFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.EventFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.LicenseFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.NetworkingFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.ServiceStateFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.SimpleFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet; +import org.gcube.resourcemanagement.model.reference.entities.resources.Configuration; +import org.gcube.resourcemanagement.model.reference.entities.resources.EService; +import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode; +import org.gcube.resourcemanagement.model.reference.entities.resources.Service; +import org.gcube.resourcemanagement.model.reference.properties.ValueSchema; +import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Activates; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -83,6 +87,85 @@ public class ERManagementTest extends ScopedTest { private static Logger logger = LoggerFactory .getLogger(ERManagementTest.class); + @Test + public void testCreateFacetWithEncrypted() throws Exception { + CPUFacet cpuFacet = new CPUFacetImpl(); + cpuFacet.setClockSpeed("1 GHz"); + cpuFacet.setModel("Opteron"); + cpuFacet.setVendor("AMD"); + Encrypted encrypted = new EncryptedImpl(); + String encryptedValue = EncryptedImpl.encrypt("plain-value"); + encrypted.setEncryptedValue(encryptedValue); + cpuFacet.setAdditionalProperty("test", encrypted); + + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setElementType(CPUFacet.NAME); + String json = ISMapper.marshal(cpuFacet); + logger.debug("{}", json); + facetManagement.setJson(json); + + /* + String cpuFacetJson = facetManagement.create(); + CPUFacet createdCpuFacet = ISMapper.unmarshal(CPUFacet.class, + cpuFacetJson); + logger.debug("Created:\nRaw Json : {}\nUnmarshalled : {}", + cpuFacetJson, createdCpuFacet); + */ + + } + + + + @Test + public void testCreatePropertyTypeNotInSchema() throws Exception { + + AccessPointFacet accessPointFacet = new AccessPointFacetImpl(); + accessPointFacet.setEndpoint(new URI("http://localhost")); + accessPointFacet.setEntryName("port1"); + + ValueSchema authorization = new ValueSchemaImpl(); + authorization.setValue("pwd"); + URI uri = new URI("http://www.gcube-system.org"); + authorization.setType(uri); + accessPointFacet.setAuthorization(authorization); + + accessPointFacet.setAdditionalProperty("Test", "MyTest"); + + Encrypted encrypted = new EncryptedImpl(); + String encryptedValue = EncryptedImpl.encrypt("Encrypted"); + encrypted.setEncryptedValue(encryptedValue); + accessPointFacet.setAdditionalProperty("Enc", encrypted); + + String marshalled = ISMapper.marshal(accessPointFacet); + logger.debug(marshalled); + + FacetManagement facetManagement = new FacetManagement(); + facetManagement.setElementType(AccessPointFacet.NAME); + facetManagement.setJson(marshalled); + + String createdJson = facetManagement.create(); + logger.debug("Created:\nRaw Json : {}", createdJson); + AccessPointFacet apf = ISMapper.unmarshal(AccessPointFacet.class, createdJson); + + Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema); + Assert.assertTrue(apf.getAdditionalProperty("Enc") instanceof Encrypted); + Encrypted enc = (Encrypted) apf.getAdditionalProperty("Enc"); + String encValue = enc.getEncryptedValue(); + Assert.assertTrue(encValue.compareTo(encryptedValue)==0); + String decryptedValue = EncryptedImpl.decrypt(encValue); + Assert.assertTrue(decryptedValue.compareTo("Encrypted")==0); + Assert.assertTrue(((String)apf.getAdditionalProperty("Test")).compareTo("MyTest")==0); + + UUID uuid = apf.getHeader().getUUID(); + + facetManagement = new FacetManagement(); + facetManagement.setUUID(uuid); + + boolean deleted = facetManagement.delete(); + Assert.assertTrue(deleted); + } + + @Test public void testCreateEService() throws Exception { EService eService = new EServiceImpl(); @@ -133,7 +216,7 @@ public class ERManagementTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); String json = resourceManagement.create(); logger.debug("Created : {}", json); @@ -177,7 +260,7 @@ public class ERManagementTest extends ScopedTest { facetManagement.setElementType(StateFacet.NAME); String json = ISMapper.marshal(stateFacet); logger.debug(json); - facetManagement.setJSON(json); + facetManagement.setJson(json); facetManagement.create(); } @@ -188,22 +271,25 @@ public class ERManagementTest extends ScopedTest { FacetManagement facetManagement = new FacetManagement(); facetManagement.setElementType(ContactFacet.NAME); - facetManagement.setJSON(ISMapper.marshal(simpleFacet)); + facetManagement.setJson(ISMapper.marshal(simpleFacet)); facetManagement.create(); } - @Test public void testCreateReadUpdateDeleteFacet() throws Exception { CPUFacet cpuFacet = new CPUFacetImpl(); cpuFacet.setClockSpeed("1 GHz"); cpuFacet.setModel("Opteron"); cpuFacet.setVendor("AMD"); - + + Encrypted encrypted = new EncryptedImpl(); + encrypted.setEncryptedValue("Value"); + cpuFacet.setAdditionalProperty("Enc", encrypted); + FacetManagement facetManagement = new FacetManagement(); facetManagement.setElementType(CPUFacet.NAME); - facetManagement.setJSON(ISMapper.marshal(cpuFacet)); + facetManagement.setJson(ISMapper.marshal(cpuFacet)); String cpuFacetJson = facetManagement.create(); CPUFacet createdCpuFacet = ISMapper.unmarshal(CPUFacet.class, @@ -249,7 +335,7 @@ public class ERManagementTest extends ScopedTest { facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); - facetManagement.setJSON(ISMapper.marshal(readCpuFacet)); + facetManagement.setJson(ISMapper.marshal(readCpuFacet)); String updatedJson = facetManagement.update(); CPUFacet updatedCpuFacet = ISMapper.unmarshal(CPUFacet.class, @@ -315,7 +401,7 @@ public class ERManagementTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); String json = resourceManagement.create(); logger.debug("Created : {}", json); @@ -354,7 +440,7 @@ public class ERManagementTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setElementType(HostingNode.NAME); - resourceManagement.setJSON(ISMapper.marshal(hostingNode)); + resourceManagement.setJson(ISMapper.marshal(hostingNode)); json = resourceManagement.create(); logger.debug("Created : {}", json); @@ -401,7 +487,7 @@ public class ERManagementTest extends ScopedTest { String json = ISMapper.marshal(consistsOf); json = json.replaceAll(SimpleFacet.NAME, EService.NAME); - consistsOfManagement.setJSON(json); + consistsOfManagement.setJson(json); consistsOfManagement.create(); logger.debug("The creation terminated correctly. This should not happen"); @@ -435,9 +521,9 @@ public class ERManagementTest extends ScopedTest { ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); consistsOfManagement.setElementType(ConsistsOf.NAME); - consistsOfManagement.setJSON("{}"); + consistsOfManagement.setJson("{}"); ConsistsOf consistsOf = new ConsistsOfImpl<>(eService, shared, null); - consistsOfManagement.setJSON(ISMapper.marshal(consistsOf)); + consistsOfManagement.setJson(ISMapper.marshal(consistsOf)); String json = consistsOfManagement.create(); logger.debug("Created : {}", json); @@ -469,7 +555,7 @@ public class ERManagementTest extends ScopedTest { public void testCreateResourceAndFacet() throws Exception { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(HostingNode.NAME); - resourceManagement.setJSON("{}"); + resourceManagement.setJson("{}"); String json = resourceManagement.create(); HostingNode hostingNode = ISMapper.unmarshal(HostingNode.class, json); @@ -481,7 +567,7 @@ public class ERManagementTest extends ScopedTest { cpuFacet.setVendor("AMD"); FacetManagement facetManagement = new FacetManagement(); - facetManagement.setJSON(ISMapper.marshal(cpuFacet)); + facetManagement.setJson(ISMapper.marshal(cpuFacet)); facetManagement.setElementType(CPUFacet.NAME); json = facetManagement.create(); CPUFacet createdCPUFacet = ISMapper.unmarshal(CPUFacet.class, json); @@ -489,7 +575,7 @@ public class ERManagementTest extends ScopedTest { ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); consistsOfManagement.setElementType(ConsistsOf.NAME); ConsistsOf consistsOf = new ConsistsOfImpl<>(hostingNode, createdCPUFacet, null); - consistsOfManagement.setJSON(ISMapper.marshal(consistsOf)); + consistsOfManagement.setJson(ISMapper.marshal(consistsOf)); json = consistsOfManagement.create(); logger.debug("Facet attached : {}", json); @@ -753,7 +839,7 @@ public class ERManagementTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setUUID(eService.getHeader().getUUID()); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); resourceManagement.update(); @@ -773,7 +859,7 @@ public class ERManagementTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setUUID(configuration.getHeader().getUUID()); - resourceManagement.setJSON(ISMapper.marshal(configuration)); + resourceManagement.setJson(ISMapper.marshal(configuration)); resourceManagement.update(); @@ -819,7 +905,7 @@ public class ERManagementTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); String json = resourceManagement.create(); logger.trace("Created {}", json); @@ -830,7 +916,7 @@ public class ERManagementTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setUUID(eService.getHeader().getUUID()); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); json = resourceManagement.update(); logger.trace("Updated {}", json); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/EncryptionTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/EncryptionTest.java new file mode 100644 index 0000000..8bcca97 --- /dev/null +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/EncryptionTest.java @@ -0,0 +1,46 @@ +package org.gcube.informationsystem.resourceregistry.er; + +import java.security.Key; + +import org.gcube.informationsystem.model.impl.properties.EncryptedImpl; +import org.gcube.informationsystem.model.reference.properties.Encrypted; +import org.gcube.informationsystem.resourceregistry.ScopedTest; +import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; +import org.junit.Assert; +import org.junit.Test; + +public class EncryptionTest extends ScopedTest { + + public static final String PLAIN_VALUE = "my-test"; + + @Test + public void test() throws Exception { + + Encrypted encrypted = new EncryptedImpl(); + String contextEncryptedValue = EncryptedImpl.encrypt(PLAIN_VALUE); + encrypted.setEncryptedValue(contextEncryptedValue); + + String getContextEncryptedValue = encrypted.getEncryptedValue(); + Assert.assertTrue(getContextEncryptedValue.compareTo(getContextEncryptedValue)==0); + + + // Decrypting with Context Key (default key) + String decryptedValue = EncryptedImpl.decrypt(contextEncryptedValue); + Assert.assertTrue(decryptedValue.compareTo(PLAIN_VALUE)==0); + + // Encrypting with DB Key + Key databaseKey = DatabaseEnvironment.getDatabaseKey(); + String dbEncryptedValue = EncryptedImpl.encrypt(decryptedValue, databaseKey); + + // Setting the value encrypted with DB key + encrypted.setEncryptedValue(dbEncryptedValue); + + String getDBEncryptedValue = encrypted.getEncryptedValue(); + Assert.assertTrue(getDBEncryptedValue.compareTo(dbEncryptedValue)==0); + + decryptedValue = EncryptedImpl.decrypt(getDBEncryptedValue, databaseKey); + Assert.assertTrue(decryptedValue.compareTo(PLAIN_VALUE)==0); + + } + +} diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java index 9e3d5bd..eff7a79 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/SmartgearResourcesTest.java @@ -22,41 +22,41 @@ import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.gcube.informationsystem.model.impl.embedded.HeaderImpl; -import org.gcube.informationsystem.model.impl.embedded.PropagationConstraintImpl; -import org.gcube.informationsystem.model.impl.relation.ConsistsOfImpl; -import org.gcube.informationsystem.model.impl.relation.IsIdentifiedByImpl; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsIdentifiedBy; +import org.gcube.informationsystem.model.impl.properties.HeaderImpl; +import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl; +import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl; +import org.gcube.informationsystem.model.impl.relations.IsIdentifiedByImpl; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Header; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsIdentifiedBy; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; -import org.gcube.resourcemanagement.model.impl.entity.facet.CPUFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.ContainerStateFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.MemoryFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.NetworkingFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.SimplePropertyFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.SoftwareFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.resource.HostingNodeImpl; -import org.gcube.resourcemanagement.model.impl.relation.consistsof.HasPersistentMemoryImpl; -import org.gcube.resourcemanagement.model.impl.relation.consistsof.HasVolatileMemoryImpl; -import org.gcube.resourcemanagement.model.reference.entity.facet.CPUFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.ContainerStateFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.MemoryFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.NetworkingFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.SimplePropertyFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.SoftwareFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.MemoryFacet.MemoryUnit; -import org.gcube.resourcemanagement.model.reference.entity.resource.EService; -import org.gcube.resourcemanagement.model.reference.entity.resource.HostingNode; -import org.gcube.resourcemanagement.model.reference.relation.consistsof.HasPersistentMemory; -import org.gcube.resourcemanagement.model.reference.relation.consistsof.HasVolatileMemory; +import org.gcube.informationsystem.utils.ISMapper; +import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.ContainerStateFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.MemoryFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.NetworkingFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.SimplePropertyFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl; +import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasPersistentMemoryImpl; +import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasVolatileMemoryImpl; +import org.gcube.resourcemanagement.model.reference.entities.facets.CPUFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.ContainerStateFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.NetworkingFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.SimplePropertyFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet.MemoryUnit; +import org.gcube.resourcemanagement.model.reference.entities.resources.EService; +import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode; +import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPersistentMemory; +import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -86,7 +86,7 @@ public class SmartgearResourcesTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(HostingNode.NAME); - resourceManagement.setJSON(HOSTING_NODE); + resourceManagement.setJson(HOSTING_NODE); String hnJson = resourceManagement.create(); logger.debug("Created : {}", hnJson); @@ -128,7 +128,7 @@ public class SmartgearResourcesTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ESERVICE); + resourceManagement.setJson(ESERVICE); String json = resourceManagement.create(); eService = ISMapper.unmarshal(EService.class, json); @@ -231,7 +231,7 @@ public class SmartgearResourcesTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(HostingNode.NAME); - resourceManagement.setJSON(ISMapper.marshal(hostingNode)); + resourceManagement.setJson(ISMapper.marshal(hostingNode)); String json = resourceManagement.create(); @@ -317,7 +317,7 @@ public class SmartgearResourcesTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setUUID(uuid); - resourceManagement.setJSON(ISMapper.marshal(hostingNodeToUpdate)); + resourceManagement.setJson(ISMapper.marshal(hostingNodeToUpdate)); String updatedHN = resourceManagement.update(); logger.debug("Updated {}", updatedHN); 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 7df7656..808bcd4 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 @@ -2,9 +2,8 @@ package org.gcube.informationsystem.resourceregistry.er.entity; import java.util.UUID; -import org.gcube.informationsystem.model.impl.utils.ISMapper; import org.gcube.informationsystem.model.reference.ER; -import org.gcube.informationsystem.model.reference.entity.Facet; +import org.gcube.informationsystem.model.reference.entities.Facet; 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; @@ -13,8 +12,9 @@ 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.gcube.resourcemanagement.model.impl.entity.facet.SoftwareFacetImpl; -import org.gcube.resourcemanagement.model.reference.entity.facet.SoftwareFacet; +import org.gcube.informationsystem.utils.ISMapper; +import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl; +import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -73,7 +73,7 @@ public class FacetManagementTest extends ScopedTest { FacetManagement facetManagement = new FacetManagement(); String facetType = Utility.getType(facet); facetManagement.setElementType(facetType); - facetManagement.setJSON(ISMapper.marshal(facet)); + facetManagement.setJson(ISMapper.marshal(facet)); String json = facetManagement.create(); logger.debug("Created : {}", json); @@ -93,7 +93,7 @@ public class FacetManagementTest extends ScopedTest { FacetManagement facetManagement = new FacetManagement(); String facetType = Utility.getType(facet); facetManagement.setElementType(facetType); - facetManagement.setJSON(ISMapper.marshal(facet)); + facetManagement.setJson(ISMapper.marshal(facet)); String json = facetManagement.update(); logger.debug("Updated : {}", json); 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 7057135..61c11c4 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 @@ -4,19 +4,19 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.gcube.informationsystem.model.impl.relation.IsIdentifiedByImpl; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsIdentifiedBy; +import org.gcube.informationsystem.model.impl.relations.IsIdentifiedByImpl; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsIdentifiedBy; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; -import org.gcube.resourcemanagement.model.impl.entity.resource.EServiceImpl; -import org.gcube.resourcemanagement.model.reference.entity.facet.SoftwareFacet; -import org.gcube.resourcemanagement.model.reference.entity.resource.EService; -import org.gcube.resourcemanagement.model.reference.entity.resource.Service; +import org.gcube.informationsystem.utils.ISMapper; +import org.gcube.resourcemanagement.model.impl.entities.resources.EServiceImpl; +import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet; +import org.gcube.resourcemanagement.model.reference.entities.resources.EService; +import org.gcube.resourcemanagement.model.reference.entities.resources.Service; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -50,7 +50,7 @@ public class ResourceManagementTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); String json = resourceManagement.create(); logger.trace("Created {}", json); eService = ISMapper.unmarshal(EService.class, json); @@ -67,7 +67,7 @@ public class ResourceManagementTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setUUID(eService.getHeader().getUUID()); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); json = resourceManagement.update(); logger.trace("Updated {}", json); 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 b8db580..fe43989 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,14 +8,13 @@ import java.net.URL; import java.util.Calendar; import java.util.UUID; -import org.gcube.informationsystem.model.impl.embedded.PropagationConstraintImpl; -import org.gcube.informationsystem.model.impl.relation.IsIdentifiedByImpl; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.AddConstraint; -import org.gcube.informationsystem.model.reference.embedded.PropagationConstraint.RemoveConstraint; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.relation.IsIdentifiedBy; +import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl; +import org.gcube.informationsystem.model.impl.relations.IsIdentifiedByImpl; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint; +import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint; +import org.gcube.informationsystem.model.reference.relations.IsIdentifiedBy; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; @@ -28,33 +27,34 @@ import org.gcube.informationsystem.resourceregistry.er.SmartgearResourcesTest; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; -import org.gcube.resourcemanagement.model.impl.entity.facet.AccessPointFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.CPUFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.EventFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.LicenseFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.MemoryFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.NetworkingFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.ServiceStateFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.facet.SoftwareFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.resource.EServiceImpl; -import org.gcube.resourcemanagement.model.impl.entity.resource.HostingNodeImpl; -import org.gcube.resourcemanagement.model.impl.relation.consistsof.HasPersistentMemoryImpl; -import org.gcube.resourcemanagement.model.impl.relation.consistsof.HasVolatileMemoryImpl; -import org.gcube.resourcemanagement.model.impl.relation.isrelatedto.ActivatesImpl; -import org.gcube.resourcemanagement.model.reference.entity.facet.AccessPointFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.CPUFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.EventFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.LicenseFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.MemoryFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.NetworkingFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.ServiceStateFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.SoftwareFacet; -import org.gcube.resourcemanagement.model.reference.entity.facet.MemoryFacet.MemoryUnit; -import org.gcube.resourcemanagement.model.reference.entity.resource.EService; -import org.gcube.resourcemanagement.model.reference.entity.resource.HostingNode; -import org.gcube.resourcemanagement.model.reference.relation.consistsof.HasPersistentMemory; -import org.gcube.resourcemanagement.model.reference.relation.consistsof.HasVolatileMemory; -import org.gcube.resourcemanagement.model.reference.relation.isrelatedto.Activates; +import org.gcube.informationsystem.utils.ISMapper; +import org.gcube.resourcemanagement.model.impl.entities.facets.AccessPointFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.LicenseFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.MemoryFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.NetworkingFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.ServiceStateFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.resources.EServiceImpl; +import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl; +import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasPersistentMemoryImpl; +import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasVolatileMemoryImpl; +import org.gcube.resourcemanagement.model.impl.relations.isrelatedto.ActivatesImpl; +import org.gcube.resourcemanagement.model.reference.entities.facets.AccessPointFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.CPUFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.EventFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.LicenseFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.NetworkingFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.ServiceStateFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet; +import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet.MemoryUnit; +import org.gcube.resourcemanagement.model.reference.entities.resources.EService; +import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode; +import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPersistentMemory; +import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory; +import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Activates; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -77,7 +77,7 @@ public class BasicTest extends ScopedTest { cpuFacet.setVendor("AMD"); FacetManagement facetManagement = new FacetManagement(); - facetManagement.setJSON(ISMapper.marshal(cpuFacet)); + facetManagement.setJson(ISMapper.marshal(cpuFacet)); facetManagement.setElementType(CPUFacet.NAME); String json = facetManagement.create(); @@ -126,7 +126,7 @@ public class BasicTest extends ScopedTest { try { facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); - facetManagement.setJSON(ISMapper.marshal(cpuFacet)); + facetManagement.setJson(ISMapper.marshal(cpuFacet)); readJson = facetManagement.update(); logger.debug("You should not be able to update Facet with UUID {}", uuid); @@ -143,7 +143,7 @@ public class BasicTest extends ScopedTest { facetManagement = new FacetManagement(); facetManagement.setUUID(uuid); - facetManagement.setJSON(ISMapper.marshal(cpuFacet)); + facetManagement.setJson(ISMapper.marshal(cpuFacet)); readJson = facetManagement.update(); logger.debug("Updated : {}", readJson); @@ -195,7 +195,7 @@ public class BasicTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); String json = resourceManagement.create(); logger.debug("Created : {}", json); @@ -246,7 +246,7 @@ public class BasicTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setElementType(HostingNode.NAME); - resourceManagement.setJSON(ISMapper.marshal(hostingNode)); + resourceManagement.setJson(ISMapper.marshal(hostingNode)); String hnJson = resourceManagement.create(); logger.debug("Created : {}", hnJson); @@ -330,7 +330,7 @@ public class BasicTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(HostingNode.NAME); - resourceManagement.setJSON(SmartgearResourcesTest.HOSTING_NODE); + resourceManagement.setJson(SmartgearResourcesTest.HOSTING_NODE); String hnJson = resourceManagement.create(); logger.debug("Created : {}", hnJson); @@ -344,7 +344,7 @@ public class BasicTest extends ScopedTest { resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(SmartgearResourcesTest.ESERVICE); + resourceManagement.setJson(SmartgearResourcesTest.ESERVICE); String eservicejson = resourceManagement.create(); logger.debug("Created : {}", eservicejson); @@ -369,7 +369,7 @@ public class BasicTest extends ScopedTest { IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); isRelatedToManagement.setElementType(Activates.NAME); String activatesJson = ISMapper.marshal(activates); - isRelatedToManagement.setJSON(activatesJson); + isRelatedToManagement.setJson(activatesJson); String createdActivatesJson = isRelatedToManagement.create(); logger.debug("Created : {}", createdActivatesJson); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java index e542c60..7e91122 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/er/multicontext/RuleTest.java @@ -2,19 +2,19 @@ package org.gcube.informationsystem.resourceregistry.er.multicontext; import java.util.UUID; -import org.gcube.informationsystem.model.impl.relation.IsIdentifiedByImpl; -import org.gcube.informationsystem.model.impl.utils.ISMapper; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.relation.IsIdentifiedBy; +import org.gcube.informationsystem.model.impl.relations.IsIdentifiedByImpl; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.relations.IsIdentifiedBy; import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; -import org.gcube.resourcemanagement.model.impl.entity.facet.SoftwareFacetImpl; -import org.gcube.resourcemanagement.model.impl.entity.resource.EServiceImpl; -import org.gcube.resourcemanagement.model.reference.entity.facet.SoftwareFacet; -import org.gcube.resourcemanagement.model.reference.entity.resource.EService; +import org.gcube.informationsystem.utils.ISMapper; +import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl; +import org.gcube.resourcemanagement.model.impl.entities.resources.EServiceImpl; +import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet; +import org.gcube.resourcemanagement.model.reference.entities.resources.EService; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -38,7 +38,7 @@ public class RuleTest extends ScopedTest { ResourceManagement resourceManagement = new ResourceManagement(); resourceManagement.setElementType(EService.NAME); - resourceManagement.setJSON(ISMapper.marshal(eService)); + resourceManagement.setJson(ISMapper.marshal(eService)); String json = resourceManagement.create(); logger.debug("Created : {}", json); @@ -88,7 +88,7 @@ public class RuleTest extends ScopedTest { // Trying to recreate SoftwareFacet FacetManagement softwareFacetManagement = new FacetManagement(); softwareFacetManagement.setElementType(SoftwareFacet.NAME); - softwareFacetManagement.setJSON(softwareFacetString); + softwareFacetManagement.setJson(softwareFacetString); try{ softwareFacetManagement.create(); }catch (FacetAlreadyPresentException e) { @@ -104,7 +104,7 @@ public class RuleTest extends ScopedTest { ResourceManagement eServiceManagement = new ResourceManagement(); eServiceManagement.setElementType(EService.NAME); - eServiceManagement.setJSON(eServiceString); + eServiceManagement.setJson(eServiceString); try{ eServiceManagement.create(); }catch (ResourceAlreadyPresentException e) { @@ -122,7 +122,7 @@ public class RuleTest extends ScopedTest { eServiceManagement = new ResourceManagement(); eServiceManagement.setElementType(EService.NAME); - eServiceManagement.setJSON(eServiceString); + eServiceManagement.setJson(eServiceString); boolean deleted = eServiceManagement.delete(); Assert.assertTrue(deleted); } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java index 2d1b33c..e09b36e 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java @@ -6,19 +6,19 @@ package org.gcube.informationsystem.resourceregistry.schema; import java.util.List; import org.gcube.informationsystem.model.reference.ISManageable; -import org.gcube.informationsystem.model.reference.embedded.Embedded; -import org.gcube.informationsystem.model.reference.embedded.Header; -import org.gcube.informationsystem.model.reference.entity.Entity; -import org.gcube.informationsystem.model.reference.entity.Facet; -import org.gcube.informationsystem.model.reference.entity.Resource; -import org.gcube.informationsystem.model.reference.relation.ConsistsOf; -import org.gcube.informationsystem.model.reference.relation.IsRelatedTo; -import org.gcube.informationsystem.model.reference.relation.Relation; +import org.gcube.informationsystem.model.reference.entities.Entity; +import org.gcube.informationsystem.model.reference.entities.Facet; +import org.gcube.informationsystem.model.reference.entities.Resource; +import org.gcube.informationsystem.model.reference.properties.Header; +import org.gcube.informationsystem.model.reference.properties.Property; +import org.gcube.informationsystem.model.reference.relations.ConsistsOf; +import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; +import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.types.TypeBinder; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; -import org.gcube.resourcemanagement.model.reference.entity.facet.ContactFacet; -import org.gcube.resourcemanagement.model.reference.entity.resource.Actor; -import org.gcube.resourcemanagement.model.reference.relation.isrelatedto.Hosts; +import org.gcube.resourcemanagement.model.reference.entities.facets.ContactFacet; +import org.gcube.resourcemanagement.model.reference.entities.resources.Actor; +import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Hosts; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,16 +35,16 @@ public class SchemaManagementImplTest { .getLogger(SchemaManagementImplTest.class); @Test - public void registerEmbeddedTypeSchema() throws Exception { - Class clz = Header.class; + public void registerPropertyTypeSchema() throws Exception { + Class clz = Header.class; String json = TypeBinder.serializeType(clz); logger.debug(json); - //new SchemaManagementImpl().create(json, AccessType.EMBEDDED); + //new SchemaManagementImpl().create(json, AccessType.PROPERTY); } @Test - public void getEmbeddedTypeSchema() throws Exception { - String json = new SchemaManagementImpl().read(Embedded.NAME, false); + public void getPropertyTypeSchema() throws Exception { + String json = new SchemaManagementImpl().read(Property.NAME, false); logger.debug(json); } @@ -101,8 +101,8 @@ public class SchemaManagementImplTest { boolean includeSubTypes = true; SchemaManagement schemaManagement = new SchemaManagementImpl(); - String list = schemaManagement.read(Embedded.NAME, includeSubTypes); - logger.debug("{} list : {}", Embedded.NAME, list); + String list = schemaManagement.read(Property.NAME, includeSubTypes); + logger.debug("{} list : {}", Property.NAME, list); ObjectMapper mapper = new ObjectMapper(); List typeDefinitions = mapper.readValue(list,