Refactored EntityManagement

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@141249 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2016-12-19 13:59:27 +00:00
parent 6960ef5738
commit b1112136fa
28 changed files with 2604 additions and 255 deletions

View File

@ -0,0 +1,211 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
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.node.JsonNodeType;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class ERManagement {
private static Logger logger = LoggerFactory.getLogger(ERManagement.class);
public static String lowerCaseFirstCharacter(String string) {
return string.substring(0, 1).toLowerCase() + string.substring(1);
}
public static String getClassProperty(JsonNode jsonNode) {
if (jsonNode.has(Entities.CLASS_PROPERTY)) {
return jsonNode.get(Entities.CLASS_PROPERTY).asText();
}
return null;
}
public static Object getObjectFromElement(JsonNode value)
throws ResourceRegistryException {
JsonNodeType jsonNodeType = value.getNodeType();
switch (jsonNodeType) {
case OBJECT:
return EmbeddedMangement.getEmbeddedType(value);
case ARRAY:
List<Object> array = new ArrayList<>();
Iterator<JsonNode> arrayElement = value.elements();
while (arrayElement.hasNext()) {
JsonNode arrayNode = arrayElement.next();
Object objectNode = getObjectFromElement(arrayNode);
if (objectNode != null) {
array.add(objectNode);
}
}
return array;
case BINARY:
break;
case BOOLEAN:
return value.asBoolean();
case NULL:
break;
case NUMBER:
if (value.isDouble() || value.isFloat()) {
return value.asDouble();
}
if (value.isBigInteger() || value.isShort() || value.isInt()) {
return value.asInt();
}
if (value.isLong()) {
return value.asLong();
}
break;
case STRING:
return value.asText();
case MISSING:
break;
case POJO:
break;
default:
break;
}
return null;
}
public static Map<String, Object> getPropertyMap(JsonNode jsonNode,
Set<String> ignoreKeys, Set<String> ignoreStartWith)
throws JsonProcessingException, IOException {
Map<String, Object> map = new HashMap<>();
if (ignoreKeys == null) {
ignoreKeys = new HashSet<>();
}
if (ignoreStartWith == null) {
ignoreStartWith = new HashSet<>();
}
Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
OUTER_WHILE: while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
String key = entry.getKey();
if (ignoreKeys.contains(key)) {
continue;
}
for (String prefix : ignoreStartWith) {
if (key.startsWith(prefix)) {
continue OUTER_WHILE;
}
}
JsonNode value = entry.getValue();
Object object = null;
try {
object = getObjectFromElement(value);
if (object != null) {
map.put(key, object);
}
} catch (ResourceRegistryException e) {
logger.warn("An invalidy property has been provided. It will be ignored.");
}
}
return map;
}
public static Element updateProperties(Element element, JsonNode jsonNode, Set<String> ignoreKeys, Set<String> ignoreStartWithKeys)
throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyKeys();
Map<String, Object> properties;
if (element instanceof Vertex || element instanceof Edge) {
try {
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
} catch ( IOException e) {
throw new ResourceRegistryException(e);
}
} else {
String error = String.format("Error while updating {} properties",
element.toString());
throw new ResourceRegistryException(error);
}
oldKeys.removeAll(properties.keySet());
for (String key : properties.keySet()) {
try {
element.setProperty(key, properties.get(key));
} catch (Exception e) {
String error = String.format(
"Error while setting property %s : %s", key, properties
.get(key).toString());
logger.error(error);
throw new ResourceRegistryException(error, e);
}
}
OUTER_FOR: for (String key : oldKeys) {
if (ignoreKeys.contains(key)) {
continue;
}
for (String prefix : ignoreStartWithKeys) {
if (key.startsWith(prefix)) {
continue OUTER_FOR;
}
}
element.removeProperty(key);
}
((OrientElement) element).save();
return element;
}
}

View File

@ -0,0 +1,78 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement;
import java.util.HashSet;
import java.util.Set;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.model.embedded.Embedded;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class EmbeddedMangement {
private static Logger logger = LoggerFactory
.getLogger(EmbeddedMangement.class);
public static final Set<String> EMBEDDED_IGNORE_KEYS;
public static final Set<String> EMBEDDED_IGNORE_START_WITH_KEYS;
public static final String AT = "@";
public static final String UNDERSCORE = "_";
static {
EMBEDDED_IGNORE_KEYS = new HashSet<String>();
EMBEDDED_IGNORE_START_WITH_KEYS = new HashSet<String>();
EMBEDDED_IGNORE_START_WITH_KEYS.add(AT);
EMBEDDED_IGNORE_START_WITH_KEYS.add(UNDERSCORE);
}
public static ODocument getEmbeddedType(JsonNode jsonNode)
throws ResourceRegistryException {
if (jsonNode.has(Entities.CLASS_PROPERTY)) {
// Complex type
String type = ERManagement.getClassProperty(jsonNode);
try {
SchemaManagementImpl.getTypeSchema(type, Embedded.NAME);
} catch (SchemaNotFoundException e) {
throw e;
}
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) {
logger.warn("An invalid Header has been provided. Anyway embedded object cannot have an Header.");
throw new ResourceRegistryException("An embedded object cannot have an Header");
}
if (header != null) {
throw new ResourceRegistryException("An embedded object cannot have an Header");
}
ODocument oDocument = new ODocument(type);
return oDocument.fromJSON(jsonNode.toString());
}
return null;
}
}

View File

