Solving Resource marshalling/unmarshalling as json using jackson

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@131206 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2016-09-08 09:57:10 +00:00
parent 1aa6f50c44
commit 2440e59082
7 changed files with 234 additions and 124 deletions

View File

@ -22,103 +22,121 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertex;
/**
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
*
*
*/
public class SecurityContext {
private static Logger logger = LoggerFactory
.getLogger(SecurityContext.class);
public static final String DEFAULT_WRITER_ROLE = "writer";
public static final String DEFAULT_READER_ROLE = "reader";
public static void addToSecurityContext(OrientGraph orientGraph, Vertex vertex, String contextID){
public static void addToSecurityContext(OrientGraph orientGraph,
Vertex vertex, String contextID) {
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
SecurityContext.addToSecurityContext(oSecurity, vertex, contextID);
}
public static void addToSecurityContext(OSecurity oSecurity, Vertex vertex, String contextID){
public static void addToSecurityContext(OSecurity oSecurity, Vertex vertex,
String contextID) {
OrientVertex orientVertex = (OrientVertex) vertex;
SecurityContext.allowSecurityContextRoles(oSecurity, orientVertex.getRecord(), contextID);
SecurityContext.allowSecurityContextRoles(oSecurity,
orientVertex.getRecord(), contextID);
Iterable<Edge> iterable = vertex.getEdges(Direction.BOTH);
Iterator<Edge> iterator = iterable.iterator();
while(iterator.hasNext()){
while (iterator.hasNext()) {
OrientEdge edge = (OrientEdge) iterator.next();
SecurityContext.allowSecurityContextRoles(oSecurity, edge.getRecord(), contextID);
SecurityContext.allowSecurityContextRoles(oSecurity,
edge.getRecord(), contextID);
}
}
public static void addToSecurityContext(OrientGraph orientGraph, Edge edge, String contextID){
public static void addToSecurityContext(OrientGraph orientGraph, Edge edge,
String contextID) {
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
SecurityContext.addToSecurityContext(oSecurity, edge, contextID);
}
public static void addToSecurityContext(OSecurity oSecurity, Edge edge, String contextID){
public static void addToSecurityContext(OSecurity oSecurity, Edge edge,
String contextID) {
OrientEdge orientEdge = (OrientEdge) edge;
SecurityContext.allowSecurityContextRoles(oSecurity, orientEdge.getRecord(), contextID);
SecurityContext.allowSecurityContextRoles(oSecurity,
orientEdge.getRecord(), contextID);
}
protected static void allowSecurityContextRoles(OSecurity oSecurity, ODocument oDocument, String contextID){
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL,
protected static void allowSecurityContextRoles(OSecurity oSecurity,
ODocument oDocument, String contextID) {
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, contextID));
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, contextID));
//oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, DEFAULT_WRITER_ROLE);
//oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, DEFAULT_READER_ROLE);
// oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL,
// DEFAULT_WRITER_ROLE);
// oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
// DEFAULT_READER_ROLE);
}
public static void createSecurityContext(OrientGraph orientGraph, String contextID){
public static void createSecurityContext(OrientGraph orientGraph,
String contextID, boolean commit) {
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
ORole writer = oSecurity.getRole(DEFAULT_WRITER_ROLE);
ORole reader = oSecurity.getRole(DEFAULT_READER_ROLE);
ORole writerRole = oSecurity.createRole(
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, contextID),
ORole writerRole = oSecurity.createRole(SecurityContextMapper
.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, contextID),
writer, ALLOW_MODES.DENY_ALL_BUT);
ORole readerRole = oSecurity.createRole(
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
ORole readerRole = oSecurity.createRole(SecurityContextMapper
.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, contextID),
reader, ALLOW_MODES.DENY_ALL_BUT);
oSecurity.createUser(
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.USER, contextID),
DatabaseEnvironment.DEFAULT_PASSWORDS.get(SecurityContextMapper.PermissionMode.WRITER) ,
writerRole);
oSecurity.createUser(
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.USER, contextID),
DatabaseEnvironment.DEFAULT_PASSWORDS.get(SecurityContextMapper.PermissionMode.READER),
readerRole);
// Commit MUST BE invoked in caller method
//orientGraph.commit();
oSecurity.createUser(SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.USER, contextID),
DatabaseEnvironment.DEFAULT_PASSWORDS
.get(SecurityContextMapper.PermissionMode.WRITER),
writerRole);
oSecurity.createUser(SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.USER, contextID),
DatabaseEnvironment.DEFAULT_PASSWORDS
.get(SecurityContextMapper.PermissionMode.READER),
readerRole);
if (commit) {
orientGraph.commit();
}
logger.trace(
"Security Context (roles and users) with UUID {} successfully created",
contextID);
}
public static void deleteSecurityContext(OrientGraph orientGraph,
String contextID) {
logger.trace("Going to remove Security Context (roles and users) with UUID {}", contextID);
String contextID, boolean commit) {
logger.trace(
"Going to remove Security Context (roles and users) with UUID {}",
contextID);
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
@ -134,11 +152,13 @@ public class SecurityContext {
oSecurity.dropRole(SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, contextID));
// Commit MUST BE invoked in caller method
//orientGraph.commit();
logger.trace("Security Context (roles and users) with UUID {} successfully removed", contextID);
if (commit) {
orientGraph.commit();
}
logger.trace(
"Security Context (roles and users) with UUID {} successfully removed",
contextID);
}
}

