From 42372f041b4b658c2679d347a0c32cfc1e798dca Mon Sep 17 00:00:00 2001 From: "luca.frosini" Date: Thu, 27 Oct 2016 15:46:09 +0000 Subject: [PATCH] Merged from private branch git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@133659 82a268e6-3cf1-43bd-a215-b396298e98cf --- .settings/org.eclipse.wst.common.component | 3 + .../context/SecurityContext.java | 53 +- .../context/SecurityContextMapper.java | 35 +- .../DatabaseIntializator.java | 12 +- .../resourceregistry/resources/Access.java | 19 +- .../resources/ContextManager.java | 18 +- .../resources/EntityManager.java | 36 +- .../ResourceRegistryExceptionMapper.java | 21 +- .../resources/SchemaManager.java | 13 + .../resources/impl/ContextManagementImpl.java | 342 ++++++----- .../resources/impl/EntityManagementImpl.java | 38 +- .../resources/impl/SchemaManagementImpl.java | 228 ++++---- .../resources/utils/ContextUtility.java | 68 ++- .../resources/utils/Utility.java | 21 +- .../ContextManagerFactory.java | 22 +- .../EntityManagementFactory.java | 26 +- .../impl/ContextManagementImplTest.java | 536 +++++++++++------- .../impl/EntityManagementImplTest.java | 24 +- 18 files changed, 872 insertions(+), 643 deletions(-) diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index 57164d3..9fb1bc0 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -7,6 +7,9 @@ uses + + uses + uses diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContext.java index 93c4d54..d293229 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContext.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContext.java @@ -4,6 +4,7 @@ package org.gcube.informationsystem.resourceregistry.context; import java.util.Iterator; +import java.util.UUID; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.slf4j.Logger; @@ -35,53 +36,53 @@ public class SecurityContext { public static final String DEFAULT_READER_ROLE = "reader"; public static void addToSecurityContext(OrientGraph orientGraph, - Vertex vertex, String contextID) { + Vertex vertex, UUID context) { OSecurity oSecurity = orientGraph.getRawGraph().getMetadata() .getSecurity(); - SecurityContext.addToSecurityContext(oSecurity, vertex, contextID); + SecurityContext.addToSecurityContext(oSecurity, vertex, context); } public static void addToSecurityContext(OSecurity oSecurity, Vertex vertex, - String contextID) { + UUID context) { OrientVertex orientVertex = (OrientVertex) vertex; SecurityContext.allowSecurityContextRoles(oSecurity, - orientVertex.getRecord(), contextID); + orientVertex.getRecord(), context); Iterable iterable = vertex.getEdges(Direction.BOTH); Iterator iterator = iterable.iterator(); while (iterator.hasNext()) { OrientEdge edge = (OrientEdge) iterator.next(); SecurityContext.allowSecurityContextRoles(oSecurity, - edge.getRecord(), contextID); + edge.getRecord(), context); } } public static void addToSecurityContext(OrientGraph orientGraph, Edge edge, - String contextID) { + UUID context) { OSecurity oSecurity = orientGraph.getRawGraph().getMetadata() .getSecurity(); - SecurityContext.addToSecurityContext(oSecurity, edge, contextID); + SecurityContext.addToSecurityContext(oSecurity, edge, context); } public static void addToSecurityContext(OSecurity oSecurity, Edge edge, - String contextID) { + UUID context) { OrientEdge orientEdge = (OrientEdge) edge; SecurityContext.allowSecurityContextRoles(oSecurity, - orientEdge.getRecord(), contextID); + orientEdge.getRecord(), context); } protected static void allowSecurityContextRoles(OSecurity oSecurity, - ODocument oDocument, String contextID) { + ODocument oDocument, UUID context) { oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.ROLE, contextID)); + SecurityContextMapper.SecurityType.ROLE, context)); oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.ROLE, contextID)); + SecurityContextMapper.SecurityType.ROLE, context)); // oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, // DEFAULT_WRITER_ROLE); @@ -91,7 +92,7 @@ public class SecurityContext { } public static void createSecurityContext(OrientGraph orientGraph, - String contextID, boolean commit) { + UUID context, boolean commit) { OSecurity oSecurity = orientGraph.getRawGraph().getMetadata() .getSecurity(); @@ -101,24 +102,24 @@ public class SecurityContext { ORole writerRole = oSecurity.createRole(SecurityContextMapper .getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.ROLE, contextID), + SecurityContextMapper.SecurityType.ROLE, context), writer, ALLOW_MODES.DENY_ALL_BUT); ORole readerRole = oSecurity.createRole(SecurityContextMapper .getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.ROLE, contextID), + SecurityContextMapper.SecurityType.ROLE, context), reader, ALLOW_MODES.DENY_ALL_BUT); oSecurity.createUser(SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.USER, contextID), + SecurityContextMapper.SecurityType.USER, context), DatabaseEnvironment.DEFAULT_PASSWORDS .get(SecurityContextMapper.PermissionMode.WRITER), writerRole); oSecurity.createUser(SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.USER, contextID), + SecurityContextMapper.SecurityType.USER, context), DatabaseEnvironment.DEFAULT_PASSWORDS .get(SecurityContextMapper.PermissionMode.READER), readerRole); @@ -129,22 +130,22 @@ public class SecurityContext { logger.trace( "Security Context (roles and users) with UUID {} successfully created", - contextID); + context.toString()); } public static void deleteSecurityContext(OrientGraph orientGraph, - String contextID, boolean commit) { + UUID context, boolean commit) { logger.trace( "Going to remove Security Context (roles and users) with UUID {}", - contextID); + context.toString()); ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph(); OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity(); String user = SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.USER, contextID); + SecurityContextMapper.SecurityType.USER, context); boolean dropped = oSecurity.dropUser(user); if(dropped){ logger.trace("{} successfully dropped", user); @@ -155,7 +156,7 @@ public class SecurityContext { user = SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.USER, contextID); + SecurityContextMapper.SecurityType.USER, context); dropped = oSecurity.dropUser(user); if(dropped){ logger.trace("{} successfully dropped", user); @@ -166,7 +167,7 @@ public class SecurityContext { String role = SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.READER, - SecurityContextMapper.SecurityType.ROLE, contextID); + SecurityContextMapper.SecurityType.ROLE, context); dropped = oSecurity.dropRole(role); if(dropped){ logger.trace("{} successfully dropped", role); @@ -177,7 +178,7 @@ public class SecurityContext { role = SecurityContextMapper.getSecurityRoleOrUserName( SecurityContextMapper.PermissionMode.WRITER, - SecurityContextMapper.SecurityType.ROLE, contextID); + SecurityContextMapper.SecurityType.ROLE, context); dropped = oSecurity.dropRole(role); if(dropped){ logger.trace("{} successfully dropped", role); @@ -185,12 +186,10 @@ public class SecurityContext { logger.error("{} was not dropped successfully", role); } - oSecurity.close(false); oDatabaseDocumentTx.commit(); - oDatabaseDocumentTx.close(); logger.trace( "Security Context (roles and users) with UUID {} successfully removed", - contextID); + context.toString()); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java b/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java index b57cb46..33ca283 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/context/SecurityContextMapper.java @@ -5,6 +5,7 @@ package org.gcube.informationsystem.resourceregistry.context; import java.util.HashMap; import java.util.Map; +import java.util.UUID; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseIntializator; @@ -23,10 +24,14 @@ public abstract class SecurityContextMapper { private static Logger logger = LoggerFactory .getLogger(SecurityContextMapper.class); + + public static final String ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000"; + public static final UUID ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT); - public static final String MANAGEMENT_SECURITY_CONTEXT = "ManagementSecurityContext"; + public static final String MANAGEMENT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff"; + public static final UUID MANAGEMENT_SECURITY_CONTEXT_UUID = UUID.fromString(MANAGEMENT_SECURITY_CONTEXT); - private static final Map> securityContextFactories; + private static final Map> securityContextFactories; static { try { @@ -48,20 +53,20 @@ public abstract class SecurityContextMapper { .ROUND_ROBIN_CONNECT.toString()); for (PermissionMode p : PermissionMode.values()) { - Map map = new HashMap<>(); - map.put(null, factory); + Map map = new HashMap<>(); + map.put(ADMIN_SECURITY_CONTEXT_UUID, factory); securityContextFactories.put(p, map); - map.put(null, factory); + map.put(ADMIN_SECURITY_CONTEXT_UUID, factory); } if (created) { OrientGraph orientGraph = factory.getTx(); SecurityContext.createSecurityContext(orientGraph, - MANAGEMENT_SECURITY_CONTEXT, true); + MANAGEMENT_SECURITY_CONTEXT_UUID, true); - getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT, + getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT_UUID, PermissionMode.READER); - getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT, + getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT_UUID, PermissionMode.WRITER); DatabaseIntializator.createEntitiesAndRelations(); @@ -108,18 +113,18 @@ public abstract class SecurityContextMapper { * @return */ public static OrientGraphFactory getSecurityContextFactory( - String contextID, PermissionMode permissionMode) { + UUID context, PermissionMode permissionMode) { OrientGraphFactory factory = null; - Map permissionSecurityContextFactories = securityContextFactories + Map permissionSecurityContextFactories = securityContextFactories .get(permissionMode); - factory = permissionSecurityContextFactories.get(contextID); + factory = permissionSecurityContextFactories.get(context); if (factory == null) { String username = getSecurityRoleOrUserName(permissionMode, - SecurityType.USER, contextID); + SecurityType.USER, context); String password = DatabaseEnvironment.DEFAULT_PASSWORDS .get(permissionMode); @@ -128,7 +133,7 @@ public abstract class SecurityContextMapper { factory.setConnectionStrategy(OStorageRemote.CONNECTION_STRATEGY .ROUND_ROBIN_CONNECT.toString()); - permissionSecurityContextFactories.put(contextID, factory); + permissionSecurityContextFactories.put(context, factory); } return factory; @@ -136,12 +141,12 @@ public abstract class SecurityContextMapper { public static String getSecurityRoleOrUserName( PermissionMode permissionMode, SecurityType securityType, - String contextID) { + UUID context) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(permissionMode); stringBuilder.append(securityType); stringBuilder.append("_"); - stringBuilder.append(contextID); + stringBuilder.append(context.toString()); return stringBuilder.toString(); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java index eacd49c..73c8913 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseIntializator.java @@ -3,11 +3,9 @@ */ package org.gcube.informationsystem.resourceregistry.dbinitialization; +import org.gcube.informationsystem.impl.utils.Entities; import org.gcube.informationsystem.impl.utils.discovery.ERDiscovery; -import org.gcube.informationsystem.model.embedded.Embedded; import org.gcube.informationsystem.model.embedded.ValueSchema; -import org.gcube.informationsystem.model.entity.Entity; -import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -112,13 +110,7 @@ public class DatabaseIntializator { } public static void createEntitiesAndRelations() throws Exception { - ERDiscovery.addPackage(Embedded.class.getPackage()); - ERDiscovery.addPackage(Entity.class.getPackage()); - ERDiscovery.addPackage(Relation.class.getPackage()); - - ERDiscovery erDiscovery = new ERDiscovery(); - erDiscovery.discoverERTypes(); - + ERDiscovery erDiscovery = Entities.getErdiscovery(); EntityRegistrationAction entityRegistrationAction = new EntityRegistrationAction(); entityRegistrationAction.manageEmbeddedClass(ValueSchema.class); erDiscovery.manageDiscoveredERTypes(entityRegistrationAction); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java index 463116b..500932a 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/Access.java @@ -1,12 +1,16 @@ package org.gcube.informationsystem.resourceregistry.resources; +import java.util.UUID; + import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; import org.gcube.informationsystem.resourceregistry.api.EntityManagement; import org.gcube.informationsystem.resourceregistry.api.Query; @@ -64,6 +68,7 @@ public class Access { @ApiResponses(value = { @ApiResponse(code=200, message="Successful query"), @ApiResponse(code=400, message="Invalid or Non-Idempotent Query")}) + @Produces(MediaType.APPLICATION_JSON) public String query(@QueryParam(AccessPath.QUERY_PARAM) String query, @QueryParam(AccessPath.LIMIT_PARAM) int limit, @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) @@ -81,10 +86,11 @@ public class Access { */ @GET @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String getFacet(@PathParam(ID_PATH_PARAM) String facetId) throws FacetNotFoundException, ResourceRegistryException { logger.info("Requested Facet with id {}", facetId); - return entityManager.readFacet(facetId); + return entityManager.readFacet(UUID.fromString(facetId)); } /** @@ -95,6 +101,7 @@ public class Access { */ @GET @Path(AccessPath.FACET_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String getFacetSchema(@PathParam(TYPE_PATH_PARAM) String facetType) throws SchemaNotFoundException { logger.info("Requested Facet Schema for type {}", facetType); @@ -108,11 +115,13 @@ public class Access { * @throws ResourceNotFoundException * @throws ResourceRegistryException */ - @GET @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @GET + @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.INSTANCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String getResource(@PathParam(ID_PATH_PARAM) String resourceId) throws ResourceNotFoundException, ResourceRegistryException { logger.info("Requested Resource with id {}", resourceId); - return entityManager.readResource(resourceId); + return entityManager.readResource(UUID.fromString(resourceId)); } /** @@ -121,7 +130,9 @@ public class Access { * @return * @throws SchemaNotFoundException */ - @GET @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @GET + @Path(AccessPath.RESOURCE_PATH_PART + "/" + AccessPath.SCHEMA_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String getResourceSchema(@PathParam(TYPE_PATH_PARAM) String resourceType) throws SchemaNotFoundException { logger.info("Requested Resource Schema for type {}", resourceType); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java index c465cf3..193634e 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ContextManager.java @@ -3,12 +3,16 @@ */ package org.gcube.informationsystem.resourceregistry.resources; +import java.util.UUID; + import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; import org.gcube.informationsystem.resourceregistry.api.ContextManagement; import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException; @@ -46,12 +50,13 @@ public class ContextManager { * @throws Exception */ @PUT + @Produces(MediaType.APPLICATION_JSON) public String create( @QueryParam(ContextPath.PARENT_CONTEXT_ID_PARAM) String parentUUID, @QueryParam(ContextPath.NAME_PARAM) String name) throws ContextCreationException, InternalException { logger.trace("requested to create context with name : {} ", name); - return contextManager.create(parentUUID, name); + return contextManager.create(UUID.fromString(parentUUID), name); } /** @@ -62,10 +67,11 @@ public class ContextManager { */ @DELETE @Path("{" + ID_PATH_PARAM + "}") - public String delete(@PathParam(ID_PATH_PARAM) String uuid) + @Produces(MediaType.APPLICATION_JSON) + public boolean delete(@PathParam(ID_PATH_PARAM) String uuid) throws ContextNotFoundException, ContextException { logger.trace("requested to delete context with id {} ", uuid); - return contextManager.delete(uuid); + return contextManager.delete(UUID.fromString(uuid)); } /** @@ -78,11 +84,12 @@ public class ContextManager { */ @POST @Path(ContextPath.RENAME_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String rename(@PathParam(ID_PATH_PARAM) String uuid, @QueryParam(ContextPath.NAME_PARAM) String name) throws ContextNotFoundException, ContextException { logger.trace("requested to rename context id {} with {} ", uuid, name); - return contextManager.rename(uuid, name); + return contextManager.rename(UUID.fromString(uuid), name); } /** @@ -95,13 +102,14 @@ public class ContextManager { */ @POST @Path(ContextPath.MOVE_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String move( @PathParam(ID_PATH_PARAM) String uuid, @QueryParam(ContextPath.PARENT_CONTEXT_ID_PARAM) String newParentUUID) throws ContextNotFoundException, ContextException { logger.trace("requested to move context id {} with new parend id {} ", uuid, newParentUUID); - return contextManager.move(newParentUUID, uuid); + return contextManager.move(UUID.fromString(newParentUUID), UUID.fromString(uuid)); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java index d49f8cc..8a9df42 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/EntityManager.java @@ -1,11 +1,16 @@ package org.gcube.informationsystem.resourceregistry.resources; +import java.util.UUID; + +import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; import org.gcube.informationsystem.model.relation.ConsistsOf; import org.gcube.informationsystem.model.relation.IsRelatedTo; @@ -49,6 +54,8 @@ public class EntityManager { */ @PUT @Path(EntityPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) public String createFacet( @PathParam(TYPE_PATH_PARAM) String type, @QueryParam(EntityPath.DEFINITION_PARAM) String definition) @@ -68,13 +75,15 @@ public class EntityManager { */ @POST @Path(EntityPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") + @Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) public String updateFacet( @PathParam(ID_PATH_PARAM) String uuid, @QueryParam(EntityPath.DEFINITION_PARAM) String definition) throws FacetNotFoundException, ResourceRegistryException { logger.trace("requested facet update for id {} with {}", uuid, definition); - return entityManager.updateFacet(uuid, definition); + return entityManager.updateFacet(UUID.fromString(uuid), definition); } /** @@ -89,7 +98,7 @@ public class EntityManager { public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) throws FacetNotFoundException, ResourceRegistryException { logger.trace("Requested to delete Facet with id {}", uuid); - return entityManager.deleteFacet(uuid); + return entityManager.deleteFacet(UUID.fromString(uuid)); } /* Resources Methods */ @@ -104,6 +113,8 @@ public class EntityManager { */ @PUT @Path(EntityPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") + @Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) public String createResource( @PathParam(TYPE_PATH_PARAM) String type, @QueryParam(EntityPath.DEFINITION_PARAM) String definition) @@ -125,7 +136,7 @@ public class EntityManager { public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception { logger.trace("requested resource deletion for id {}", uuid); - return entityManager.deleteResource(uuid); + return entityManager.deleteResource(UUID.fromString(uuid)); } /* Relations Methods */ @@ -147,6 +158,7 @@ public class EntityManager { + SOURCE_ID_PATH_PARAM + "}/" + EntityPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}") + @Produces(MediaType.APPLICATION_JSON) public String attachFacet( @PathParam(SOURCE_ID_PATH_PARAM) String resourceUUID, @PathParam(TARGET_ID_PATH_PARAM) String facetUUID, @@ -158,7 +170,7 @@ public class EntityManager { "requested to attach resource {} to facet {} ({} Type {}) with properties {}", resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(), type, properties); - return entityManager.attachFacet(resourceUUID, facetUUID, type, + return entityManager.attachFacet(UUID.fromString(resourceUUID), UUID.fromString(facetUUID), type, properties); } @@ -169,12 +181,11 @@ public class EntityManager { * @throws ResourceRegistryException */ @DELETE - @Path(EntityPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM - + "}") + @Path(EntityPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException { logger.trace("requested to detach {}", consistOfUUID); - return entityManager.detachFacet(consistOfUUID); + return entityManager.detachFacet(UUID.fromString(consistOfUUID)); } /** @@ -193,6 +204,8 @@ public class EntityManager { + SOURCE_ID_PATH_PARAM + "}/" + EntityPath.TARGET_PATH_PART + "/{" + TARGET_ID_PATH_PARAM + "}") + @Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON}) + @Produces(MediaType.APPLICATION_JSON) public String attachResource( @PathParam(SOURCE_ID_PATH_PARAM) String sourceResourceUUID, @PathParam(TARGET_ID_PATH_PARAM) String targetResourceUUID, @@ -203,8 +216,8 @@ public class EntityManager { "requested to attach source resource {} and target resource {} ({} Type {}) with properties {}", sourceResourceUUID, targetResourceUUID, IsRelatedTo.class.getSimpleName(), type, properties); - return entityManager.attachResource(sourceResourceUUID, - targetResourceUUID, type, properties); + return entityManager.attachResource(UUID.fromString(sourceResourceUUID), + UUID.fromString(targetResourceUUID), type, properties); } /** @@ -214,12 +227,11 @@ public class EntityManager { * @throws ResourceRegistryException */ @DELETE - @Path(EntityPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM - + "}") + @Path(EntityPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException { logger.trace("requested to detach {}", relatedToUUID); - return entityManager.detachResource(relatedToUUID); + return entityManager.detachResource(UUID.fromString(relatedToUUID)); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java index 991fe90..ce46a91 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/ResourceRegistryExceptionMapper.java @@ -1,5 +1,6 @@ package org.gcube.informationsystem.resourceregistry.resources; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; @@ -18,21 +19,19 @@ public class ResourceRegistryExceptionMapper implements ExceptionMapper\"" + parentContextUUID + "\""; + + "<>\"" + parentContext.toString() + "\""; logger.trace(select); String message = "A context with the same name (" + contextName + ") has been already created as child of " - + parentContextUUID + "(name=" + + parentContext.toString() + "(name=" + parent.getProperty(Context.NAME_PROPERTY).toString() + ")"; @@ -99,211 +99,271 @@ public class ContextManagementImpl implements ContextManagement { } - public Vertex getContext(OrientGraph orientGraph, String contextUUID) + public Vertex getContext(OrientGraph orientGraph, UUID context) throws ContextNotFoundException { try { return Utility.getEntityByUUID(orientGraph, org.gcube.informationsystem.model.entity.Context.NAME, - contextUUID); + context); } catch (ResourceRegistryException e) { throw new ContextNotFoundException(e.getMessage()); } } @Override - public String create(String parentContextUUID, String name) + public String create(UUID parentContext, String name) throws ContextCreationException, InternalException { - logger.info("Trying to create {} with name {} and parent {} UUID {}", - org.gcube.informationsystem.model.entity.Context.NAME, name, - org.gcube.informationsystem.model.entity.Context.NAME, - parentContextUUID); - - if (parentContextUUID != null && parentContextUUID.compareTo("") == 0) { - parentContextUUID = null; - } - - OrientGraph orientGraph = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER).getTx(); - - Vertex parent; - try { - parent = checkContext(orientGraph, parentContextUUID, name); - } catch (ContextException e) { - throw new ContextCreationException(e.getMessage()); - } - + OrientGraph orientGraph = null; UUID uuid = UUID.randomUUID(); - String uuidString = uuid.toString(); - - SecurityContext.createSecurityContext(orientGraph, uuidString, true); try { + logger.info( + "Trying to create {} with name {} and parent {} UUID {}", + org.gcube.informationsystem.model.entity.Context.NAME, + name, + org.gcube.informationsystem.model.entity.Context.NAME, + parentContext); + + orientGraph = SecurityContextMapper.getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER).getTx(); + + Vertex parent; + try { + parent = checkContext(orientGraph, parentContext, name); + } catch (ContextException e) { + throw new ContextCreationException(e.getMessage()); + } + + SecurityContext.createSecurityContext(orientGraph, uuid, true); OrientVertex context = orientGraph.addVertex("class:" + Context.NAME); context.setProperty(Context.NAME_PROPERTY, name); context.save(); - + HeaderUtility.addHeader(context, uuid); - if (parentContextUUID != null) { - OrientEdge edge = orientGraph.addEdge(null, parent, context, IsParentOf.NAME); + if (parentContext != null) { + OrientEdge edge = orientGraph.addEdge(null, parent, context, + IsParentOf.NAME); HeaderUtility.addHeader(edge, null); edge.save(); } - - SecurityContext.addToSecurityContext(orientGraph, context, - uuidString); - - String contextJsonString = Utility.toJsonString(context, true); - logger.trace("Creating {}", contextJsonString); + + SecurityContext.addToSecurityContext(orientGraph, context, uuid); + + logger.trace("Creating {}", Utility.toJsonString(context, true)); orientGraph.commit(); - logger.info("Context {} created", contextJsonString); - return uuidString; + Vertex readContext = getContext(orientGraph, uuid); + logger.info("Context {} created", + Utility.toJsonString((OrientVertex) readContext, true)); + return Utility.toJsonString((OrientVertex) readContext, false); + } catch (ContextCreationException e) { + throw e; } catch (Exception e) { - orientGraph.rollback(); - SecurityContext - .deleteSecurityContext(orientGraph, uuidString, true); + if (orientGraph != null) { + orientGraph.rollback(); + SecurityContext.deleteSecurityContext(orientGraph, uuid, true); + } throw new InternalException(e.getMessage()); } finally { - orientGraph.shutdown(); + if (orientGraph != null) { + orientGraph.shutdown(); + } } } @Override - public String read(String contextUUID) throws ContextNotFoundException, + public String read(UUID contextUUID) throws ContextNotFoundException, ContextException { - OrientGraph orientGraph = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.READER).getTx(); + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.READER).getTx(); Vertex context = getContext(orientGraph, contextUUID); - return Utility.toJsonString(context, false); + return Utility.toJsonString((OrientVertex) context, false); } @Override - public String rename(String contextUUID, String newName) + public String rename(UUID contextUUID, String newName) throws ContextNotFoundException, ContextException { - logger.info("Trying to rename {} with UUID {} to {}", - org.gcube.informationsystem.model.entity.Context.NAME, - contextUUID, newName); + OrientGraph orientGraph = null; - OrientGraph orientGraph = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER).getTx(); + try { + logger.info("Trying to rename {} with UUID {} to {}", Context.NAME, + contextUUID, newName); - Vertex context = getContext(orientGraph, contextUUID); + orientGraph = SecurityContextMapper.getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER).getTx(); - String parentUUID = null; + Vertex context = getContext(orientGraph, contextUUID); - Iterable edges = context.getEdges(Direction.IN, IsParentOf.NAME); - if (edges != null && edges.iterator().hasNext()) { - Iterator iteratorEdge = edges.iterator(); - Edge edge = iteratorEdge.next(); + UUID parentUUID = null; - if (iteratorEdge.hasNext()) { - throw new ContextException(""); + Iterable edges = context.getEdges(Direction.IN, + IsParentOf.NAME); + if (edges != null && edges.iterator().hasNext()) { + Iterator iteratorEdge = edges.iterator(); + Edge edge = iteratorEdge.next(); + + if (iteratorEdge.hasNext()) { + throw new ContextException(""); + } + + Vertex parent = edge.getVertex(Direction.OUT); + parentUUID = UUID.fromString((String) parent.getProperty(Context.HEADER_PROPERTY + "." + + Header.UUID_PROPERTY)); } - Vertex parent = edge.getVertex(Direction.OUT); - parentUUID = parent.getProperty( - Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY) - .toString(); + checkContext(orientGraph, parentUUID, newName); + context.setProperty(Context.NAME_PROPERTY, newName); + + orientGraph.commit(); + + String contextJsonString = Utility.toJsonString(context, true); + logger.info("Context renamed {}", contextJsonString); + + return Utility.toJsonString((OrientVertex) context, false); + } catch (ContextException ce) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw ce; + } catch (Exception e) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ContextException(e.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } } - - checkContext(orientGraph, parentUUID, newName); - context.setProperty(Context.NAME_PROPERTY, newName); - - orientGraph.commit(); - - String contextJsonString = Utility.toJsonString(context, true); - logger.info("Context renamed {}", contextJsonString); - - orientGraph.shutdown(); - - return contextUUID; } @Override - public String move(String newParentUUID, String contextToMoveUUID) + public String move(UUID newParentUUID, UUID contextToMoveUUID) throws ContextNotFoundException, ContextException { - logger.info( - "Trying to move {} with UUID {} as child of {} with UUID {}", - org.gcube.informationsystem.model.entity.Context.NAME, - contextToMoveUUID, - org.gcube.informationsystem.model.entity.Context.NAME, - newParentUUID); + OrientGraph orientGraph = null; + try { + logger.info( + "Trying to move {} with UUID {} as child of {} with UUID {}", + Context.NAME, contextToMoveUUID, Context.NAME, + newParentUUID); - OrientGraph orientGraph = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER).getTx(); - Vertex context = getContext(orientGraph, contextToMoveUUID); + orientGraph = SecurityContextMapper.getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER).getTx(); + Vertex context = getContext(orientGraph, contextToMoveUUID); - logger.trace("Context to move {}", Utility.toJsonString(context, true)); + logger.trace("Context to move {}", + Utility.toJsonString(context, true)); - checkContext(orientGraph, newParentUUID, - context.getProperty(Context.NAME_PROPERTY).toString()); + checkContext(orientGraph, newParentUUID, + context.getProperty(Context.NAME_PROPERTY).toString()); - // Removing the old parent relationship if any - Iterable edges = context.getEdges(Direction.IN, IsParentOf.NAME); - if (edges != null && edges.iterator().hasNext()) { - Iterator edgeIterator = edges.iterator(); - Edge edge = edgeIterator.next(); - logger.trace("Removing {} {}", Edge.class.getSimpleName(), edge); - edge.remove(); + // Removing the old parent relationship if any + Iterable edges = context.getEdges(Direction.IN, + IsParentOf.NAME); + if (edges != null && edges.iterator().hasNext()) { + Iterator edgeIterator = edges.iterator(); + Edge edge = edgeIterator.next(); + logger.trace("Removing {} {}", Edge.class.getSimpleName(), edge); + edge.remove(); + } + + if (newParentUUID != null) { + Vertex parent = getContext(orientGraph, newParentUUID); + logger.trace("New Parent Context {}", + Utility.toJsonString(parent, true)); + OrientEdge edge = orientGraph.addEdge(null, parent, context, + IsParentOf.NAME); + HeaderUtility.addHeader(edge, null); + edge.save(); + } + + orientGraph.commit(); + + context = getContext(orientGraph, contextToMoveUUID); + String contextJsonString = Utility.toJsonString(context, true); + logger.info("Context moved {}", contextJsonString); + + return Utility.toJsonString((OrientVertex) context, false); + + } catch (ContextException ce) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw ce; + } catch (Exception e) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ContextException(e.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } } - - if (newParentUUID != null) { - Vertex parent = getContext(orientGraph, newParentUUID); - logger.trace("New Parent Context {}", - Utility.toJsonString(parent, true)); - orientGraph.addEdge(null, parent, context, IsParentOf.NAME); - } - - orientGraph.commit(); - - context = getContext(orientGraph, contextToMoveUUID); - String contextJsonString = Utility.toJsonString(context, true); - logger.info("Context moved {}", contextJsonString); - - orientGraph.shutdown(); - return contextToMoveUUID; } @Override - public String delete(String uuid) throws ContextNotFoundException, + public boolean delete(UUID uuid) throws ContextNotFoundException, ContextException { - logger.info("Trying to remove {} with UUID {}", - org.gcube.informationsystem.model.entity.Context.NAME, uuid); + OrientGraph orientGraph = null; - OrientGraph orientGraph = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER).getTx(); - Vertex context = getContext(orientGraph, uuid); - logger.trace("Context to be delete {}", - Utility.toJsonString(context, true)); + try { + logger.info("Trying to remove {} with UUID {}", Context.NAME, uuid); - Iterable edges = context.getEdges(Direction.OUT, IsParentOf.NAME); - if (edges != null && edges.iterator().hasNext()) { - throw new ContextException( - "Only context with no children can be deleted"); + orientGraph = SecurityContextMapper.getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER).getTx(); + + Vertex context = getContext(orientGraph, uuid); + logger.trace("Context to be delete {}", + Utility.toJsonString(context, true)); + + Iterable edges = context.getEdges(Direction.OUT, + IsParentOf.NAME); + if (edges != null && edges.iterator().hasNext()) { + throw new ContextException( + "Only context with no children can be deleted"); + } + + SecurityContext.deleteSecurityContext(orientGraph, uuid, false); + + context.remove(); + + orientGraph.commit(); + logger.info("{} with UUID {} successfully removed", Context.NAME, + uuid); + return true; + + } catch (ContextException ce) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw ce; + } catch (Exception e) { + if (orientGraph != null) { + orientGraph.rollback(); + } + throw new ContextException(e.getMessage()); + } finally { + if (orientGraph != null) { + orientGraph.shutdown(); + } } - - SecurityContext.deleteSecurityContext(orientGraph, uuid, false); - - context.remove(); - - orientGraph.commit(); - orientGraph.shutdown(); - - logger.info("{} with UUID {} successfully removed", - org.gcube.informationsystem.model.entity.Context.NAME, uuid); - - return uuid; } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java index 9a104f0..bd5fcb0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImpl.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import java.util.UUID; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; @@ -59,7 +60,7 @@ public class EntityManagementImpl implements EntityManagement { private static Logger logger = LoggerFactory .getLogger(EntityManagementImpl.class); - public Vertex getEntity(OrientGraph orientGraph, String uuid, + public Vertex getEntity(OrientGraph orientGraph, UUID uuid, String entityType, Class entityClass) throws FacetNotFoundException, ResourceNotFoundException, ResourceRegistryException { @@ -87,7 +88,7 @@ public class EntityManagementImpl implements EntityManagement { public Edge getRelation( OrientGraph orientGraph, - String uuid, + UUID uuid, String relationType, @SuppressWarnings("rawtypes") Class relationClass) throws ResourceRegistryException { @@ -308,7 +309,7 @@ public class EntityManagementImpl implements EntityManagement { throw new ResourceRegistryException(error); } - String targetUUID = targetHeader.getUUID().toString(); + UUID targetUUID = targetHeader.getUUID(); String entityType = getClassProperty(target); targetVertex = getEntity(orientGraph, targetUUID, entityType, targetClass); @@ -427,8 +428,8 @@ public class EntityManagementImpl implements EntityManagement { } public Edge createEdgeRelation( - String sourceUUID, Class sourceClass, - String targetUUID, Class targetClass, + UUID sourceUUID, Class sourceClass, + UUID targetUUID, Class targetClass, String relationType, @SuppressWarnings("rawtypes") Class relationBaseClass, String jsonProperties) throws FacetNotFoundException, ResourceNotFoundException, @@ -555,13 +556,13 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public String readFacet(String uuid) throws FacetNotFoundException, + public String readFacet(UUID uuid) throws FacetNotFoundException, ResourceRegistryException { return readFacet(uuid, Facet.NAME); } @Override - public String readFacet(String uuid, String facetType) + public String readFacet(UUID uuid, String facetType) throws FacetNotFoundException, ResourceRegistryException { OrientGraph orientGraph = null; @@ -587,7 +588,7 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public String updateFacet(String uuid, String jsonRepresentation) + public String updateFacet(UUID uuid, String jsonRepresentation) throws ResourceRegistryException { OrientGraph orientGraph = null; @@ -661,7 +662,7 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public boolean deleteFacet(String uuid) throws FacetNotFoundException, + public boolean deleteFacet(UUID uuid) throws FacetNotFoundException, ResourceRegistryException { OrientGraph orientGraph = null; @@ -693,7 +694,7 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public String attachFacet(String resourceUUID, String facetUUID, + public String attachFacet(UUID resourceUUID, UUID facetUUID, String consistOfType, String jsonProperties) throws FacetNotFoundException, ResourceNotFoundException, ResourceRegistryException { @@ -705,7 +706,7 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public boolean detachFacet(String consistOfUUID) + public boolean detachFacet(UUID consistOfUUID) throws ResourceRegistryException { OrientGraph orientGraph = null; @@ -739,8 +740,8 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public String attachResource(String sourceResourceUuid, - String targetResourceUuid, String relatedToType, + public String attachResource(UUID sourceResourceUuid, + UUID targetResourceUuid, String relatedToType, String jsonProperties) throws ResourceNotFoundException, ResourceRegistryException { Edge edge = createEdgeRelation(sourceResourceUuid, Resource.class, @@ -751,7 +752,7 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public boolean detachResource(String relatedToUUID) + public boolean detachResource(UUID relatedToUUID) throws ResourceRegistryException { OrientGraph orientGraph = null; @@ -866,12 +867,12 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public String readResource(String uuid) throws ResourceNotFoundException { + public String readResource(UUID uuid) throws ResourceNotFoundException { return readResource(uuid, Resource.NAME); } @Override - public String readResource(String uuid, String resourceType) + public String readResource(UUID uuid, String resourceType) throws ResourceNotFoundException { OrientGraph orientGraph = null; @@ -898,7 +899,7 @@ public class EntityManagementImpl implements EntityManagement { } @Override - public boolean deleteResource(String uuid) + public boolean deleteResource(UUID uuid) throws ResourceNotFoundException, ResourceRegistryException { OrientGraph orientGraph = null; @@ -913,6 +914,7 @@ public class EntityManagementImpl implements EntityManagement { resource.remove(); orientGraph.commit(); + return true; } catch (ResourceNotFoundException fnfe) { if (orientGraph != null) { orientGraph.rollback(); @@ -928,8 +930,6 @@ public class EntityManagementImpl implements EntityManagement { orientGraph.shutdown(); } } - - return true; } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImpl.java index da667c8..777ff05 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/impl/SchemaManagementImpl.java @@ -50,16 +50,19 @@ public class SchemaManagementImpl implements SchemaManagement { private static Logger logger = LoggerFactory .getLogger(SchemaManagementImpl.class); - protected static OClass getEntityOClass(OrientGraphNoTx orientGraphNoTx, String entityType) throws SchemaException { + protected static OClass getEntityOClass(OrientGraphNoTx orientGraphNoTx, + String entityType) throws SchemaException { OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OSchema oSchema = oMetadata.getSchema(); return oSchema.getClass(entityType); } - + protected OClass getTypeSchema(String type, String baseType) throws SchemaNotFoundException { OrientGraphFactory orientGraphFactory = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.READER); + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.READER); OrientGraphNoTx orientGraphNoTx = null; try { @@ -97,8 +100,8 @@ public class SchemaManagementImpl implements SchemaManagement { String baseType) throws SchemaException { Set superClasses = typeDefinition.getSuperclasses(); - if (baseType !=null){ - if(superClasses == null || superClasses.size() == 0){ + if (baseType != null) { + if (superClasses == null || superClasses.size() == 0) { throw new RuntimeException( String.format( "No Superclass found in schema %s. The Type Definition must extend %s", @@ -128,7 +131,9 @@ public class SchemaManagementImpl implements SchemaManagement { protected String getTypeSchemaAsString(String type, String baseType) throws SchemaNotFoundException { OrientGraphFactory orientGraphFactory = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.READER); + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.READER); OrientGraphNoTx orientGraphNoTx = null; try { @@ -148,7 +153,9 @@ public class SchemaManagementImpl implements SchemaManagement { Class baseType) throws SchemaException { OrientGraphFactory orientGraphFactory = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER); + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER); OrientGraphNoTx orientGraphNoTx = null; try { @@ -165,8 +172,10 @@ public class SchemaManagementImpl implements SchemaManagement { ovt.setDescription(typeDefinition.getDescription()); try { ovt.setAbstract(typeDefinition.isAbstractType()); - }catch(Exception e){ - logger.error("Unable to set the Vertex Type {} as abstract. This is an OrientDB bug. The Type will be created as it is not abstarct.", typeDefinition.getName()); + } catch (Exception e) { + logger.error( + "Unable to set the Vertex Type {} as abstract. This is an OrientDB bug. The Type will be created as it is not abstarct.", + typeDefinition.getName()); } List oSuperclasses = getSuperclassesAndCheckCompliancy( @@ -185,19 +194,21 @@ public class SchemaManagementImpl implements SchemaManagement { property.getName(), OType.getById(property.getType().byteValue())); ovp.setDescription(property.getDescription()); - - /* Mandatory and notNull does not work in distributed mode: - * so that on Type declaration they are forced to false + + /* + * Mandatory and notNull does not work in distributed mode: + * so that on Type declaration they are forced to false * ovp.setMandatory(property.isMandatory()); * ovp.setNotNull(property.isNotnull()); - */ + */ ovp.setMandatory(false); ovp.setNotNull(false); - + ovp.setReadonly(property.isReadonly()); ovp.setRegexp(property.getRegexpr()); if (property.getLinkedClass() != null) { - OClass linkedClass = getEntityOClass(orientGraphNoTx, property.getLinkedClass()); + OClass linkedClass = getEntityOClass(orientGraphNoTx, + property.getLinkedClass()); if (linkedClass == null) { logger.trace("class {} not found in schema", property.getLinkedClass()); @@ -220,11 +231,11 @@ public class SchemaManagementImpl implements SchemaManagement { } } - //orientGraphNoTx.commit(); - + // orientGraphNoTx.commit(); + OClass oClass = getTypeSchema(typeDefinition.getName(), null); return serializeOClass(oClass); - + } catch (Exception e) { throw new SchemaException(e); } finally { @@ -237,7 +248,9 @@ public class SchemaManagementImpl implements SchemaManagement { protected String registerEdgeTypeSchema(String jsonSchema, String baseType) throws SchemaException { OrientGraphFactory orientGraphFactory = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER); + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER); OrientGraphNoTx orientGraphNoTx = null; try { @@ -254,10 +267,12 @@ public class SchemaManagementImpl implements SchemaManagement { oet.setDescription(typeDefinition.getDescription()); try { oet.setAbstract(typeDefinition.isAbstractType()); - }catch(Exception e){ - logger.error("Unable to set the Edge Type {} as abstract. This is an OrientDB bug. The Type will be created as it is not abstarct.", typeDefinition.getName()); + } catch (Exception e) { + logger.error( + "Unable to set the Edge Type {} as abstract. This is an OrientDB bug. The Type will be created as it is not abstarct.", + typeDefinition.getName()); } - + List oSuperclasses = getSuperclassesAndCheckCompliancy( orientGraphNoTx, typeDefinition, baseType); oet.setSuperClasses(oSuperclasses); @@ -266,15 +281,16 @@ public class SchemaManagementImpl implements SchemaManagement { OProperty op = oet.createProperty(property.getName(), OType.getById(property.getType().byteValue())); op.setDescription(property.getDescription()); - - /* Mandatory and notNull does not work in distributed mode: - * so that on Type declaration they are forced to false + + /* + * Mandatory and notNull does not work in distributed mode: so + * that on Type declaration they are forced to false * op.setMandatory(property.isMandatory()); * op.setNotNull(property.isNotnull()); - */ + */ op.setMandatory(false); op.setNotNull(false); - + op.setReadonly(property.isReadonly()); op.setRegexp(property.getRegexpr()); if (property.getLinkedClass() != null) { @@ -297,8 +313,8 @@ public class SchemaManagementImpl implements SchemaManagement { } } - //orientGraphNoTx.commit(); - + // orientGraphNoTx.commit(); + OClass oClass = getTypeSchema(typeDefinition.getName(), null); return serializeOClass(oClass); } catch (Exception e) { @@ -313,19 +329,22 @@ public class SchemaManagementImpl implements SchemaManagement { public String registerDocumentSchema(String jsonSchema) throws SchemaException { OrientGraphFactory orientGraphFactory = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER); + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.WRITER); OrientGraphNoTx orientGraphNoTx = null; try { logger.info("Trying to register {}", jsonSchema); - + ObjectMapper mapper = new ObjectMapper(); TypeDefinition typeDefinition = mapper.readValue(jsonSchema, - TypeDefinition.class); - + TypeDefinition.class); + orientGraphNoTx = orientGraphFactory.getNoTx(); - ODatabaseDocumentTx oDatabaseDocumentTx = orientGraphNoTx.getRawGraph(); + ODatabaseDocumentTx oDatabaseDocumentTx = orientGraphNoTx + .getRawGraph(); OMetadata oMetadata = oDatabaseDocumentTx.getMetadata(); OSchema oSchema = oMetadata.getSchema(); @@ -338,21 +357,21 @@ public class SchemaManagementImpl implements SchemaManagement { oClass.setSuperClasses(oSuperclasses); oDatabaseDocumentTx.commit(); - - + for (Property property : typeDefinition.getProperties()) { OProperty ovp = oClass.createProperty(property.getName(), OType.getById(property.getType().byteValue())); ovp.setDescription(property.getDescription()); - - /* Mandatory and notNull does not work in distributed mode: - * so that on Type declaration they are forced to false + + /* + * Mandatory and notNull does not work in distributed mode: so + * that on Type declaration they are forced to false * ovp.setMandatory(property.isMandatory()); * ovp.setNotNull(property.isNotnull()); - */ + */ ovp.setMandatory(false); ovp.setNotNull(false); - + ovp.setReadonly(property.isReadonly()); ovp.setRegexp(property.getRegexpr()); if (property.getLinkedClass() != null) { @@ -374,11 +393,11 @@ public class SchemaManagementImpl implements SchemaManagement { ovp.setLinkedClass(linkedClass); } } - - //orientGraphNoTx.commit(); - + + // orientGraphNoTx.commit(); + return serializeOClass(oClass); - + } catch (Exception e) { throw new SchemaException(e); } finally { @@ -389,62 +408,46 @@ public class SchemaManagementImpl implements SchemaManagement { } /* - public void addDocumentProperties(TypeDefinition typeDefinition) throws SchemaException { - OrientGraphFactory orientGraphFactory = SecurityContextMapper - .getSecurityContextFactory(null, PermissionMode.WRITER); + * public void addDocumentProperties(TypeDefinition typeDefinition) throws + * SchemaException { OrientGraphFactory orientGraphFactory = + * SecurityContextMapper .getSecurityContextFactory(null, + * PermissionMode.WRITER); + * + * OrientGraphNoTx orientGraphNoTx = null; try { + * logger.trace("Adding properties to {}", typeDefinition); + * + * OClass oClass = getEntityOClass(orientGraphNoTx, + * typeDefinition.getName()); + * + * orientGraphNoTx = orientGraphFactory.getNoTx(); + * + * for (Property property : typeDefinition.getProperties()) { OProperty ovp + * = oClass.createProperty(property.getName(), + * OType.getById(property.getType().byteValue())); + * ovp.setDescription(property.getDescription()); + * + * /* Mandatory and notNull does not work in distributed mode: so that on + * Type declaration they are forced to false + * ovp.setMandatory(property.isMandatory()); + * ovp.setNotNull(property.isNotnull()); / ovp.setMandatory(false); + * ovp.setNotNull(false); + * + * ovp.setReadonly(property.isReadonly()); + * ovp.setRegexp(property.getRegexpr()); if (property.getLinkedClass() != + * null) { OClass linkedClass = getEntityOClass(orientGraphNoTx, + * property.getLinkedClass()); if (linkedClass == null) { + * logger.trace("class {} not found in schema", property.getLinkedClass()); + * throw new Exception("class " + property.getLinkedClass() + + * " not found in schema"); } + * + * if (linkedClass.isEdgeType() || linkedClass.isVertexType()) { throw new + * Exception( "An Embedded Field cannot be an Entity or a Relation"); } + * + * ovp.setLinkedClass(linkedClass); } } } catch (Exception e) { throw new + * SchemaException(e); } finally { if (orientGraphNoTx != null) { + * orientGraphNoTx.shutdown(); } } } + */ - OrientGraphNoTx orientGraphNoTx = null; - try { - logger.trace("Adding properties to {}", typeDefinition); - - OClass oClass = getEntityOClass(orientGraphNoTx, typeDefinition.getName()); - - orientGraphNoTx = orientGraphFactory.getNoTx(); - - for (Property property : typeDefinition.getProperties()) { - OProperty ovp = oClass.createProperty(property.getName(), - OType.getById(property.getType().byteValue())); - ovp.setDescription(property.getDescription()); - - /* Mandatory and notNull does not work in distributed mode: - * so that on Type declaration they are forced to false - * ovp.setMandatory(property.isMandatory()); - * ovp.setNotNull(property.isNotnull()); - * / - ovp.setMandatory(false); - ovp.setNotNull(false); - - ovp.setReadonly(property.isReadonly()); - ovp.setRegexp(property.getRegexpr()); - if (property.getLinkedClass() != null) { - OClass linkedClass = getEntityOClass(orientGraphNoTx, - property.getLinkedClass()); - if (linkedClass == null) { - logger.trace("class {} not found in schema", - property.getLinkedClass()); - throw new Exception("class " - + property.getLinkedClass() - + " not found in schema"); - } - - if (linkedClass.isEdgeType() || linkedClass.isVertexType()) { - throw new Exception( - "An Embedded Field cannot be an Entity or a Relation"); - } - - ovp.setLinkedClass(linkedClass); - } - } - } catch (Exception e) { - throw new SchemaException(e); - } finally { - if (orientGraphNoTx != null) { - orientGraphNoTx.shutdown(); - } - } - } - */ - @Override public String registerEntitySchema(String jsonSchema) throws SchemaException { @@ -519,24 +522,17 @@ public class SchemaManagementImpl implements SchemaManagement { @Override public String registerEmbeddedTypeSchema(String jsonSchema) throws SchemaException { - + return registerDocumentSchema(jsonSchema); /* - ObjectMapper mapper = new ObjectMapper(); - TypeDefinition typeDefinition; - try { - typeDefinition = mapper.readValue(jsonSchema, - TypeDefinition.class); - registerDocumentSchema(typeDefinition); - addDocumentProperties(typeDefinition); - - return jsonSchema; - } catch (SchemaException e) { - throw e; - } catch (Exception e) { - throw new SchemaException(e); - } - */ + * ObjectMapper mapper = new ObjectMapper(); TypeDefinition + * typeDefinition; try { typeDefinition = mapper.readValue(jsonSchema, + * TypeDefinition.class); registerDocumentSchema(typeDefinition); + * addDocumentProperties(typeDefinition); + * + * return jsonSchema; } catch (SchemaException e) { throw e; } catch + * (Exception e) { throw new SchemaException(e); } + */ } @Override diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/ContextUtility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/ContextUtility.java index adfbc42..c91325c 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/ContextUtility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/ContextUtility.java @@ -4,6 +4,7 @@ package org.gcube.informationsystem.resourceregistry.resources.utils; import java.util.Iterator; +import java.util.UUID; import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.impl.ScopeBean; @@ -33,43 +34,48 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; * */ public class ContextUtility { - - private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class); - + + private static final Logger logger = LoggerFactory + .getLogger(ContextUtility.class); + public static void addToActualContext(OrientGraph orientGraph, Vertex vertex) throws ContextException { - String contextID = ContextUtility.getActualContextUUID(); - SecurityContext.addToSecurityContext(orientGraph, vertex, contextID); + UUID contextUUID = ContextUtility.getActualContextUUID(); + SecurityContext.addToSecurityContext(orientGraph, vertex, contextUUID); } public static void addToActualContext(OSecurity oSecurity, Vertex vertex) throws ContextException { - String contextID = ContextUtility.getActualContextUUID(); - SecurityContext.addToSecurityContext(oSecurity, vertex, contextID); + UUID contextUUID = ContextUtility.getActualContextUUID(); + SecurityContext.addToSecurityContext(oSecurity, vertex, contextUUID); } public static void addToActualContext(OrientGraph orientGraph, Edge edge) throws ContextException { - String contextID = ContextUtility.getActualContextUUID(); - SecurityContext.addToSecurityContext(orientGraph, edge, contextID); + UUID contextUUID = ContextUtility.getActualContextUUID(); + SecurityContext.addToSecurityContext(orientGraph, edge, contextUUID); } public static void addToActualContext(OSecurity oSecurity, Edge edge) throws ContextException { - String contextID = ContextUtility.getActualContextUUID(); - SecurityContext.addToSecurityContext(oSecurity, edge, contextID); + UUID contextUUID = ContextUtility.getActualContextUUID(); + SecurityContext.addToSecurityContext(oSecurity, edge, contextUUID); } - protected static String getContextUUIDFromContextVertex(Vertex vertex) { + protected static UUID getContextUUIDFromContextVertex(Vertex vertex) { ODocument header = vertex.getProperty(Entity.HEADER_PROPERTY); - String contextID = header.field(org.gcube.informationsystem.model.embedded.Header.UUID_PROPERTY); - return contextID; + String contextID = header + .field(org.gcube.informationsystem.model.embedded.Header.UUID_PROPERTY); + return UUID.fromString(contextID); } - public static String getActualContextUUID() throws ContextException { + public static UUID getActualContextUUID() throws ContextException { try { String scope = ScopeProvider.instance.get(); - OrientGraphFactory factory = SecurityContextMapper.getSecurityContextFactory(null, PermissionMode.READER); + OrientGraphFactory factory = SecurityContextMapper + .getSecurityContextFactory( + SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID, + PermissionMode.READER); Vertex context = ContextUtility.getContextVertexByFullName( factory.getTx(), scope); return getContextUUIDFromContextVertex(context); @@ -79,12 +85,12 @@ public class ContextUtility { } } - - public static OrientGraphFactory getFactory(PermissionMode permissionMode) throws ResourceRegistryException{ + public static OrientGraphFactory getFactory(PermissionMode permissionMode) + throws ResourceRegistryException { try { - String contextID = getActualContextUUID(); - return SecurityContextMapper - .getSecurityContextFactory(contextID, permissionMode); + UUID contextUUID = getActualContextUUID(); + return SecurityContextMapper.getSecurityContextFactory(contextUUID, + permissionMode); } catch (ContextException ce) { logger.error("Unable to retrieve context.", ce); throw ce; @@ -93,7 +99,7 @@ public class ContextUtility { throw new ResourceRegistryException(e); } } - + public static OrientGraph getActualSecurityContextGraph( PermissionMode permissionMode) throws ResourceRegistryException { try { @@ -107,7 +113,7 @@ public class ContextUtility { throw new ResourceRegistryException(e); } } - + public static OrientGraphNoTx getActualSecurityContextGraphNoTx( PermissionMode permissionMode) throws ResourceRegistryException { try { @@ -121,7 +127,7 @@ public class ContextUtility { throw new ResourceRegistryException(e); } } - + public static ODatabaseDocumentTx getActualSecurityContextDatabaseTx( PermissionMode permissionMode) throws ResourceRegistryException { try { @@ -135,8 +141,7 @@ public class ContextUtility { throw new ResourceRegistryException(e); } } - - + public static Vertex getContextVertexByFullName(OrientGraph orientGraph, String fullName) throws ContextNotFoundException { @@ -164,7 +169,7 @@ public class ContextUtility { logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true)); - + if (iterator.hasNext()) { throw new ContextNotFoundException( "Found more than one context with name " + name @@ -177,10 +182,11 @@ public class ContextUtility { public static String getActualSecurityRoleOrUserName( SecurityContextMapper.PermissionMode permissionMode, - SecurityContextMapper.SecurityType securityType) throws ContextException { - String contexUUID = getActualContextUUID(); + SecurityContextMapper.SecurityType securityType) + throws ContextException { + UUID contextUUID = getActualContextUUID(); return SecurityContextMapper.getSecurityRoleOrUserName(permissionMode, - securityType, contexUUID); + securityType, contextUUID); } - + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/Utility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/Utility.java index 804f654..f6c3eb9 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/Utility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/resources/utils/Utility.java @@ -6,6 +6,7 @@ package org.gcube.informationsystem.resourceregistry.resources.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; @@ -77,7 +78,7 @@ public class Utility { } public static Vertex getEntityByUUID(OrientGraph orientGraph, - String entityType, String uuid) throws ResourceRegistryException { + String entityType, UUID uuid) throws ResourceRegistryException { if (entityType == null) { entityType = Entity.NAME; @@ -86,7 +87,7 @@ public class Utility { // TODO Rewrite using Gremlin String select = "SELECT FROM " + entityType + " WHERE " + Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY + " = \"" - + uuid + "\""; + + uuid.toString() + "\""; OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery( select); @@ -95,7 +96,7 @@ public class Utility { .execute(); if (vertexes == null || !vertexes.iterator().hasNext()) { String error = String.format("No %s with UUID %s was found", - entityType, uuid); + entityType, uuid.toString()); logger.info(error); throw new EntityException(error); } @@ -103,11 +104,11 @@ public class Utility { Iterator iterator = vertexes.iterator(); Vertex entity = iterator.next(); - logger.trace("{} with {} is : {}", entityType, uuid, Utility.toJsonString(entity, true)); + logger.trace("{} with {} is : {}", entityType, uuid.toString(), Utility.toJsonString(entity, true)); if (iterator.hasNext()) { throw new ResourceRegistryException("Found more than one " - + entityType + " with uuid " + uuid + + entityType + " with uuid " + uuid.toString() + ". This is a fatal error please contact Admnistrator"); } @@ -115,7 +116,7 @@ public class Utility { } public static Edge getRelationByUUID(OrientGraph orientGraph, - String relationType, String uuid) throws ResourceRegistryException { + String relationType, UUID uuid) throws ResourceRegistryException { if (relationType == null) { relationType = Relation.class.getSimpleName(); @@ -124,14 +125,14 @@ public class Utility { // TODO Rewrite using Gremlin String select = "SELECT FROM " + relationType + " WHERE " + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY - + " = \"" + uuid + "\""; + + " = \"" + uuid.toString() + "\""; OSQLSynchQuery osqlSynchQuery = new OSQLSynchQuery(select); Iterable edges = orientGraph.command(osqlSynchQuery).execute(); if (edges == null || !edges.iterator().hasNext()) { String error = String.format("No %s with UUID %s was found", - relationType, uuid); + relationType, uuid.toString()); logger.info(error); throw new FacetNotFoundException(error); } @@ -139,12 +140,12 @@ public class Utility { Iterator iterator = edges.iterator(); Edge relation = iterator.next(); - logger.trace("{} with {} is : {}", relationType, uuid, + logger.trace("{} with {} is : {}", relationType, uuid.toString(), Utility.toJsonString(relation, true)); if (iterator.hasNext()) { throw new ResourceRegistryException("Found more than one " - + relationType + " with uuid " + uuid + + relationType + " with uuid " + uuid.toString() + ". This is a fatal error please contact Admnistrator"); } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/ContextManagerFactory.java b/src/test/java/org/gcube/informationsystem/resourceregistry/ContextManagerFactory.java index d2c119c..579cd0b 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/ContextManagerFactory.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/ContextManagerFactory.java @@ -1,5 +1,7 @@ package org.gcube.informationsystem.resourceregistry; +import java.util.UUID; + import org.gcube.informationsystem.resourceregistry.api.ContextManagement; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; @@ -17,34 +19,34 @@ public class ContextManagerFactory implements Factory { return new ContextManagement() { @Override - public String delete(String uuid) throws ContextNotFoundException { - return "{fake resource}"; + public boolean delete(UUID uuid) throws ContextNotFoundException { + return false; } @Override - public String create(String parentContextUUID, String name) + public String create(UUID parentContextUUID, String name) throws ContextCreationException { - return parentContextUUID+"newContext-"+name; + return "{}"; } @Override - public String rename(String contextUUID, String name) + public String rename(UUID contextUUID, String name) throws ContextNotFoundException { - return contextUUID+"-newName:"+name; + return "{}"; } @Override - public String move(String newParentUUID, String contextToMoveUUID) + public String move(UUID newParentUUID, UUID contextToMoveUUID) throws ContextNotFoundException { - return newParentUUID+"-"+contextToMoveUUID; + return "{}"; } @Override - public String read(String contextUUID) + public String read(UUID contextUUID) throws ContextNotFoundException, ContextException { - return contextUUID; + return "{}"; } }; diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/EntityManagementFactory.java b/src/test/java/org/gcube/informationsystem/resourceregistry/EntityManagementFactory.java index 75a09da..9814e9f 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/EntityManagementFactory.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/EntityManagementFactory.java @@ -1,5 +1,7 @@ package org.gcube.informationsystem.resourceregistry; +import java.util.UUID; + import org.gcube.informationsystem.resourceregistry.api.EntityManagement; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.FacetNotFoundException; @@ -18,30 +20,30 @@ public class EntityManagementFactory implements Factory { return new EntityManagement() { @Override - public String updateFacet(String uuid, String jsonRepresentation) + public String updateFacet(UUID uuid, String jsonRepresentation) throws FacetNotFoundException { return null; } @Override - public String readResource(String uuid) + public String readResource(UUID uuid) throws ResourceNotFoundException { return "resource"; } @Override - public String readFacet(String uuid) throws FacetNotFoundException { + public String readFacet(UUID uuid) throws FacetNotFoundException { return "facet"; } @Override - public boolean deleteResource(String uuid) + public boolean deleteResource(UUID uuid) throws ResourceNotFoundException, ResourceRegistryException { return false; } @Override - public boolean deleteFacet(String uuid) + public boolean deleteFacet(UUID uuid) throws FacetNotFoundException, ResourceRegistryException { return false; } @@ -59,15 +61,15 @@ public class EntityManagementFactory implements Factory { } @Override - public String attachResource(String sourceResourceUuid, - String targetResourceUuid, String relatedToType, + public String attachResource(UUID sourceResourceUuid, + UUID targetResourceUuid, String relatedToType, String jsonProperties) throws ResourceNotFoundException, ResourceRegistryException { return null; } @Override - public String attachFacet(String resourceUuid, String facetUuid, + public String attachFacet(UUID resourceUuid, UUID facetUuid, String consistOfType, String jsonProperties) throws FacetNotFoundException, ResourceNotFoundException, ResourceRegistryException { @@ -75,28 +77,28 @@ public class EntityManagementFactory implements Factory { } @Override - public String readFacet(String uuid, String facetType) + public String readFacet(UUID uuid, String facetType) throws FacetNotFoundException, ResourceRegistryException { // TODO Auto-generated method stub return null; } @Override - public String readResource(String uuid, String resourceType) + public String readResource(UUID uuid, String resourceType) throws ResourceNotFoundException, ResourceRegistryException { // TODO Auto-generated method stub return null; } @Override - public boolean detachFacet(String consistOfUUID) + public boolean detachFacet(UUID consistOfUUID) throws ResourceRegistryException { // TODO Auto-generated method stub return false; } @Override - public boolean detachResource(String relatedToUUID) + public boolean detachResource(UUID relatedToUUID) throws ResourceRegistryException { // TODO Auto-generated method stub return false; diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java index aa825c0..ca8d7f4 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/ContextManagementImplTest.java @@ -3,6 +3,11 @@ */ package org.gcube.informationsystem.resourceregistry.resources.impl; +import java.io.IOException; +import java.util.UUID; + +import org.gcube.informationsystem.impl.utils.Entities; +import org.gcube.informationsystem.model.entity.Context; import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; @@ -12,333 +17,448 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; + /** * @author Luca Frosini (ISTI - CNR) * */ public class ContextManagementImplTest { - - private static Logger logger = LoggerFactory.getLogger(ContextManagementImplTest.class); - - protected ContextManagementImpl contextManagementImpl; - - /* - private static final String VALID_CHARACTER = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); - private String randomString(int lenght) { - StringBuilder sb = new StringBuilder(lenght); - for (int i = 0; i < lenght; i++) { - sb.append(VALID_CHARACTER.charAt(SECURE_RANDOM - .nextInt(VALID_CHARACTER.length()))); - } - return sb.toString(); - } - */ - - public ContextManagementImplTest(){ + private static Logger logger = LoggerFactory + .getLogger(ContextManagementImplTest.class); + + protected ContextManagementImpl contextManagementImpl; + + /* + * private static final String VALID_CHARACTER = + * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private + * static final SecureRandom SECURE_RANDOM = new SecureRandom(); + * + * private String randomString(int lenght) { StringBuilder sb = new + * StringBuilder(lenght); for (int i = 0; i < lenght; i++) { + * sb.append(VALID_CHARACTER.charAt(SECURE_RANDOM + * .nextInt(VALID_CHARACTER.length()))); } return sb.toString(); } + */ + + public ContextManagementImplTest() { contextManagementImpl = new ContextManagementImpl(); } - + public static final String CTX_NAME_A = "A"; public static final String CTX_NAME_B = "B"; public static final String CTX_NAME_C = "C"; - - protected void invalidCreation(String parentUUID, String name) throws InternalException { + + protected void invalidCreation(UUID parentUUID, String name) + throws InternalException { try { contextManagementImpl.create(parentUUID, name); - throw new RuntimeException("The context " + name + " with parent " + parentUUID + " was already created and MUST throw " + ContextCreationException.class.getSimpleName() + ". This is a bug in your code."); + throw new RuntimeException("The context " + name + " with parent " + + parentUUID + " was already created and MUST throw " + + ContextCreationException.class.getSimpleName() + + ". This is a bug in your code."); } catch (ContextCreationException e) { - logger.debug("As expected the context {} with parent {} was already created and a {} has been thrown", name, parentUUID, e.getClass().getSimpleName()); + logger.debug( + "As expected the context {} with parent {} was already created and a {} has been thrown", + name, parentUUID, e.getClass().getSimpleName()); } } - - protected void invalidMoving(String parentUUID, String name){ + + protected void invalidMoving(UUID parentUUID, UUID contextToMove) { try { - contextManagementImpl.move(parentUUID, name); - throw new RuntimeException("The context " + name + " with parent " + parentUUID + " was already created and MUST throw " + ContextException.class.getSimpleName() + ". This is a bug in your code."); + contextManagementImpl.move(parentUUID, contextToMove); + throw new RuntimeException("The context " + contextToMove + + " with parent " + parentUUID + + " was already created and MUST throw " + + ContextException.class.getSimpleName() + + ". This is a bug in your code."); } catch (ContextNotFoundException e) { throw new RuntimeException(e); } catch (ContextException e) { - logger.debug("As expected the context {} with parent {} was already created and a {} has been thrown", name, parentUUID, e.getClass().getSimpleName()); - } + logger.debug( + "As expected the context {} with parent {} was already created and a {} has been thrown", + contextToMove, parentUUID, e.getClass().getSimpleName()); + } } - - protected void invalidRename(String uuid, String newName){ + + protected void invalidRename(UUID uuid, String newName) { try { contextManagementImpl.rename(uuid, newName); - throw new RuntimeException("The context with uuid " + uuid + " cannot be renamed to " + newName + " and MUST throw " + ContextException.class.getSimpleName() + ". This is a bug in your code."); + throw new RuntimeException("The context with uuid " + uuid + + " cannot be renamed to " + newName + " and MUST throw " + + ContextException.class.getSimpleName() + + ". This is a bug in your code."); } catch (ContextNotFoundException e) { throw new RuntimeException(e); } catch (ContextException e) { - logger.debug("As expected the context with uuid {} cannot be renamed to {} and a {} has been thrown", uuid, newName, e.getClass().getSimpleName()); - } + logger.debug( + "As expected the context with uuid {} cannot be renamed to {} and a {} has been thrown", + uuid, newName, e.getClass().getSimpleName()); + } } - - - protected void invalidDelete(String uuid){ + + protected void invalidDelete(UUID uuid) { try { contextManagementImpl.delete(uuid); - throw new RuntimeException("The context with uuid " + uuid + " cannot be deleted and MUST throw " + ContextException.class.getSimpleName() + ". This is a bug in your code."); + throw new RuntimeException("The context with uuid " + uuid + + " cannot be deleted and MUST throw " + + ContextException.class.getSimpleName() + + ". This is a bug in your code."); } catch (ContextNotFoundException e) { throw new RuntimeException(e); } catch (ContextException e) { - logger.debug("As expected the context with uuid {} cannot be deleted and a {} has been thrown", uuid, e.getClass().getSimpleName()); - } + logger.debug( + "As expected the context with uuid {} cannot be deleted and a {} has been thrown", + uuid, e.getClass().getSimpleName()); + } } - + @Test - public void simpleTest() throws ContextNotFoundException, ContextException, InternalException { - String A_1 = contextManagementImpl.create(null, CTX_NAME_A); + public void simpleTest() throws ContextNotFoundException, ContextException, + InternalException, JsonParseException, JsonMappingException, + IOException { + String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A); + Context createdContexA1 = Entities.unmarshal(Context.class, + contextJsonA1); + UUID A_1 = createdContexA1.getHeader().getUUID(); + logger.info("{}", contextJsonA1); + /* - * A(1) + * A(1) */ - - String A_2 = contextManagementImpl.create(A_1, CTX_NAME_A); + + String contextJsonA2 = contextManagementImpl.create(A_1, CTX_NAME_A); + Context createdContexA2 = Entities.unmarshal(Context.class, + contextJsonA2); + logger.info("{}", contextJsonA2); + UUID A_2 = createdContexA2.getHeader().getUUID(); /* - * A_1 - * A_2 + * A_1 A_2 */ - String B_3 = contextManagementImpl.create(A_2, CTX_NAME_B); + + String contextJsonB3 = contextManagementImpl.create(A_2, CTX_NAME_B); + Context createdContexB3 = Entities.unmarshal(Context.class, + contextJsonB3); + logger.info("{}", contextJsonB3); + UUID B_3 = createdContexB3.getHeader().getUUID(); /* - * A_1 - * A_2 - * B_3 + * A_1 A_2 B_3 */ - - contextManagementImpl.move(A_1, B_3); + + contextJsonB3 = contextManagementImpl.move(A_1, B_3); + createdContexB3 = Entities.unmarshal(Context.class, contextJsonB3); + logger.info("{}", contextJsonB3); + /* - * A_1 - * A_2 B_3 + * A_1 A_2 B_3 */ - - contextManagementImpl.rename(B_3, CTX_NAME_C); + + contextJsonB3 = contextManagementImpl.rename(B_3, CTX_NAME_C); + createdContexB3 = Entities.unmarshal(Context.class, contextJsonB3); + logger.info("{}", contextJsonB3); /* - * A_1 - * A_2 C_3 + * A_1 A_2 C_3 */ - - contextManagementImpl.rename(B_3, CTX_NAME_B); + + contextJsonB3 = contextManagementImpl.rename(B_3, CTX_NAME_B); + createdContexB3 = Entities.unmarshal(Context.class, contextJsonB3); + logger.info("{}", contextJsonB3); /* - * A_1 - * A_2 C_3 + * A_1 A_2 B_3 */ - - contextManagementImpl.move(A_2, B_3); + + contextJsonB3 = contextManagementImpl.move(A_2, B_3); + createdContexB3 = Entities.unmarshal(Context.class, contextJsonB3); + logger.info("{}", contextJsonB3); /* - * A_1 - * A_2 - * B_3 + * A_1 A_2 B_3 */ - - contextManagementImpl.delete(B_3); + + boolean deleted = contextManagementImpl.delete(B_3); + Assert.assertTrue(deleted); /* - * A_1 - * A_2 + * A_1 A_2 */ - contextManagementImpl.delete(A_2); + + deleted = contextManagementImpl.delete(A_2); + Assert.assertTrue(deleted); /* - * A_1 + * A_1 */ - contextManagementImpl.delete(A_1); + + deleted = contextManagementImpl.delete(A_1); + Assert.assertTrue(deleted); /* * */ + logger.debug("The DB should be now clean"); } - - + @Test - public void createDevContext() throws ContextNotFoundException, ContextException, InternalException { - String gcube = contextManagementImpl.create(null, "gcube"); - logger.trace("/gcube : {}", gcube); - String devsec = contextManagementImpl.create(gcube, "devsec"); - logger.trace("/gcube/devsec : {}", devsec); - String devVRE = contextManagementImpl.create(devsec, "devVRE"); - logger.trace("/gcube/devsec/devVRE : {}", devVRE); - String devNext = contextManagementImpl.create(gcube, "devNext"); - logger.trace("/gcube/devNext : {}", devNext); - String NextNext = contextManagementImpl.create(devNext, "NextNext"); - logger.trace("/gcube/devNext/NextNext : {}", NextNext); - + public void createDevContext() throws ContextNotFoundException, + ContextException, InternalException, JsonParseException, + JsonMappingException, IOException { + String gcubeJson = contextManagementImpl.create(null, "gcube"); + Context gcubeContex = Entities.unmarshal(Context.class, gcubeJson); + UUID gcube = gcubeContex.getHeader().getUUID(); + logger.trace("/gcube : {}", gcubeJson); + + String devsecJson = contextManagementImpl.create(gcube, "devsec"); + Context devsecContex = Entities.unmarshal(Context.class, devsecJson); + UUID devsec = devsecContex.getHeader().getUUID(); + logger.trace("/gcube/devsec : {}", devsecJson); + + String devVREJson = contextManagementImpl.create(devsec, "devVRE"); + Context devVREContex = Entities.unmarshal(Context.class, devVREJson); + @SuppressWarnings("unused") + UUID devVRE = devVREContex.getHeader().getUUID(); + logger.trace("/gcube/devsec/devVRE : {}", devVREJson); + + String devNextJson = contextManagementImpl.create(gcube, "devNext"); + Context devNextContex = Entities.unmarshal(Context.class, devNextJson); + UUID devNext = devNextContex.getHeader().getUUID(); + logger.trace("/gcube/devNext : {}", devNextJson); + + String NextNextJson = contextManagementImpl.create(devNext, "NextNext"); + Context NextNextContex = Entities.unmarshal(Context.class, NextNextJson); + @SuppressWarnings("unused") + UUID NextNext = NextNextContex.getHeader().getUUID(); + logger.trace("/gcube/devNext/NextNext : {}", NextNextJson); + /* - contextManagementImpl.delete(NextNext); - contextManagementImpl.delete(devNext); - contextManagementImpl.delete(devVRE); - contextManagementImpl.delete(devsec); - contextManagementImpl.delete(gcube); - */ - + * contextManagementImpl.delete(NextNext); + * contextManagementImpl.delete(devNext); + * contextManagementImpl.delete(devVRE); + * contextManagementImpl.delete(devsec); + * contextManagementImpl.delete(gcube); + */ + logger.debug("The DB should be now clean"); } - + //@Test - public void removeDevContext() throws ContextNotFoundException, ContextException, InternalException { - contextManagementImpl.delete("508da10a-b8e7-414f-b176-65e227addcae"); - contextManagementImpl.delete("d729c993-32f9-4bcd-9311-d92f791e5e12"); - contextManagementImpl.delete("8bf286f8-a93c-4936-9826-91f1b1c2af34"); - contextManagementImpl.delete("7273c1c7-bc06-4d49-bade-19dc3ab322f7"); - contextManagementImpl.delete("132691d2-e22d-4e3b-b605-f8b2c94f2c77"); + public void removeDevContext() throws ContextNotFoundException, + ContextException, InternalException { + contextManagementImpl.delete(UUID + .fromString("28f2ce60-e1dd-47e6-9780-58ad8aeb35ed")); } - + @Test - public void readTest() throws ContextNotFoundException, ContextException, InternalException { - String A_1 = contextManagementImpl.create(null, "LLL"); - String read = contextManagementImpl.read(A_1); - logger.trace("A : {}", read); - contextManagementImpl.delete(A_1); + public void readTest() throws ContextNotFoundException, ContextException, + InternalException, JsonParseException, JsonMappingException, + IOException { + String name = "LLL"; + String contextJsonA1 = contextManagementImpl.create(null, name); + Context createdContexA1 = Entities.unmarshal(Context.class, + contextJsonA1); + UUID A_1 = createdContexA1.getHeader().getUUID(); + logger.info("{}", contextJsonA1); + Assert.assertTrue(createdContexA1.getName().compareTo(name) == 0); + + String readContextJsonA1 = contextManagementImpl.read(A_1); + Context readContexA1 = Entities.unmarshal(Context.class, + readContextJsonA1); + Assert.assertTrue(readContexA1.getName().compareTo(name) == 0); + Assert.assertTrue(A_1.compareTo(readContexA1.getHeader().getUUID()) == 0); + logger.trace("{}", createdContexA1); + + boolean deleted = contextManagementImpl.delete(A_1); + Assert.assertTrue(deleted); } - + @Test - public void completeTest() throws ContextNotFoundException, ContextException, InternalException { - String A_1 = contextManagementImpl.create(null, CTX_NAME_A); + public void completeTest() throws ContextNotFoundException, + ContextException, InternalException, JsonParseException, + JsonMappingException, IOException { + String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A); + Context createdContexA1 = Entities.unmarshal(Context.class, + contextJsonA1); + UUID A_1 = createdContexA1.getHeader().getUUID(); + logger.info("{}", contextJsonA1); /* - * A(1) + * A(1) */ - - String A_2 = contextManagementImpl.create(A_1, CTX_NAME_A); + + String contextJsonA2 = contextManagementImpl.create(A_1, CTX_NAME_A); + Context createdContexA2 = Entities.unmarshal(Context.class, + contextJsonA2); + logger.info("{}", contextJsonA2); + UUID A_2 = createdContexA2.getHeader().getUUID(); + /* - * A_1 - * A_2 + * A_1 A_2 */ - - String B_3 = contextManagementImpl.create(A_2, CTX_NAME_B); + + String contextJsonB3 = contextManagementImpl.create(A_2, CTX_NAME_B); + Context createdContexB3 = Entities.unmarshal(Context.class, + contextJsonB3); + logger.info("{}", contextJsonB3); + UUID B_3 = createdContexB3.getHeader().getUUID(); /* - * A_1 - * A_2 - * B_3 + * A_1 A_2 B_3 */ - - - String B_4 = contextManagementImpl.create(A_1, CTX_NAME_B); + + String contextJsonB4 = contextManagementImpl.create(A_1, CTX_NAME_B); + Context createdContexB4 = Entities.unmarshal(Context.class, + contextJsonB4); + logger.info("{}", contextJsonB4); + UUID B_4 = createdContexB4.getHeader().getUUID(); /* - * A_1 - * A_2 B_4 - * B_3 + * A_1 A_2 B_4 B_3 */ - - String A_5 = contextManagementImpl.create(B_4, CTX_NAME_A); + + String contextJsonA5 = contextManagementImpl.create(B_4, CTX_NAME_A); + Context createdContexA5 = Entities.unmarshal(Context.class, + contextJsonA5); + logger.info("{}", contextJsonA5); + UUID A_5 = createdContexA5.getHeader().getUUID(); /* - * A_1 - * A_2 B_4 - * B_3 A_5 + * A_1 A_2 B_4 B_3 A_5 */ - - + invalidCreation(null, CTX_NAME_A); // Trying to recreate A_1. Fails - invalidCreation(A_1, CTX_NAME_A); // Trying to recreate A_2. Fails - invalidCreation(A_2, CTX_NAME_B); // Trying to recreate B_3. Fails - invalidCreation(A_1, CTX_NAME_B); // Trying to recreate B_4. Fails - invalidCreation(B_4, CTX_NAME_A); // Trying to recreate A_5. Fails - - + invalidCreation(A_1, CTX_NAME_A); // Trying to recreate A_2. Fails + invalidCreation(A_2, CTX_NAME_B); // Trying to recreate B_3. Fails + invalidCreation(A_1, CTX_NAME_B); // Trying to recreate B_4. Fails + invalidCreation(B_4, CTX_NAME_A); // Trying to recreate A_5. Fails + // Trying to move B_3 as child of A_1. It fails due to B_4. Fails invalidMoving(A_1, B_3); // Trying to move A_5 as child of A_1. It fails due to A_2. Fails invalidMoving(A_1, A_5); - - - + // Moving B_3 as child of B_4. OK - contextManagementImpl.move(B_4, B_3); + String movedContextJsonB3 = contextManagementImpl.move(B_4, B_3); + Context movedContexB3 = Entities.unmarshal(Context.class, + movedContextJsonB3); + Assert.assertTrue(B_3.compareTo(movedContexB3.getHeader().getUUID()) == 0); + logger.info("{}", contextJsonB3); /* - * A_1 - * A_2 B_4 - * B_3 A_5 + * A_1 A_2 B_4 B_3 A_5 */ - + // Restoring the initial situation by moving B_3 as child of A_2 - contextManagementImpl.move(A_2, B_3); + String movedAgainJsonB3 = contextManagementImpl.move(A_2, B_3); + Context movedAgainContexB3 = Entities.unmarshal(Context.class, + movedAgainJsonB3); + Assert.assertTrue(B_3.compareTo(movedAgainContexB3.getHeader() + .getUUID()) == 0); + logger.info("{}", contextJsonB3); /* - * A_1 - * A_2 B_4 - * B_3 A_5 + * A_1 A_2 B_4 B_3 A_5 */ - - + // Trying to move B_3 as child of A_1. It fails due to B_4. Fails invalidMoving(A_1, B_3); - + // Renaming B_3 as C_3 - String C_3 = contextManagementImpl.rename(B_3, CTX_NAME_C); - Assert.assertTrue(C_3.compareTo(B_3)==0); + String contextJsonC3 = contextManagementImpl.rename(B_3, CTX_NAME_C); + Context createdContexC3 = Entities.unmarshal(Context.class, + contextJsonC3); + logger.info("{}", contextJsonC3); + UUID C_3 = createdContexC3.getHeader().getUUID(); + Assert.assertTrue(C_3.compareTo(B_3) == 0); /* - * A_1 - * A_2 B_4 - * C_3 A_5 + * A_1 A_2 B_4 C_3 A_5 */ - + // Moving C_3 (was B_3) as child of A_1. Now it is possible - contextManagementImpl.move(A_1, B_3); + contextJsonC3 = contextManagementImpl.move(A_1, C_3); + createdContexC3 = Entities.unmarshal(Context.class, contextJsonC3); + logger.info("{}", contextJsonC3); /* - * A_1 - * C_3 A_2 B_4 - * A_5 + * A_1 C_3 A_2 B_4 A_5 */ - - - + // Trying to rename C_3 (was B_3) newly to B_3. Fails due to B_4 invalidRename(C_3, CTX_NAME_B); - // Moving back C_3 (was B_3) as child of A_2. - contextManagementImpl.move(A_2, B_3); - String BC_3 = contextManagementImpl.rename(C_3, CTX_NAME_B); - Assert.assertTrue(BC_3.compareTo(B_3)==0); - Assert.assertTrue(BC_3.compareTo(C_3)==0); + contextJsonB3 = contextManagementImpl.move(A_2, C_3); + createdContexB3 = Entities.unmarshal(Context.class, contextJsonB3); + logger.info("{}", contextJsonB3); + + String contextJsonBC3 = contextManagementImpl.rename(C_3, CTX_NAME_B); + Context createdContexBC3 = Entities.unmarshal(Context.class, + contextJsonBC3); + logger.info("{}", contextJsonBC3); + UUID BC_3 = createdContexBC3.getHeader().getUUID(); + Assert.assertTrue(BC_3.compareTo(B_3) == 0); + Assert.assertTrue(BC_3.compareTo(C_3) == 0); /* - * A_1 - * A_2 B_4 - * B_3 A_5 + * A_1 A_2 B_4 B_3 A_5 */ - - + invalidDelete(A_1); invalidDelete(A_2); invalidDelete(B_4); - contextManagementImpl.delete(A_5); + boolean deleted = contextManagementImpl.delete(A_5); + Assert.assertTrue(deleted); /* - * A_1 - * A_2 B_4 - * B_3 + * A_1 A_2 B_4 B_3 */ try { contextManagementImpl.delete(A_5); - } catch(ContextNotFoundException e){ - logger.debug("The context with uuid {} was not found. (Was already deleted)", A_5); - } - - contextManagementImpl.delete(B_3); + } catch (ContextNotFoundException e) { + logger.debug( + "The context with uuid {} was not found. (Was already deleted)", + A_5); + } + + deleted = contextManagementImpl.delete(B_3); + Assert.assertTrue(deleted); /* - * A_1 - * A_2 B_4 + * A_1 A_2 B_4 */ invalidDelete(A_1); - contextManagementImpl.delete(B_4); + deleted = contextManagementImpl.delete(B_4); + Assert.assertTrue(deleted); /* - * A_1 - * A_2 + * A_1 A_2 */ - contextManagementImpl.delete(A_2); + deleted = contextManagementImpl.delete(A_2); + Assert.assertTrue(deleted); /* - * A_1 + * A_1 */ - - contextManagementImpl.delete(A_1); - - + + deleted = contextManagementImpl.delete(A_1); + Assert.assertTrue(deleted); + logger.debug("The DB should be now clean"); } - - + @Test - public void moveToRootTest() throws ContextNotFoundException, ContextException, InternalException { - String A_1 = contextManagementImpl.create(null, CTX_NAME_A); - String A_2 = contextManagementImpl.create(A_1, CTX_NAME_B); - contextManagementImpl.move(null, A_2); + public void moveToRootTest() throws ContextNotFoundException, + ContextException, InternalException, JsonParseException, + JsonMappingException, IOException { + String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A); + Context createdContexA1 = Entities.unmarshal(Context.class, + contextJsonA1); + UUID A_1 = createdContexA1.getHeader().getUUID(); + logger.info("{}", contextJsonA1); + /* + * A(1) + */ + + String contextJsonB2 = contextManagementImpl.create(A_1, CTX_NAME_B); + Context createdContexB2 = Entities.unmarshal(Context.class, + contextJsonB2); + logger.info("{}", contextJsonB2); + UUID B_2 = createdContexB2.getHeader().getUUID(); + + /* + * A_1 B_2 + */ + + String movedContextJsonB2 = contextManagementImpl.move(null, B_2); + Context movedContexB2 = Entities.unmarshal(Context.class, + movedContextJsonB2); + Assert.assertTrue(B_2.compareTo(movedContexB2.getHeader().getUUID()) == 0); contextManagementImpl.delete(A_1); - contextManagementImpl.delete(A_2); + contextManagementImpl.delete(B_2); logger.debug("The DB should be now clean"); } diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java index 7b9a6b7..814c793 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/resources/impl/EntityManagementImplTest.java @@ -74,7 +74,7 @@ public class EntityManagementImplTest { UUID uuid = createdCpuFacet.getHeader().getUUID(); - String readJson = entityManagementImpl.readFacet(uuid.toString()); + String readJson = entityManagementImpl.readFacet(uuid); CPUFacet readCpuFacet = Entities.unmarshal(CPUFacet.class, readJson); logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet); Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(readCpuFacet.getClockSpeed())==0); @@ -92,7 +92,7 @@ public class EntityManagementImplTest { readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue); - String updatedJson = entityManagementImpl.updateFacet(uuid.toString(),Entities.marshal(readCpuFacet)); + String updatedJson = entityManagementImpl.updateFacet(uuid,Entities.marshal(readCpuFacet)); CPUFacet updatedCpuFacet = Entities.unmarshal(CPUFacet.class, updatedJson); logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, updatedCpuFacet); Assert.assertTrue(readCpuFacet.getClockSpeed().compareTo(updatedCpuFacet.getClockSpeed())==0); @@ -102,7 +102,7 @@ public class EntityManagementImplTest { Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID())==0); - String readUpdatedJson = entityManagementImpl.readFacet(uuid.toString()); + String readUpdatedJson = entityManagementImpl.readFacet(uuid); CPUFacet readUpdatedCpuFacet = Entities.unmarshal(CPUFacet.class, readUpdatedJson); logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet); Assert.assertTrue(updatedCpuFacet.getClockSpeed().compareTo(readUpdatedCpuFacet.getClockSpeed())==0); @@ -111,7 +111,7 @@ public class EntityManagementImplTest { Assert.assertTrue(((String)updatedCpuFacet.getAdditionalProperty(additionPropertyKey)).compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey))==0); Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID())==0); - boolean deleted = entityManagementImpl.deleteFacet(uuid.toString()); + boolean deleted = entityManagementImpl.deleteFacet(uuid); Assert.assertTrue(deleted); } @@ -133,7 +133,7 @@ public class EntityManagementImplTest { JSONObject jsonObject = new JSONObject(json); JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY); - String uuid = header.getString(Header.UUID_PROPERTY); + UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY)); String readJson = entityManagementImpl.readFacet(uuid); logger.debug("Read : {}", readJson); @@ -308,7 +308,7 @@ public class EntityManagementImplTest { String json = entityManagementImpl.createResource( HostingNode.class.getSimpleName(), "{}"); - String resourceUUID = Utility.getUUIDFromJSONString(json); + UUID resourceUUID = Utility.getUUIDFromJSONString(json); CPUFacetImpl cpuFacetImpl = new CPUFacetImpl(); cpuFacetImpl.setClockSpeed("1 GHz"); @@ -320,13 +320,13 @@ public class EntityManagementImplTest { json = entityManagementImpl.createFacet(CPUFacet.class.getSimpleName(), stringWriter.toString()); logger.debug("Created : {}", json); - String facetUUID = Utility.getUUIDFromJSONString(json); + UUID facetUUID = Utility.getUUIDFromJSONString(json); json = entityManagementImpl.attachFacet(resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(), null); logger.debug("Facet attached : {}", json); - String consistOfUUID = Utility.getUUIDFromJSONString(json); + UUID consistOfUUID = Utility.getUUIDFromJSONString(json); boolean detached = entityManagementImpl.detachFacet(consistOfUUID); @@ -360,7 +360,7 @@ public class EntityManagementImplTest { String json = entityManagementImpl.createFacet(CPUFacet.class.getSimpleName(), stringWriter.toString()); logger.debug("Created : {}", json); - String createdFacetUUID = Utility.getUUIDFromJSONString(json); + UUID createdFacetUUID = Utility.getUUIDFromJSONString(json); HostingNode hostingNode = new HostingNodeImpl(); @@ -371,7 +371,7 @@ public class EntityManagementImplTest { hostingNode.addFacet(cpuFacetImpl); - hostingNode.attachFacet(UUID.fromString(createdFacetUUID)); + hostingNode.attachFacet(createdFacetUUID); StringWriter resourceStringWriter = new StringWriter(); @@ -381,9 +381,9 @@ public class EntityManagementImplTest { json = entityManagementImpl.createResource( HostingNode.class.getSimpleName(), resourceStringWriter.toString()); - String resourceUUID = Utility.getUUIDFromJSONString(json); + UUID resourceUUID = Utility.getUUIDFromJSONString(json); - logger.debug(resourceUUID); + logger.debug("{}", resourceUUID); //entityManagementImpl.deleteResource(resourceUUID);