@ -0,0 +1,537 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement.entity;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.embedded.Header;
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.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility;
import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public abstract class EntityManagement<E extends Entity> {
private static Logger logger = LoggerFactory
.getLogger(EntityManagement.class);
public final String AT = "@";
public final String UNDERSCORE = "_";
protected final Set<String> ignoreKeys;
protected final Set<String> ignoreStartWithKeys;
protected final Class<E> entityClass;
protected final String baseType;
protected OrientGraph orientGraph;
protected UUID uuid;
protected JsonNode jsonNode;
protected String entityType;
protected Vertex vertex;
protected EntityManagement(Class<E> entityClass) {
this.ignoreKeys = new HashSet<String>();
this.ignoreKeys.add(Entity.HEADER_PROPERTY);
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX
.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX
.toUpperCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
.toUpperCase());
this.ignoreStartWithKeys.add(AT);
this.ignoreStartWithKeys.add(UNDERSCORE);
this.entityClass = entityClass;
if (Facet.class.isAssignableFrom(entityClass)) {
this.baseType = Facet.NAME;
} else if (Resource.class.isAssignableFrom(entityClass)) {
this.baseType = Resource.NAME;
} else {
this.baseType = Entity.NAME;
}
}
protected EntityManagement(Class<E> entityClass, OrientGraph orientGraph) {
this(entityClass);
this.orientGraph = orientGraph;
}
public void setVertex(Vertex vertex) throws ResourceRegistryException {
if(vertex==null){
throw new ResourceRegistryException("Trying to set null Vertex in " + this);
}
this.vertex = vertex;
this.uuid = HeaderUtility.getHeader(vertex).getUUID();
}
public void setUUID(UUID uuid) throws ResourceRegistryException {
this.uuid = uuid;
if (jsonNode != null) {
checkUUIDMatch();
}
}
public void setJSON(JsonNode jsonNode) throws ResourceRegistryException {
this.jsonNode = jsonNode;
checkJSON();
}
public void setJSON(String jsonRepresentation)
throws ResourceRegistryException {
ObjectMapper mapper = new ObjectMapper();
try {
this.jsonNode = mapper.readTree(jsonRepresentation);
} catch (IOException e) {
throw new ResourceRegistryException(e);
}
checkJSON();
}
protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) {
try {
uuid = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {
}
} else {
checkUUIDMatch();
}
if (this.entityType == null) {
this.entityType = ERManagement.getClassProperty(jsonNode);
} else {
checkEntityMatch();
}
}
public void setEntityType(String entityType)
throws ResourceRegistryException {
this.entityType = entityType;
if (entityType == null || entityType.compareTo("") == 0) {
if (Facet.class.isAssignableFrom(entityClass)) {
entityType = Facet.NAME;
}
if (Resource.class.isAssignableFrom(entityClass)) {
entityType = Resource.NAME;
}
}
if (jsonNode != null) {
checkEntityMatch();
}
}
protected void checkEntityMatch() throws ResourceRegistryException {
String type = ERManagement.getClassProperty(jsonNode);
if (type != null && type.compareTo(entityType) != 0) {
String error = String
.format("Declared resourceType does not match with json representation %s!=%s",
entityType, type);
logger.trace(error);
throw new ResourceRegistryException(error);
}
try {
SchemaManagementImpl.getTypeSchema(entityType, baseType);
} catch (SchemaNotFoundException e) {
throw e;
}
}
protected void checkUUIDMatch() throws ResourceRegistryException {
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) {
throw new ResourceRegistryException(e);
}
if (header != null) {
UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) {
String error = String
.format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(),
entityType);
throw new ResourceRegistryException(error);
}
}
}
public Vertex getVertex() throws EntityNotFoundException, ResourceRegistryException {
try {
if(vertex == null){
vertex = Utility.getElementByUUID(orientGraph,
entityType == null ? baseType : entityType, uuid,
Vertex.class);
}
return vertex;
} catch (ResourceRegistryException e) {
if(Resource.class.isAssignableFrom(entityClass)){
throw new ResourceNotFoundException(e);
}else if(Facet.class.isAssignableFrom(entityClass)){
throw new FacetNotFoundException(e);
}else {
throw e;
}
}
}
protected Vertex createVertex() throws EntityAlreadyPresentException,
ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}",
Vertex.class.getSimpleName(), baseType, entityType, jsonNode);
try {
vertex = orientGraph.addVertex("class:" + entityType);
try {
Vertex v = getVertex();
if (v != null) {
String error = String.format(
"A %s with UUID %s already exist", entityType,
uuid.toString());
throw new EntityAlreadyPresentException(error);
}
} catch (EntityAlreadyPresentException e) {
throw e;
} catch (Exception e) {
// no header or no header with uuid is provided and it is fine
}
Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
if (entityHeader != null) {
vertex.setProperty(Entity.HEADER_PROPERTY, entityHeader);
} else {
entityHeader = HeaderUtility.addHeader(vertex, null);
}
if (Resource.class.isAssignableFrom(entityClass)) {
// Facet and relation are created in calling method
} else {
ERManagement.updateProperties(vertex, jsonNode, ignoreKeys,
ignoreStartWithKeys);
}
ContextUtility.addToActualContext(orientGraph, vertex);
((OrientVertex) vertex).save();
logger.info("Created {} is {}", Vertex.class.getSimpleName(),
Utility.toJsonString((OrientVertex) vertex, true));
return vertex;
} catch (ResourceRegistryException e) {
throw e;
} catch (Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}",
Vertex.class.getSimpleName(), baseType, entityType,
jsonNode, e);
throw new ResourceRegistryException("Error Creating " + entityType
+ " with " + jsonNode, e.getCause());
}
}
public abstract String serialize() throws ResourceRegistryException;
public abstract JSONObject serializeAsJson() throws ResourceRegistryException;
public abstract Vertex reallyCreate() throws EntityAlreadyPresentException,
ResourceRegistryException;
public abstract Vertex reallyUpdate() throws EntityNotFoundException,
ResourceRegistryException;
public abstract boolean reallyDelete() throws EntityNotFoundException,
ResourceRegistryException;
public boolean reallyAddToContext() throws ContextException, ResourceRegistryException {
getVertex();
ContextUtility.addToActualContext(orientGraph, vertex);
Iterable<Edge> edges = vertex.getEdges(Direction.OUT, ConsistsOf.NAME);
/*
* Use this when the add integrity directive are inserted
* Iterable<Edge> edges = vertex.getEdges(Direction.OUT);
*
*/
for (Edge edge : edges) {
@SuppressWarnings("rawtypes")
RelationManagement relationManagement = RelationManagement.getRelationManagement(orientGraph, edge);
relationManagement.reallyAddToContext();
}
return true;
}
public boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("rawtypes")
public static EntityManagement getEntityManagement(OrientGraph orientGraph, Vertex vertex) throws ResourceRegistryException{
OrientVertexType orientVertexType = ((OrientVertex) vertex).getType();
EntityManagement entityManagement = null;
if (orientVertexType.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(orientGraph);
} else if (orientVertexType.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange ad should not occur. "
+ "Please Investigate it.", vertex,
Resource.NAME, Facet.NAME);
throw new ResourceRegistryException(error);
}
entityManagement.setVertex(vertex);
return entityManagement;
}
public String create() throws EntityAlreadyPresentException,
ResourceRegistryException {
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
reallyCreate();
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String read() throws EntityNotFoundException,
ResourceRegistryException {
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER);
}
getVertex();
return serialize();
} catch (ResourceRegistryException fnfe) {
throw fnfe;
} catch (Exception e) {
throw new ResourceRegistryException(e.getMessage());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String update() throws EntityNotFoundException,
ResourceRegistryException {
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
reallyUpdate();
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
logger.debug("Unable to update {} with UUID {} usign {}", baseType,
uuid, jsonNode, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException("Error Updating " + baseType,
e.getCause());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean delete() throws FacetNotFoundException,
ResourceRegistryException {
logger.debug("Going to delete {} with UUID {}", baseType, uuid);
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
boolean deleted = reallyDelete();
orientGraph.commit();
logger.info("{} with UUID {} was successfully deleted.", baseType,
uuid);
return deleted;
} catch (FacetNotFoundException fnfe) {
logger.error("Unable to delete {} with UUID {}", baseType, uuid,
fnfe);
if (orientGraph != null) {
orientGraph.rollback();
}
throw fnfe;
} catch (Exception e) {
logger.error("Unable to delete {} with UUID {}", baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean addToContext() throws ContextException {
logger.debug("Going to add {} with UUID {} to actual Context",
baseType, uuid);
try {
if (orientGraph == null) {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
}
boolean added = reallyAddToContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context",
baseType, uuid);
return added;
} catch (Exception e) {
logger.error(
"Unable to add {} with UUID {} to actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e.getMessage());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean removeFromContext() throws ContextException {
logger.debug("Going to remove {} with UUID {} from actual Context",
baseType, uuid);
try {
if (orientGraph == null) {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
}
boolean removed = reallyRemoveFromContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully removed from actual Context",
baseType, uuid);
return removed;
} catch (Exception e) {
logger.error(
"Unable to remove {} with UUID {} from actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e.getMessage());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
}

View File

@ -0,0 +1,60 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement.entity;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement;
import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class FacetManagement extends EntityManagement<Facet> {
public FacetManagement() {
super(Facet.class);
}
public FacetManagement(OrientGraph orientGraph) {
super(Facet.class, orientGraph);
}
@Override
public String serialize() throws ResourceRegistryException {
return Utility.toJsonString((OrientVertex) vertex, true);
}
@Override
public JSONObject serializeAsJson() throws ResourceRegistryException {
return Utility.toJsonObject((OrientVertex) vertex, true);
}
public Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
return createVertex();
}
@Override
public Vertex reallyUpdate() throws ResourceRegistryException {
Vertex facet = getVertex();
facet = (Vertex) ERManagement.updateProperties(facet, jsonNode, ignoreKeys, ignoreStartWithKeys);
((OrientVertex) facet).save();
return facet;
}
public boolean reallyDelete() throws FacetNotFoundException, ResourceRegistryException {
Vertex facet = getVertex();
facet.remove();
return true;
}
}

View File

@ -0,0 +1,198 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement.entity;
import java.util.Iterator;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
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.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ResourceManagement extends EntityManagement<Resource> {
private static Logger logger = LoggerFactory
.getLogger(ResourceManagement.class);
public ResourceManagement() {
super(Resource.class);
}
public ResourceManagement(OrientGraph orientGraph) {
super(Resource.class, orientGraph);
}
private static JSONObject marshallResource(OrientGraph orientGraph,
Vertex vertex) throws ResourceRegistryException {
JSONObject jsonObject = Utility.toJsonObject((OrientVertex) vertex,
true);
JSONArray consistsOfArray = new JSONArray();
/*
* JSONArray isRelatedToArray = new JSONArray();
* Iterable<Edge> edges = vertex.getEdges(Direction.OUT);
*/
Iterable<Edge> edges = vertex.getEdges(Direction.OUT, ConsistsOf.NAME);
for (Edge edge : edges) {
@SuppressWarnings("rawtypes")
RelationManagement relationManagement = RelationManagement.getRelationManagement(orientGraph, edge);
JSONObject relationJsonObject = relationManagement.serializeAsJson();
consistsOfArray.put(relationJsonObject);
/*
* else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){
* isRelatedToArray.put(jsonObjectEdge); }
*/
}
try {
jsonObject.put(ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME),
consistsOfArray);
} catch (JSONException e) {
throw new ResourceRegistryException(e);
}
/*
* jsonObject.put(lowerCaseFirstCharacter(IsRelatedTo.NAME),
* isRelatedToArray);
*/
return jsonObject;
}
@Override
public String serialize() throws ResourceRegistryException {
return marshallResource(orientGraph, getVertex()).toString();
}
@Override
public JSONObject serializeAsJson() throws ResourceRegistryException {
return marshallResource(orientGraph, getVertex());
}
@Override
public Vertex reallyCreate() throws EntityAlreadyPresentException,
ResourceRegistryException {
createVertex();
String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME);
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph);
com.setJSON(consistOfJsonNode);
com.reallyCreate(vertex);
}
}
property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME);
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(
orientGraph);
irtm.setJSON(relationJsonNode);
irtm.reallyCreate(vertex);
}
}
return vertex;
}
@Override
public Vertex reallyUpdate() throws ResourceRegistryException {
getVertex();
String property = ERManagement.lowerCaseFirstCharacter(ConsistsOf.NAME);
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph);
com.setJSON(relationJsonNode);
com.reallyUpdate();
}
}
property = ERManagement.lowerCaseFirstCharacter(IsRelatedTo.NAME);
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(
orientGraph);
irtm.setJSON(relationJsonNode);
irtm.reallyUpdate();
}
}
((OrientVertex) vertex).save();
return vertex;
}
@Override
public boolean reallyDelete() throws ResourceNotFoundException,
ResourceRegistryException {
//internalDeleteResource(orientGraph, uuid, null);
getVertex();
Iterable<Edge> iterable = vertex.getEdges(Direction.OUT);
Iterator<Edge> iterator = iterable.iterator();
while(iterator.hasNext()){
Edge edge = iterator.next();
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
@SuppressWarnings("rawtypes")
RelationManagement relationManagement = null;
if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){
relationManagement = new IsRelatedToManagement(orientGraph);
}else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)){
relationManagement = new ConsistsOfManagement(orientGraph);
}else{
logger.warn("{} is not a {} nor a {}. "
+ "This is really strange ad should not occur. "
+ "Please Investigate it.",
Utility.toJsonString(edge, true),
IsRelatedTo.NAME, ConsistsOf.NAME);
}
if(relationManagement!=null){
relationManagement.setEdge(edge);
relationManagement.reallyDelete();
}
}
((OrientVertex) vertex).remove();
return true;
}
}