View File

@ -49,12 +49,11 @@ public abstract class SecurityContextMapper {
if(created){
OrientGraph orientGraph = factory.getTx();
SecurityContext.createSecurityContext(orientGraph, MANAGEMENT_SECURITY_CONTEXT);
orientGraph.commit();
SecurityContext.createSecurityContext(orientGraph, MANAGEMENT_SECURITY_CONTEXT, true);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT, PermissionMode.READER);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT, PermissionMode.WRITER);
DatabaseIntializator.createEntitiesAndRelations();
}

View File

@ -133,13 +133,15 @@ public class ContextManagementImpl implements ContextManagement {
} catch (ContextException e) {
throw new ContextCreationException(e.getMessage());
}
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString();
SecurityContext.createSecurityContext(orientGraph, uuidString, true);
try {
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString();
SecurityContext.createSecurityContext(orientGraph, uuidString);
FramedGraphFactory framedGraphFactory = new FramedGraphFactory();
FramedGraph<OrientGraph> framedGraph = framedGraphFactory
.create(orientGraph);
@ -164,14 +166,16 @@ public class ContextManagementImpl implements ContextManagement {
logger.trace("Creating {}", contextJsonString);
orientGraph.commit();
orientGraph.shutdown();
logger.info("Context {} created", contextJsonString);
return uuidString;
} catch (Exception e) {
orientGraph.rollback();
SecurityContext.deleteSecurityContext(orientGraph, uuidString, true);
throw new InternalException(e.getMessage());
} finally {
orientGraph.shutdown();
}
}
@ -301,7 +305,7 @@ public class ContextManagementImpl implements ContextManagement {
"Only context with no children can be deleted");
}
SecurityContext.deleteSecurityContext(orientGraph, uuid);
SecurityContext.deleteSecurityContext(orientGraph, uuid, false);
context.remove();

View File

@ -3,6 +3,7 @@
*/
package org.gcube.informationsystem.resourceregistry.resources.impl;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
@ -10,9 +11,9 @@ import java.util.Set;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.EntityManagement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.FacetNotFoundException;
@ -25,6 +26,7 @@ import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinkerpop.blueprints.Edge;
@ -132,8 +134,12 @@ public class EntityManagementImpl implements EntityManagement {
entityVertex.save();
orientGraph.commit();
return Utility
.orientVertexToJsonString((OrientVertex) entityVertex);
logger.trace("Created {} is {} orientVertexToJsonString", Vertex.class.getSimpleName(),
Utility.orientVertexToJsonString((OrientVertex) entityVertex, true));
return Utility.orientVertexToJsonString((OrientVertex) entityVertex, false);
//return Utility.orientVertexToJsonString((OrientVertex) entityVertex);
} catch (Exception e) {
if (orientGraph != null) {
@ -251,7 +257,9 @@ public class EntityManagementImpl implements EntityManagement {
Vertex facet = getEntity(orientGraph, uuid, facetType, Facet.class);
return Utility.orientVertexToJsonString((OrientVertex) facet);
logger.trace("{} of type {} with UUID {} is {}", Facet.NAME, facetType, uuid, Utility.orientVertexToJsonString((OrientVertex) facet, true));
return Utility.orientVertexToJsonString((OrientVertex) facet, true);
} catch (FacetNotFoundException fnfe) {
throw fnfe;
} catch (Exception e) {
@ -314,7 +322,11 @@ public class EntityManagementImpl implements EntityManagement {
((OrientVertex) facet).save();
orientGraph.commit();
return Utility.orientVertexToJsonString((OrientVertex) facet);
logger.trace("{} with UUID {} has been updated {}", Facet.NAME, uuid, Utility.orientVertexToJsonString((OrientVertex) facet, true));
return Utility.orientVertexToJsonString((OrientVertex) facet, false);
} catch (FacetNotFoundException fnfe) {
if (orientGraph != null) {
@ -455,6 +467,13 @@ public class EntityManagementImpl implements EntityManagement {
@Override
public String createResource(String resourceType, String jsonRepresentation)
throws ResourceRegistryException {
try {
JsonNode jsonNode = org.gcube.informationsystem.impl.utils.Utility.getJSONNode(jsonRepresentation);
} catch (IOException e) {
throw new ResourceRegistryException(e);
}
return createVertexEntity(resourceType, Resource.class,
jsonRepresentation);
}
@ -477,8 +496,10 @@ public class EntityManagementImpl implements EntityManagement {
Resource.class);
// TODO get all attached facets
return Utility.orientVertexToJsonString((OrientVertex) resource);
logger.trace("{} of type {} with UUID {} is {}", Resource.NAME, resourceType, uuid, Utility.orientVertexToJsonString((OrientVertex) resource, true));
return Utility.orientVertexToJsonString((OrientVertex) resource, false);
} catch (ResourceNotFoundException rnfe) {
throw rnfe;
} catch (Exception e) {

View File

@ -35,9 +35,12 @@ public class Utility {
private static final Logger logger = LoggerFactory.getLogger(Utility.class);
public static String orientVertexToJsonString(OrientVertex orientVertex) {
public static String orientVertexToJsonString(OrientVertex orientVertex, boolean raw) {
ORecord oRecord = orientVertex.getRecord();
return oRecord.toJSON();
if(raw){
return oRecord.toJSON();
}
return oRecord.toJSON("class");
}
public static String vertexToJsonString(Vertex vertex, boolean raw)

View File

@ -155,7 +155,7 @@ public class ContextManagementImplTest {
}
//@Test
@Test
public void devContextTest() throws ContextNotFoundException, ContextException, InternalException {
String gcube = contextManagementImpl.create(null, "gcube");
logger.trace("/gcube : {}", gcube);

View File

@ -4,6 +4,7 @@
package org.gcube.informationsystem.resourceregistry.resources.impl;
import java.io.StringWriter;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.common.scope.api.ScopeProvider;
@ -20,13 +21,11 @@ import org.gcube.informationsystem.model.entity.resource.HostingNode;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.FacetNotFoundException;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
*
@ -46,46 +45,63 @@ public class EntityManagementImplTest {
public void testCreateReadDeleteFacet() throws Exception {
ScopeProvider.instance.set("/gcube/devNext");
CPUFacetImpl cpuFacetImpl = new CPUFacetImpl();
cpuFacetImpl.setClockSpeed("1 GHz");
cpuFacetImpl.setModel("Opteron");
cpuFacetImpl.setVendor("AMD");
StringWriter stringWriter = new StringWriter();
Entities.marshal(cpuFacetImpl, stringWriter);
String json = entityManagementImpl.createFacet(
CPUFacet.class.getSimpleName(), stringWriter.toString());
logger.debug("Created : {}", json);
String uuid = Utility.getUUIDFromJSONString(json);
String readJson = entityManagementImpl.readFacet(uuid);
logger.debug("Read : {}", readJson);
stringWriter = new StringWriter();
Entities.marshal(cpuFacetImpl, stringWriter);
cpuFacetImpl.setVendor("Luca");
String newclockSpeed = "2 GHz";
JsonNode jsonNode = Utility.getJSONNode(stringWriter.toString());
((ObjectNode) jsonNode).put("clockSpeed", newclockSpeed);
((ObjectNode) jsonNode).put("My", "Test");
stringWriter = new StringWriter();
Entities.marshal(jsonNode, stringWriter);
readJson = entityManagementImpl.updateFacet(uuid,
stringWriter.toString());
logger.debug("Updated : {}", readJson);
readJson = entityManagementImpl.readFacet(uuid);
logger.debug("Read Updated : {}", readJson);
boolean deleted = entityManagementImpl.deleteFacet(uuid);
if (!deleted) {
throw new Exception("Facet Not Deleted");
}
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
String cpuFacetJson = entityManagementImpl.createFacet(CPUFacet.class.getSimpleName(), Entities.marshal(cpuFacet));
CPUFacet createdCpuFacet = Entities.unmarshal(CPUFacet.class, cpuFacetJson);
logger.debug("Created:\nRaw Json : {}\nUnmarshalled : {}", cpuFacetJson, createdCpuFacet);
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(createdCpuFacet.getClockSpeed())==0);
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel())==0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor())==0);
UUID uuid = createdCpuFacet.getHeader().getUUID();
String readJson = entityManagementImpl.readFacet(uuid.toString());
CPUFacet readCpuFacet = Entities.unmarshal(CPUFacet.class, readJson);
logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet);
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(readCpuFacet.getClockSpeed())==0);
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel())==0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor())==0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getHeader().getUUID())==0);
String newVendor = "Intel";
String newClockSpeed = "2 GHz";
readCpuFacet.setVendor(newVendor);
readCpuFacet.setClockSpeed(newClockSpeed);
String additionPropertyKey = "My";
String additionPropertyValue = "Test";
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
String updatedJson = entityManagementImpl.updateFacet(uuid.toString(),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);
Assert.assertTrue(readCpuFacet.getModel().compareTo(updatedCpuFacet.getModel())==0);
Assert.assertTrue(readCpuFacet.getVendor().compareTo(updatedCpuFacet.getVendor())==0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey)).compareTo((String) readCpuFacet.getAdditionalProperty(additionPropertyKey))==0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID())==0);
String readUpdatedJson = entityManagementImpl.readFacet(uuid.toString());
CPUFacet readUpdatedCpuFacet = Entities.unmarshal(CPUFacet.class, readUpdatedJson);
logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet);
Assert.assertTrue(updatedCpuFacet.getClockSpeed().compareTo(readUpdatedCpuFacet.getClockSpeed())==0);
Assert.assertTrue(updatedCpuFacet.getModel().compareTo(readUpdatedCpuFacet.getModel())==0);
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(readUpdatedCpuFacet.getVendor())==0);
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());
Assert.assertTrue(deleted);
}
@Test
@ -283,4 +299,51 @@ public class EntityManagementImplTest {
}
@Test
public void testCreateResourceAndFacetTogheter() throws Exception {
ScopeProvider.instance.set("/gcube/devsec");
CPUFacetImpl cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("2 GHz");
cpuFacet.setModel("Celeron");
cpuFacet.setVendor("Intel");
StringWriter stringWriter = new StringWriter();
Entities.marshal(cpuFacet, stringWriter);
String json = entityManagementImpl.createFacet(CPUFacet.class.getSimpleName(),
stringWriter.toString());
logger.debug("Created : {}", json);
String createdFacetUUID = Utility.getUUIDFromJSONString(json);
HostingNode hostingNode = new HostingNodeImpl();
CPUFacetImpl cpuFacetImpl = new CPUFacetImpl();
cpuFacetImpl.setClockSpeed("1 GHz");
cpuFacetImpl.setModel("Opteron");
cpuFacetImpl.setVendor("AMD");
hostingNode.addFacet(cpuFacetImpl);
hostingNode.attachFacet(UUID.fromString(createdFacetUUID));
StringWriter resourceStringWriter = new StringWriter();
Entities.marshal(hostingNode, resourceStringWriter);
logger.trace(resourceStringWriter.toString());
json = entityManagementImpl.createResource(
HostingNode.class.getSimpleName(), resourceStringWriter.toString());
String resourceUUID = Utility.getUUIDFromJSONString(json);
//entityManagementImpl.deleteResource(resourceUUID);
}
}