View File

@ -0,0 +1,24 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement.relation;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("rawtypes")
public class ConsistsOfManagement extends RelationManagement<ConsistsOf> {
public ConsistsOfManagement() {
super(ConsistsOf.class);
}
public ConsistsOfManagement(OrientGraph orientGraph) {
super(ConsistsOf.class, orientGraph);
}
}

View File

@ -0,0 +1,24 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement.relation;
import org.gcube.informationsystem.model.relation.IsRelatedTo;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("rawtypes")
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo> {
public IsRelatedToManagement() {
super(IsRelatedTo.class);
}
public IsRelatedToManagement(OrientGraph orientGraph) {
super(IsRelatedTo.class, orientGraph);
}
}

View File

@ -0,0 +1,639 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.ermanagement.relation;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.embedded.RelationProperty;
import org.gcube.informationsystem.model.embedded.RelationProperty.ReferentialIntegrity;
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.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.ermanagement.ERManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility;
import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
@SuppressWarnings("rawtypes")
public abstract class RelationManagement<R extends Relation> {
private static Logger logger = LoggerFactory
.getLogger(RelationManagement.class);
public final Set<String> ignoreKeys;
public final Set<String> ignoreStartWithKeys;
public static final String AT = "@";
public static final String UNDERSCORE = "_";
protected final Class<R> relationClass;
protected final String baseType;
protected final Class<? extends Entity> targetEntityClass;
protected OrientGraph orientGraph;
protected UUID uuid;
protected JsonNode jsonNode;
protected String relationType;
protected Edge edge;
protected RelationManagement(Class<R> relationClass) {
this.ignoreKeys = new HashSet<String>();
this.ignoreKeys.add(Relation.HEADER_PROPERTY);
this.ignoreKeys.add(Relation.TARGET_PROPERTY);
this.ignoreKeys.add(Relation.SOURCE_PROPERTY);
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toLowerCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toLowerCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase());
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(AT);
this.ignoreStartWithKeys.add(UNDERSCORE);
this.relationClass = relationClass;
if (ConsistsOf.class.isAssignableFrom(relationClass)) {
this.baseType = ConsistsOf.NAME;
this.targetEntityClass = Facet.class;
} else if (IsRelatedTo.class.isAssignableFrom(relationClass)) {
this.baseType = IsRelatedTo.NAME;
this.targetEntityClass = Resource.class;
} else {
this.baseType = Relation.NAME;
this.targetEntityClass = Resource.class;
}
}
protected RelationManagement(Class<R> relationClass, OrientGraph orientGraph) {
this(relationClass);
this.orientGraph = orientGraph;
}
public void setEdge(Edge edge) {
this.edge = edge;
}
public void setUUID(UUID uuid) throws ResourceRegistryException {
this.uuid = uuid;
if (jsonNode != null) {
checkUUIDMatch();
}
}
protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) {
try {
uuid = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {
}
} else {
checkUUIDMatch();
}
if (this.relationType == null) {
this.relationType = ERManagement.getClassProperty(jsonNode);
} else {
checkEntityMatch();
}
}
public void setJSON(JsonNode jsonNode) throws ResourceRegistryException {
this.jsonNode = jsonNode;
checkJSON();
}
public void setJSON(String jsonRepresentation)
throws ResourceRegistryException {
ObjectMapper mapper = new ObjectMapper();
try {
this.jsonNode = mapper.readTree(jsonRepresentation);
} catch (IOException e) {
throw new ResourceRegistryException(e);
}
checkJSON();
}
public void setRelationType(String relationType)
throws ResourceRegistryException {
this.relationType = relationType;
if (relationType == null || relationType.compareTo("") == 0) {
if (ConsistsOf.class.isAssignableFrom(relationClass)) {
this.relationType = ConsistsOf.NAME;
} else if (IsRelatedTo.class.isAssignableFrom(relationClass)) {
this.relationType = IsRelatedTo.NAME;
}
}
if (jsonNode != null) {
checkEntityMatch();
}
}
protected void checkEntityMatch() throws ResourceRegistryException {
String type = ERManagement.getClassProperty(jsonNode);
if (type != null && type.compareTo(relationType) != 0) {
String error = String
.format("Declared resourceType does not match with json representation %s!=%s",
relationType, type);
logger.trace(error);
throw new ResourceRegistryException(error);
}
try {
SchemaManagementImpl.getTypeSchema(relationType, baseType);
} catch (SchemaNotFoundException e) {
throw e;
}
}
protected void checkUUIDMatch() throws ResourceRegistryException {
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) {
throw new ResourceRegistryException(e);
}
if (header != null) {
UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) {
String error = String
.format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(),
relationType);
throw new ResourceRegistryException(error);
}
}
}
public Edge getEdge() throws ResourceRegistryException {
try {
if (edge == null) {
edge = Utility.getElementByUUID(orientGraph,
relationType == null ? baseType : relationType, uuid,
Edge.class);
}
return edge;
} catch (ResourceRegistryException e) {
throw e;
} catch (Exception e) {
throw new ResourceRegistryException(e);
}
}
public String serialize() throws ResourceRegistryException {
return Utility.toJsonString((OrientEdge) getEdge(), false);
}
public JSONObject serializeAsJson() throws ResourceRegistryException {
return Utility.toJsonObject((OrientEdge) getEdge(), false);
}
public Edge reallyCreate(UUID sourceUUID, UUID targetUUID)
throws ResourceRegistryException {
ResourceManagement srmSource = new ResourceManagement(orientGraph);
srmSource.setUUID(sourceUUID);
Vertex source = srmSource.getVertex();
Vertex target = null;
if (ConsistsOf.class.isAssignableFrom(relationClass)) {
FacetManagement fmTarget = new FacetManagement(orientGraph);
fmTarget.setUUID(targetUUID);
target = fmTarget.getVertex();
} else if (IsRelatedTo.class.isAssignableFrom(relationClass)) {
ResourceManagement srmTarget = new ResourceManagement(orientGraph);
srmTarget.setUUID(targetUUID);
target = srmTarget.getVertex();
}
return reallyCreate(source, target);
}
protected Edge reallyCreate(Vertex source, Vertex target)
throws ResourceRegistryException {
// TODO Check the relation compatibility between source and target
logger.trace("Creating {} ({}) beetween {} -> {}",
Relation.class.getSimpleName(), relationType,
Utility.toJsonString(source, true),
Utility.toJsonString(target, true));
edge = orientGraph.addEdge(null, source, target, relationType);
ERManagement.updateProperties(edge, jsonNode, ignoreKeys,
ignoreStartWithKeys);
HeaderUtility.addHeader(edge, null);
ContextUtility.addToActualContext(orientGraph, edge);
((OrientEdge) edge).save();
logger.info("{} successfully created", relationType);
return edge;
}
public Edge reallyCreate(Vertex source) throws ResourceRegistryException {
Vertex target = null;
EntityManagement entityManagement = getEntityManagement();
if (!jsonNode.has(Relation.TARGET_PROPERTY)) {
throw new ResourceRegistryException(
"Error while creating relation. No target definition found");
}
entityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
try {
target = entityManagement.getVertex();
} catch (Exception e) {
target = entityManagement.reallyCreate();
}
return reallyCreate(source, target);
}
public Edge reallyCreate(UUID sourceUUID) throws ResourceRegistryException {
ResourceManagement srmSource = new ResourceManagement(orientGraph);
srmSource.setUUID(sourceUUID);
Vertex source = srmSource.getVertex();
return reallyCreate(source);
}
public Edge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", relationClass.getSimpleName(),
jsonNode);
Edge edge = getEdge();
ERManagement.updateProperties(edge, jsonNode, ignoreKeys,
ignoreStartWithKeys);
if (ConsistsOf.class.isAssignableFrom(relationClass)) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if (target != null) {
FacetManagement fm = new FacetManagement(orientGraph);
fm.setJSON(target);
fm.reallyUpdate();
}
}
logger.info("{} {} successfully updated", relationType, jsonNode);
return edge;
}
public boolean reallyAddToContext() throws ContextException,
ResourceRegistryException {
getEdge();
// TODO check add integrity directive
ContextUtility.addToActualContext(orientGraph, edge);
Vertex vertex = edge.getVertex(Direction.IN);
EntityManagement entityManagement = EntityManagement
.getEntityManagement(orientGraph, vertex);
entityManagement.reallyAddToContext();
return true;
}
public boolean reallyRemoveFromContext() throws ContextException,
ResourceRegistryException {
throw new UnsupportedOperationException();
}
protected EntityManagement getEntityManagement()
throws ResourceRegistryException {
EntityManagement entityManagement;
if (ConsistsOf.class.isAssignableFrom(relationClass)) {
entityManagement = new FacetManagement(orientGraph);
} else if (IsRelatedTo.class.isAssignableFrom(relationClass)) {
entityManagement = new ResourceManagement(orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange ad should not occur. "
+ "Please Investigate it.", relationClass, ConsistsOf.NAME,
IsRelatedTo.NAME);
throw new ResourceRegistryException(error);
}
return entityManagement;
}
public static RelationManagement getRelationManagement(
OrientGraph orientGraph, Edge edge)
throws ResourceRegistryException {
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(orientGraph);
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. "
+ "This is really strange ad should not occur. "
+ "Please Investigate it.", edge, ConsistsOf.NAME,
IsRelatedTo.NAME);
throw new ResourceRegistryException(error);
}
relationManagement.setEdge(edge);
return relationManagement;
}
protected boolean deleteTargetVertex(Vertex target)
throws ResourceRegistryException {
EntityManagement entityManagement = EntityManagement
.getEntityManagement(orientGraph, target);
if (entityManagement != null) {
entityManagement.reallyDelete();
return true;
} else {
return false;
}
}
public boolean reallyDelete() throws RelationNotFoundException,
ResourceRegistryException {
getEdge();
ReferentialIntegrity referentialIntegrity = ReferentialIntegrity.onDeleteKeep;
try {
RelationProperty relationProperty = Utility.getEmbedded(
RelationProperty.class, edge, Relation.RELATION_PROPERTY);
referentialIntegrity = relationProperty.getReferentialIntegrity();
} catch (Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. "
+ "This is really strange ad should not occur. "
+ "Please Investigate it.",
RelationProperty.REFERENTIAL_INTEGRITY,
Utility.toJsonString(edge, true),
ReferentialIntegrity.onDeleteKeep);
}
Vertex target = edge.getVertex(Direction.IN);
edge.remove();
switch (referentialIntegrity) {
case onDeleteCascade:
deleteTargetVertex(target);
break;
case onDeleteCascadeWhenOrphan:
Iterable<Edge> iterable = target.getEdges(Direction.IN);
Iterator<Edge> iterator = iterable.iterator();
if (iterator.hasNext()) {
logger.trace(
"{} point to {} which is not orphan. Giving {} directive, it will be keep.",
edge, target, referentialIntegrity);
} else {
deleteTargetVertex(target);
}
break;
case onDeleteKeep:
break;
default:
break;
}
return true;
}
public String create(UUID sourceUUID, UUID targetUUID)
throws ResourceRegistryException {
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
edge = reallyCreate(sourceUUID, targetUUID);
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String read() throws RelationNotFoundException,
ResourceRegistryException {
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public String update() throws RelationNotFoundException,
ResourceRegistryException {
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
edge = reallyUpdate();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean delete() throws RelationNotFoundException,
ResourceRegistryException {
logger.debug(
"Going to remove {} with UUID {}. Related {}s will be detached.",
baseType, uuid, targetEntityClass.getSimpleName());
try {
if (orientGraph == null) {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER);
}
boolean deleted = reallyDelete();
orientGraph.commit();
logger.info("{} {} with UUID {} successfully removed.", baseType,
uuid);
return deleted;
} catch (ResourceRegistryException rre) {
logger.error("Unable to remove {} with UUID.", baseType, uuid);
if (orientGraph != null) {
orientGraph.rollback();
}
throw rre;
} catch (Exception e) {
logger.error("Unable to remove {} with UUID {}.", baseType, uuid);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean addToContext() throws ContextException {
logger.debug("Going to add {} with UUID {} to actual Context",
baseType, uuid);
try {
if (orientGraph == null) {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
}
boolean added = reallyAddToContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context",
baseType, uuid);
return added;
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e.getMessage());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean removeFromContext() throws ContextException {
logger.debug("Going to remove {} with UUID {} from actual Context",
baseType, uuid);
try {
if (orientGraph == null) {
orientGraph = SecurityContextMapper.getSecurityContextFactory(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.WRITER).getTx();
}
boolean removed = reallyRemoveFromContext();
orientGraph.commit();
logger.info(
"{} with UUID {} successfully removed from actual Context",
baseType, uuid);
return removed;
} catch (Exception e) {
logger.error(
"Unable to remove {} with UUID {} from actual Context",
baseType, uuid, e);
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e.getMessage());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
}

View File

@ -9,7 +9,6 @@ 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;
import org.gcube.informationsystem.resourceregistry.api.SchemaManagement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException;
@ -18,7 +17,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.resources.impl.EntityManagementImpl;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.resources.impl.QueryImpl;
import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl;
import org.slf4j.Logger;
@ -35,10 +35,6 @@ public class Access {
public static final String ID_PATH_PARAM = "id";
public static final String TYPE_PATH_PARAM = "type";
protected Query queryManager = new QueryImpl();
protected EntityManagement entityManager = new EntityManagementImpl();
protected SchemaManagement schemaManager = new SchemaManagementImpl();
/**
* It allows to query Entities and Relations in the current Context.<br />
@ -68,6 +64,7 @@ public class Access {
@QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan)
throws InvalidQueryException {
logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query);
Query queryManager = new QueryImpl();
return queryManager.query(query, limit, fetchPlan);
}
@ -84,7 +81,9 @@ public class Access {
public String getFacet(@PathParam(ID_PATH_PARAM) String facetId)
throws FacetNotFoundException, ResourceRegistryException {
logger.info("Requested Facet with id {}", facetId);
return entityManager.readFacet(UUID.fromString(facetId));
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(facetId));
return facetManagement.read();
}
/**
@ -99,6 +98,7 @@ public class Access {
public String getFacetSchema(@PathParam(TYPE_PATH_PARAM) String facetType)
throws SchemaNotFoundException {
logger.info("Requested Facet Schema for type {}", facetType);
SchemaManagement schemaManager = new SchemaManagementImpl();
return schemaManager.getFacetSchema(facetType);
}
@ -115,7 +115,9 @@ public class Access {
public String getResource(@PathParam(ID_PATH_PARAM) String resourceId)
throws ResourceNotFoundException, ResourceRegistryException {
logger.info("Requested Resource with id {}", resourceId);
return entityManager.readResource(UUID.fromString(resourceId));
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(resourceId));
return resourceManagement.read();
}
/**
@ -130,6 +132,7 @@ public class Access {
public String getResourceSchema(@PathParam(TYPE_PATH_PARAM) String resourceType)
throws SchemaNotFoundException {
logger.info("Requested Resource Schema for type {}", resourceType);
SchemaManagement schemaManager = new SchemaManagementImpl();
return schemaManager.getResourceSchema(resourceType);
}

View File

@ -15,7 +15,7 @@ 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;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
@ -54,7 +54,7 @@ public class ContextManager {
public String create(
@QueryParam(ContextPath.PARENT_CONTEXT_ID_PARAM) String parentUUID,
@QueryParam(ContextPath.NAME_PARAM) String name)
throws ContextCreationException, InternalException {
throws ContextCreationException, ResourceRegistryException {
logger.trace("requested to create context with name : {} ", name);
return contextManager.create(UUID.fromString(parentUUID), name);
}

View File

@ -15,14 +15,16 @@ 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.resourceregistry.api.EntityManagement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.EntityPath;
import org.gcube.informationsystem.resourceregistry.resources.impl.EntityManagementImpl;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -42,8 +44,6 @@ public class EntityManager {
public static final String SOURCE_ID_PATH_PARAM = "sourceId";
public static final String TARGET_ID_PATH_PARAM = "targetId";
protected EntityManagement entityManager = new EntityManagementImpl();
/* Facets Methods */
/**
* e.g. PUT /resource-registry/entity/facet/ContactFacet
@ -64,7 +64,10 @@ public class EntityManager {
String json) throws EntityException, ResourceRegistryException {
logger.info("requested facet creation for type {} defined by {} ",
type, json);
return entityManager.createFacet(type, json);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setEntityType(type);
facetManagement.setJSON(json);
return facetManagement.create();
}
/**
@ -86,7 +89,10 @@ public class EntityManager {
public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json)
throws FacetNotFoundException, ResourceRegistryException {
logger.info("requested facet update for id {} with {}", uuid, json);
return entityManager.updateFacet(UUID.fromString(uuid), json);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
facetManagement.setJSON(json);
return facetManagement.update();
}
/**
@ -103,7 +109,9 @@ public class EntityManager {
public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ResourceRegistryException {
logger.info("Requested to delete Facet with id {}", uuid);
return entityManager.deleteFacet(UUID.fromString(uuid));
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.delete();
}
/* Resources Methods */
@ -128,7 +136,10 @@ public class EntityManager {
ResourceRegistryException {
logger.info("requested resource creation for type {} with json {}",
type, json);
return entityManager.createResource(type, json);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(type);
resourceManagement.setJSON(json);
return resourceManagement.create();
}
@POST
@ -139,10 +150,12 @@ public class EntityManager {
String json) throws FacetNotFoundException,
ResourceRegistryException {
logger.info("requested resource update for id {} with {}", uuid, json);
return entityManager.updateResource(UUID.fromString(uuid), json);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
resourceManagement.setJSON(json);
return resourceManagement.update();
}
/**
* e.g. DELETE
* /resource-registry/entity/resource/67062c11-9c3a-4906-870d-7df6a43408b0
@ -157,7 +170,9 @@ public class EntityManager {
public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, Exception {
logger.info("requested resource deletion for id {}", uuid);
return entityManager.deleteResource(UUID.fromString(uuid));
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.delete();
}
/* Relations Methods */
@ -193,8 +208,11 @@ public class EntityManager {
"requested to attach resource {} to facet {} ({} Type {}) with properties {}",
resourceUUID, facetUUID, ConsistsOf.class.getSimpleName(),
type, json);
return entityManager.attachFacet(UUID.fromString(resourceUUID),
UUID.fromString(facetUUID), type, json);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setRelationType(type);
consistsOfManagement.setJSON(json);
return consistsOfManagement.create(UUID.fromString(resourceUUID),
UUID.fromString(facetUUID));
}
/**
@ -210,7 +228,9 @@ public class EntityManager {
public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID)
throws ResourceRegistryException {
logger.info("requested to detach {}", consistOfUUID);
return entityManager.detachFacet(UUID.fromString(consistOfUUID));
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setUUID(UUID.fromString(consistOfUUID));
return consistsOfManagement.delete();
}
/**
@ -245,9 +265,14 @@ public class EntityManager {
Resource.NAME, sourceResourceUUID, Resource.NAME,
targetResourceUUID, IsRelatedTo.class.getSimpleName(), type,
json);
return entityManager.attachResource(
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setRelationType(type);
isRelatedToManagement.setJSON(json);
return isRelatedToManagement.create(
UUID.fromString(sourceResourceUUID),
UUID.fromString(targetResourceUUID), type, json);
UUID.fromString(targetResourceUUID));
}
/**
@ -263,7 +288,9 @@ public class EntityManager {
public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID)
throws ResourceRegistryException {
logger.info("requested to detach {}", relatedToUUID);
return entityManager.detachResource(UUID.fromString(relatedToUUID));
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID));
return isRelatedToManagement.delete();
}
/**
@ -284,7 +311,9 @@ public class EntityManager {
ResourceRegistryException {
logger.info("requested to add {} with UUID {} to current context {}",
Resource.NAME, uuid, ContextUtility.getCurrentContext());
return entityManager.addResourceToContext(UUID.fromString(uuid));
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.addToContext();
}
/**
@ -305,7 +334,9 @@ public class EntityManager {
ResourceRegistryException {
logger.info("requested to add {} with UUID {} to current context {}",
Facet.NAME, uuid, ContextUtility.getCurrentContext());
return entityManager.addFacetToContext(UUID.fromString(uuid));
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.addToContext();
}
}

View File

@ -6,8 +6,7 @@ import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotAllowedException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ElementAlreadyPresent;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ElementNotFound;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
@ -25,9 +24,9 @@ public class ResourceRegistryExceptionMapper implements ExceptionMapper<Resource
if(ElementNotFound.class.isAssignableFrom(exception.getClass())){
status = Status.NOT_FOUND;
}else if(NotAllowedException.class.isAssignableFrom(exception.getClass())){
}else if(ElementAlreadyPresent.class.isAssignableFrom(exception.getClass())){
status = Status.FORBIDDEN;
} else if(InternalException.class.isAssignableFrom(exception.getClass())){
} else {
status = Status.INTERNAL_SERVER_ERROR;
}

View File

@ -10,7 +10,6 @@ import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.resourceregistry.api.ContextManagement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.InternalException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
@ -110,7 +109,7 @@ public class ContextManagementImpl implements ContextManagement {
@Override
public String create(UUID parentContext, String name)
throws ContextCreationException, InternalException {
throws ContextCreationException, ResourceRegistryException {
OrientGraph orientGraph = null;
UUID uuid = UUID.randomUUID();
@ -165,7 +164,7 @@ public class ContextManagementImpl implements ContextManagement {
orientGraph.rollback();
SecurityContext.deleteSecurityContext(orientGraph, uuid, true);
}
throw new InternalException(e.getMessage());
throw new ResourceRegistryException(e.getMessage());
} finally {
if (orientGraph != null) {
orientGraph.shutdown();

View File

@ -57,7 +57,7 @@ public class SchemaManagementImpl implements SchemaManagement {
return oSchema.getClass(entityType);
}
protected static OClass getTypeSchema(OrientBaseGraph orientBaseGraph,
public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph,
String type, String baseType) throws SchemaNotFoundException {
try {
OClass oClass = getEntityOClass(orientBaseGraph, type);
@ -76,7 +76,7 @@ public class SchemaManagementImpl implements SchemaManagement {
}
}
protected static OClass getTypeSchema(String type, String baseType)
public static OClass getTypeSchema(String type, String baseType)
throws SchemaNotFoundException {
OrientGraphFactory orientGraphFactory = SecurityContextMapper
.getSecurityContextFactory(

View File

@ -11,9 +11,7 @@ import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
@ -25,7 +23,6 @@ import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
@ -70,12 +67,6 @@ public class ContextUtility {
return contextUUID;
}
protected static UUID getContextUUIDFromContextVertex(Vertex vertex) {
ODocument header = vertex.getProperty(Entity.HEADER_PROPERTY);
String contextID = header.field(Header.UUID_PROPERTY);
return UUID.fromString(contextID);
}
public static String getCurrentContext(){
String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null;
@ -104,7 +95,7 @@ public class ContextUtility {
orientGraph = factory.getTx();
Vertex context = ContextUtility.getContextVertexByFullName(
orientGraph, scope);
return getContextUUIDFromContextVertex(context);
return Utility.getUUID(context);
} catch (ContextException e) {
throw e;
} catch (Exception e) {

View File

@ -15,6 +15,7 @@ import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -22,6 +23,7 @@ import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
/**
@ -103,5 +105,10 @@ public class HeaderUtility {
edge.setProperty(Entity.HEADER_PROPERTY, header);
return header;
}
public static Header getHeader(Element element)
throws ResourceRegistryException {
return Utility.getEmbedded(Header.class, element, Entity.HEADER_PROPERTY);
}
}

View File

@ -10,6 +10,7 @@ import java.util.UUID;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation;
@ -18,6 +19,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
@ -35,8 +37,13 @@ public class Utility {
private static final Logger logger = LoggerFactory.getLogger(Utility.class);
public static JSONObject toJsonObject(OrientElement element, boolean raw) throws JSONException {
return new JSONObject(toJsonString(element, raw));
public static JSONObject toJsonObject(OrientElement element, boolean raw)
throws ResourceRegistryException {
try {
return new JSONObject(toJsonString(element, raw));
}catch(Exception e){
throw new ResourceRegistryException(e);
}
}
public static String toJsonString(OrientElement element, boolean raw) {
@ -50,12 +57,13 @@ public class Utility {
}
return oRecord.toJSON("class");
}
public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException {
if(raw){
public static JSONObject toJsonObject(Element element, boolean raw)
throws JSONException {
if (raw) {
return GraphSONUtility.jsonFromElement(element,
element.getPropertyKeys(), GraphSONMode.EXTENDED);
}else{
} else {
Set<String> keys = new HashSet<>(element.getPropertyKeys());
for (String key : element.getPropertyKeys()) {
if (key.startsWith("_")) {
@ -74,15 +82,16 @@ public class Utility {
return String.valueOf(element);
}
}
public static <El extends Element> El getElementByUUID(OrientGraph orientGraph,
String elementType, UUID uuid, Class<? extends El> clz) throws ResourceRegistryException {
if (elementType == null || elementType.compareTo("")==0) {
if(Vertex.class.isAssignableFrom(clz)){
public static <El extends Element> El getElementByUUID(
OrientGraph orientGraph, String elementType, UUID uuid,
Class<? extends El> clz) throws ResourceRegistryException {
if (elementType == null || elementType.compareTo("") == 0) {
if (Vertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME;
}
if(Edge.class.isAssignableFrom(clz)){
if (Edge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME;
}
}
@ -116,5 +125,30 @@ public class Utility {
return element;
}
public static <T> T getEmbedded(Class<T> clz, Element element, String property)
throws ResourceRegistryException {
try {
ODocument oDocument = element.getProperty(property);
T t = Entities.unmarshal(clz, oDocument.toJSON());
return t;
} catch (Exception e) {
String error = String.format("Error while getting %s from %s",
property, toJsonString(element, true));
throw new ResourceRegistryException(error, e);
}
}
public static UUID getUUID(Element element)
throws ResourceRegistryException {
/*
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY);
* String contextID = header.field(Header.UUID_PROPERTY); return
* UUID.fromString(contextID);
*/
Header header = HeaderUtility.getHeader(element);
return header.getUUID();
}
}

View File

@ -0,0 +1,90 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.gcube.common.authorization.client.Constants;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class ScopedTest {
private static final Logger logger = LoggerFactory.getLogger(ScopedTest.class);
protected static final String PROPERTIES_FILENAME = "token.properties";
private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT";
public static final String GCUBE_DEVNEXT;
private static final String GCUBE_DEVNEXT_NEXTNEXT_VARNAME = "GCUBE_DEVNEXT_NEXTNEXT";
public static final String GCUBE_DEVNEXT_NEXTNEXT;
public static final String GCUBE_DEVSEC_VARNAME = "GCUBE_DEVSEC";
public static final String GCUBE_DEVSEC;
public static final String GCUBE_DEVSEC_DEVVRE_VARNAME = "GCUBE_DEVSEC_DEVVRE";
public static final String GCUBE_DEVSEC_DEVVRE;
public static final String DEFAULT_TEST_SCOPE;
public static final String ALTERNATIVE_TEST_SCOPE;
static {
Properties properties = new Properties();
InputStream input = ScopedTest.class.getClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
try {
// load the properties file
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME);
GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME);
GCUBE_DEVSEC = properties.getProperty(GCUBE_DEVSEC_VARNAME);
GCUBE_DEVSEC_DEVVRE = properties.getProperty(GCUBE_DEVSEC_DEVVRE_VARNAME);
DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT;
ALTERNATIVE_TEST_SCOPE = GCUBE_DEVSEC;
}
public static String getCurrentScope(String token) throws ObjectNotFound, Exception{
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
String context = authorizationEntry.getContext();
logger.info("Context of token {} is {}", token, context);
return context;
}
public static void setContext(String token) throws ObjectNotFound, Exception{
SecurityTokenProvider.instance.set(token);
ScopeProvider.instance.set(getCurrentScope(token));
}
@BeforeClass
public static void beforeClass() throws Exception{
setContext(DEFAULT_TEST_SCOPE);
}
@AfterClass
public static void afterClass() throws Exception{
SecurityTokenProvider.instance.reset();
ScopeProvider.instance.reset();
}
}

View File

@ -1,49 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.facet;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.model.entity.facet.AccessPointFacet;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.resources.impl.EntityManagementImpl;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class FacetCreationTest {
private static Logger logger = LoggerFactory
.getLogger(FacetCreationTest.class);
protected EntityManagementImpl entityManagementImpl;
public FacetCreationTest() {
entityManagementImpl = new EntityManagementImpl();
}
@Test
public void createAccessPointFacet() throws URISyntaxException, ResourceRegistryException, IOException{
ScopeProvider.instance.set("/gcube/devNext");
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEndpoint(new URI("http://localhost"));
accessPointFacet.setEntryName("port1");
String json = entityManagementImpl.createFacet(AccessPointFacet.NAME, Entities.marshal(accessPointFacet));
logger.debug("Created : {}", json);
accessPointFacet = Entities.unmarshal(AccessPointFacet.class, json);
logger.debug("Unmarshalled {} {}", AccessPointFacet.NAME, accessPointFacet);
}
}

View File

@ -3,12 +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.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextCreationException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
@ -17,9 +16,6 @@ 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)
*
@ -31,17 +27,6 @@ public class ContextManagementImplTest {
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();
}
@ -51,7 +36,7 @@ public class ContextManagementImplTest {
public static final String CTX_NAME_C = "C";
protected void invalidCreation(UUID parentUUID, String name)
throws InternalException {
throws ResourceRegistryException {
try {
contextManagementImpl.create(parentUUID, name);
throw new RuntimeException("The context " + name + " with parent "
@ -115,9 +100,7 @@ public class ContextManagementImplTest {
}
@Test
public void simpleTest() throws ContextNotFoundException, ContextException,
InternalException, JsonParseException, JsonMappingException,
IOException {
public void simpleTest() throws Exception {
String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A);
Context createdContexA1 = Entities.unmarshal(Context.class,
contextJsonA1);
@ -195,28 +178,24 @@ public class ContextManagementImplTest {
logger.debug("The DB should be now clean");
}
@Test
public void createContext() throws ContextNotFoundException,
ContextException, InternalException, JsonParseException,
JsonMappingException, IOException {
public void createContext() throws Exception {
String name = "test";
String testJson = contextManagementImpl.create(null, name);
Context testContext = Entities.unmarshal(Context.class, testJson);
Assert.assertTrue(testContext.getName().compareTo(name)==0);
Assert.assertTrue(testContext.getName().compareTo(name) == 0);
UUID testUUID = testContext.getHeader().getUUID();
logger.trace("/test : {}", testUUID);
boolean deleted = contextManagementImpl.delete(testUUID);
Assert.assertTrue(deleted);
logger.debug("The DB should be now clean");
}
@Test
public void createDevContext() throws ContextNotFoundException,
ContextException, InternalException, JsonParseException,
JsonMappingException, IOException {
// @Test
public void createDevContext() throws Exception {
String gcubeJson = contextManagementImpl.create(null, "gcube");
Context gcubeContext = Entities.unmarshal(Context.class, gcubeJson);
UUID gcube = gcubeContext.getHeader().getUUID();
@ -239,7 +218,8 @@ public class ContextManagementImplTest {
logger.trace("/gcube/devNext : {}", devNextJson);
String NextNextJson = contextManagementImpl.create(devNext, "NextNext");
Context NextNextContex = Entities.unmarshal(Context.class, NextNextJson);
Context NextNextContex = Entities
.unmarshal(Context.class, NextNextJson);
@SuppressWarnings("unused")
UUID NextNext = NextNextContex.getHeader().getUUID();
logger.trace("/gcube/devNext/NextNext : {}", NextNextJson);
@ -252,30 +232,22 @@ public class ContextManagementImplTest {
* contextManagementImpl.delete(gcube);
*/
//logger.debug("The DB should be now clean");
// logger.debug("The DB should be now clean");
}
//@Test
public void removeContext() throws ContextNotFoundException,
ContextException, InternalException {
// @Test
public void removeContext() throws Exception {
/*
contextManagementImpl.delete(UUID
.fromString(""));
contextManagementImpl.delete(UUID
.fromString(""));
contextManagementImpl.delete(UUID
.fromString(""));
contextManagementImpl.delete(UUID
.fromString(""));
contextManagementImpl.delete(UUID
.fromString(""));
*/
* contextManagementImpl.delete(UUID .fromString(""));
* contextManagementImpl.delete(UUID .fromString(""));
* contextManagementImpl.delete(UUID .fromString(""));
* contextManagementImpl.delete(UUID .fromString(""));
* contextManagementImpl.delete(UUID .fromString(""));
*/
}
@Test
public void readTest() throws ContextNotFoundException, ContextException,
InternalException, JsonParseException, JsonMappingException,
IOException {
public void readTest() throws Exception {
String name = "LLL";
String contextJsonA1 = contextManagementImpl.create(null, name);
Context createdContexA1 = Entities.unmarshal(Context.class,
@ -296,9 +268,7 @@ public class ContextManagementImplTest {
}
@Test
public void completeTest() throws ContextNotFoundException,
ContextException, InternalException, JsonParseException,
JsonMappingException, IOException {
public void completeTest() throws Exception {
String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A);
Context createdContexA1 = Entities.unmarshal(Context.class,
contextJsonA1);
@ -458,9 +428,7 @@ public class ContextManagementImplTest {
}
@Test
public void moveToRootTest() throws ContextNotFoundException,
ContextException, InternalException, JsonParseException,
JsonMappingException, IOException {
public void moveToRootTest() throws Exception {
String contextJsonA1 = contextManagementImpl.create(null, CTX_NAME_A);
Context createdContexA1 = Entities.unmarshal(Context.class,
contextJsonA1);

View File

@ -0,0 +1,409 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.resources.impl;
import java.net.URI;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.gcube.informationsystem.impl.embedded.RelationPropertyImpl;
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.EventFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.LicenseFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.NetworkingFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.ServiceStateFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl;
import org.gcube.informationsystem.impl.entity.resource.EServiceImpl;
import org.gcube.informationsystem.impl.entity.resource.HostingNodeImpl;
import org.gcube.informationsystem.impl.relation.IsIdentifiedByImpl;
import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.impl.utils.Utility;
import org.gcube.informationsystem.model.embedded.RelationProperty;
import org.gcube.informationsystem.model.embedded.RelationProperty.ReferentialIntegrity;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.entity.facet.AccessPointFacet;
import org.gcube.informationsystem.model.entity.facet.CPUFacet;
import org.gcube.informationsystem.model.entity.facet.EventFacet;
import org.gcube.informationsystem.model.entity.facet.LicenseFacet;
import org.gcube.informationsystem.model.entity.facet.NetworkingFacet;
import org.gcube.informationsystem.model.entity.facet.ServiceStateFacet;
import org.gcube.informationsystem.model.entity.facet.SoftwareFacet;
import org.gcube.informationsystem.model.entity.resource.EService;
import org.gcube.informationsystem.model.entity.resource.HostingNode;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.model.relation.IsIdentifiedBy;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.model.relation.isrelatedto.Hosts;
import org.gcube.informationsystem.resourceregistry.ScopedTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.relation.ConsistsOfManagement;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class ERManagementTest extends ScopedTest {
private static Logger logger = LoggerFactory
.getLogger(ERManagementTest.class);
@Test
public void testCreateEService() throws Exception {
EService eService = new EServiceImpl();
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
softwareFacet.setGroup("InformationSystem");
softwareFacet.setName("resource-registry");
softwareFacet.setVersion("1.1.0");
IsIdentifiedBy<EService, Facet> isIdentifiedBy = new IsIdentifiedByImpl<EService, Facet>(
eService, softwareFacet, null);
eService.addFacet(isIdentifiedBy);
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEndpoint(new URI("http://localhost"));
accessPointFacet.setEntryName("port1");
eService.addFacet(accessPointFacet);
EventFacet eventFacet = new EventFacetImpl();
eventFacet.setDate(Calendar.getInstance().getTime());
eventFacet.setValue("Created");
eService.addFacet(eventFacet);
ServiceStateFacet serviceStateFacet = new ServiceStateFacetImpl();
serviceStateFacet.setValue("ready");
eService.addFacet(serviceStateFacet);
LicenseFacet licenseFacet = new LicenseFacetImpl();
licenseFacet.setName("EUPL");
licenseFacet
.setTextURL(new URL(
"https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11"));
eService.addFacet(licenseFacet);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME);
resourceManagement.setJSON(Entities.marshal(eService));
String json = resourceManagement.create();
logger.debug("Created : {}", json);
eService = Entities.unmarshal(EService.class, json);
logger.debug("Unmarshalled {} {}", EService.NAME, eService);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(eService.getHeader().getUUID());
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
}
//@Test
public void testDeleteResource() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID
.fromString("64635295-7ced-4931-a55f-40fc8199b280"));
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
}
@Test
public void testCreateReadDeleteFacet() throws Exception {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
FacetManagement facetManagement = new FacetManagement();
facetManagement.setEntityType(CPUFacet.NAME);
facetManagement.setJSON(Entities.marshal(cpuFacet));
String cpuFacetJson = facetManagement.create();
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();
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
String readJson = facetManagement.read();
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);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
facetManagement.setJSON(Entities.marshal(readCpuFacet));
String updatedJson = facetManagement.update();
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);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
String readUpdatedJson = facetManagement.read();
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);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted);
}
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
Map<String, Resource> map = new HashMap<>();
EService eService = new EServiceImpl();
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
softwareFacet.setGroup("InformationSystem");
softwareFacet.setName("resource-registry");
softwareFacet.setVersion("1.1.0");
IsIdentifiedBy<Resource, Facet> isIdentifiedBy = new IsIdentifiedByImpl<Resource, Facet>(
eService, softwareFacet, null);
eService.addFacet(isIdentifiedBy);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME);
resourceManagement.setJSON(Entities.marshal(eService));
String json = resourceManagement.create();
logger.debug("Created : {}", json);
eService = Entities.unmarshal(EService.class, json);
logger.debug("Unmarshalled {} {}", EService.NAME, eService);
map.put(EService.NAME, eService);
NetworkingFacet networkingFacet = new NetworkingFacetImpl();
networkingFacet.setIPAddress("146.48.87.183");
networkingFacet.setHostName("pc-frosini.isti.cnr.it");
networkingFacet.setDomainName("isti.cnr.it");
networkingFacet.setMask("255.255.248.0");
networkingFacet.setBroadcastAddress("146.48.87.255");
FacetManagement facetManagement = new FacetManagement();
facetManagement.setJSON(Entities.marshal(networkingFacet));
facetManagement.setEntityType(NetworkingFacet.NAME);
json = facetManagement.create();
logger.debug("Created : {}", json);
networkingFacet = Entities.unmarshal(NetworkingFacet.class, json);
logger.debug("Unmarshalled {} {}", NetworkingFacet.NAME,
networkingFacet);
HostingNode hostingNode = new HostingNodeImpl();
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
hostingNode.addFacet(cpuFacet);
isIdentifiedBy = new IsIdentifiedByImpl<Resource, Facet>(hostingNode,
networkingFacet, null);
hostingNode.attachFacet(isIdentifiedBy);
RelationProperty relationProperty = new RelationPropertyImpl();
relationProperty.setReferentialIntegrity(ReferentialIntegrity.onDeleteCascade);
Hosts<HostingNode, EService> hosts = new HostsImpl<HostingNode, EService>(
hostingNode, eService, relationProperty);
hostingNode.attachResource(hosts);
resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME);
resourceManagement.setJSON(Entities.marshal(hostingNode));
json = resourceManagement.create();
logger.debug("Created : {}", json);
hostingNode = Entities.unmarshal(HostingNode.class, json);
logger.debug("Unmarshalled {} {}", HostingNode.NAME, hostingNode);
map.put(HostingNode.NAME, hostingNode);
return map;
}
@Test
public void testCreateHostingNodeAndEService() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(map.get(EService.NAME).getHeader().getUUID());
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(map.get(HostingNode.NAME).getHeader().getUUID());
deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
}
@Test
public void testCreateHostingNodeAndEServiceWithSharedFacet() throws Exception {
ScopedTest.setContext(ScopedTest.GCUBE_DEVNEXT);
Map<String, Resource> map = createHostingNodeAndEService();
EService eService = (EService) map.get(EService.NAME);
HostingNode hostingNode = (HostingNode) map.get(HostingNode.NAME);
Facet shared = hostingNode.getConsistsOf().get(0).getTarget();
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setRelationType(ConsistsOf.NAME);
consistsOfManagement.setJSON("{}");
UUID eServiceUUID = eService.getHeader().getUUID();
UUID sharedFacetUUID = shared.getHeader().getUUID();
String json = consistsOfManagement.create(eServiceUUID, sharedFacetUUID);
logger.debug("Created : {}", json);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(eService.getHeader().getUUID());
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(hostingNode.getHeader().getUUID());
deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(sharedFacetUUID);
try {
facetManagement.read();
throw new Exception(String.format("Shared Facet %s was not deleted", shared));
}catch(ResourceRegistryException e){
logger.debug("Shared Facet was not foud as expected");
}
}
@Test
public void testCreateResourceAndFacet() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME);
resourceManagement.setJSON("{}");
String json = resourceManagement.create();
UUID resourceUUID = Utility.getUUIDFromJSONString(json);
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
FacetManagement facetManagement = new FacetManagement();
facetManagement.setJSON(Entities.marshal(cpuFacet));
facetManagement.setEntityType(CPUFacet.NAME);
json = facetManagement.create();
logger.debug("Created : {}", json);
UUID facetUUID = Utility.getUUIDFromJSONString(json);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setRelationType(ConsistsOf.NAME);
consistsOfManagement.setJSON("{}");
json = consistsOfManagement.create(resourceUUID, facetUUID);
logger.debug("Facet attached : {}", json);
UUID consistOfUUID = Utility.getUUIDFromJSONString(json);
consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setUUID(consistOfUUID);
boolean detached = consistsOfManagement.delete();
if (detached) {
logger.trace("{} {} with uuid {} removed successfully",
ConsistsOf.NAME, Relation.NAME, consistOfUUID);
} else {
String error = String.format("Unable to remove %s %s with uuid %s",
ConsistsOf.NAME, Relation.NAME, consistOfUUID);
logger.error(error);
throw new Exception(error);
}
facetManagement = new FacetManagement();
facetManagement.setUUID(facetUUID);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(resourceUUID);
resourceManagement.delete();
}
}

View File

@ -8,6 +8,7 @@ import java.net.URL;
import java.util.Calendar;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl;
@ -24,6 +25,8 @@ import org.gcube.informationsystem.impl.relation.consistsof.HasPersistentMemoryI
import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl;
import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.facet.AccessPointFacet;
import org.gcube.informationsystem.model.entity.facet.CPUFacet;
@ -40,9 +43,13 @@ import org.gcube.informationsystem.model.relation.IsIdentifiedBy;
import org.gcube.informationsystem.model.relation.consistsof.HasPersistentMemory;
import org.gcube.informationsystem.model.relation.consistsof.HasVolatileMemory;
import org.gcube.informationsystem.model.relation.isrelatedto.Hosts;
import org.gcube.informationsystem.resourceregistry.ScopedTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.ermanagement.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.resources.old.EntityManagementImplTest;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -52,21 +59,102 @@ import org.slf4j.LoggerFactory;
* @author Luca Frosini (ISTI - CNR)
*
*/
public class MultiContextTest {
public class MultiContextTest extends ScopedTest {
private static Logger logger = LoggerFactory
.getLogger(EntityManagementImplTest.class);
protected EntityManagementImpl entityManagementImpl;
@Test
public void testDifferentScopes() throws Exception {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
public MultiContextTest() {
entityManagementImpl = new EntityManagementImpl();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setJSON(Entities.marshal(cpuFacet));
facetManagement.setEntityType(CPUFacet.NAME);
String json = facetManagement.create();
logger.debug("Created : {}", json);
JSONObject jsonObject = new JSONObject(json);
JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY);
UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY));
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
String readJson = facetManagement.read();
logger.debug("Read : {}", readJson);
/* ------------------------------------------------------------------ */
logger.debug("Switching to another scope");
ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE);
try {
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
readJson = facetManagement.read();
logger.debug("You should not be able to read Facet with UUID {}",
uuid);
throw new Exception(
"You should not be able to read Facet with UUID " + uuid);
} catch (ResourceRegistryException e) {
logger.debug("Good the facet created in /gcube/devsec is not visible in /gcube/devNext");
}
cpuFacet.setAdditionalProperty("My", "Test");
try {
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
facetManagement.setJSON(Entities.marshal(cpuFacet));
readJson = facetManagement.update();
logger.debug("You should not be able to update Facet with UUID {}",
uuid);
throw new Exception(
"You should not be able to read Facet with UUID " + uuid);
} catch (ResourceRegistryException e) {
logger.debug("Good the Facet created in /gcube/devsec cannot be updated in /gcube/devNext");
}
try {
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
facetManagement.delete();
logger.debug("You should not be able to delete Facet with UUID {}",
uuid);
throw new Exception(
"You should not be able to delete Facet with UUID " + uuid);
} catch (ResourceRegistryException e) {
logger.debug("Good the Facet created in /gcube/devsec cannot be deleted in /gcube/devNext");
}
/* ------------------------------------------------------------------ */
logger.debug("Setting back default scope");
ScopedTest.setContext(ScopedTest.DEFAULT_TEST_SCOPE);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
facetManagement.setJSON(Entities.marshal(cpuFacet));
readJson = facetManagement.update();
logger.debug("Updated : {}", readJson);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
readJson = facetManagement.read();
logger.debug("Read Updated : {}", readJson);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted);
}
@Test
public void testCreateEServiceHostingNode() throws Exception {
ScopeProvider.instance.set("/gcube/devNext");
EService eService = new EServiceImpl();
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
@ -97,14 +185,17 @@ public class MultiContextTest {
.setTextURL(new URL(
"https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11"));
eService.addFacet(licenseFacet);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(EService.NAME);
resourceManagement.setJSON(Entities.marshal(eService));
String json = entityManagementImpl.createResource(EService.NAME,
Entities.marshal(eService));
String json = resourceManagement.create();
logger.debug("Created : {}", json);
eService = Entities.unmarshal(EService.class, json);
logger.debug("Unmarshalled {} {}", EService.NAME, eService);
/* ----- */
HostingNode hostingNode = new HostingNodeImpl();
@ -147,50 +238,76 @@ public class MultiContextTest {
hostingNode, eService, null);
hostingNode.attachResource(hosts);
String hnJson = entityManagementImpl.createResource(HostingNode.NAME,
Entities.marshal(hostingNode));
resourceManagement = new ResourceManagement();
resourceManagement.setEntityType(HostingNode.NAME);
resourceManagement.setJSON(Entities.marshal(hostingNode));
String hnJson = resourceManagement.create();
logger.debug("Created : {}", hnJson);
hostingNode = Entities.unmarshal(HostingNode.class, hnJson);
logger.debug("Unmarshalled {} {}", HostingNode.NAME, hostingNode);
ScopeProvider.instance.set("/gcube/devNext/NextNext");
UUID uuid = hostingNode.getHeader().getUUID();
boolean addedToContext = entityManagementImpl
.addResourceToContext(uuid);
/* ------------------------------------------------------------------ */
logger.debug("Switching to another scope");
ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
boolean addedToContext = resourceManagement.addToContext();
Assert.assertTrue(addedToContext);
String hnString = entityManagementImpl.readResource(uuid);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
String hnString = resourceManagement.read();
HostingNode readHN = Entities.unmarshal(HostingNode.class, hnString);
Assert.assertTrue(readHN.getHeader().getUUID().compareTo(uuid) == 0);
UUID eServiceUUID = eService.getHeader().getUUID();
try {
entityManagementImpl.readResource(eServiceUUID);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(eServiceUUID);
resourceManagement.read();
} catch (ResourceNotFoundException e) {
logger.debug("Resource with {} Not Found as Expected",
uuid.toString());
eServiceUUID);
}
try {
entityManagementImpl.deleteResource(uuid);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(eServiceUUID);
resourceManagement.delete();
} catch (ResourceNotFoundException e) {
logger.debug("Resource with {} Not Found as Expected",
uuid.toString());
eServiceUUID);
}
try {
entityManagementImpl.deleteResource(eService.getHeader().getUUID());
} catch (ResourceNotFoundException e) {
logger.debug("Resource with {} Not Found as Expected",
uuid.toString());
}
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
/* ------------------------------------------------------------------ */
logger.debug("Setting back default scope");
ScopedTest.setContext(ScopedTest.DEFAULT_TEST_SCOPE);
resourceManagement = new ResourceManagement();
resourceManagement.setUUID(eServiceUUID);
deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
}
// @Test
public void addTest() throws ResourceNotFoundException,
ContextNotFoundException, ResourceRegistryException {
ScopeProvider.instance.set("/gcube/devNext/NextNext");
entityManagementImpl.addResourceToContext(UUID.fromString(""));
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(""));
resourceManagement.addToContext();
}
}

View File

@ -3,7 +3,7 @@
*/
package org.gcube.informationsystem.resourceregistry.resources.impl;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.resourceregistry.ScopedTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.InvalidQueryException;
import org.junit.Test;
import org.slf4j.Logger;
@ -13,13 +13,12 @@ import org.slf4j.LoggerFactory;
* @author Luca Frosini (ISTI - CNR)
*
*/
public class QueryImplTest {
public class QueryImplTest extends ScopedTest {
private static Logger logger = LoggerFactory.getLogger(QueryImplTest.class);
@Test
public void testQuery() throws InvalidQueryException{
ScopeProvider.instance.set("/gcube/devNext");
QueryImpl queryImpl = new QueryImpl();
String query = "select * from CPUFacet";

View File

@ -1,33 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.resources.impl;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.Before;
import org.junit.Test;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class ReferentialIntegrityTest {
protected EntityManagementImpl entityManagementImpl;
@Before
public void before(){
ScopeProvider.instance.set("/gcube/devNext");
}
public ReferentialIntegrityTest() {
entityManagementImpl = new EntityManagementImpl();
}
@Test
public void test() throws Exception{
}
}

View File

@ -26,7 +26,7 @@ public class SchemaManagementImplTest {
Class<?> clz = Header.class;
String json = TypeBinder.serializeType(clz);
logger.trace(json);
new SchemaManagementImpl().registerEmbeddedTypeSchema(json);
//new SchemaManagementImpl().registerEmbeddedTypeSchema(json);
}
@Test

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.resources.impl;
package org.gcube.informationsystem.resourceregistry.resources.old;
import java.io.IOException;
import java.util.ArrayList;
@ -41,6 +41,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.resources.impl.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.resources.utils.ContextUtility;
import org.gcube.informationsystem.resourceregistry.resources.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.resources.utils.Utility;
@ -1175,7 +1176,7 @@ public class EntityManagementImpl implements EntityManagement {
}
private static String marshallResource(OrientGraph orientGraph,
Vertex vertex) throws JSONException {
Vertex vertex) throws JSONException, ResourceRegistryException {
JSONObject jsonObject = Utility.toJsonObject((OrientVertex) vertex,
true);

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.resources.impl;
package org.gcube.informationsystem.resourceregistry.resources.old;
import java.io.StringWriter;
import java.net.URI;