Refs #10435: Add support for hierarchical roles to support child context overview

Task-Url: https://support.d4science.org/issues/10435

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry@158968 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2017-11-30 17:06:08 +00:00
parent d1fe6daa64
commit 1fcdccd7af
41 changed files with 2526 additions and 2442 deletions

View File

@ -10,12 +10,12 @@ import org.glassfish.jersey.server.ResourceConfig;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@ApplicationPath("/") @ApplicationPath("/")
public class ResourceInitializer extends ResourceConfig { public class ResourceInitializer extends ResourceConfig {
public static final String APPLICATION_JSON_CHARSET_UTF_8 = MediaType.APPLICATION_JSON + ";charset=UTF-8"; public static final String APPLICATION_JSON_CHARSET_UTF_8 = MediaType.APPLICATION_JSON + ";charset=UTF-8";
public ResourceInitializer(){ public ResourceInitializer() {
packages(Access.class.getPackage().toString()); packages(Access.class.getPackage().toString());
} }
} }

View File

@ -1,65 +0,0 @@
package org.gcube.informationsystem.resourceregistry.context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class AdminSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public AdminSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
}
@Override
public void create() {
throw new RuntimeException("Cannot use this method for Admin Context");
}
@Override
public void create(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
ORole admin = oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
ORole writerRole = oSecurity.createRole(writerRoleName, admin, ALLOW_MODES.DENY_ALL_BUT);
writerRole.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL);
writerRole.save();
logger.trace("{} created", writerRole);
ORole readerRole = oSecurity.createRole(readerRoleName, admin, ALLOW_MODES.DENY_ALL_BUT);
readerRole.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_READ);
readerRole.save();
logger.trace("{} created", readerRole);
OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
writerUser.save();
logger.trace("{} created", writerUser);
OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
readerUser.save();
logger.trace("{} created", readerUser);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
}

View File

@ -18,6 +18,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
@ -33,8 +34,11 @@ import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ContextManagement extends EntityManagement<Context> { public class ContextManagement extends EntityManagement<Context> {
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class); private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
protected String name; protected String name;
@ -57,12 +61,12 @@ public class ContextManagement extends EntityManagement<Context> {
} }
public String getName() { public String getName() {
if(name==null) { if(name == null) {
if(element==null) { if(element == null) {
if(jsonNode!=null) { if(jsonNode != null) {
name = jsonNode.get(Context.NAME_PROPERTY).asText(); name = jsonNode.get(Context.NAME_PROPERTY).asText();
} }
}else { } else {
name = element.getProperty(Context.NAME_PROPERTY); name = element.getProperty(Context.NAME_PROPERTY);
} }
} }
@ -71,7 +75,8 @@ public class ContextManagement extends EntityManagement<Context> {
protected SecurityContext getWorkingContext() throws ResourceRegistryException { protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) { if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID); workingContext = ContextUtility.getInstace()
.getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
} }
return workingContext; return workingContext;
} }
@ -91,109 +96,99 @@ public class ContextManagement extends EntityManagement<Context> {
return new ContextAlreadyPresentException(message); return new ContextAlreadyPresentException(message);
} }
protected void checkContext(ContextManagement parentContext) throws ContextNotFoundException, protected void checkContext(ContextManagement parentContext)
ContextAlreadyPresentException, ResourceRegistryException { throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException {
if (parentContext != null) { if(parentContext != null) {
String parentId = parentContext.getElement().getId().toString(); String parentId = parentContext.getElement().getId().toString();
// TODO Rewrite using Gremlin // TODO Rewrite using Gremlin
String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME + ") FROM " + parentId
+ ") FROM " + parentId + " MAXDEPTH 1) WHERE " + " MAXDEPTH 1) WHERE " + Context.NAME_PROPERTY + "=\"" + getName() + "\" AND "
+ Context.NAME_PROPERTY + "=\"" + getName() + "\" AND " + Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY + "<>\"" + parentContext.uuid + "\"";
+ Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ "<>\"" + parentContext.uuid + "\"";
logger.trace(select); logger.trace(select);
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.append("A context with name ("); message.append("A context with name (");
message.append(getName()); message.append(getName());
message.append(") has been already created as child of "); message.append(") has been already created as child of ");
message.append(parentContext.serializeSelfOnly().toString()); message.append(parentContext.serializeSelfOnly().toString());
logger.trace("Checking if {} -> {}", message, select); logger.trace("Checking if {} -> {}", message, select);
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>( OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
select); Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery).execute();
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery)
.execute(); if(vertexes != null && vertexes.iterator().hasNext()) {
if (vertexes != null && vertexes.iterator().hasNext()) {
throw new ContextAlreadyPresentException(message.toString()); throw new ContextAlreadyPresentException(message.toString());
} }
} else { } else {
// TODO Rewrite using Gremlin // TODO Rewrite using Gremlin
String select = "SELECT FROM " String select = "SELECT FROM " + org.gcube.informationsystem.model.entity.Context.NAME + " WHERE "
+ org.gcube.informationsystem.model.entity.Context.NAME + Context.NAME_PROPERTY + " = \"" + getName() + "\"" + " AND in(\"" + IsParentOf.NAME
+ " WHERE " + Context.NAME_PROPERTY + " = \"" + getName() + "\").size() = 0";
+ "\"" + " AND in(\"" + IsParentOf.NAME + "\").size() = 0";
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>( Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery).execute();
select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery) if(vertexes != null && vertexes.iterator().hasNext()) {
.execute();
if (vertexes != null && vertexes.iterator().hasNext()) {
throw new ContextAlreadyPresentException( throw new ContextAlreadyPresentException(
"A root context with the same name (" + this.getName() "A root context with the same name (" + this.getName() + ") already exist");
+ ") already exist");
} }
} }
} }
@Override @Override
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString(); return serializeAsJson().toString();
} }
@Override @Override
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
JSONObject context = serializeSelfOnly(); JSONObject context = serializeSelfOnly();
int count=0; int count = 0;
Iterable<Edge> parents = getElement().getEdges(Direction.IN); Iterable<Edge> parents = getElement().getEdges(Direction.IN);
for(Edge edge : parents){ for(Edge edge : parents) {
if(++count>1) { if(++count > 1) {
throw new ContextException("A " + Context.NAME + " can not have more than one parent"); throw new ContextException("A " + Context.NAME + " can not have more than one parent");
} }
try { try {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
JSONObject isParentOf = isParentOfManagement.serializeAsJson(true,false); JSONObject isParentOf = isParentOfManagement.serializeAsJson(true, false);
context.putOpt(Context.PARENT_PROPERTY, isParentOf); context.putOpt(Context.PARENT_PROPERTY, isParentOf);
} catch (JSONException e) { } catch(JSONException e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ContextException(""); throw new ContextException("");
} }
} }
Iterable<Edge> childrenEdges = getElement().getEdges(Direction.OUT); Iterable<Edge> childrenEdges = getElement().getEdges(Direction.OUT);
for (Edge edge : childrenEdges) { for(Edge edge : childrenEdges) {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
try { try {
JSONObject isParentOf = isParentOfManagement.serializeAsJson(); JSONObject isParentOf = isParentOfManagement.serializeAsJson();
context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY); context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY);
}catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e; throw e;
}catch (Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
return context; return context;
} }
@Override @Override
protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null; SecurityContext securityContext = null;
@ -201,14 +196,14 @@ public class ContextManagement extends EntityManagement<Context> {
try { try {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
if (isParentOfJsonNode!=null && !(isParentOfJsonNode instanceof NullNode)) { if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY); JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
ContextManagement parentContext = new ContextManagement(orientGraph); ContextManagement parentContext = new ContextManagement(orientGraph);
parentContext.setJSON(parentJsonNode); parentContext.setJSON(parentJsonNode);
checkContext(parentContext); checkContext(parentContext);
if(uuid==null){ if(uuid == null) {
uuid = UUID.randomUUID(); uuid = UUID.randomUUID();
} }
@ -221,7 +216,7 @@ public class ContextManagement extends EntityManagement<Context> {
isParentOfManagement.internalCreate(); isParentOfManagement.internalCreate();
}else { } else {
checkContext(null); checkContext(null);
createVertex(); createVertex();
} }
@ -230,15 +225,15 @@ public class ContextManagement extends EntityManagement<Context> {
securityContext.create(orientGraph); securityContext.create(orientGraph);
return getElement(); return getElement();
}catch (Exception e) { } catch(Exception e) {
orientGraph.rollback(); orientGraph.rollback();
if(securityContext!=null) { if(securityContext != null) {
securityContext.delete(orientGraph); securityContext.delete(orientGraph);
} }
throw e; throw e;
} }
} }
@Override @Override
protected Vertex reallyUpdate() throws ERNotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws ERNotFoundException, ResourceRegistryException {
@ -250,8 +245,8 @@ public class ContextManagement extends EntityManagement<Context> {
Iterable<Vertex> iterable = getElement().getVertices(Direction.IN, IsParentOf.NAME); Iterable<Vertex> iterable = getElement().getVertices(Direction.IN, IsParentOf.NAME);
for(Vertex p : iterable) { for(Vertex p : iterable) {
if(found){ if(found) {
String message = String.format("{} has more than one parent. {}", Context.NAME, String message = String.format("{} has more than one parent. {}", Context.NAME,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(message.toString()); throw new ResourceRegistryException(message.toString());
} }
@ -259,9 +254,8 @@ public class ContextManagement extends EntityManagement<Context> {
found = true; found = true;
} }
ContextManagement actualParentContextManagement = null; ContextManagement actualParentContextManagement = null;
if(parent!=null) { if(parent != null) {
actualParentContextManagement = new ContextManagement(orientGraph); actualParentContextManagement = new ContextManagement(orientGraph);
actualParentContextManagement.setElement(parent); actualParentContextManagement.setElement(parent);
} }
@ -270,27 +264,26 @@ public class ContextManagement extends EntityManagement<Context> {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
JsonNode parentContextJsonNode = null; JsonNode parentContextJsonNode = null;
if (isParentOfJsonNode!=null && !(isParentOfJsonNode instanceof NullNode)) { if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
parentContextJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY); parentContextJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
} }
if(parentContextJsonNode != null && !(parentContextJsonNode instanceof NullNode)) {
if(parentContextJsonNode!=null && !(parentContextJsonNode instanceof NullNode)) {
UUID parentUUID = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode); UUID parentUUID = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode);
if(actualParentContextManagement!=null){ if(actualParentContextManagement != null) {
if(parentUUID.compareTo(actualParentContextManagement.uuid)!=0) { if(parentUUID.compareTo(actualParentContextManagement.uuid) != 0) {
parentChanged = true; parentChanged = true;
} }
}else { } else {
parentChanged = true; parentChanged = true;
} }
if(parentChanged){ if(parentChanged) {
newParentContextManagement = new ContextManagement(orientGraph); newParentContextManagement = new ContextManagement(orientGraph);
newParentContextManagement.setJSON(parentContextJsonNode); newParentContextManagement.setJSON(parentContextJsonNode);
} }
}else{ } else {
if(actualParentContextManagement!=null) { if(actualParentContextManagement != null) {
parentChanged = true; parentChanged = true;
newParentContextManagement = null; newParentContextManagement = null;
} }
@ -299,7 +292,7 @@ public class ContextManagement extends EntityManagement<Context> {
String oldName = getElement().getProperty(Context.NAME_PROPERTY); String oldName = getElement().getProperty(Context.NAME_PROPERTY);
String newName = jsonNode.get(Context.NAME_PROPERTY).asText(); String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
if(oldName.compareTo(newName)!=0){ if(oldName.compareTo(newName) != 0) {
nameChanged = true; nameChanged = true;
name = newName; name = newName;
} }
@ -312,36 +305,36 @@ public class ContextManagement extends EntityManagement<Context> {
move(newParentContextManagement, false); move(newParentContextManagement, false);
} }
element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys); element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys,
ignoreStartWithKeys);
ContextUtility.getInstace().removeFromCache(uuid); ContextUtility.getInstace().removeFromCache(uuid);
return element; return element;
} }
private void move(ContextManagement newParentContextManagement, boolean check)
private void move(ContextManagement newParentContextManagement, boolean check)
throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException { throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException {
if(check){ if(check) {
checkContext(newParentContextManagement); checkContext(newParentContextManagement);
} }
// Removing the old parent relationship if any // Removing the old parent relationship if any
Iterable<Edge> edges = getElement().getEdges(Direction.IN, IsParentOf.NAME); Iterable<Edge> edges = getElement().getEdges(Direction.IN, IsParentOf.NAME);
if (edges != null && edges.iterator().hasNext()) { if(edges != null && edges.iterator().hasNext()) {
Iterator<Edge> edgeIterator = edges.iterator(); Iterator<Edge> edgeIterator = edges.iterator();
Edge edge = edgeIterator.next(); Edge edge = edgeIterator.next();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(); IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
isParentOfManagement.setElement(edge); isParentOfManagement.setElement(edge);
isParentOfManagement.internalDelete(); isParentOfManagement.internalDelete();
if (edgeIterator.hasNext()) { if(edgeIterator.hasNext()) {
throw new ContextException("Seems that the Context has more than one Parent. " throw new ContextException(
+ Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); "Seems that the Context has more than one Parent. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
if(newParentContextManagement!=null){ if(newParentContextManagement != null) {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY); JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph); IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
isParentOfManagement.setJSON(isParentOfJsonNode); isParentOfManagement.setJSON(isParentOfJsonNode);
@ -351,17 +344,17 @@ public class ContextManagement extends EntityManagement<Context> {
} }
} }
@Override @Override
protected boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException { protected boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException {
Iterable<Edge> iterable = getElement().getEdges(Direction.OUT); Iterable<Edge> iterable = getElement().getEdges(Direction.OUT);
Iterator<Edge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
while (iterator.hasNext()) { while(iterator.hasNext()) {
throw new ContextException("Cannot remove a " + Context.NAME + " having children"); throw new ContextException("Cannot remove a " + Context.NAME + " having children");
} }
element.remove(); element.remove();
ContextUtility contextUtility = ContextUtility.getInstace(); ContextUtility contextUtility = ContextUtility.getInstace();
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid); SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(orientGraph); securityContext.delete(orientGraph);
@ -376,18 +369,18 @@ public class ContextManagement extends EntityManagement<Context> {
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic); Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
for(Vertex vertex : iterable){ for(Vertex vertex : iterable) {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
contextManagement.setElement(vertex); contextManagement.setElement(vertex);
try { try {
JSONObject jsonObject = contextManagement.serializeAsJson(); JSONObject jsonObject = contextManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);
}catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
return jsonArray.toString(); return jsonArray.toString();
} }
} }

View File

@ -1,72 +0,0 @@
package org.gcube.informationsystem.resourceregistry.context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class ContextSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public ContextSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
@Override
public void create(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
ORole writer = oSecurity.getRole(DEFAULT_WRITER_ROLE);
ORole reader = oSecurity.getRole(DEFAULT_READER_ROLE);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
/*
String writerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, true);
String readerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, true);
String writerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, true);
String readerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, true);
*/
ORole writerRole = oSecurity.createRole(writerRoleName, writer, ALLOW_MODES.DENY_ALL_BUT);
writerRole.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL);
writerRole.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL);
writerRole.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL);
writerRole.save();
logger.trace("{} created", writerRole);
ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT);
readerRole.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ);
readerRole.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ);
readerRole.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ);
readerRole.save();
logger.trace("{} created", readerRole);
OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
writerUser.save();
logger.trace("{} created", writerUser);
OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
readerUser.save();
logger.trace("{} created", readerUser);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context; package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap; import java.util.HashMap;
@ -19,7 +16,9 @@ import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -31,145 +30,156 @@ import com.tinkerpop.blueprints.Vertex;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*
*/ */
public class ContextUtility { public class ContextUtility {
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class); private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
private Map<String, UUID> contextUUIDs; private Map<String,UUID> contextUUIDs;
private Map<UUID, SecurityContext> contexts; private Map<UUID,SecurityContext> contexts;
private static ContextUtility contextUtility; private static ContextUtility contextUtility;
public static ContextUtility getInstace() { public static ContextUtility getInstace() {
if (contextUtility == null) { if(contextUtility == null) {
contextUtility = new ContextUtility(); contextUtility = new ContextUtility();
} }
return contextUtility; return contextUtility;
} }
private ContextUtility() { private ContextUtility() {
contextUUIDs = new HashMap<>(); contextUUIDs = new HashMap<>();
contexts = new HashMap<>(); contexts = new HashMap<>();
} }
private static final InheritableThreadLocal<Boolean> hierarchicMode = new InheritableThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
public static InheritableThreadLocal<Boolean> getHierarchicMode() {
return hierarchicMode;
}
private static String getCurrentContextFullName() { private static String getCurrentContextFullName() {
String token = SecurityTokenProvider.instance.get(); String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null; AuthorizationEntry authorizationEntry = null;
try { try {
authorizationEntry = Constants.authorizationService().get(token); authorizationEntry = Constants.authorizationService().get(token);
} catch (Exception e) { } catch(Exception e) {
return ScopeProvider.instance.get(); return ScopeProvider.instance.get();
} }
return authorizationEntry.getContext(); return authorizationEntry.getContext();
} }
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException { public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
String fullName = getCurrentContextFullName(); String fullName = getCurrentContextFullName();
if (fullName == null) { if(fullName == null) {
throw new ContextException("Null Token and Scope. Please set your token first."); throw new ContextException("Null Token and Scope. Please set your token first.");
} }
return ContextUtility.getInstace().getSecurityContextByFullName(fullName); return ContextUtility.getInstace().getSecurityContextByFullName(fullName);
} }
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException { public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace(). AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace()
getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID); .getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
return adminSecurityContext; return adminSecurityContext;
} }
public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException { public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException {
for (String fullName : contextUUIDs.keySet()) { for(String fullName : contextUUIDs.keySet()) {
UUID uuidKey = contextUUIDs.get(fullName); UUID uuidKey = contextUUIDs.get(fullName);
if (uuidKey.compareTo(uuid) == 0) { if(uuidKey.compareTo(uuid) == 0) {
contextUUIDs.remove(fullName); contextUUIDs.remove(fullName);
contexts.remove(uuid); contexts.remove(uuid);
return; return;
} }
} }
} }
public synchronized void addSecurityContext(String fullname, SecurityContext securityContext) { public synchronized void addSecurityContext(String fullname, SecurityContext securityContext) {
contextUUIDs.put(fullname, securityContext.getUUID()); contextUUIDs.put(fullname, securityContext.getUUID());
contexts.put(securityContext.getUUID(), securityContext); contexts.put(securityContext.getUUID(), securityContext);
} }
private synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException { private synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException {
try { try {
SecurityContext securityContext = null; SecurityContext securityContext = null;
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName); logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
UUID uuid = contextUUIDs.get(fullName); UUID uuid = contextUUIDs.get(fullName);
if (uuid == null) { if(uuid == null) {
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(), logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
fullName); fullName);
Vertex contextVertex = getContextVertexByFullName(fullName); Vertex contextVertex = getContextVertexByFullName(fullName);
uuid = Utility.getUUID(contextVertex); uuid = Utility.getUUID(contextVertex);
securityContext = getSecurityContextByUUID(uuid, contextVertex); securityContext = getSecurityContextByUUID(uuid, contextVertex);
addSecurityContext(fullName, securityContext); addSecurityContext(fullName, securityContext);
} else { } else {
securityContext = contexts.get(uuid); securityContext = contexts.get(uuid);
} }
return securityContext; return securityContext;
} catch (ContextException e) { } catch(ContextException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new ContextException("Unable to restrive Context UUID from current Context", e); throw new ContextException("Unable to restrive Context UUID from current Context", e);
} }
} }
protected SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException { protected SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException {
return getSecurityContextByUUID(uuid, null); return getSecurityContextByUUID(uuid, null);
} }
private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException { private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
return Utility.getElementByUUID(getAdminSecurityContext().getGraph(PermissionMode.READER), Context.NAME, uuid, return Utility.getElementByUUID(getAdminSecurityContext().getGraph(PermissionMode.READER), Context.NAME, uuid,
Vertex.class); Vertex.class);
} }
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException { private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid); SecurityContext securityContext = contexts.get(uuid);
if (securityContext == null) { if(securityContext == null) {
securityContext = new SecurityContext(uuid); securityContext = new SecurityContext(uuid);
try { try {
if (contextVertex == null) { if(contextVertex == null) {
contextVertex = getContextVertexByUUID(uuid); contextVertex = getContextVertexByUUID(uuid);
} }
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next(); Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next();
if (parentVertex != null) { if(parentVertex != null) {
UUID parentUUID = Utility.getUUID(parentVertex); UUID parentUUID = Utility.getUUID(parentVertex);
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex)); securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
} }
} catch (NoSuchElementException e) { } catch(NoSuchElementException e) {
// No parent // No parent
} }
contexts.put(uuid, securityContext); contexts.put(uuid, securityContext);
} }
return securityContext; return securityContext;
} }
private Vertex getContextVertexByFullName(String fullName) throws ResourceRegistryException { private Vertex getContextVertexByFullName(String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} from full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName); logger.trace("Going to get {} {} from full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName);
ScopeBean scopeBean = new ScopeBean(fullName); ScopeBean scopeBean = new ScopeBean(fullName);
String name = scopeBean.name(); String name = scopeBean.name();
// TODO Rewrite the query using Gremlin // TODO Rewrite the query using Gremlin
// Please note that this query works because all the scope parts has a // Please note that this query works because all the scope parts has a
// different name // different name
@ -177,25 +187,25 @@ public class ContextUtility {
+ name + "\""; + name + "\"";
; ;
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select); OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery) Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
.execute(); .execute();
if (vertexes == null || !vertexes.iterator().hasNext()) { if(vertexes == null || !vertexes.iterator().hasNext()) {
throw new ContextNotFoundException("Error retrieving context with name " + fullName); throw new ContextNotFoundException("Error retrieving context with name " + fullName);
} }
Iterator<Vertex> iterator = vertexes.iterator(); Iterator<Vertex> iterator = vertexes.iterator();
Vertex context = iterator.next(); Vertex context = iterator.next();
logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true)); logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
if (iterator.hasNext()) { if(iterator.hasNext()) {
throw new ContextNotFoundException("Found more than one context with name " + name throw new ContextNotFoundException("Found more than one context with name " + name
+ "but required the one with path" + fullName + ". Please Reimplement the query"); + "but required the one with path" + fullName + ". Please Reimplement the query");
} }
return context; return context;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context; package org.gcube.informationsystem.resourceregistry.context;
import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.json.JSONObject;
@ -16,6 +13,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment; import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
@ -29,12 +27,12 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class IsParentOfManagement extends RelationManagement<IsParentOf, ContextManagement, ContextManagement> { public class IsParentOfManagement extends RelationManagement<IsParentOf,ContextManagement,ContextManagement> {
public IsParentOfManagement() { public IsParentOfManagement() {
super(AccessType.IS_PARENT_OF); super(AccessType.IS_PARENT_OF);
} }
public IsParentOfManagement(OrientGraph orientGraph) throws ResourceRegistryException { public IsParentOfManagement(OrientGraph orientGraph) throws ResourceRegistryException {
this(); this();
this.orientGraph = orientGraph; this.orientGraph = orientGraph;
@ -44,7 +42,8 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
@Override @Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException { protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) { if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID); workingContext = ContextUtility.getInstace()
.getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
} }
return workingContext; return workingContext;
} }
@ -60,7 +59,7 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
if(propagationConstraint.has(PropagationConstraint.REMOVE_PROPERTY)) { if(propagationConstraint.has(PropagationConstraint.REMOVE_PROPERTY)) {
String removeProperty = propagationConstraint.get(PropagationConstraint.REMOVE_PROPERTY).asText(); String removeProperty = propagationConstraint.get(PropagationConstraint.REMOVE_PROPERTY).asText();
RemoveConstraint removeConstraint = RemoveConstraint.valueOf(removeProperty); RemoveConstraint removeConstraint = RemoveConstraint.valueOf(removeProperty);
if(removeConstraint!=RemoveConstraint.keep){ if(removeConstraint != RemoveConstraint.keep) {
message = new StringBuilder(); message = new StringBuilder();
message.append(RemoveConstraint.class.getSimpleName()); message.append(RemoveConstraint.class.getSimpleName());
message.append(" can only be "); message.append(" can only be ");
@ -71,10 +70,10 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
if(propagationConstraint.has(PropagationConstraint.ADD_PROPERTY)) { if(propagationConstraint.has(PropagationConstraint.ADD_PROPERTY)) {
String addProperty = propagationConstraint.get(PropagationConstraint.ADD_PROPERTY).asText(); String addProperty = propagationConstraint.get(PropagationConstraint.ADD_PROPERTY).asText();
AddConstraint addConstraint = AddConstraint.valueOf(addProperty); AddConstraint addConstraint = AddConstraint.valueOf(addProperty);
if(addConstraint!=AddConstraint.unpropagate){ if(addConstraint != AddConstraint.unpropagate) {
if(message==null) { if(message == null) {
message = new StringBuilder(); message = new StringBuilder();
}else { } else {
message.append(" and "); message.append(" and ");
} }
message.append(AddConstraint.class.getSimpleName()); message.append(AddConstraint.class.getSimpleName());
@ -83,7 +82,7 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
} }
} }
if(message!=null) { if(message != null) {
throw new ResourceRegistryException(message.toString()); throw new ResourceRegistryException(message.toString());
} }
} }
@ -94,70 +93,70 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
protected IsParentOfNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { protected IsParentOfNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) {
return new IsParentOfNotFoundException(e.getMessage(), e.getCause()); return new IsParentOfNotFoundException(e.getMessage(), e.getCause());
} }
@Override @Override
protected RelationAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( protected RelationAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message) { String message) {
return new RelationAvailableInAnotherContextException(message); return new RelationAvailableInAnotherContextException(message);
} }
@Override @Override
protected IsParentOfAlreadyPresentException getSpecificERAlreadyPresentException(String message) { protected IsParentOfAlreadyPresentException getSpecificERAlreadyPresentException(String message) {
return new IsParentOfAlreadyPresentException(message); return new IsParentOfAlreadyPresentException(message);
} }
@Override @Override
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
return serializeAsJson(false, true); return serializeAsJson(false, true);
} }
public JSONObject serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException { public JSONObject serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException {
JSONObject relation = serializeSelfOnly(); JSONObject relation = serializeSelfOnly();
try { try {
Vertex source = element.getVertex(Direction.OUT); Vertex source = element.getVertex(Direction.OUT);
ContextManagement sourceContextManagement = new ContextManagement(orientGraph); ContextManagement sourceContextManagement = new ContextManagement(orientGraph);
sourceContextManagement.setElement(source); sourceContextManagement.setElement(source);
if (includeSource) { if(includeSource) {
relation.put(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly()); relation.put(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
} }
Vertex target = element.getVertex(Direction.IN); Vertex target = element.getVertex(Direction.IN);
ContextManagement targetContextManagement = new ContextManagement(orientGraph); ContextManagement targetContextManagement = new ContextManagement(orientGraph);
targetContextManagement.setElement(target); targetContextManagement.setElement(target);
if (includeTarget) { if(includeTarget) {
relation.put(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly()); relation.put(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly());
} }
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
return relation; return relation;
} }
@Override @Override
public boolean addToContext() throws ERNotFoundException, ContextException { public boolean addToContext() throws ERNotFoundException, ContextException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public boolean removeFromContext() throws ERNotFoundException, ContextException { public boolean removeFromContext() throws ERNotFoundException, ContextException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException { protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ContextManagement(orientGraph); return new ContextManagement(orientGraph);
} }
@Override @Override
protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException { protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ContextManagement(orientGraph); return new ContextManagement(orientGraph);
} }
} }

View File

@ -1,301 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public static final String DEFAULT_WRITER_ROLE = "writer";
public static final String DEFAULT_READER_ROLE = "reader";
public static final String H = "H";
public enum SecurityType {
ROLE("Role"), USER("User");
private final String name;
private SecurityType(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
public enum PermissionMode {
READER("Reader"), WRITER("Writer");
private final String name;
private PermissionMode(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
protected final UUID context;
protected final Map<PermissionMode, OrientGraphFactory> factories;
protected SecurityContext parentSecurityContext;
public void setParentSecurityContext(SecurityContext parentSecurityContext) {
this.parentSecurityContext = parentSecurityContext;
}
public SecurityContext(UUID context) throws ResourceRegistryException {
this.context = context;
this.factories = new HashMap<>();
}
private synchronized OrientGraphFactory getFactory(PermissionMode permissionMode, boolean recreate) {
OrientGraphFactory factory = null;
if (recreate) {
factories.remove(permissionMode);
} else {
factory = factories.get(permissionMode);
}
if (factory == null) {
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI, username, password).setupPool(1, 10);
factory.setConnectionStrategy(DatabaseEnvironment.CONNECTION_STRATEGY_PARAMETER.toString());
factories.put(permissionMode, factory);
}
return factory;
}
public UUID getUUID() {
return context;
}
protected String getSecurityRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
boolean hierarchic) {
StringBuilder stringBuilder = new StringBuilder();
if (hierarchic) {
stringBuilder.append(H);
}
stringBuilder.append(permissionMode);
stringBuilder.append(securityType);
stringBuilder.append("_");
stringBuilder.append(context.toString());
return stringBuilder.toString();
}
protected ODatabaseDocumentTx getAdminODatabaseDocumentTx(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
return oDatabaseDocumentTx;
}
protected OSecurity getAdminOSecurity(ODatabaseDocumentTx oDatabaseDocumentTx) {
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
return oSecurity;
}
private OSecurity getAdminOSecurity(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
return getAdminOSecurity(oDatabaseDocumentTx);
}
public void addElement(Element element) throws ResourceRegistryException {
addElement(element, ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER));
}
public void addElement(Element element, OrientGraph orientGraph) {
OrientElement orientElement = (OrientElement) element;
ODocument oDocument = orientElement.getRecord();
OSecurity oSecurity = getAdminOSecurity(orientGraph);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
oDocument.save();
orientElement.save();
}
public void removeElement(Element element) throws ResourceRegistryException {
removeElement(element, ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER));
}
public void removeElement(Element element, OrientGraph orientGraph) {
OrientElement orientElement = (OrientElement) element;
ODocument oDocument = orientElement.getRecord();
OSecurity oSecurity = getAdminOSecurity(orientGraph);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
oDocument.save();
orientElement.save();
}
public void create() throws ResourceRegistryException {
OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
create(orientGraph);
orientGraph.commit();
orientGraph.shutdown();
}
public void create(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
ORole writer = oSecurity.getRole(DEFAULT_WRITER_ROLE);
ORole reader = oSecurity.getRole(DEFAULT_READER_ROLE);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
/*
String writerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, true);
String readerHierarchicalRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, true);
String writerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, true);
String readerHierarchicalUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, true);
*/
ORole writerRole = oSecurity.createRole(writerRoleName, writer, ALLOW_MODES.DENY_ALL_BUT);
writerRole.save();
logger.trace("{} created", writerRole);
ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT);
readerRole.save();
logger.trace("{} created", readerRole);
OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
writerUser.save();
logger.trace("{} created", writerUser);
OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
readerUser.save();
logger.trace("{} created", readerUser);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
private void drop(OSecurity oSecurity, String name, SecurityType securityType) {
boolean dropped = false;
switch (securityType) {
case ROLE:
dropped = oSecurity.dropRole(name);
break;
case USER:
dropped = oSecurity.dropUser(name);
break;
default:
break;
}
if (dropped) {
logger.trace("{} successfully dropped", name);
} else {
logger.error("{} was not dropped successfully", name);
}
}
public void delete() throws ResourceRegistryException {
OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
delete(orientGraph);
orientGraph.commit();
orientGraph.shutdown();
}
public void delete(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString());
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, false);
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, false);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.USER, false);
drop(oSecurity, readerUserName, SecurityType.USER);
drop(oSecurity, writerUserName, SecurityType.USER);
drop(oSecurity, readerRoleName, SecurityType.ROLE);
drop(oSecurity, writerRoleName, SecurityType.ROLE);
logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString());
}
public OrientGraph getGraph(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraph orientGraph = factory.getTx();
if (orientGraph.isClosed()) {
factory = getFactory(permissionMode, true);
orientGraph = factory.getTx();
}
return orientGraph;
}
public OrientGraphNoTx getGraphNoTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
if (orientGraphNoTx.isClosed()) {
factory = getFactory(permissionMode, true);
orientGraphNoTx = factory.getNoTx();
}
return orientGraphNoTx;
}
public ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if (databaseDocumentTx.isClosed()) {
factory = getFactory(permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
@Override
public String toString() {
return String.format("%s %s", Context.NAME, getUUID().toString());
}
}

View File

@ -0,0 +1,50 @@
package org.gcube.informationsystem.resourceregistry.context.security;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class AdminSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public AdminSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID, false);
}
@Override
public void create() {
throw new RuntimeException("Cannot use this method for Admin Context");
}
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) {
return oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL);
break;
case READER:
role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -0,0 +1,44 @@
package org.gcube.informationsystem.resourceregistry.context.security;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ContextSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public ContextSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID, false);
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL);
break;
case READER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -0,0 +1,44 @@
package org.gcube.informationsystem.resourceregistry.context.security;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class SchemaSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
public SchemaSecurityContext() throws ResourceRegistryException {
super(DatabaseEnvironment.SCHEMA_SECURITY_CONTEXT_UUID, false);
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL);
break;
case READER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -0,0 +1,457 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context.security;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
protected static final String DEFAULT_WRITER_ROLE = "writer";
protected static final String DEFAULT_READER_ROLE = "reader";
public static final String H = "H";
protected final boolean hierarchic;
public enum SecurityType {
ROLE("Role"), USER("User");
private final String name;
private SecurityType(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
public enum PermissionMode {
READER("Reader"), WRITER("Writer");
private final String name;
private PermissionMode(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
protected final UUID context;
protected final Map<Boolean,Map<PermissionMode,OrientGraphFactory>> factoryMap;
protected SecurityContext parentSecurityContext;
protected boolean isHierarchicMode() {
return hierarchic && ContextUtility.getHierarchicMode().get();
}
public void setParentSecurityContext(SecurityContext parentSecurityContext) {
this.parentSecurityContext = parentSecurityContext;
}
public SecurityContext getParentSecurityContext() {
return parentSecurityContext;
}
/**
* Use to change the parent not to set the first time
*
* @param newParentSecurityContext
* @throws ResourceRegistryException
*/
public void changeParentSecurityContext(SecurityContext newParentSecurityContext) throws ResourceRegistryException {
OrientGraph orientGraph = getAdminOrientGraph();
changeParentSecurityContext(newParentSecurityContext, orientGraph);
}
protected OrientGraph getAdminOrientGraph() throws ResourceRegistryException {
return ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
}
/**
* Use to change the parent not to set the first time
*
* @param newParentSecurityContext
* @param orientGraph
*/
public void changeParentSecurityContext(SecurityContext newParentSecurityContext, OrientGraph orientGraph) {
// TODO Remove from old hierarchy
// TODO Add to new Hierarchy
// In both cases take in account the new and the old parent
setParentSecurityContext(newParentSecurityContext);
}
protected SecurityContext(UUID context, boolean hierarchic) throws ResourceRegistryException {
this.context = context;
this.factoryMap = new HashMap<>();
this.hierarchic = hierarchic;
}
public SecurityContext(UUID context) throws ResourceRegistryException {
this(context, true);
}
private synchronized OrientGraphFactory getFactory(PermissionMode permissionMode, boolean recreate) {
OrientGraphFactory factory = null;
Boolean h = hierarchic && isHierarchicMode();
Map<PermissionMode,OrientGraphFactory> factories = factoryMap.get(h);
if(factories == null) {
factories = new HashMap<>();
} else {
if(recreate) {
factories.remove(permissionMode);
}
}
factory = factories.get(permissionMode);
if(factory == null) {
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI, username, password).setupPool(1, 10);
factory.setConnectionStrategy(DatabaseEnvironment.CONNECTION_STRATEGY_PARAMETER.toString());
factories.put(permissionMode, factory);
}
return factory;
}
public UUID getUUID() {
return context;
}
public String getSecurityRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
boolean hierarchic) {
StringBuilder stringBuilder = new StringBuilder();
if(hierarchic) {
stringBuilder.append(H);
}
stringBuilder.append(permissionMode);
stringBuilder.append(securityType);
stringBuilder.append("_");
stringBuilder.append(context.toString());
return stringBuilder.toString();
}
private ODatabaseDocumentTx getAdminODatabaseDocumentTx(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
return oDatabaseDocumentTx;
}
private OSecurity getAdminOSecurity(ODatabaseDocumentTx oDatabaseDocumentTx) {
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
return oSecurity;
}
private OSecurity getAdminOSecurity(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
return getAdminOSecurity(oDatabaseDocumentTx);
}
public void addElement(Element element) throws ResourceRegistryException {
addElement(element, getAdminOrientGraph());
}
protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) {
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic);
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
}
public void addElement(Element element, OrientGraph orientGraph) {
OrientElement orientElement = (OrientElement) element;
ODocument oDocument = orientElement.getRecord();
OSecurity oSecurity = getAdminOSecurity(orientGraph);
allow(oSecurity, oDocument, false);
if(hierarchic) {
allow(oSecurity, oDocument, true);
if(getParentSecurityContext() != null) {
getParentSecurityContext().addElementToHierarchy(oSecurity, oDocument);
}
}
oDocument.save();
orientElement.save();
}
protected void addElementToHierarchy(OSecurity oSecurity, ODocument oDocument) {
allow(oSecurity, oDocument, true);
if(getParentSecurityContext() != null) {
getParentSecurityContext().addElementToHierarchy(oSecurity, oDocument);
}
}
public void removeElement(Element element) throws ResourceRegistryException {
removeElement(element, getAdminOrientGraph());
}
protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) {
// The element could be created in such a context so the writerUser for the
// context is allowed by default
// because it was the creator
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchic);
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_ALL, writerUserName);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchic);
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic);
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
}
public void removeElement(Element element, OrientGraph orientGraph) {
OrientElement orientElement = (OrientElement) element;
ODocument oDocument = orientElement.getRecord();
OSecurity oSecurity = getAdminOSecurity(orientGraph);
deny(oSecurity, oDocument, false);
if(hierarchic) {
deny(oSecurity, oDocument, true);
if(getParentSecurityContext() != null) {
getParentSecurityContext().removeElementFromHierarchy(oSecurity, oDocument);
}
}
oDocument.save();
orientElement.save();
}
protected boolean allowed(final ORole role, final ODocument oDocument) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
ContextUtility.getHierarchicMode().set(false);
OrientGraphNoTx orientGraphNoTx = getGraphNoTx(PermissionMode.READER);
try {
OrientElement element = orientGraphNoTx.getElement(oDocument.getIdentity());
if(element == null) {
return false;
}
return true;
} catch(Exception e) {
return false;
} finally {
orientGraphNoTx.shutdown();
}
}
};
Future<Boolean> result = executor.submit(callable);
try {
return result.get();
} catch(Exception e) {
return false;
}
}
protected void removeElementFromHierarchy(OSecurity oSecurity, ODocument oDocument) {
// I don't have to deny the Hierarchic role if the element belong to context
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, false);
ORole writerRole = oSecurity.getRole(writerRoleName);
/*
* This check if the writerRole (not hierarchic) has the right to operate on the
* document. In such a case don't have to deny the hierarchy
*/
boolean allowed = allowed(writerRole, oDocument);
// If allowed not denying the hierarchy and continuing to parents
if(!allowed) {
deny(oSecurity, oDocument, true);
if(getParentSecurityContext() != null) {
getParentSecurityContext().removeElementFromHierarchy(oSecurity, oDocument);
}
}
}
public void create() throws ResourceRegistryException {
OrientGraph orientGraph = getAdminOrientGraph();
create(orientGraph);
orientGraph.commit();
orientGraph.shutdown();
}
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
return role;
}
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) {
return oSecurity.getRole(permissionMode.name().toLowerCase());
}
protected void createRolesAndUsers(OSecurity oSecurity) {
boolean[] booleanArray;
if(hierarchic) {
booleanArray = new boolean[] {false, true};
} else {
booleanArray = new boolean[] {false};
}
for(boolean hierarchic : booleanArray) {
for(PermissionMode permissionMode : PermissionMode.values()) {
ORole superRole = getSuperRole(oSecurity, permissionMode);
String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
ORole role = oSecurity.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT);
addExtraRules(role, permissionMode);
role.save();
logger.trace("{} created", role);
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
OUser user = oSecurity.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode),
role);
user.save();
logger.trace("{} created", user);
}
}
}
public void create(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
createRolesAndUsers(oSecurity);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
private void drop(OSecurity oSecurity, String name, SecurityType securityType) {
boolean dropped = false;
switch(securityType) {
case ROLE:
dropped = oSecurity.dropRole(name);
break;
case USER:
dropped = oSecurity.dropUser(name);
break;
default:
break;
}
if(dropped) {
logger.trace("{} successfully dropped", name);
} else {
logger.error("{} was not dropped successfully", name);
}
}
public void delete() throws ResourceRegistryException {
OrientGraph orientGraph = getAdminOrientGraph();
delete(orientGraph);
orientGraph.commit();
orientGraph.shutdown();
}
protected void deleteRolesAndUsers(OSecurity oSecurity) {
boolean[] booleanArray;
if(hierarchic) {
booleanArray = new boolean[] {false, true};
} else {
booleanArray = new boolean[] {false};
}
for(boolean hierarchic : booleanArray) {
for(PermissionMode permissionMode : PermissionMode.values()) {
for(SecurityType securityType : SecurityType.values()) {
String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic);
drop(oSecurity, name, securityType);
}
}
}
}
public void delete(OrientGraph orientGraph) {
ODatabaseDocumentTx oDatabaseDocumentTx = getAdminODatabaseDocumentTx(orientGraph);
OSecurity oSecurity = getAdminOSecurity(oDatabaseDocumentTx);
logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString());
deleteRolesAndUsers(oSecurity);
logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString());
}
public OrientGraph getGraph(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraph orientGraph = factory.getTx();
if(orientGraph.isClosed()) {
factory = getFactory(permissionMode, true);
orientGraph = factory.getTx();
}
return orientGraph;
}
public OrientGraphNoTx getGraphNoTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
if(orientGraphNoTx.isClosed()) {
factory = getFactory(permissionMode, true);
orientGraphNoTx = factory.getNoTx();
}
return orientGraphNoTx;
}
public ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if(databaseDocumentTx.isClosed()) {
factory = getFactory(permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
@Override
public String toString() {
return String.format("%s %s", Context.NAME, getUUID().toString());
}
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.dbinitialization; package org.gcube.informationsystem.resourceregistry.dbinitialization;
import java.io.InputStream; import java.io.InputStream;
@ -14,11 +11,11 @@ import org.gcube.informationsystem.impl.utils.discovery.ERDiscovery;
import org.gcube.informationsystem.model.ISConstants; import org.gcube.informationsystem.model.ISConstants;
import org.gcube.informationsystem.model.embedded.Embedded; import org.gcube.informationsystem.model.embedded.Embedded;
import org.gcube.informationsystem.model.embedded.ValueSchema; import org.gcube.informationsystem.model.embedded.ValueSchema;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SchemaSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,160 +37,156 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*
*/ */
public class DatabaseEnvironment { public class DatabaseEnvironment {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class); private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class);
private static final String PROPERTY_FILENAME = "config.properties"; private static final String PROPERTY_FILENAME = "config.properties";
private static final String HOST_VARNAME = "HOST"; private static final String HOST_VARNAME = "HOST";
private static final String REMOTE_PROTOCOL; private static final String REMOTE_PROTOCOL;
private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL"; private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL";
private static final String DB; private static final String DB;
private static final String DB_VARNAME = "DB"; private static final String DB_VARNAME = "DB";
private static final String ROOT_USERNAME; private static final String ROOT_USERNAME;
private static final String ROOT_USERNAME_VARNAME = "ROOT_USERNAME"; private static final String ROOT_USERNAME_VARNAME = "ROOT_USERNAME";
private static final String ROOT_PASSWORD; private static final String ROOT_PASSWORD;
private static final String ROOT_PASSWORD_VARNAME = "ROOT_PASSWORD"; private static final String ROOT_PASSWORD_VARNAME = "ROOT_PASSWORD";
private static final String DEFAULT_ADMIN_USERNAME; private static final String DEFAULT_ADMIN_USERNAME;
private static final String DEFAULT_ADMIN_USERNAME_VARNAME = "DEFAULT_ADMIN_USERNAME"; private static final String DEFAULT_ADMIN_USERNAME_VARNAME = "DEFAULT_ADMIN_USERNAME";
public static final String DEFAULT_ADMIN_ROLE = "admin"; public static final String DEFAULT_ADMIN_ROLE = "admin";
private static final String CHANGED_ADMIN_USERNAME; private static final String CHANGED_ADMIN_USERNAME;
private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME"; private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME";
private static final String DEFAULT_ADMIN_PASSWORD; private static final String DEFAULT_ADMIN_PASSWORD;
private static final String DEFAULT_ADMIN_PASSWORD_VARNAME = "DEFAULT_ADMIN_PASSWORD"; private static final String DEFAULT_ADMIN_PASSWORD_VARNAME = "DEFAULT_ADMIN_PASSWORD";
private static final String CHANGED_ADMIN_PASSWORD; private static final String CHANGED_ADMIN_PASSWORD;
private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD"; private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD";
private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD; private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD;
private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_WRITER_USER_PASSWORD"; private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_WRITER_USER_PASSWORD";
private static final String DEFAULT_CREATED_READER_USER_PASSWORD; private static final String DEFAULT_CREATED_READER_USER_PASSWORD;
private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD"; private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD";
public static final Map<PermissionMode, String> DEFAULT_PASSWORDS; public static final Map<PermissionMode,String> DEFAULT_PASSWORDS;
private static final String HOSTS; private static final String HOSTS;
private static final String SERVER_URI; private static final String SERVER_URI;
public static final String DB_URI; public static final String DB_URI;
private static final String DATABASE_TYPE = "graph"; private static final String DATABASE_TYPE = "graph";
private static final String STORAGE_MODE = "plocal"; private static final String STORAGE_MODE = "plocal";
public static final String O_RESTRICTED_CLASS = "ORestricted"; public static final String O_RESTRICTED_CLASS = "ORestricted";
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT; public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT \"%s\""; private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT \"%s\"";
// Used to indicate virtual admin security context // Used to indicate virtual admin security context
private static final String ADMIN_SECURITY_CONTEXT; private static final String ADMIN_SECURITY_CONTEXT;
public static final UUID ADMIN_SECURITY_CONTEXT_UUID; public static final UUID ADMIN_SECURITY_CONTEXT_UUID;
// Used to persist Schemas // Used to persist Schemas
private static final String SCHEMA_SECURITY_CONTEXT; private static final String SCHEMA_SECURITY_CONTEXT;
public static final UUID SCHEMA_SECURITY_CONTEXT_UUID; public static final UUID SCHEMA_SECURITY_CONTEXT_UUID;
// Used to Persist Context and their relations // Used to Persist Context and their relations
private static final String CONTEXT_SECURITY_CONTEXT; private static final String CONTEXT_SECURITY_CONTEXT;
public static final UUID CONTEXT_SECURITY_CONTEXT_UUID; public static final UUID CONTEXT_SECURITY_CONTEXT_UUID;
static { static {
Properties properties = new Properties(); Properties properties = new Properties();
InputStream input = null; InputStream input = null;
try { try {
input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME); input = DatabaseEnvironment.class.getClassLoader().getResourceAsStream(PROPERTY_FILENAME);
// load a properties file // load a properties file
properties.load(input); properties.load(input);
HOSTS = properties.getProperty(HOST_VARNAME); HOSTS = properties.getProperty(HOST_VARNAME);
REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME); REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME);
DB = properties.getProperty(DB_VARNAME); DB = properties.getProperty(DB_VARNAME);
SERVER_URI = REMOTE_PROTOCOL + HOSTS; SERVER_URI = REMOTE_PROTOCOL + HOSTS;
DB_URI = SERVER_URI + "/" + DB; DB_URI = SERVER_URI + "/" + DB;
ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME); ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME);
ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME); ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME);
String changedAdminUsername = null; String changedAdminUsername = null;
try { try {
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME); changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
if (changedAdminUsername == null) { if(changedAdminUsername == null) {
// To be compliant with old configuration.properties which does not have // To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username // CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB; changedAdminUsername = DB;
} }
} catch (Exception e) { } catch(Exception e) {
// To be compliant with old configuration.properties which does not have // To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username // CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB; changedAdminUsername = DB;
} }
CHANGED_ADMIN_USERNAME = changedAdminUsername; CHANGED_ADMIN_USERNAME = changedAdminUsername;
CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_ADMIN_PASSWORD_VARNAME); CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_ADMIN_PASSWORD_VARNAME);
DEFAULT_CREATED_WRITER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME); DEFAULT_CREATED_WRITER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME);
DEFAULT_CREATED_READER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME); DEFAULT_CREATED_READER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME);
DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME); DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME);
DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME); DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME);
DEFAULT_PASSWORDS = new HashMap<PermissionMode, String>(); DEFAULT_PASSWORDS = new HashMap<PermissionMode,String>();
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD);
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD); DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
} catch (Exception e) { } catch(Exception e) {
logger.error("Unable to load properties from {}", PROPERTY_FILENAME); logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
throw new RuntimeException("Unable to load properties", e); throw new RuntimeException("Unable to load properties", e);
} }
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000"; ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT); ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
// Used to persist Schemas // Used to persist Schemas
SCHEMA_SECURITY_CONTEXT = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"; SCHEMA_SECURITY_CONTEXT = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
SCHEMA_SECURITY_CONTEXT_UUID = UUID.fromString(SCHEMA_SECURITY_CONTEXT); SCHEMA_SECURITY_CONTEXT_UUID = UUID.fromString(SCHEMA_SECURITY_CONTEXT);
// Used to Persist Context and their relations // Used to Persist Context and their relations
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff"; CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT); CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
try { try {
boolean created = initGraphDB(); boolean created = initGraphDB();
ContextUtility contextUtility = ContextUtility.getInstace(); ContextUtility contextUtility = ContextUtility.getInstace();
AdminSecurityContext adminSecurityContext = new AdminSecurityContext(); AdminSecurityContext adminSecurityContext = new AdminSecurityContext();
contextUtility.addSecurityContext(adminSecurityContext.getUUID().toString(), adminSecurityContext); contextUtility.addSecurityContext(adminSecurityContext.getUUID().toString(), adminSecurityContext);
ContextSecurityContext contextSecurityContext = new ContextSecurityContext(); ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
contextUtility.addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext); contextUtility.addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
SecurityContext schemaSecurityContext = new SecurityContext(SCHEMA_SECURITY_CONTEXT_UUID); SchemaSecurityContext schemaSecurityContext = new SchemaSecurityContext();
contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext); contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext);
if (created) { if(created) {
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME, OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD).setupPool(1, 10); CHANGED_ADMIN_PASSWORD).setupPool(1, 10);
OrientGraph orientGraph = factory.getTx(); OrientGraph orientGraph = factory.getTx();
@ -205,39 +198,39 @@ public class DatabaseEnvironment {
contextSecurityContext.create(); contextSecurityContext.create();
schemaSecurityContext.create(); schemaSecurityContext.create();
createEntitiesAndRelations(); createEntitiesAndRelations();
} }
} catch (Exception e) { } catch(Exception e) {
logger.error("Error initializing database connection", e); logger.error("Error initializing database connection", e);
throw new RuntimeException("Error initializing database connection", e); throw new RuntimeException("Error initializing database connection", e);
} }
} }
private static boolean initGraphDB() throws Exception { private static boolean initGraphDB() throws Exception {
OLogManager.instance().setWarnEnabled(false); OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false); OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false); OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false); OLogManager.instance().setDebugEnabled(false);
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI); logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD); OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD);
if (!serverAdmin.existsDatabase(DB, STORAGE_MODE)) { if(!serverAdmin.existsDatabase(DB, STORAGE_MODE)) {
logger.info("The database {} does not exist. Going to create it.", DB_URI); logger.info("The database {} does not exist. Going to create it.", DB_URI);
serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE); serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE);
logger.trace("Connecting to newly created database {} as {} with default password", DB_URI, logger.trace("Connecting to newly created database {} as {} with default password", DB_URI,
DEFAULT_ADMIN_USERNAME); DEFAULT_ADMIN_USERNAME);
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD) OrientGraphFactory factory = new OrientGraphFactory(DB_URI, DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD)
.setupPool(1, 10); .setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx(); OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
/* Updating DateTimeFormat to be aligned with IS model definition */ /* Updating DateTimeFormat to be aligned with IS model definition */
/* /*
* This solution does not work OStorageConfiguration configuration = * This solution does not work OStorageConfiguration configuration =
@ -248,51 +241,51 @@ public class DatabaseEnvironment {
String query = String.format(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, ISConstants.DATETIME_PATTERN); String query = String.format(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, ISConstants.DATETIME_PATTERN);
OCommandSQL preparedQuery = new OCommandSQL(query); OCommandSQL preparedQuery = new OCommandSQL(query);
orientGraphNoTx.getRawGraph().command(preparedQuery).execute(); orientGraphNoTx.getRawGraph().command(preparedQuery).execute();
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSecurity oSecurity = oMetadata.getSecurity(); OSecurity oSecurity = oMetadata.getSecurity();
logger.trace("Changing {} password", DEFAULT_ADMIN_USERNAME); logger.trace("Changing {} password", DEFAULT_ADMIN_USERNAME);
OUser admin = oSecurity.getUser(DEFAULT_ADMIN_USERNAME); OUser admin = oSecurity.getUser(DEFAULT_ADMIN_USERNAME);
admin.setPassword(CHANGED_ADMIN_PASSWORD); admin.setPassword(CHANGED_ADMIN_PASSWORD);
admin.save(); admin.save();
logger.trace("Creating new admin named '{}'", CHANGED_ADMIN_USERNAME); logger.trace("Creating new admin named '{}'", CHANGED_ADMIN_USERNAME);
ORole adminRole = oSecurity.getRole(DEFAULT_ADMIN_ROLE); ORole adminRole = oSecurity.getRole(DEFAULT_ADMIN_ROLE);
OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole); OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
newAdminUser.save(); newAdminUser.save();
for (PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) { for(PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
OUser oUser = oSecurity.getUser(permissionMode.toString()); OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode)); oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
oUser.save(); oUser.save();
logger.trace("Updating password for user {}", permissionMode.toString()); logger.trace("Updating password for user {}", permissionMode.toString());
} }
logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)"); logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)");
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass oRestricted = oSchema.getClass(O_RESTRICTED_CLASS); OClass oRestricted = oSchema.getClass(O_RESTRICTED_CLASS);
OrientVertexType v = orientGraphNoTx.getVertexBaseType(); OrientVertexType v = orientGraphNoTx.getVertexBaseType();
v.addSuperClass(oRestricted); v.addSuperClass(oRestricted);
OrientEdgeType e = orientGraphNoTx.getEdgeBaseType(); OrientEdgeType e = orientGraphNoTx.getEdgeBaseType();
e.addSuperClass(oRestricted); e.addSuperClass(oRestricted);
// orientGraphNoTx.commit(); // orientGraphNoTx.commit();
orientGraphNoTx.shutdown(); orientGraphNoTx.shutdown();
factory.close(); factory.close();
return true; return true;
} }
serverAdmin.close(); serverAdmin.close();
return false; return false;
} }
private static void createEntitiesAndRelations() throws Exception { private static void createEntitiesAndRelations() throws Exception {
ERDiscovery erDiscovery = ISMapper.getErdiscovery(); ERDiscovery erDiscovery = ISMapper.getErdiscovery();
SchemaActionImpl entityRegistrationAction = new SchemaActionImpl(); SchemaActionImpl entityRegistrationAction = new SchemaActionImpl();
@ -300,5 +293,5 @@ public class DatabaseEnvironment {
entityRegistrationAction.manageEmbeddedClass(ValueSchema.class); entityRegistrationAction.manageEmbeddedClass(ValueSchema.class);
erDiscovery.manageDiscoveredERTypes(entityRegistrationAction); erDiscovery.manageDiscoveredERTypes(entityRegistrationAction);
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.dbinitialization; package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.gcube.informationsystem.impl.utils.discovery.SchemaAction; import org.gcube.informationsystem.impl.utils.discovery.SchemaAction;
@ -18,53 +15,52 @@ import org.gcube.informationsystem.types.TypeBinder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class SchemaActionImpl implements SchemaAction { public class SchemaActionImpl implements SchemaAction {
private static Logger logger = LoggerFactory.getLogger(SchemaActionImpl.class); private static Logger logger = LoggerFactory.getLogger(SchemaActionImpl.class);
protected SchemaManagement schemaManagement; protected SchemaManagement schemaManagement;
public SchemaActionImpl(){ public SchemaActionImpl() {
this.schemaManagement = new SchemaManagementImpl(); this.schemaManagement = new SchemaManagementImpl();
} }
@Override @Override
public <R extends Relation<? extends Entity, ? extends Entity>> void manageRelationClass( public <R extends Relation<? extends Entity,? extends Entity>> void manageRelationClass(Class<R> r)
Class<R> r) throws Exception { throws Exception {
try{ try {
String json = TypeBinder.serializeType(r); String json = TypeBinder.serializeType(r);
logger.trace(json); logger.trace(json);
if (ConsistsOf.class.isAssignableFrom(r)) { if(ConsistsOf.class.isAssignableFrom(r)) {
schemaManagement.create(json, AccessType.CONSISTS_OF); schemaManagement.create(json, AccessType.CONSISTS_OF);
} else if(IsRelatedTo.class.isAssignableFrom(r)){ } else if(IsRelatedTo.class.isAssignableFrom(r)) {
schemaManagement.create(json, AccessType.IS_RELATED_TO); schemaManagement.create(json, AccessType.IS_RELATED_TO);
} else { } else {
schemaManagement.create(json, AccessType.RELATION); schemaManagement.create(json, AccessType.RELATION);
} }
} catch(Exception ex){ } catch(Exception ex) {
logger.error("Error creating schema for {} type {} : {}", Relation.NAME, r.getSimpleName(), ex.getMessage()); logger.error("Error creating schema for {} type {} : {}", Relation.NAME, r.getSimpleName(),
ex.getMessage());
throw ex; throw ex;
} }
} }
@Override @Override
public <E extends Entity> void manageEntityClass(Class<E> e) throws Exception { public <E extends Entity> void manageEntityClass(Class<E> e) throws Exception {
try{ try {
String json = TypeBinder.serializeType(e); String json = TypeBinder.serializeType(e);
logger.trace(json); logger.trace(json);
if (Facet.class.isAssignableFrom(e)) { if(Facet.class.isAssignableFrom(e)) {
schemaManagement.create(json, AccessType.FACET); schemaManagement.create(json, AccessType.FACET);
} else if(Resource.class.isAssignableFrom(e)){ } else if(Resource.class.isAssignableFrom(e)) {
schemaManagement.create(json, AccessType.RESOURCE); schemaManagement.create(json, AccessType.RESOURCE);
} else { } else {
schemaManagement.create(json, AccessType.ENTITY); schemaManagement.create(json, AccessType.ENTITY);
} }
} catch(Exception ex){ } catch(Exception ex) {
logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage()); logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage());
throw ex; throw ex;
} }
@ -76,12 +72,11 @@ public class SchemaActionImpl implements SchemaAction {
String json = TypeBinder.serializeType(e); String json = TypeBinder.serializeType(e);
logger.trace(json); logger.trace(json);
schemaManagement.create(json, AccessType.EMBEDDED); schemaManagement.create(json, AccessType.EMBEDDED);
} catch (Exception ex) { } catch(Exception ex) {
logger.error("Error creating schema for {} type {} : {}", logger.error("Error creating schema for {} type {} : {}", Embedded.NAME, e.getSimpleName(),
Embedded.NAME, e.getSimpleName(),
ex.getMessage()); ex.getMessage());
throw ex; throw ex;
} }
} }
} }

View File

@ -10,7 +10,7 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -32,150 +32,152 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex; import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType; import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ERManagementUtility { public class ERManagementUtility {
private static Logger logger = LoggerFactory.getLogger(EntityManagement.class); private static Logger logger = LoggerFactory.getLogger(EntityManagement.class);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static ERManagement getERManagement(String type) throws ResourceRegistryException { public static ERManagement getERManagement(String type) throws ResourceRegistryException {
OClass oClass = SchemaManagementImpl.getTypeSchema(type, null); OClass oClass = SchemaManagementImpl.getTypeSchema(type, null);
ERManagement erManagement = null; ERManagement erManagement = null;
if (oClass.isSubClassOf(Resource.NAME)) { if(oClass.isSubClassOf(Resource.NAME)) {
erManagement = new ResourceManagement(); erManagement = new ResourceManagement();
} else if (oClass.isSubClassOf(Facet.NAME)) { } else if(oClass.isSubClassOf(Facet.NAME)) {
erManagement = new FacetManagement(); erManagement = new FacetManagement();
} else if (oClass.isSubClassOf(ConsistsOf.NAME)) { } else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
erManagement = new ConsistsOfManagement(); erManagement = new ConsistsOfManagement();
} else if (oClass.isSubClassOf(IsRelatedTo.NAME)) { } else if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
erManagement = new IsRelatedToManagement(); erManagement = new IsRelatedToManagement();
} }
if (erManagement == null) { if(erManagement == null) {
throw new ResourceRegistryException(String.format("%s is not querable", type.toString())); throw new ResourceRegistryException(String.format("%s is not querable", type.toString()));
} }
erManagement.setElementType(type); erManagement.setElementType(type);
return erManagement; return erManagement;
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element) private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph,
throws ResourceRegistryException { Element element) throws ResourceRegistryException {
if (element instanceof Vertex) { if(element instanceof Vertex) {
return getEntityManagement(workingContext, orientGraph, (Vertex) element); return getEntityManagement(workingContext, orientGraph, (Vertex) element);
} else if (element instanceof Edge) { } else if(element instanceof Edge) {
return getRelationManagement(workingContext, orientGraph, (Edge) element); return getRelationManagement(workingContext, orientGraph, (Edge) element);
} }
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(), throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
Entity.NAME, Relation.NAME)); Entity.NAME, Relation.NAME));
} }
public static Element getAnyElementByUUID(UUID uuid) throws ERNotFoundException, ResourceRegistryException { public static Element getAnyElementByUUID(UUID uuid) throws ERNotFoundException, ResourceRegistryException {
try { try {
return Utility.getElementByUUIDAsAdmin(null, uuid, Vertex.class); return Utility.getElementByUUIDAsAdmin(null, uuid, Vertex.class);
} catch (ERNotFoundException e) { } catch(ERNotFoundException e) {
return Utility.getElementByUUIDAsAdmin(null, uuid, Edge.class); return Utility.getElementByUUIDAsAdmin(null, uuid, Edge.class);
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
private static Element getAnyElementByUUID(OrientGraph orientGraph, UUID uuid) private static Element getAnyElementByUUID(OrientGraph orientGraph, UUID uuid)
throws ERNotFoundException, ResourceRegistryException { throws ERNotFoundException, ResourceRegistryException {
try { try {
return Utility.getElementByUUID(orientGraph, null, uuid, Vertex.class); return Utility.getElementByUUID(orientGraph, null, uuid, Vertex.class);
} catch (ERNotFoundException e) { } catch(ERNotFoundException e) {
return Utility.getElementByUUID(orientGraph, null, uuid, Edge.class); return Utility.getElementByUUID(orientGraph, null, uuid, Edge.class);
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, UUID uuid) public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph,
throws ResourceRegistryException { UUID uuid) throws ResourceRegistryException {
Element element; Element element;
try { try {
element = getAnyElementByUUID(orientGraph, uuid); element = getAnyElementByUUID(orientGraph, uuid);
return getERManagement(workingContext, orientGraph, element); return getERManagement(workingContext, orientGraph, element);
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s", throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
uuid.toString(), Entity.NAME, Relation.NAME)); uuid.toString(), Entity.NAME, Relation.NAME));
} }
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, Vertex vertex) public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph,
throws ResourceRegistryException { Vertex vertex) throws ResourceRegistryException {
if (orientGraph == null) { if(orientGraph == null) {
throw new ResourceRegistryException(OrientGraph.class.getSimpleName() throw new ResourceRegistryException(
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if (vertex == null) { if(vertex == null) {
throw new ResourceRegistryException(Vertex.class.getSimpleName() throw new ResourceRegistryException(
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Vertex.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
OrientVertexType orientVertexType = null; OrientVertexType orientVertexType = null;
try { try {
orientVertexType = ((OrientVertex) vertex).getType(); orientVertexType = ((OrientVertex) vertex).getType();
} catch (Exception e) { } catch(Exception e) {
String error = String.format( String error = String.format("Unable to detect type of %s. %s", vertex.toString(),
"Unable to detect type of %s. %s", Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e); logger.error(error, e);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
EntityManagement entityManagement = null; EntityManagement entityManagement = null;
if (orientVertexType.isSubClassOf(Resource.NAME)) { if(orientVertexType.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(workingContext, orientGraph); entityManagement = new ResourceManagement(workingContext, orientGraph);
} else if (orientVertexType.isSubClassOf(Facet.NAME)) { } else if(orientVertexType.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(workingContext, orientGraph); entityManagement = new FacetManagement(workingContext, orientGraph);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME,
vertex, Resource.NAME, Facet.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
entityManagement.setElement(vertex); entityManagement.setElement(vertex);
return entityManagement; return entityManagement;
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"})
public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, Edge edge) public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph,
throws ResourceRegistryException { Edge edge) throws ResourceRegistryException {
if (orientGraph == null) { if(orientGraph == null) {
throw new ResourceRegistryException(OrientGraph.class.getSimpleName() throw new ResourceRegistryException(
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if (edge == null) { if(edge == null) {
throw new ResourceRegistryException(Edge.class.getSimpleName() throw new ResourceRegistryException(
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Edge.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
RelationManagement relationManagement = null; RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(workingContext, orientGraph); relationManagement = new ConsistsOfManagement(workingContext, orientGraph);
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { } else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(workingContext, orientGraph); relationManagement = new IsRelatedToManagement(workingContext, orientGraph);
} else { } else {
String error = String.format("{%s is not a %s nor a %s. %s", String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME,
edge, ConsistsOf.NAME, IsRelatedTo.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
relationManagement.setElement(edge); relationManagement.setElement(edge);
return relationManagement; return relationManagement;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er; package org.gcube.informationsystem.resourceregistry.er;
import java.util.HashSet; import java.util.HashSet;
@ -23,9 +20,8 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class EmbeddedMangement { public class EmbeddedMangement {
private static Logger logger = LoggerFactory private static Logger logger = LoggerFactory.getLogger(EmbeddedMangement.class);
.getLogger(EmbeddedMangement.class);
public static final Set<String> EMBEDDED_IGNORE_KEYS; public static final Set<String> EMBEDDED_IGNORE_KEYS;
public static final Set<String> EMBEDDED_IGNORE_START_WITH_KEYS; public static final Set<String> EMBEDDED_IGNORE_START_WITH_KEYS;
@ -35,42 +31,40 @@ public class EmbeddedMangement {
static { static {
EMBEDDED_IGNORE_KEYS = new HashSet<String>(); EMBEDDED_IGNORE_KEYS = new HashSet<String>();
EMBEDDED_IGNORE_START_WITH_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(AT);
EMBEDDED_IGNORE_START_WITH_KEYS.add(UNDERSCORE); EMBEDDED_IGNORE_START_WITH_KEYS.add(UNDERSCORE);
} }
public static ODocument getEmbeddedType(JsonNode jsonNode) throws ResourceRegistryException {
public static ODocument getEmbeddedType(JsonNode jsonNode) if(jsonNode.has(ISManageable.CLASS_PROPERTY)) {
throws ResourceRegistryException {
if (jsonNode.has(ISManageable.CLASS_PROPERTY)) {
// Complex type // Complex type
String type = ERManagement.getClassProperty(jsonNode); String type = ERManagement.getClassProperty(jsonNode);
try { try {
SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED); SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED);
} catch (SchemaNotFoundException e) { } catch(SchemaNotFoundException e) {
throw e; throw e;
} }
Header header = null; Header header = null;
try { try {
header = HeaderUtility.getHeader(jsonNode, false); header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) { } catch(Exception e) {
logger.warn("An invalid Header has been provided. Anyway embedded object cannot have an Header."); 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"); throw new ResourceRegistryException("An embedded object cannot have an Header");
} }
if (header != null) { if(header != null) {
throw new ResourceRegistryException("An embedded object cannot have an Header"); throw new ResourceRegistryException("An embedded object cannot have an Header");
} }
ODocument oDocument = new ODocument(type); ODocument oDocument = new ODocument(type);
return oDocument.fromJSON(jsonNode.toString()); return oDocument.fromJSON(jsonNode.toString());
} }
ODocument oDocument = new ODocument(); ODocument oDocument = new ODocument();

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.entity; package org.gcube.informationsystem.resourceregistry.er.entity;
import java.util.HashMap; import java.util.HashMap;
@ -16,7 +13,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement; import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
@ -32,33 +29,27 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertex;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public abstract class EntityManagement<E extends Entity> extends public abstract class EntityManagement<E extends Entity> extends ERManagement<E,Vertex> {
ERManagement<E, Vertex> {
/** /**
* Provide a cache edge-internal-id -> RelationManagement * Provide a cache edge-internal-id -> RelationManagement
* this avoid to recreate the relationManagement of already visited * this avoid to recreate the relationManagement of already visited edges
* edges
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected Map<String, RelationManagement> relationManagements; protected Map<String,RelationManagement> relationManagements;
protected EntityManagement(AccessType accessType) { protected EntityManagement(AccessType accessType) {
super(accessType); super(accessType);
this.ignoreKeys.add(Entity.HEADER_PROPERTY); this.ignoreKeys.add(Entity.HEADER_PROPERTY);
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toLowerCase());
.toLowerCase()); this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toUpperCase());
.toLowerCase()); this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX
.toUpperCase());
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
.toUpperCase());
this.relationManagements = new HashMap<>(); this.relationManagements = new HashMap<>();
} }
protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) { protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) {
@ -69,24 +60,26 @@ public abstract class EntityManagement<E extends Entity> extends
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
/* /*
* It works perfectly in case of any kind of update. * It works perfectly in case of any kind of update. In case of use from create
* In case of use from create the cache does not work by using the ID because until commit the edge has a fake id * the cache does not work by using the ID because until commit the edge has a
* starting with - (minus) sign. This not imply any collateral effect but a better solution is a desiderata. * fake id starting with - (minus) sign. This not imply any collateral effect
* but a better solution is a desiderata.
*/ */
protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException { protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException {
String id = edge.getId().toString(); String id = edge.getId().toString();
RelationManagement relationManagement = relationManagements.get(id); RelationManagement relationManagement = relationManagements.get(id);
if(relationManagement==null) { if(relationManagement == null) {
relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
return relationManagement; return relationManagement;
} }
protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement) throws ResourceRegistryException { protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement)
throws ResourceRegistryException {
Element elem = relationManagement.getElement(); Element elem = relationManagement.getElement();
String id = elem.getId().toString(); String id = elem.getId().toString();
if(relationManagements.get(id)!=null && relationManagements.get(id)!=relationManagement) { if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Two different instance of "); errorMessage.append("Two different instance of ");
errorMessage.append(relationManagement.getClass().getSimpleName()); errorMessage.append(relationManagement.getClass().getSimpleName());
@ -99,142 +92,133 @@ public abstract class EntityManagement<E extends Entity> extends
relationManagements.put(id, relationManagement); relationManagements.put(id, relationManagement);
} }
protected static JSONObject addRelation(JSONObject sourceResource, protected static JSONObject addRelation(JSONObject sourceResource, JSONObject relation, String arrayKey)
JSONObject relation, String arrayKey)
throws ResourceRegistryException { throws ResourceRegistryException {
JSONArray relationArray = null; JSONArray relationArray = null;
try { try {
if (sourceResource.has(arrayKey)) { if(sourceResource.has(arrayKey)) {
relationArray = sourceResource.getJSONArray(arrayKey); relationArray = sourceResource.getJSONArray(arrayKey);
} else { } else {
relationArray = new JSONArray(); relationArray = new JSONArray();
} }
relationArray.put(relation); relationArray.put(relation);
sourceResource.putOpt(arrayKey, relationArray); sourceResource.putOpt(arrayKey, relationArray);
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
return sourceResource; return sourceResource;
} }
protected Vertex createVertex() throws EntityAlreadyPresentException, protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
logger.trace("Going to create {} for {} ({}) using {}", erType, jsonNode);
Vertex.class.getSimpleName(), accessType.getName(), erType, jsonNode);
try { try {
if(oClass.isAbstract()){ if(oClass.isAbstract()) {
String error = String.format("Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.", String error = String.format(
"Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
accessType.getName(), erType); accessType.getName(), erType);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
Vertex vertexEntity = orientGraph.addVertex("class:" + erType); Vertex vertexEntity = orientGraph.addVertex("class:" + erType);
try { try {
if(uuid!=null){ if(uuid != null) {
Vertex v = getElement(); Vertex v = getElement();
if (v != null) { if(v != null) {
String error = String.format( String error = String.format("A %s with UUID %s already exist", erType, uuid.toString());
"A %s with UUID %s already exist", erType,
uuid.toString());
throw getSpecificERAlreadyPresentException(error); throw getSpecificERAlreadyPresentException(error);
} }
} }
} catch (ERNotFoundException e) { } catch(ERNotFoundException e) {
try { try {
Element el = ERManagementUtility.getAnyElementByUUID(uuid); Element el = ERManagementUtility.getAnyElementByUUID(uuid);
String error = String.format( String error = String.format("UUID %s is already used by another %s. This is not allowed.",
"UUID %s is already used by another %s. This is not allowed.",
uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME); uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME);
throw getSpecificERAvailableInAnotherContextException(error); throw getSpecificERAvailableInAnotherContextException(error);
}catch (ERNotFoundException e1) { } catch(ERNotFoundException e1) {
// OK the UUID is not already used. // OK the UUID is not already used.
} }
} catch (ERAvailableInAnotherContextException e) { } catch(ERAvailableInAnotherContextException e) {
throw e; throw e;
} }
this.element = vertexEntity; this.element = vertexEntity;
if (accessType==AccessType.RESOURCE) { if(accessType == AccessType.RESOURCE) {
// Facet and relation are created in calling method // Facet and relation are created in calling method
} else { } else {
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
ignoreStartWithKeys);
} }
logger.info("Created {} is {}", Vertex.class.getSimpleName(), logger.info("Created {} is {}", Vertex.class.getSimpleName(),
Utility.toJsonString((OrientVertex) element, true)); Utility.toJsonString((OrientVertex) element, true));
return element; return element;
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
Vertex.class.getSimpleName(), accessType.getName(), erType, jsonNode, e); accessType.getName(), erType, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + erType throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause());
+ " with " + jsonNode, e.getCause());
} }
} }
@Override @Override
protected boolean reallyAddToContext() throws ContextException, protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException {
ResourceRegistryException {
getWorkingContext().addElement(getElement(), orientGraph); getWorkingContext().addElement(getElement(), orientGraph);
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
for (Edge edge : edges) { for(Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge); RelationManagement relationManagement = getRelationManagement(edge);
relationManagement.internalAddToContext(); relationManagement.internalAddToContext();
} }
return true; return true;
} }
@Override @Override
protected boolean reallyRemoveFromContext() throws ContextException, protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException {
ResourceRegistryException {
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
for (Edge edge : edges) { for(Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge); RelationManagement relationManagement = getRelationManagement(edge);
relationManagement.internalRemoveFromContext(); relationManagement.internalRemoveFromContext();
} }
getWorkingContext().removeElement(getElement(), orientGraph); getWorkingContext().removeElement(getElement(), orientGraph);
return true; return true;
} }
@Override @Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic); Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
for(Vertex vertex : iterable){ for(Vertex vertex : iterable) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, vertex);
try { try {
JSONObject jsonObject = entityManagement.serializeAsJson(); JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);
}catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
return jsonArray.toString(); return jsonArray.toString();
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.entity; package org.gcube.informationsystem.resourceregistry.er.entity;
import org.codehaus.jettison.json.JSONObject; import org.codehaus.jettison.json.JSONObject;
@ -11,7 +8,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
@ -19,10 +16,9 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*
*/ */
public class FacetManagement extends EntityManagement<Facet> { public class FacetManagement extends EntityManagement<Facet> {
public FacetManagement() { public FacetManagement() {
super(AccessType.FACET); super(AccessType.FACET);
} }
@ -60,7 +56,7 @@ public class FacetManagement extends EntityManagement<Facet> {
protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException { protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
return createVertex(); return createVertex();
} }
@Override @Override
protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException {
Vertex facet = getElement(); Vertex facet = getElement();
@ -73,5 +69,5 @@ public class FacetManagement extends EntityManagement<Facet> {
getElement().remove(); getElement().remove();
return true; return true;
} }
} }

View File

@ -15,8 +15,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement; import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement; import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
@ -40,13 +40,13 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class ResourceManagement extends EntityManagement<Resource> { public class ResourceManagement extends EntityManagement<Resource> {
public ResourceManagement() { public ResourceManagement() {
super(AccessType.RESOURCE); super(AccessType.RESOURCE);
} }
public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) { public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.RESOURCE, workingContext, orientGraph); super(AccessType.RESOURCE, workingContext, orientGraph);
} }
@Override @Override
@ -55,7 +55,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
} }
@Override @Override
protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message) { protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message) {
return new ResourceAvailableInAnotherContextException(message); return new ResourceAvailableInAnotherContextException(message);
} }
@ -68,33 +69,31 @@ public class ResourceManagement extends EntityManagement<Resource> {
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString(); return serializeAsJson().toString();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
JSONObject sourceResource = serializeSelfOnly(); JSONObject sourceResource = serializeSelfOnly();
/* /*
* Cannot get ConsistsOf edge only because is not polymorphic for a * Cannot get ConsistsOf edge only because is not polymorphic for a
* com.tinkerpop.blueprints.Vertex * com.tinkerpop.blueprints.Vertex vertex.getEdges(Direction.OUT,
* vertex.getEdges(Direction.OUT, ConsistsOf.NAME); * ConsistsOf.NAME); TODO Looks for a different query
* TODO Looks for a different query
*/ */
Iterable<Edge> edges = getElement().getEdges(Direction.OUT); Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
for (Edge edge : edges) { for(Edge edge : edges) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge); RelationManagement relationManagement = getRelationManagement(edge);
relationManagement.setReload(reload); relationManagement.setReload(reload);
if(relationManagement.giveMeSourceEntityManagementAsIs()==null) { if(relationManagement.giveMeSourceEntityManagementAsIs() == null) {
relationManagement.setSourceEntityManagement(this); relationManagement.setSourceEntityManagement(this);
} }
if(relationManagement.giveMeSourceEntityManagementAsIs() != this) {
if(relationManagement.giveMeSourceEntityManagementAsIs()!=this) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("SourceEntityManagement for "); errorMessage.append("SourceEntityManagement for ");
errorMessage.append(relationManagement.getClass().getSimpleName()); errorMessage.append(relationManagement.getClass().getSimpleName());
@ -103,53 +102,51 @@ public class ResourceManagement extends EntityManagement<Resource> {
throw new ResourceRegistryException(errorMessage.toString()); throw new ResourceRegistryException(errorMessage.toString());
} }
if (relationManagement instanceof ConsistsOfManagement) { if(relationManagement instanceof ConsistsOfManagement) {
try { try {
JSONObject consistsOf = relationManagement.serializeAsJson(true, true); JSONObject consistsOf = relationManagement.serializeAsJson(true, true);
sourceResource = addConsistsOf(sourceResource, consistsOf); sourceResource = addConsistsOf(sourceResource, consistsOf);
}catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e; throw e;
}catch (Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
/* /*
* This comment is just to show that IsRelatedTo is not serialized * This comment is just to show that IsRelatedTo is not serialized by default as
* by default as design choice and not because forget * design choice and not because forget
* *
* else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ * else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ JSONObject
* JSONObject isRelatedTo = relationManagement.serializeAsJson(true, true); * isRelatedTo = relationManagement.serializeAsJson(true, true); sourceResource
* sourceResource = addIsRelatedTo(sourceResource, isRelatedTo); * = addIsRelatedTo(sourceResource, isRelatedTo); }
* }
*/ */
} }
return sourceResource; return sourceResource;
} }
public static JSONObject addConsistsOf(JSONObject sourceResource, public static JSONObject addConsistsOf(JSONObject sourceResource, JSONObject consistsOf)
JSONObject consistsOf) throws ResourceRegistryException { throws ResourceRegistryException {
return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter()); return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter());
} }
public static JSONObject addIsRelatedTo(JSONObject sourceResource, public static JSONObject addIsRelatedTo(JSONObject sourceResource, JSONObject isRelatedTo)
JSONObject isRelatedTo) throws ResourceRegistryException { throws ResourceRegistryException {
return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter()); return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter());
} }
@Override @Override
protected Vertex reallyCreate() throws ResourceAlreadyPresentException, protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
ResourceRegistryException {
createVertex(); createVertex();
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter(); String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode consistOfJsonNode : jsonNodeArray) { for(JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(consistOfJsonNode); com.setJSON(consistOfJsonNode);
com.setSourceEntityManagement(this); com.setSourceEntityManagement(this);
@ -157,11 +154,11 @@ public class ResourceManagement extends EntityManagement<Resource> {
addToRelationManagement(com); addToRelationManagement(com);
} }
} }
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter(); property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
irtm.setJSON(relationJsonNode); irtm.setJSON(relationJsonNode);
irtm.setSourceEntityManagement(this); irtm.setSourceEntityManagement(this);
@ -169,95 +166,92 @@ public class ResourceManagement extends EntityManagement<Resource> {
addToRelationManagement(irtm); addToRelationManagement(irtm);
} }
} }
return element; return element;
} }
@Override @Override
protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException { protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
getElement(); getElement();
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter(); String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for(JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph); ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(relationJsonNode); com.setJSON(relationJsonNode);
com.internalCreateOrUdate(); com.internalCreateOrUdate();
addToRelationManagement(com); addToRelationManagement(com);
} }
} }
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter(); property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
if (jsonNode.has(property)) { if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property); JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) { for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph); IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
irtm.setJSON(relationJsonNode); irtm.setJSON(relationJsonNode);
irtm.internalUpdate(); irtm.internalUpdate();
addToRelationManagement(irtm); addToRelationManagement(irtm);
} }
} }
return element; return element;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
protected boolean reallyDelete() throws ResourceNotFoundException, protected boolean reallyDelete() throws ResourceNotFoundException, ResourceRegistryException {
ResourceRegistryException {
// internalDeleteResource(orientGraph, uuid, null); // internalDeleteResource(orientGraph, uuid, null);
getElement(); getElement();
Iterable<Edge> iterable = element.getEdges(Direction.OUT); Iterable<Edge> iterable = element.getEdges(Direction.OUT);
Iterator<Edge> iterator = iterable.iterator(); Iterator<Edge> iterator = iterable.iterator();
while (iterator.hasNext()) { while(iterator.hasNext()) {
Edge edge = iterator.next(); Edge edge = iterator.next();
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType(); OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
RelationManagement relationManagement = null; RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) { if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph); relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph);
} else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) { } else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph); relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph);
} else { } else {
logger.warn("{} is not a {} nor a {}. {}", logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME,
Utility.toJsonString(edge, true), IsRelatedTo.NAME,
ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
if (relationManagement != null) { if(relationManagement != null) {
relationManagement.setElement(edge); relationManagement.setElement(edge);
relationManagement.internalDelete(); relationManagement.internalDelete();
} }
} }
element.remove(); element.remove();
return true; return true;
} }
public String all(boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
public String all(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAll(polymorphic, constraint); return reallyGetAll(polymorphic, constraint);
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if (orientGraph != null) { if(orientGraph != null) {
orientGraph.shutdown(); orientGraph.shutdown();
} }
} }
} }
public String reallyGetAll(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException{ public String reallyGetAll(boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART); String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART);
@ -267,11 +261,11 @@ public class ResourceManagement extends EntityManagement<Resource> {
// TODO check types // TODO check types
/* /*
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') * SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
* FROM (SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor')) * FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
* *
* WHERE @class='EService' // Only is not polymorphic * WHERE @class='EService' // Only is not polymorphic
*/ */
boolean first = true; boolean first = true;
@ -282,11 +276,11 @@ public class ResourceManagement extends EntityManagement<Resource> {
selectStringBuilder.append(erType); selectStringBuilder.append(erType);
selectStringBuilder.append("') FROM (SELECT FROM "); selectStringBuilder.append("') FROM (SELECT FROM ");
selectStringBuilder.append(facetType); selectStringBuilder.append(facetType);
for(String key : constraint.keySet()){ for(String key : constraint.keySet()) {
if(first){ if(first) {
selectStringBuilder.append(" WHERE "); selectStringBuilder.append(" WHERE ");
first = false; first = false;
}else{ } else {
selectStringBuilder.append(" AND "); selectStringBuilder.append(" AND ");
} }
selectStringBuilder.append(key); selectStringBuilder.append(key);
@ -297,64 +291,59 @@ public class ResourceManagement extends EntityManagement<Resource> {
selectStringBuilder.append("'"); selectStringBuilder.append("'");
} }
selectStringBuilder.append(" ))"); selectStringBuilder.append(" ))");
if(!polymorphic){ if(!polymorphic) {
selectStringBuilder.append(" WHERE @class='"); selectStringBuilder.append(" WHERE @class='");
selectStringBuilder.append(erType); selectStringBuilder.append(erType);
selectStringBuilder.append("'"); selectStringBuilder.append("'");
} }
String select = selectStringBuilder.toString(); String select = selectStringBuilder.toString();
logger.trace(select); logger.trace(select);
OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>( OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>(select);
select); Iterable<Element> elements = orientGraph.command(osqlSynchQuery).execute();
Iterable<Element> elements = orientGraph.command(osqlSynchQuery)
.execute();
for(Element element : elements){ for(Element element : elements) {
if(polymorphic){ if(polymorphic) {
OrientVertexType orientVertexType = null; OrientVertexType orientVertexType = null;
try { try {
OrientElement orientElement = ((OrientElement) element); OrientElement orientElement = ((OrientElement) element);
if(orientElement instanceof OrientEdge){ if(orientElement instanceof OrientEdge) {
continue; continue;
} }
orientVertexType = ((OrientVertex) orientElement).getType(); orientVertexType = ((OrientVertex) orientElement).getType();
}catch (Exception e) { } catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", String error = String.format("Unable to detect type of %s. %s", element.toString(),
element.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e); logger.error(error, e);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
if(orientVertexType.getName().compareTo(erType)!=0){ if(orientVertexType.getName().compareTo(erType) != 0) {
if(!orientVertexType.isSubClassOf(erType) ) { if(!orientVertexType.isSubClassOf(erType)) {
continue; continue;
} }
} }
} }
Vertex vertex = (Vertex) element; Vertex vertex = (Vertex) element;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex); EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, vertex);
try { try {
JSONObject jsonObject = entityManagement.serializeAsJson(); JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject); jsonArray.put(jsonObject);
}catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}", logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
return jsonArray.toString(); return jsonArray.toString();
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.relation; package org.gcube.informationsystem.resourceregistry.er.relation;
import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.AccessType;
@ -10,7 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -20,21 +17,21 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ConsistsOfManagement extends RelationManagement<ConsistsOf, ResourceManagement, FacetManagement> { public class ConsistsOfManagement extends RelationManagement<ConsistsOf,ResourceManagement,FacetManagement> {
public ConsistsOfManagement() { public ConsistsOfManagement() {
super(AccessType.CONSISTS_OF); super(AccessType.CONSISTS_OF);
} }
public ConsistsOfManagement(SecurityContext workingContext, OrientGraph orientGraph) { public ConsistsOfManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.CONSISTS_OF, workingContext, orientGraph); super(AccessType.CONSISTS_OF, workingContext, orientGraph);
} }
@Override @Override
protected ConsistsOfNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { protected ConsistsOfNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) {
return new ConsistsOfNotFoundException(e.getMessage(), e.getCause()); return new ConsistsOfNotFoundException(e.getMessage(), e.getCause());
} }
@Override @Override
protected ConsistsOfAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( protected ConsistsOfAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message) { String message) {
@ -50,10 +47,10 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf, Resourc
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(getWorkingContext(), orientGraph); return new ResourceManagement(getWorkingContext(), orientGraph);
} }
@Override @Override
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException { protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
return new FacetManagement(getWorkingContext(), orientGraph); return new FacetManagement(getWorkingContext(), orientGraph);
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.relation; package org.gcube.informationsystem.resourceregistry.er.relation;
import org.gcube.informationsystem.model.AccessType; import org.gcube.informationsystem.model.AccessType;
@ -10,7 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph;
@ -19,40 +16,40 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, ResourceManagement, ResourceManagement> { public class IsRelatedToManagement extends RelationManagement<IsRelatedTo,ResourceManagement,ResourceManagement> {
public IsRelatedToManagement() { public IsRelatedToManagement() {
super(AccessType.IS_RELATED_TO); super(AccessType.IS_RELATED_TO);
} }
public IsRelatedToManagement(SecurityContext workingContext, OrientGraph orientGraph) { public IsRelatedToManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.IS_RELATED_TO, workingContext, orientGraph); super(AccessType.IS_RELATED_TO, workingContext, orientGraph);
} }
@Override @Override
protected IsRelatedToNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) { protected IsRelatedToNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) {
return new IsRelatedToNotFoundException(e.getMessage(), e.getCause()); return new IsRelatedToNotFoundException(e.getMessage(), e.getCause());
} }
@Override @Override
protected IsRelatedToAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException( protected IsRelatedToAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message) { String message) {
return new IsRelatedToAvailableInAnotherContextException(message); return new IsRelatedToAvailableInAnotherContextException(message);
} }
@Override @Override
protected IsRelatedToAlreadyPresentException getSpecificERAlreadyPresentException(String message) { protected IsRelatedToAlreadyPresentException getSpecificERAlreadyPresentException(String message) {
return new IsRelatedToAlreadyPresentException(message); return new IsRelatedToAlreadyPresentException(message);
} }
@Override @Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException { protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(getWorkingContext(), orientGraph); return new ResourceManagement(getWorkingContext(), orientGraph);
} }
@Override @Override
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException { protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(getWorkingContext(), orientGraph); return new ResourceManagement(getWorkingContext(), orientGraph);
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.relation; package org.gcube.informationsystem.resourceregistry.er.relation;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,8 +24,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagement; import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility; import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement; import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
@ -49,16 +46,16 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public abstract class RelationManagement<R extends Relation, S extends EntityManagement, T extends EntityManagement> public abstract class RelationManagement<R extends Relation, S extends EntityManagement, T extends EntityManagement>
extends ERManagement<R, Edge> { extends ERManagement<R,Edge> {
protected final Class<? extends Entity> targetEntityClass; protected final Class<? extends Entity> targetEntityClass;
protected S sourceEntityManagement; protected S sourceEntityManagement;
protected T targetEntityManagement; protected T targetEntityManagement;
protected RelationManagement(AccessType accessType) { protected RelationManagement(AccessType accessType) {
super(accessType); super(accessType);
this.ignoreKeys.add(Relation.HEADER_PROPERTY); this.ignoreKeys.add(Relation.HEADER_PROPERTY);
this.ignoreKeys.add(Relation.TARGET_PROPERTY); this.ignoreKeys.add(Relation.TARGET_PROPERTY);
this.ignoreKeys.add(Relation.SOURCE_PROPERTY); this.ignoreKeys.add(Relation.SOURCE_PROPERTY);
@ -66,35 +63,36 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toLowerCase()); this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toLowerCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase()); this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase()); this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase());
switch (accessType) { switch(accessType) {
case CONSISTS_OF: case CONSISTS_OF:
this.targetEntityClass = Facet.class; this.targetEntityClass = Facet.class;
break; break;
case IS_RELATED_TO: case IS_RELATED_TO:
this.targetEntityClass = Resource.class; this.targetEntityClass = Resource.class;
break; break;
default: default:
this.targetEntityClass = Resource.class; this.targetEntityClass = Resource.class;
break; break;
} }
sourceEntityManagement = null; sourceEntityManagement = null;
targetEntityManagement = null; targetEntityManagement = null;
} }
protected RelationManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) { protected RelationManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) {
this(accessType); this(accessType);
this.orientGraph = orientGraph; this.orientGraph = orientGraph;
setWorkingContext(workingContext); setWorkingContext(workingContext);
} }
/* /*
* Needed for ResourceManagement.serializeAsJson() function to check that sourceEntityManagement is the same of * Needed for ResourceManagement.serializeAsJson() function to check that
* the instance is creating this RelationManagement. TODO Look for a workaround * sourceEntityManagement is the same of the instance is creating this
* RelationManagement. TODO Look for a workaround
*/ */
public S giveMeSourceEntityManagementAsIs() throws ResourceRegistryException { public S giveMeSourceEntityManagementAsIs() throws ResourceRegistryException {
return sourceEntityManagement; return sourceEntityManagement;
@ -102,7 +100,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public S getSourceEntityManagement() throws ResourceRegistryException { public S getSourceEntityManagement() throws ResourceRegistryException {
if (sourceEntityManagement == null) { if(sourceEntityManagement == null) {
Vertex source = getElement().getVertex(Direction.OUT); Vertex source = getElement().getVertex(Direction.OUT);
sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElement(source); sourceEntityManagement.setElement(source);
@ -110,10 +108,10 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
sourceEntityManagement.setReload(reload); sourceEntityManagement.setReload(reload);
return sourceEntityManagement; return sourceEntityManagement;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T getTargetEntityManagement() throws ResourceRegistryException { public T getTargetEntityManagement() throws ResourceRegistryException {
if (targetEntityManagement == null) { if(targetEntityManagement == null) {
Vertex target = getElement().getVertex(Direction.IN); Vertex target = getElement().getVertex(Direction.IN);
targetEntityManagement = newTargetEntityManagement(); targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElement(target); targetEntityManagement.setElement(target);
@ -121,119 +119,117 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
targetEntityManagement.setReload(reload); targetEntityManagement.setReload(reload);
return targetEntityManagement; return targetEntityManagement;
} }
public void setSourceEntityManagement(S sourceEntityManagement) { public void setSourceEntityManagement(S sourceEntityManagement) {
this.sourceEntityManagement = sourceEntityManagement; this.sourceEntityManagement = sourceEntityManagement;
} }
public void setTargetEntityManagement(T targetEntityManagement) { public void setTargetEntityManagement(T targetEntityManagement) {
this.targetEntityManagement = targetEntityManagement; this.targetEntityManagement = targetEntityManagement;
} }
@Override @Override
public String serialize() throws ResourceRegistryException { public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString(); return serializeAsJson().toString();
} }
@Override @Override
public JSONObject serializeAsJson() throws ResourceRegistryException { public JSONObject serializeAsJson() throws ResourceRegistryException {
return serializeAsJson(true, true); return serializeAsJson(true, true);
} }
public JSONObject serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException { public JSONObject serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException {
JSONObject relation = serializeSelfOnly(); JSONObject relation = serializeSelfOnly();
try { try {
if (includeSource) { if(includeSource) {
EntityManagement sourceEntityManagement = getSourceEntityManagement(); EntityManagement sourceEntityManagement = getSourceEntityManagement();
relation.put(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly()); relation.put(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly());
} }
if (includeTarget) { if(includeTarget) {
EntityManagement targetEntityManagement = getTargetEntityManagement(); EntityManagement targetEntityManagement = getTargetEntityManagement();
relation.put(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson()); relation.put(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson());
} }
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e); logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
return relation; return relation;
} }
protected Map<String, JSONObject> fullSerialize(Map<String, JSONObject> visitedSourceResources) protected Map<String,JSONObject> fullSerialize(Map<String,JSONObject> visitedSourceResources)
throws ResourceRegistryException { throws ResourceRegistryException {
Vertex source = getElement().getVertex(Direction.OUT); Vertex source = getElement().getVertex(Direction.OUT);
String id = source.getId().toString(); String id = source.getId().toString();
JSONObject sourceResource = visitedSourceResources.get(id); JSONObject sourceResource = visitedSourceResources.get(id);
ResourceManagement resourceManagement = null; ResourceManagement resourceManagement = null;
if (sourceResource == null) { if(sourceResource == null) {
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, source); resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(),
if (this instanceof IsRelatedToManagement) { orientGraph, source);
if(this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.serializeAsJson(); sourceResource = resourceManagement.serializeAsJson();
} else if (this instanceof ConsistsOfManagement) { } else if(this instanceof ConsistsOfManagement) {
sourceResource = resourceManagement.serializeSelfOnly(); sourceResource = resourceManagement.serializeSelfOnly();
} else { } else {
String error = String.format( String error = String.format("{%s is not a %s nor a %s. %s", this,
"{%s is not a %s nor a %s. %s", IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} }
if (this instanceof IsRelatedToManagement) { if(this instanceof IsRelatedToManagement) {
sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson()); sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson());
} else if (this instanceof ConsistsOfManagement) { } else if(this instanceof ConsistsOfManagement) {
sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson()); sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson());
} else { } else {
String error = String.format( String error = String.format("{%s is not a %s nor a %s. %s", this,
"{%s is not a %s nor a %s. %s", IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
visitedSourceResources.put(id, sourceResource); visitedSourceResources.put(id, sourceResource);
return visitedSourceResources; return visitedSourceResources;
} }
@Override @Override
protected Edge reallyCreate() throws ResourceRegistryException { protected Edge reallyCreate() throws ResourceRegistryException {
if (sourceEntityManagement == null) { if(sourceEntityManagement == null) {
if (!jsonNode.has(Relation.SOURCE_PROPERTY)) { if(!jsonNode.has(Relation.SOURCE_PROPERTY)) {
throw new ResourceRegistryException("Error while creating relation. No source definition found"); throw new ResourceRegistryException("Error while creating relation. No source definition found");
} }
UUID sourceUUID = org.gcube.informationsystem.impl.utils.Utility UUID sourceUUID = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY)); .getUUIDFromJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY));
sourceEntityManagement = newSourceEntityManagement(); sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setUUID(sourceUUID); sourceEntityManagement.setUUID(sourceUUID);
} }
if (targetEntityManagement == null) { if(targetEntityManagement == null) {
targetEntityManagement = newTargetEntityManagement(); targetEntityManagement = newTargetEntityManagement();
if (!jsonNode.has(Relation.TARGET_PROPERTY)) { if(!jsonNode.has(Relation.TARGET_PROPERTY)) {
throw new ResourceRegistryException("Error while creating " + erType + ". No target definition found"); throw new ResourceRegistryException("Error while creating " + erType + ". No target definition found");
} }
try { try {
targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY)); targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
} catch (SchemaException e) { } catch(SchemaException e) {
StringBuilder errorMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder();
errorMessage.append("A "); errorMessage.append("A ");
errorMessage.append(erType); errorMessage.append(erType);
@ -243,347 +239,342 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
errorMessage.append(targetEntityManagement.getAccessType().getName()); errorMessage.append(targetEntityManagement.getAccessType().getName());
throw new ResourceRegistryException(errorMessage.toString(), e); throw new ResourceRegistryException(errorMessage.toString(), e);
} }
try { try {
targetEntityManagement.getElement(); targetEntityManagement.getElement();
} catch (Exception e) { } catch(Exception e) {
targetEntityManagement.internalCreate(); targetEntityManagement.internalCreate();
} }
} }
logger.trace("Creating {} beetween {} -> {}", erType, getSourceEntityManagement().serialize(), logger.trace("Creating {} beetween {} -> {}", erType, getSourceEntityManagement().serialize(),
getTargetEntityManagement().serialize()); getTargetEntityManagement().serialize());
Vertex source = (Vertex) getSourceEntityManagement().getElement(); Vertex source = (Vertex) getSourceEntityManagement().getElement();
Vertex target = (Vertex) getTargetEntityManagement().getElement(); Vertex target = (Vertex) getTargetEntityManagement().getElement();
element = orientGraph.addEdge(null, source, target, erType); element = orientGraph.addEdge(null, source, target, erType);
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.info("{} successfully created", erType); logger.info("{} successfully created", erType);
return element; return element;
} }
protected abstract S newSourceEntityManagement() throws ResourceRegistryException; protected abstract S newSourceEntityManagement() throws ResourceRegistryException;
protected abstract T newTargetEntityManagement() throws ResourceRegistryException; protected abstract T newTargetEntityManagement() throws ResourceRegistryException;
@Override @Override
protected Edge reallyUpdate() throws ResourceRegistryException { protected Edge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", erType, jsonNode); logger.debug("Trying to update {} : {}", erType, jsonNode);
Edge edge = getElement(); Edge edge = getElement();
ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys); ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) { if(accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY); JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if (target != null) { if(target != null) {
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph); FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph);
fm.setJSON(target); fm.setJSON(target);
fm.internalUpdate(); fm.internalUpdate();
} }
} }
logger.info("{} {} successfully updated", erType, jsonNode); logger.info("{} {} successfully updated", erType, jsonNode);
return edge; return edge;
} }
@Override @Override
protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException { protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException {
getElement(); getElement();
AddConstraint addConstraint = AddConstraint.unpropagate; AddConstraint addConstraint = AddConstraint.unpropagate;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element, PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getAddConstraint() != null) { if(propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint(); addConstraint = propagationConstraint.getAddConstraint();
} else { } else {
String error = String.format( String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
"%s.%s in %s is null. %s", PropagationConstraint.ADD_PROPERTY, Utility.toJsonString(element, true),
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.ADD_PROPERTY, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch (Exception e) { } catch(Exception e) {
String error = String.format( String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
"Error while getting %s from %s while performing AddToContext. %s", Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error); logger.warn(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
} }
switch (addConstraint) { switch(addConstraint) {
case propagate: case propagate:
/* /*
* The relation must be added only in the case the target vertex must be added. * The relation must be added only in the case the target vertex must be added.
* Otherwise we have a relation which point to an entity outside of the context. * Otherwise we have a relation which point to an entity outside of the context.
*/ */
getTargetEntityManagement().internalAddToContext(); getTargetEntityManagement().internalAddToContext();
getWorkingContext().addElement(getElement(), orientGraph); getWorkingContext().addElement(getElement(), orientGraph);
break; break;
case unpropagate: case unpropagate:
break; break;
default: default:
break; break;
} }
return true; return true;
} }
public boolean forcedAddToContext() throws ContextException, ResourceRegistryException { public boolean forcedAddToContext() throws ContextException, ResourceRegistryException {
getElement(); getElement();
/* Adding source to Context */ /* Adding source to Context */
getSourceEntityManagement().internalAddToContext(); getSourceEntityManagement().internalAddToContext();
/* Adding target to Context */ /* Adding target to Context */
getTargetEntityManagement().internalAddToContext(); getTargetEntityManagement().internalAddToContext();
getWorkingContext().addElement(getElement(), orientGraph); getWorkingContext().addElement(getElement(), orientGraph);
return true; return true;
} }
@Override @Override
protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException { protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException {
getElement(); getElement();
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element, PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) { if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
} else { } else {
String error = String.format( String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
"%s.%s in %s is null. %s", PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch (Exception e) { } catch(Exception e) {
String error = String.format( String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
"Error while getting %s from %s while performing RemoveFromContext. %s", Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error, e); throw new ResourceRegistryException(error, e);
} }
/* /*
* In any removeConstraint value the relation MUST be removed from context to * In any removeConstraint value the relation MUST be removed from context to
* avoid to have edge having a source outside of the context. * avoid to have edge having a source outside of the context.
*/ */
getWorkingContext().removeElement(getElement(), orientGraph); getWorkingContext().removeElement(getElement(), orientGraph);
switch (removeConstraint) { switch(removeConstraint) {
case cascade: case cascade:
getTargetEntityManagement().internalRemoveFromContext();
break;
case cascadeWhenOrphan:
Vertex target = (Vertex) getTargetEntityManagement().getElement();
Iterable<Edge> iterable = target.getEdges(Direction.IN);
Iterator<Edge> iterator = iterable.iterator();
int count = 0;
OrientEdge edge = null;
while (iterator.hasNext()) {
edge = (OrientEdge) iterator.next();
OrientEdge thisOrientEdge = (OrientEdge) getElement();
if (edge.compareTo(thisOrientEdge) != 0) {
if (thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
count++;
break;
}
/*
* else{ ContextUtility.removeFromActualContext(orientGraph, edge); }
*/
}
}
if (count > 0) {
logger.trace(
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.",
element, target, edge, removeConstraint);
} else {
getTargetEntityManagement().internalRemoveFromContext(); getTargetEntityManagement().internalRemoveFromContext();
} break;
break;
case cascadeWhenOrphan:
case keep: Vertex target = (Vertex) getTargetEntityManagement().getElement();
break;
Iterable<Edge> iterable = target.getEdges(Direction.IN);
default: Iterator<Edge> iterator = iterable.iterator();
break; int count = 0;
OrientEdge edge = null;
while(iterator.hasNext()) {
edge = (OrientEdge) iterator.next();
OrientEdge thisOrientEdge = (OrientEdge) getElement();
if(edge.compareTo(thisOrientEdge) != 0) {
if(thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
count++;
break;
}
/*
* else{ ContextUtility.removeFromActualContext(orientGraph, edge); }
*/
}
}
if(count > 0) {
logger.trace(
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.",
element, target, edge, removeConstraint);
} else {
getTargetEntityManagement().internalRemoveFromContext();
}
break;
case keep:
break;
default:
break;
} }
return true; return true;
} }
@Override @Override
protected boolean reallyDelete() throws RelationNotFoundException, ResourceRegistryException { protected boolean reallyDelete() throws RelationNotFoundException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {}. Related {}s will be detached.", accessType.getName(), uuid, logger.debug("Going to remove {} with UUID {}. Related {}s will be detached.", accessType.getName(), uuid,
targetEntityClass.getSimpleName()); targetEntityClass.getSimpleName());
getElement(); getElement();
RemoveConstraint removeConstraint = RemoveConstraint.keep; RemoveConstraint removeConstraint = RemoveConstraint.keep;
try { try {
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element, PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT); Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) { if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint(); removeConstraint = propagationConstraint.getRemoveConstraint();
} else { } else {
String error = String.format( String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
"%s.%s in %s is null. %s", PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error); logger.error(error);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
} catch (Exception e) { } catch(Exception e) {
logger.warn( logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT,
"Error while getting {} from {}. Assuming {}. {}", Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), removeConstraint,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
Vertex target = (Vertex) getTargetEntityManagement().getElement(); Vertex target = (Vertex) getTargetEntityManagement().getElement();
element.remove(); element.remove();
switch (removeConstraint) { switch(removeConstraint) {
case cascade: case cascade:
getTargetEntityManagement().internalDelete();
break;
case cascadeWhenOrphan:
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.", element,
target, removeConstraint);
} else {
getTargetEntityManagement().internalDelete(); getTargetEntityManagement().internalDelete();
} break;
break;
case cascadeWhenOrphan:
case keep: Iterable<Edge> iterable = target.getEdges(Direction.IN);
break; Iterator<Edge> iterator = iterable.iterator();
if(iterator.hasNext()) {
default: logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
break; target, removeConstraint);
} else {
getTargetEntityManagement().internalDelete();
}
break;
case keep:
break;
default:
break;
} }
return true; return true;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic) protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException { throws ResourceRegistryException {
Map<String, JSONObject> visitedSourceResources = new HashMap<>(); Map<String,JSONObject> visitedSourceResources = new HashMap<>();
for (Edge edge : edges) { for(Edge edge : edges) {
if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) { if(postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
continue; continue;
} }
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge); RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(),
orientGraph, edge);
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
} }
return visitedSourceResources.values(); return visitedSourceResources.values();
} }
protected String serializeJSONObjectList(Collection<JSONObject> list) { protected String serializeJSONObjectList(Collection<JSONObject> list) {
JSONArray jsonArray = new JSONArray(list); JSONArray jsonArray = new JSONArray(list);
return jsonArray.toString(); return jsonArray.toString();
} }
@Override @Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
Iterable<Edge> edges = orientGraph.getEdgesOfClass(erType, polymorphic); Iterable<Edge> edges = orientGraph.getEdgesOfClass(erType, polymorphic);
Collection<JSONObject> collection = serializeEdges(edges, false); Collection<JSONObject> collection = serializeEdges(edges, false);
return serializeJSONObjectList(collection); return serializeJSONObjectList(collection);
} }
public String reallyGetAllFrom(UUID uuid, Direction direction, boolean polymorphic) public String reallyGetAllFrom(UUID uuid, Direction direction, boolean polymorphic)
throws ResourceRegistryException { throws ResourceRegistryException {
EntityManagement entityManagement = null; EntityManagement entityManagement = null;
try { try {
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), orientGraph, uuid); entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(),
} catch (ResourceRegistryException e) { orientGraph, uuid);
} catch(ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME)); String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME));
} }
Vertex vertex = (Vertex) entityManagement.getElement(); Vertex vertex = (Vertex) entityManagement.getElement();
List<JSONObject> list = new ArrayList<>(); List<JSONObject> list = new ArrayList<>();
Iterable<Edge> edges = vertex.getEdges(direction, erType); Iterable<Edge> edges = vertex.getEdges(direction, erType);
list.addAll(serializeEdges(edges, !polymorphic)); list.addAll(serializeEdges(edges, !polymorphic));
return serializeJSONObjectList(list); return serializeJSONObjectList(list);
} }
public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException { public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException {
try { try {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER); orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAllFrom(uuid, direction, polymorphic); return reallyGetAllFrom(uuid, direction, polymorphic);
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} finally { } finally {
if (orientGraph != null) { if(orientGraph != null) {
orientGraph.shutdown(); orientGraph.shutdown();
} }
} }
} }
@Override @Override
public boolean addToContext() throws ERNotFoundException, ContextException { public boolean addToContext() throws ERNotFoundException, ContextException {
logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid); logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid);
try { try {
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER); orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean added = forcedAddToContext(); boolean added = forcedAddToContext();
orientGraph.commit(); orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid); logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
return added; return added;
} catch (Exception e) { } catch(Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e); logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
if (orientGraph != null) { if(orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }
throw new ContextException(e); throw new ContextException(e);
} finally { } finally {
if (orientGraph != null) { if(orientGraph != null) {
orientGraph.shutdown(); orientGraph.shutdown();
} }
} }
} }
} }

View File

@ -1,26 +1,21 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.query; package org.gcube.informationsystem.resourceregistry.query;
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*
*/ */
public interface Query { public interface Query {
/** /**
* @param query * @param query
* @param limit * @param limit
* @param fetchPlan * @param fetchPlan
* @return * @return
* @throws InvalidQueryException * @throws InvalidQueryException
* http://orientdb.com/docs/last/OrientDB-REST.html#query * http://orientdb.com/docs/last/OrientDB-REST.html#query
*/ */
public String query(String query, Integer limit, String fetchPlan) public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException;
throws InvalidQueryException;
public String gremlinQuery(String query) throws InvalidQueryException; public String gremlinQuery(String query) throws InvalidQueryException;

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.query; package org.gcube.informationsystem.resourceregistry.query;
import java.io.StringWriter; import java.io.StringWriter;
@ -10,8 +7,8 @@ import java.util.List;
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.utils.Utility; import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -22,116 +19,20 @@ import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*
*/ */
public class QueryImpl implements Query { public class QueryImpl implements Query {
private static Logger logger = LoggerFactory.getLogger(QueryImpl.class); private static Logger logger = LoggerFactory.getLogger(QueryImpl.class);
/*
private static final String QUERY = "query/";
private static final String SQL = "sql/";
private static final String DEFAULT_LIMIT = DEFAULT_LIMIT_INT + "/";
private static final URL BASE_QUERY_URL;
static {
try {
URL url = new URL(DatabaseEnvironment.HTTP_URL_STRINGS[0]);
URL urlQuery = new URL(url, QUERY);
URL urlDB = new URL(urlQuery, DatabaseEnvironment.DB + "/");
BASE_QUERY_URL = new URL(urlDB, SQL);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void checkStatus(HttpURLConnection connection) throws Exception {
int statusCode = connection.getResponseCode();
switch (statusCode) {
case 200:
case 201:
return;
default:
throw new Exception(connection.getResponseMessage());
}
}
@Override
public String execute(String query, String fetchPlan)
throws InvalidQueryException {
String readerUsername;
try {
readerUsername = ContextUtility.getActualSecurityRoleOrUserName(SecurityContextMapper.PermissionMode.READER, SecurityContextMapper.SecurityType.USER);
} catch (ContextException e1) {
throw new RuntimeException(e1);
}
logger.trace("Reader Username : {}", readerUsername);
try {
URL queryURL = new URL(BASE_QUERY_URL, URLEncoder.encode(query,
"UTF-8") + "/");
/ *
if (limit != null && limit > 0) {
queryURL = new URL(queryURL, limit.toString() + "/");
} else {
queryURL = new URL(queryURL, DEFAULT_LIMIT);
}
* /
queryURL = new URL(queryURL, DEFAULT_LIMIT);
if (fetchPlan != null && fetchPlan.compareTo("") != 0) {
queryURL = new URL(queryURL, fetchPlan + "/");
}
logger.debug("Connecting to {}", queryURL.toString());
HttpURLConnection connection = (HttpURLConnection) queryURL
.openConnection();
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER);
String authString = String.format("%s:%s", readerUsername, password);
byte[] authEncBytes = Base64.encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
connection.setRequestProperty("Authorization", "Basic "
+ authStringEnc);
connection.setRequestMethod(HTTPMethods.GET.toString());
connection.connect();
checkStatus(connection);
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString("UTF-8");
} catch (Exception e) {
throw new InvalidQueryException(e.getMessage(), e);
}
}
*/
@Override @Override
public String query(String query, Integer limit, String fetchPlan) public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException {
throws InvalidQueryException { if(limit == null) {
if(limit == null){
limit = AccessPath.DEFAULT_LIMIT; limit = AccessPath.DEFAULT_LIMIT;
} }
limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit; limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit;
ODatabaseDocumentTx oDatabaseDocumentTx = null; ODatabaseDocumentTx oDatabaseDocumentTx = null;
try { try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext(); SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
@ -140,47 +41,45 @@ public class QueryImpl implements Query {
OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit); OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit);
osqlSynchQuery.setFetchPlan(fetchPlan); osqlSynchQuery.setFetchPlan(fetchPlan);
osqlSynchQuery.setCacheableResult(true); osqlSynchQuery.setCacheableResult(true);
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(),
osqlSynchQuery.getText(), osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit());
osqlSynchQuery.getLimit());
List<Object> records = oDatabaseDocumentTx.query(osqlSynchQuery); List<Object> records = oDatabaseDocumentTx.query(osqlSynchQuery);
Writer writer = new StringWriter();
writer.append("{\"result\":[");
for(int i=0; i<records.size(); i++){
ODocument oDocument = (ODocument) records.get(i);
writer.append(Utility.toJsonString(oDocument, false));
if( i<(records.size()-1) ){
writer.append(",");
}
}
writer.append("]}");
return writer.toString();
} catch (Exception e) { Writer writer = new StringWriter();
writer.append("{\"result\":[");
for(int i = 0; i < records.size(); i++) {
ODocument oDocument = (ODocument) records.get(i);
writer.append(Utility.toJsonString(oDocument, false));
if(i < (records.size() - 1)) {
writer.append(",");
}
}
writer.append("]}");
return writer.toString();
} catch(Exception e) {
throw new InvalidQueryException(e.getMessage()); throw new InvalidQueryException(e.getMessage());
} finally { } finally {
if (oDatabaseDocumentTx != null) { if(oDatabaseDocumentTx != null) {
oDatabaseDocumentTx.close(); oDatabaseDocumentTx.close();
} }
} }
} }
@Override @Override
public String gremlinQuery(String query) throws InvalidQueryException { public String gremlinQuery(String query) throws InvalidQueryException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
/* /*
OGremlinHelper.global().create(); OGremlinHelper.global().create();
ODatabaseDocumentTx oDatabaseDocumentTx = null; ODatabaseDocumentTx oDatabaseDocumentTx = null;
try { try {
oDatabaseDocumentTx = ContextUtility oDatabaseDocumentTx = ContextUtility.getActualSecurityContextDatabaseTx(PermissionMode.READER);
.getActualSecurityContextDatabaseTx(PermissionMode.READER);
String finalQuery = String.format("select gremlin('%s')", query); String finalQuery = String.format("select gremlin('%s')", query);
OCommandSQL OCommandSQL = new OCommandSQL(finalQuery); OCommandSQL OCommandSQL = new OCommandSQL(finalQuery);
@ -189,22 +88,21 @@ public class QueryImpl implements Query {
Iterator iterator = res.iterator(); Iterator iterator = res.iterator();
while(iterator.hasNext()){ while(iterator.hasNext()) {
ODocument oDocument = (ODocument) iterator.next(); ODocument oDocument = (ODocument) iterator.next();
logger.debug("{}", oDocument); logger.debug("{}", oDocument);
} }
return res.toString(); return res.toString();
} catch (Exception e) { } catch(Exception e) {
throw new InvalidQueryException(e.getMessage()); throw new InvalidQueryException(e.getMessage());
} finally { } finally {
if (oDatabaseDocumentTx != null) { if(oDatabaseDocumentTx != null) {
oDatabaseDocumentTx.close(); oDatabaseDocumentTx.close();
} }
} }
*/ */
} }
} }

View File

@ -50,33 +50,33 @@ import com.tinkerpop.blueprints.Direction;
*/ */
@Path(AccessPath.ACCESS_PATH_PART) @Path(AccessPath.ACCESS_PATH_PART)
public class Access { public class Access {
private static Logger logger = LoggerFactory.getLogger(Access.class); private static Logger logger = LoggerFactory.getLogger(Access.class);
public static final String ID_PATH_PARAM = "id"; public static final String ID_PATH_PARAM = "id";
public static final String TYPE_PATH_PARAM = "type"; public static final String TYPE_PATH_PARAM = "type";
/** /**
* It includeSubtypesows to query Entities and Relations in the current * It includeSubtypes to query Entities and Relations in the current Context.<br />
* Context.<br />
* It accepts idempotent query only.. <br /> * It accepts idempotent query only.. <br />
* <br /> * <br />
* For query syntax please refer to<br /> * For query syntax please refer to<br />
*
* <a href="https://orientdb.com/docs/last/SQL-Syntax.html" target="_blank"> * <a href="https://orientdb.com/docs/last/SQL-Syntax.html" target="_blank">
* https://orientdb.com/docs/last/SQL-Syntax.html </a> <br /> * https://orientdb.com/docs/last/SQL-Syntax.html </a> <br />
* <br /> * <br />
*
* e.g. GET /resource-registry/access?query=SELECT FROM V * e.g. GET /resource-registry/access?query=SELECT FROM V
* *
* @param query * @param query
* Defines the query to send to the backend. * Defines the query to send to the backend.
* @param limit * @param limit
* Defines the number of results you want returned, defaults to * Defines the number of results you want returned, defaults to includeSubtypes results.
* includeSubtypes results.
* @param fetchPlan * @param fetchPlan
* Defines the fetching strategy you want to use. See <a * Defines the fetching strategy you want to use. See
* href="https://orientdb.com/docs/last/Fetching-Strategies.html" * <a href="https://orientdb.com/docs/last/Fetching-Strategies.html" target="_blank">
* target="_blank"> * https://orientdb.com/docs/last/Fetching-Strategies.html
* https://orientdb.com/docs/last/Fetching-Strategies.html </a> * </a>
* @return The JSON representation of the result * @return The JSON representation of the result
* @throws InvalidQueryException * @throws InvalidQueryException
* if the query is invalid or no idempotent * if the query is invalid or no idempotent
@ -85,23 +85,18 @@ public class Access {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String query(@QueryParam(AccessPath.QUERY_PARAM) String query, public String query(@QueryParam(AccessPath.QUERY_PARAM) String query,
@QueryParam(AccessPath.LIMIT_PARAM) Integer limit, @QueryParam(AccessPath.LIMIT_PARAM) Integer limit,
@QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) @QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) throws InvalidQueryException {
throws InvalidQueryException { logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query);
logger.info("Requested query (fetch plan {}, limit : {}):\n{}",
fetchPlan, limit, query);
Query queryManager = new QueryImpl(); Query queryManager = new QueryImpl();
return queryManager.query(query, limit, fetchPlan); return queryManager.query(query, limit, fetchPlan);
} }
@HEAD @HEAD
@Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/{" + ID_PATH_PARAM + "}")
+ "/{" + ID_PATH_PARAM + "}") public Response exists(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(ID_PATH_PARAM) String id)
public Response exists(@PathParam(TYPE_PATH_PARAM) String type, throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
@PathParam(ID_PATH_PARAM) String id) throws ERNotFoundException, CalledMethodProvider.instance.set(HTTPMETHOD.HEAD.name() + " /" + AccessPath.ACCESS_PATH_PART + "/"
ERAvailableInAnotherContextException, ResourceRegistryException { + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(
HTTPMETHOD.HEAD.name() + " /" + AccessPath.ACCESS_PATH_PART +
"/" + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to check if {} with id {} exists", type, id); logger.info("Requested to check if {} with id {} exists", type, id);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -109,152 +104,137 @@ public class Access {
UUID uuid = null; UUID uuid = null;
try { try {
uuid = UUID.fromString(id); uuid = UUID.fromString(id);
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
erManagement.setUUID(uuid); erManagement.setUUID(uuid);
try { try {
boolean found = erManagement.exists(); boolean found = erManagement.exists();
if(found){ if(found) {
return Response.status(Status.NO_CONTENT).build(); return Response.status(Status.NO_CONTENT).build();
}else{ } else {
// This code should never be reached due to exception management // This code should never be reached due to exception management
// anyway adding it for safety reason // anyway adding it for safety reason
return Response.status(Status.NOT_FOUND).build(); return Response.status(Status.NOT_FOUND).build();
} }
} catch (ERNotFoundException e) { } catch(ERNotFoundException e) {
return Response.status(Status.NOT_FOUND).build(); return Response.status(Status.NOT_FOUND).build();
} catch (ERAvailableInAnotherContextException e) { } catch(ERAvailableInAnotherContextException e) {
return Response.status(Status.FORBIDDEN).build(); return Response.status(Status.FORBIDDEN).build();
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} }
} }
/* /*
* e.g. GET * e.g. GET
* /resource-registry/access/instance/ContactFacet/4d28077b-566d-4132-b073- * /resource-registry/access/instance/ContactFacet/4d28077b-566d-4132-b073-f4edaf61dcb9
* f4edaf61dcb9
*/ */
@GET @GET
@Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" @Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/{" + ID_PATH_PARAM + "}")
+ "/{" + ID_PATH_PARAM + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String getInstance(@PathParam(TYPE_PATH_PARAM) String type, public String getInstance(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(ID_PATH_PARAM) String id)
@PathParam(ID_PATH_PARAM) String id)
throws ERNotFoundException, ResourceRegistryException { throws ERNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.GET.name() + " /" + AccessPath.ACCESS_PATH_PART + "/"
HTTPMETHOD.GET.name() + " /" + AccessPath.ACCESS_PATH_PART + + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
"/" + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested {} with id {}", type, id); logger.info("Requested {} with id {}", type, id);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
ERManagement erManagement = ERManagementUtility.getERManagement(type); ERManagement erManagement = ERManagementUtility.getERManagement(type);
UUID uuid = null; UUID uuid = null;
try { try {
uuid = UUID.fromString(id); uuid = UUID.fromString(id);
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
erManagement.setUUID(uuid); erManagement.setUUID(uuid);
return erManagement.read(); return erManagement.read();
} }
/* /*
* e.g. GET /resource-registry/access/instances/EService?polymorphic=true * e.g.
* * GET /resource-registry/access/instances/EService?polymorphic=true
* &reference=4d28077b-566d-4132-b073-f4edaf61dcb9 &direction=(in|out|both) * &reference=4d28077b-566d-4132-b073-f4edaf61dcb9 &direction=(in|out|both)
*/ */
@SuppressWarnings({ "rawtypes" }) @SuppressWarnings({"rawtypes"})
@GET @GET
@Path(AccessPath.INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}") @Path(AccessPath.INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String getInstances(@PathParam(TYPE_PATH_PARAM) String type, public String getInstances(@PathParam(TYPE_PATH_PARAM) String type,
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic, @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic,
@QueryParam(AccessPath.REFERENCE) String reference, @QueryParam(AccessPath.REFERENCE) String reference,
@QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction) @QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction) throws ResourceRegistryException {
throws ResourceRegistryException { logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic);
logger.info("Requested {} ({}={}) instances", type,
AccessPath.POLYMORPHIC_PARAM, polymorphic);
ERManagement erManagement = ERManagementUtility.getERManagement(type); ERManagement erManagement = ERManagementUtility.getERManagement(type);
if (erManagement instanceof EntityManagement) { if(erManagement instanceof EntityManagement) {
return erManagement.all(polymorphic); return erManagement.all(polymorphic);
} }
if (erManagement instanceof RelationManagement) { if(erManagement instanceof RelationManagement) {
if (reference != null) { if(reference != null) {
UUID uuid = null; UUID uuid = null;
try { try {
uuid = UUID.fromString(reference); uuid = UUID.fromString(reference);
} catch (Exception e) { } catch(Exception e) {
String errror = String.format( String errror = String.format("Provided %s (%s) is not a valid %s", AccessPath.REFERENCE, reference,
"Provided %s (%s) is not a valid %s",
AccessPath.REFERENCE, reference,
UUID.class.getSimpleName()); UUID.class.getSimpleName());
throw new ResourceRegistryException(errror); throw new ResourceRegistryException(errror);
} }
Direction directionEnum; Direction directionEnum;
if (direction == null) { if(direction == null) {
directionEnum = Direction.BOTH; directionEnum = Direction.BOTH;
} else { } else {
try { try {
directionEnum = Enum.valueOf(Direction.class, direction directionEnum = Enum.valueOf(Direction.class, direction.trim().toUpperCase());
.trim().toUpperCase()); } catch(Exception e) {
} catch (Exception e) { String errror = String.format("Provided %s (%s) is not valid. Allowed values are %s",
String errror = String AccessPath.DIRECTION, direction, Arrays.toString(Direction.values()).toLowerCase());
.format("Provided %s (%s) is not valid. Allowed values are %s",
AccessPath.DIRECTION, direction,
Arrays.toString(Direction.values()).toLowerCase());
throw new ResourceRegistryException(errror); throw new ResourceRegistryException(errror);
} }
} }
return ((RelationManagement) erManagement).allFrom(uuid, return ((RelationManagement) erManagement).allFrom(uuid, directionEnum, polymorphic);
directionEnum, polymorphic);
} else { } else {
return erManagement.all(polymorphic); return erManagement.all(polymorphic);
} }
} }
throw new ResourceRegistryException("Invalid Request"); throw new ResourceRegistryException("Invalid Request");
} }
/* /*
* e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet?polymorphic=true * e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet
* ?polymorphic=true
*/ */
@SuppressWarnings({ "rawtypes" }) @SuppressWarnings({"rawtypes"})
@GET @GET
@Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + @Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/" + "{"
"/" + "{" + AccessPath.RELATION_TYPE_PATH_PART + "}"+ "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}") + AccessPath.RELATION_TYPE_PATH_PART + "}" + "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String getFilteredInstances( public String getFilteredInstances(@PathParam(TYPE_PATH_PARAM) String type,
@PathParam(TYPE_PATH_PARAM) String type,
@PathParam(AccessPath.RELATION_TYPE_PATH_PART) @DefaultValue(ConsistsOf.NAME) String relationType, @PathParam(AccessPath.RELATION_TYPE_PATH_PART) @DefaultValue(ConsistsOf.NAME) String relationType,
@PathParam(AccessPath.FACET_TYPE_PATH_PART) @DefaultValue(Facet.NAME) String facetType, @PathParam(AccessPath.FACET_TYPE_PATH_PART) @DefaultValue(Facet.NAME) String facetType,
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic, @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic,
@Context UriInfo uriInfo) @Context UriInfo uriInfo) throws ResourceRegistryException {
throws ResourceRegistryException { logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic);
logger.info("Requested {} ({}={}) instances", type,
AccessPath.POLYMORPHIC_PARAM, polymorphic);
MultivaluedMap<String, String> multivaluedMap = uriInfo.getQueryParameters(); MultivaluedMap<String,String> multivaluedMap = uriInfo.getQueryParameters();
Map<String, String> constraint = new HashMap<>(); Map<String,String> constraint = new HashMap<>();
for(String key : multivaluedMap.keySet()){ for(String key : multivaluedMap.keySet()) {
if(key.compareTo(AccessPath.POLYMORPHIC_PARAM)==0){ if(key.compareTo(AccessPath.POLYMORPHIC_PARAM) == 0) {
continue; continue;
} }
if(key.compareTo("gcube-token")==0){ if(key.compareTo("gcube-token") == 0) {
continue; continue;
} }
if(key.compareTo("gcube-scope")==0){ if(key.compareTo("gcube-scope") == 0) {
continue; continue;
} }
constraint.put(key, multivaluedMap.getFirst(key)); constraint.put(key, multivaluedMap.getFirst(key));
@ -263,16 +243,14 @@ public class Access {
constraint.put(AccessPath.FACET_TYPE_PATH_PART, facetType); constraint.put(AccessPath.FACET_TYPE_PATH_PART, facetType);
ERManagement erManagement = ERManagementUtility.getERManagement(type); ERManagement erManagement = ERManagementUtility.getERManagement(type);
if (erManagement instanceof ResourceManagement) { if(erManagement instanceof ResourceManagement) {
return ((ResourceManagement) erManagement).all(polymorphic, constraint); return ((ResourceManagement) erManagement).all(polymorphic, constraint);
} }
throw new ResourceRegistryException("Invalid Request"); throw new ResourceRegistryException("Invalid Request");
} }
/* /*
* e.g. GET /resource-registry/access/schema/ContactFacet?polymorphic=true * e.g. GET /resource-registry/access/schema/ContactFacet?polymorphic=true
*/ */
@ -286,7 +264,6 @@ public class Access {
SchemaManagement schemaManagement = new SchemaManagementImpl(); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.read(type, polymorphic); return schemaManagement.read(type, polymorphic);
} }
/* /*
* e.g. GET /resource-registry/access/context/c0f314e7-2807-4241-a792-2a6c79ed4fd0 * e.g. GET /resource-registry/access/context/c0f314e7-2807-4241-a792-2a6c79ed4fd0

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.rest; package org.gcube.informationsystem.resourceregistry.rest;
import java.util.UUID; import java.util.UUID;

View File

@ -40,12 +40,12 @@ import org.slf4j.LoggerFactory;
*/ */
@Path(ERPath.ER_PATH_PART) @Path(ERPath.ER_PATH_PART)
public class ERManager { public class ERManager {
private static Logger logger = LoggerFactory.getLogger(ERManager.class); private static Logger logger = LoggerFactory.getLogger(ERManager.class);
public static final String ID_PATH_PARAM = "id"; public static final String ID_PATH_PARAM = "id";
public static final String TYPE_PATH_PARAM = "type"; public static final String TYPE_PATH_PARAM = "type";
/** /**
* e.g. PUT /resource-registry/er/facet/ContactFacet * e.g. PUT /resource-registry/er/facet/ContactFacet
* *
@ -54,13 +54,12 @@ public class ERManager {
*/ */
@PUT @PUT
@Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json) public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws FacetAlreadyPresentException, ResourceRegistryException { throws FacetAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + .set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/" + type);
"/" + ERPath.FACET_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {}", Facet.NAME, type); logger.info("Requested to create {} of type {}", Facet.NAME, type);
logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json); logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json);
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
@ -70,7 +69,7 @@ public class ERManager {
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build(); .build();
} }
/** /**
* e.g. POST /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 * e.g. POST /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86
* *
@ -79,13 +78,12 @@ public class ERManager {
*/ */
@POST @POST
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json) public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json)
throws FacetNotFoundException, ResourceRegistryException { throws FacetNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to update {} with id {}", Facet.NAME, uuid); logger.info("Requested to update {} with id {}", Facet.NAME, uuid);
logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json); logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json);
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
@ -93,26 +91,25 @@ public class ERManager {
facetManagement.setJSON(json); facetManagement.setJSON(json);
return facetManagement.update(); return facetManagement.update();
} }
/** /**
* e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86 * e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86
* *
*/ */
@DELETE @DELETE
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid) public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ResourceRegistryException { throws FacetNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", Facet.NAME, uuid); logger.info("Requested to delete {} with id {}", Facet.NAME, uuid);
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid)); facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.delete(); return facetManagement.delete();
} }
/* Resources Methods */ /* Resources Methods */
/** /**
* e.g. PUT /resource-registry/er/resource/HostingNode * e.g. PUT /resource-registry/er/resource/HostingNode
* *
@ -121,13 +118,12 @@ public class ERManager {
*/ */
@PUT @PUT
@Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json) public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws ResourceAlreadyPresentException, ResourceRegistryException { throws ResourceAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + .set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/" + type);
"/" + ERPath.RESOURCE_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {}", Resource.NAME, type); logger.info("Requested to create {} of type {}", Resource.NAME, type);
logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json); logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
@ -137,7 +133,7 @@ public class ERManager {
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build(); .build();
} }
/** /**
* e.g. POST /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * e.g. POST /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0
* *
@ -146,13 +142,12 @@ public class ERManager {
*/ */
@POST @POST
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json) public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json)
throws ResourceNotFoundException, ResourceRegistryException { throws ResourceNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to update {} with id {}", Resource.NAME, uuid); logger.info("Requested to update {} with id {}", Resource.NAME, uuid);
logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json); logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
@ -160,24 +155,23 @@ public class ERManager {
resourceManagement.setJSON(json); resourceManagement.setJSON(json);
return resourceManagement.update(); return resourceManagement.update();
} }
/** /**
* e.g. DELETE /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * e.g. DELETE
* /resource-registry/er/resource/67062c11-9c3a-4906-870d-7df6a43408b0
* *
*/ */
@DELETE @DELETE
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception { public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", Resource.NAME, uuid); logger.info("Requested to delete {} with id {}", Resource.NAME, uuid);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid)); resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.delete(); return resourceManagement.delete();
} }
/** /**
* e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy * e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy
* *
@ -186,13 +180,12 @@ public class ERManager {
*/ */
@PUT @PUT
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json) public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws ResourceAlreadyPresentException, ResourceRegistryException { throws ResourceAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type);
"/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type); logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type);
logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json); logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
@ -202,23 +195,23 @@ public class ERManager {
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build(); .build();
} }
/** /**
* e.g. DELETE /resource-registry/er/consistsOf/9bff49c8-c0a7-45de-827c-accb71defbd3 * e.g. DELETE
* /resource-registry/er/consistsOf/9bff49c8-c0a7-45de-827c-accb71defbd3
* *
*/ */
@DELETE @DELETE
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException { public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID); logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement(); ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setUUID(UUID.fromString(consistOfUUID)); consistsOfManagement.setUUID(UUID.fromString(consistOfUUID));
return consistsOfManagement.delete(); return consistsOfManagement.delete();
} }
/** /**
* e.g. PUT /resource-registry/er/isRelatedTo/Hosts * e.g. PUT /resource-registry/er/isRelatedTo/Hosts
* *
@ -227,13 +220,12 @@ public class ERManager {
*/ */
@PUT @PUT
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + TYPE_PATH_PARAM + "}") @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json) public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws ResourceAlreadyPresentException, ResourceRegistryException { throws ResourceAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type);
"/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json); logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json);
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(type); isRelatedToManagement.setElementType(type);
@ -242,40 +234,40 @@ public class ERManager {
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build(); .build();
} }
/** /**
* e.g. DELETE /resource-registry/er/isRelatedTo/b3982715-a7aa-4530-9a5f-2f60008d256e * e.g. DELETE
* /resource-registry/er/isRelatedTo/b3982715-a7aa-4530-9a5f-2f60008d256e
* *
*/ */
@DELETE @DELETE
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException { public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID); logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID);
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement(); IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID)); isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID));
return isRelatedToManagement.delete(); return isRelatedToManagement.delete();
} }
/** /**
* e.g POST /resource-registry/er/add/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * e.g POST
* /resource-registry/er/add/resource/67062c11-9c3a-4906-870d-7df6a43408b0
* *
*/ */
@POST @POST
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME); logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid)); resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.addToContext(); return resourceManagement.addToContext();
} }
/** /**
* e.g POST /resource-registry/er/add/facet/f6931232-c034-4979-9b2f-7193d3fba7df * e.g POST /resource-registry/er/add/facet/f6931232-c034-4979-9b2f-7193d3fba7df
* *
@ -284,47 +276,46 @@ public class ERManager {
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException { throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME); logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME);
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid)); facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.addToContext(); return facetManagement.addToContext();
} }
/** /**
* e.g POST /resource-registry/er/remove/resource/67062c11-9c3a-4906-870d-7df6a43408b0 * e.g POST
* /resource-registry/er/remove/resource/67062c11-9c3a-4906-870d-7df6a43408b0
* *
*/ */
@POST @POST
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException { throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME); logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME);
ResourceManagement resourceManagement = new ResourceManagement(); ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid)); resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.removeFromContext(); return resourceManagement.removeFromContext();
} }
/** /**
* e.g POST /resource-registry/er/remove/facet/f6931232-c034-4979-9b2f-7193d3fba7df * e.g POST
* /resource-registry/er/remove/facet/f6931232-c034-4979-9b2f-7193d3fba7df
* *
*/ */
@POST @POST
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}") @Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid) public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException { throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set( CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME); logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME);
FacetManagement facetManagement = new FacetManagement(); FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid)); facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.removeFromContext(); return facetManagement.removeFromContext();
} }
} }

View File

@ -15,28 +15,29 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@Provider @Provider
public class ResourceRegistryExceptionMapper implements ExceptionMapper<ResourceRegistryException>{ public class ResourceRegistryExceptionMapper implements ExceptionMapper<ResourceRegistryException> {
@Override @Override
public Response toResponse(ResourceRegistryException exception) { public Response toResponse(ResourceRegistryException exception) {
Status status = Status.BAD_REQUEST; Status status = Status.BAD_REQUEST;
if(ERNotFoundException.class.isAssignableFrom(exception.getClass())){ if(ERNotFoundException.class.isAssignableFrom(exception.getClass())) {
status = Status.NOT_FOUND; status = Status.NOT_FOUND;
} else if(ERAlreadyPresentException.class.isAssignableFrom(exception.getClass())){ } else if(ERAlreadyPresentException.class.isAssignableFrom(exception.getClass())) {
status = Status.CONFLICT; status = Status.CONFLICT;
} else if(ERAvailableInAnotherContextException.class.isAssignableFrom(exception.getClass())){ } else if(ERAvailableInAnotherContextException.class.isAssignableFrom(exception.getClass())) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
} else if(exception.getClass() == ResourceRegistryException.class){ } else if(exception.getClass() == ResourceRegistryException.class) {
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
try { try {
String entity = org.gcube.informationsystem.resourceregistry.api.exceptions.ExceptionMapper.marshal(exception); String entity = org.gcube.informationsystem.resourceregistry.api.exceptions.ExceptionMapper
.marshal(exception);
MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
return Response.status(status).entity(entity).type(mediaType).build(); return Response.status(status).entity(entity).type(mediaType).build();
}catch (Exception e) { } catch(Exception e) {
String entity = exception.getMessage(); String entity = exception.getMessage();
MediaType mediaType = MediaType.TEXT_PLAIN_TYPE; MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
return Response.status(status).entity(entity).type(mediaType).build(); return Response.status(status).entity(entity).type(mediaType).build();

View File

@ -30,10 +30,10 @@ import org.slf4j.LoggerFactory;
*/ */
@ApplicationPath(SchemaPath.SCHEMA_PATH_PART) @ApplicationPath(SchemaPath.SCHEMA_PATH_PART)
public class SchemaManager { public class SchemaManager {
private static Logger logger = LoggerFactory.getLogger(SchemaManager.class); private static Logger logger = LoggerFactory.getLogger(SchemaManager.class);
public static final String TYPE_PATH_PARAM = "type"; public static final String TYPE_PATH_PARAM = "type";
/** /**
* e.g. PUT /resource-registry/schema/{E-R} * e.g. PUT /resource-registry/schema/{E-R}
* *
@ -46,52 +46,52 @@ public class SchemaManager {
*/ */
@PUT @PUT
@Path("{" + TYPE_PATH_PARAM + "}") @Path("{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public Response create(@PathParam(TYPE_PATH_PARAM) String type, String json) public Response create(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws SchemaException, ResourceRegistryException { throws SchemaException, ResourceRegistryException {
logger.info("Requested {} registration with schema {}", type, json); logger.info("Requested {} registration with schema {}", type, json);
AccessType accessType = null; AccessType accessType = null;
try { try {
accessType = AccessType.valueOf(type); accessType = AccessType.valueOf(type);
switch (accessType) { switch(accessType) {
case EMBEDDED: case EMBEDDED:
break; break;
case FACET: case FACET:
break; break;
case RESOURCE: case RESOURCE:
break; break;
case IS_RELATED_TO: case IS_RELATED_TO:
break; break;
case CONSISTS_OF: case CONSISTS_OF:
break; break;
default: default:
throw new Exception(); throw new Exception();
} }
} catch (Exception e) { } catch(Exception e) {
String error = String.format("Cannot register %s schema", type); String error = String.format("Cannot register %s schema", type);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
SchemaManagement schemaManagement = new SchemaManagementImpl(); SchemaManagement schemaManagement = new SchemaManagementImpl();
String ret = schemaManagement.create(json, accessType); String ret = schemaManagement.create(json, accessType);
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build(); .build();
} }
/* /*
* e.g. GET /resource-registry/schema/ContactFacet?polymorphic=true * e.g. GET /resource-registry/schema/ContactFacet?polymorphic=true
*/ */
@GET @GET
@Path("{" + TYPE_PATH_PARAM + "}") @Path("{" + TYPE_PATH_PARAM + "}")
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 }) @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8) @Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String read(@PathParam(TYPE_PATH_PARAM) String type, public String read(@PathParam(TYPE_PATH_PARAM) String type,
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic) @QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic)
@ -100,5 +100,5 @@ public class SchemaManager {
SchemaManagement schemaManagement = new SchemaManagementImpl(); SchemaManagement schemaManagement = new SchemaManagementImpl();
return schemaManagement.read(type, polymorphic); return schemaManagement.read(type, polymorphic);
} }
} }

View File

@ -8,9 +8,9 @@ import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -23,17 +23,17 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex; import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class SchemaContextManagement implements SchemaManagement { public class SchemaContextManagement implements SchemaManagement {
private static Logger logger = LoggerFactory.getLogger(SchemaContextManagement.class); private static Logger logger = LoggerFactory.getLogger(SchemaContextManagement.class);
public static final String SCHEMA = "__SCHEMA"; public static final String SCHEMA = "__SCHEMA";
protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception{ protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception {
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(vertexType, false); Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(vertexType, false);
Iterator<Vertex> iterator = iterable.iterator(); Iterator<Vertex> iterator = iterable.iterator();
Vertex vertex = null; Vertex vertex = null;
if(iterator.hasNext()){ if(iterator.hasNext()) {
vertex = iterator.next(); vertex = iterator.next();
} else { } else {
String error = String.format("%s is not a registered type", vertexType); String error = String.format("%s is not a registered type", vertexType);
@ -41,8 +41,10 @@ public class SchemaContextManagement implements SchemaManagement {
throw new Exception(error); throw new Exception(error);
} }
if(iterator.hasNext()){ if(iterator.hasNext()) {
String error = String.format("More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.", vertexType); String error = String.format(
"More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.",
vertexType);
logger.error(error); logger.error(error);
throw new Exception(error); throw new Exception(error);
} }
@ -52,7 +54,7 @@ public class SchemaContextManagement implements SchemaManagement {
@Override @Override
public String create(String json, AccessType baseType) throws SchemaException { public String create(String json, AccessType baseType) throws SchemaException {
OrientGraph orientGraph = null; OrientGraph orientGraph = null;
try { try {
@ -62,11 +64,11 @@ public class SchemaContextManagement implements SchemaManagement {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class); TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class);
if (Entity.class.isAssignableFrom(baseType.getTypeClass())) { if(Entity.class.isAssignableFrom(baseType.getTypeClass())) {
OrientVertex orientVertex = orientGraph.addVertex("class:" + typeDefinition.getName()); OrientVertex orientVertex = orientGraph.addVertex("class:" + typeDefinition.getName());
orientVertex.setProperty(SCHEMA, json); orientVertex.setProperty(SCHEMA, json);
orientVertex.save(); orientVertex.save();
} else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) { } else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) {
String sourceClass = typeDefinition.getSourceType(); String sourceClass = typeDefinition.getSourceType();
Vertex source = getVertex(orientGraph, sourceClass); Vertex source = getVertex(orientGraph, sourceClass);
@ -77,7 +79,7 @@ public class SchemaContextManagement implements SchemaManagement {
orientEdge.setProperty(SCHEMA, json); orientEdge.setProperty(SCHEMA, json);
orientEdge.save(); orientEdge.save();
} else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) { } else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
ODocument doc = new ODocument(typeDefinition.getName()); ODocument doc = new ODocument(typeDefinition.getName());
doc.field(SCHEMA, json); doc.field(SCHEMA, json);
doc.save(); doc.save();
@ -86,31 +88,31 @@ public class SchemaContextManagement implements SchemaManagement {
orientGraph.commit(); orientGraph.commit();
return json; return json;
}catch (Exception e) { } catch(Exception e) {
if (orientGraph != null) { if(orientGraph != null) {
orientGraph.rollback(); orientGraph.rollback();
} }
throw new SchemaException(e); throw new SchemaException(e);
} finally { } finally {
if (orientGraph != null) { if(orientGraph != null) {
orientGraph.shutdown(); orientGraph.shutdown();
} }
} }
} }
@Override @Override
public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException { public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
@Override @Override
public String update(String type, AccessType accessType, String json) public String update(String type, AccessType accessType, String json)
throws SchemaNotFoundException, SchemaException { throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override @Override
public String delete(String type, AccessType accessType) throws SchemaNotFoundException { public String delete(String type, AccessType accessType) throws SchemaNotFoundException {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");

View File

@ -7,8 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
* *
* For JSON schema see * For JSON schema see http://orientdb.com/docs/last/OrientDB-REST.html#class
* http://orientdb.com/docs/last/OrientDB-REST.html#class
* *
*/ */
public interface SchemaManagement { public interface SchemaManagement {
@ -17,7 +16,8 @@ public interface SchemaManagement {
public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException; public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException;
public String update(String type, AccessType accessType, String json) throws SchemaNotFoundException, SchemaException; public String update(String type, AccessType accessType, String json)
throws SchemaNotFoundException, SchemaException;
public String delete(String type, AccessType accessType) throws SchemaNotFoundException; public String delete(String type, AccessType accessType) throws SchemaNotFoundException;

View File

@ -19,9 +19,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder; import org.gcube.informationsystem.types.TypeBinder;
import org.gcube.informationsystem.types.TypeBinder.Property; import org.gcube.informationsystem.types.TypeBinder.Property;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition; import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
@ -44,298 +44,271 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
* *
* TODO Create an instance for each Registered Type in a management * TODO Create an instance for each Registered Type in a management SecurityContext so that that management context
* SecurityContext so that that management context can be used to see * can be used to see Entity and Relations as graph.
* Entity and Relations as graph.
* *
*/ */
public class SchemaManagementImpl implements SchemaManagement { public class SchemaManagementImpl implements SchemaManagement {
private static Logger logger = LoggerFactory private static Logger logger = LoggerFactory.getLogger(SchemaManagementImpl.class);
.getLogger(SchemaManagementImpl.class);
protected static OClass getOClass(OSchema oSchema, String type) throws SchemaException {
protected static OClass getOClass(OSchema oSchema, String type)
throws SchemaException {
return oSchema.getClass(type); return oSchema.getClass(type);
} }
public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, String type, AccessType accessType)
String type, AccessType accessType) throws SchemaException { throws SchemaException {
OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata(); OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
return getTypeSchema(oSchema, type, accessType); return getTypeSchema(oSchema, type, accessType);
} }
public static OClass getTypeSchema(OSchema oSchema, String type, public static OClass getTypeSchema(OSchema oSchema, String type, AccessType accessType) throws SchemaException {
AccessType accessType) throws SchemaException {
try { try {
OClass oClass = oSchema.getClass(type); OClass oClass = oSchema.getClass(type);
if (oClass == null) { if(oClass == null) {
throw new SchemaNotFoundException(type + " was not registered"); throw new SchemaNotFoundException(type + " was not registered");
} }
if(accessType!=null && type.compareTo(accessType.getName())!= 0) { if(accessType != null && type.compareTo(accessType.getName()) != 0) {
if (!oClass.isSubClassOf(accessType.getName())) { if(!oClass.isSubClassOf(accessType.getName())) {
throw new SchemaException(type + " is not a " + accessType.getName()); throw new SchemaException(type + " is not a " + accessType.getName());
} }
} }
return oClass; return oClass;
} catch (SchemaNotFoundException snfe) { } catch(SchemaNotFoundException snfe) {
throw snfe; throw snfe;
} catch (Exception e) { } catch(Exception e) {
throw new SchemaException(e.getMessage()); throw new SchemaException(e.getMessage());
} }
} }
public static OClass getTypeSchema(String type, AccessType accessType) public static OClass getTypeSchema(String type, AccessType accessType)
throws SchemaException, ResourceRegistryException { throws SchemaException, ResourceRegistryException {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
logger.debug("Getting {} Type {} schema", logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type);
accessType != null ? accessType.getName() : "", type);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return getTypeSchema(orientGraphNoTx, type, accessType); return getTypeSchema(orientGraphNoTx, type, accessType);
} catch (ResourceRegistryException e) { } catch(ResourceRegistryException e) {
throw e; throw e;
} finally { } finally {
if (orientGraphNoTx != null) { if(orientGraphNoTx != null) {
orientGraphNoTx.shutdown(); orientGraphNoTx.shutdown();
} }
} }
} }
protected static TypeDefinition getTypeDefinition(OClass oClass) protected static TypeDefinition getTypeDefinition(OClass oClass) throws SchemaException {
throws SchemaException {
ODocument oDocument = ((OClassImpl) oClass).toStream(); ODocument oDocument = ((OClassImpl) oClass).toStream();
String json = oDocument.toJSON(); String json = oDocument.toJSON();
try { try {
return TypeBinder.deserializeTypeDefinition(json); return TypeBinder.deserializeTypeDefinition(json);
} catch (Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} }
} }
protected static String getTypeDefinitionAsString(OClass oClass) protected static String getTypeDefinitionAsString(OClass oClass) throws SchemaException {
throws SchemaException {
try { try {
TypeDefinition typeDefinition = getTypeDefinition(oClass); TypeDefinition typeDefinition = getTypeDefinition(oClass);
return TypeBinder.serializeTypeDefinition(typeDefinition); return TypeBinder.serializeTypeDefinition(typeDefinition);
} catch (Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} }
} }
protected List<OClass> getSuperclassesAndCheckCompliancy( protected List<OClass> getSuperclassesAndCheckCompliancy(OrientGraphNoTx orientGraphNoTx,
OrientGraphNoTx orientGraphNoTx, TypeDefinition typeDefinition, TypeDefinition typeDefinition, String baseType) throws SchemaException {
String baseType) throws SchemaException {
Set<String> superClasses = typeDefinition.getSuperClasses(); Set<String> superClasses = typeDefinition.getSuperClasses();
if (baseType != null) { if(baseType != null) {
if (superClasses == null || superClasses.size() == 0) { if(superClasses == null || superClasses.size() == 0) {
throw new RuntimeException( throw new RuntimeException(
String.format( String.format("No Superclass found in schema %s. The Type Definition must extend %s",
"No Superclass found in schema %s. The Type Definition must extend %s",
typeDefinition, baseType)); typeDefinition, baseType));
} }
} }
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
List<OClass> oSuperclasses = new ArrayList<>(); List<OClass> oSuperclasses = new ArrayList<>();
for (String superClass : superClasses) { for(String superClass : superClasses) {
OClass oSuperClass = getOClass(oSchema, superClass); OClass oSuperClass = getOClass(oSchema, superClass);
if(oSuperClass==null){ if(oSuperClass == null) {
throw new SchemaNotFoundException("Superclass "+ superClass + " does not exists"); throw new SchemaNotFoundException("Superclass " + superClass + " does not exists");
} }
if (baseType != null) { if(baseType != null) {
if (typeDefinition.getName().compareTo(baseType) != 0) { if(typeDefinition.getName().compareTo(baseType) != 0) {
if (!oSuperClass.isSubClassOf(baseType)) { if(!oSuperClass.isSubClassOf(baseType)) {
throw new RuntimeException(superClass throw new RuntimeException(superClass + " is not a subsclass of " + baseType
+ " is not a subsclass of " + baseType + ". Each Superclass MUST be a subclass of " + baseType);
+ ". Each Superclass MUST be a subclass of "
+ baseType);
} }
} }
} }
oSuperclasses.add(oSuperClass); oSuperclasses.add(oSuperClass);
} }
return oSuperclasses; return oSuperclasses;
} }
protected String registerTypeSchema(String jsonSchema, AccessType baseType) protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException {
throws SchemaException {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
logger.info("Trying to register {} {}", baseType.getName(), logger.info("Trying to register {} {}", baseType.getName(), jsonSchema);
jsonSchema);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
TypeDefinition typeDefinition = mapper.readValue(jsonSchema, TypeDefinition typeDefinition = mapper.readValue(jsonSchema, TypeDefinition.class);
TypeDefinition.class);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass oClass = null; OClass oClass = null;
if (Entity.class.isAssignableFrom(baseType.getTypeClass())) { if(Entity.class.isAssignableFrom(baseType.getTypeClass())) {
oClass = orientGraphNoTx.createVertexType(typeDefinition oClass = orientGraphNoTx.createVertexType(typeDefinition.getName());
.getName()); } else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) {
} else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) { oClass = orientGraphNoTx.createEdgeType(typeDefinition.getName());
oClass = orientGraphNoTx.createEdgeType(typeDefinition
.getName());
/* /*
* This information are persisted in Management Context * This information are persisted in Management Context String outBaseType =
* * typeDefinition.getOutBaseType(); String inBaseType =
* String outBaseType = typeDefinition.getOutBaseType(); * typeDefinition.getInBaseType();
* String inBaseType = typeDefinition.getInBaseType();
*
*/ */
} else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) { } else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
oClass = oSchema.createClass(typeDefinition.getName()); oClass = oSchema.createClass(typeDefinition.getName());
} else { } else {
String error = String String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.",
.format("Allowed superclass are %s, %s, %s, or any subclasses of them.", Entity.NAME, Relation.NAME, Embedded.NAME);
Entity.NAME, Relation.NAME, Embedded.NAME);
throw new ResourceRegistryException(error); throw new ResourceRegistryException(error);
} }
try { try {
if (typeDefinition.getDescription() != null) { if(typeDefinition.getDescription() != null) {
try { try {
oClass.setDescription(typeDefinition.getDescription()); oClass.setDescription(typeDefinition.getDescription());
}catch (Exception e) { } catch(Exception e) {
logger.warn("Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065"); logger.warn(
"Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
} }
} }
try { try {
// oClass.setAbstract(false); // Used to allow to persist Schema in Context Management // oClass.setAbstract(false); // Used to allow to persist Schema in Context
// Management
oClass.setAbstract(typeDefinition.isAbstract()); oClass.setAbstract(typeDefinition.isAbstract());
} catch (Exception e) { } catch(Exception e) {
logger.error( logger.error(
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.", "Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
typeDefinition.getName()); typeDefinition.getName());
} }
if (typeDefinition.getName().compareTo(Embedded.NAME) != 0) { if(typeDefinition.getName().compareTo(Embedded.NAME) != 0) {
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy( List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(orientGraphNoTx, typeDefinition,
orientGraphNoTx, typeDefinition, baseType.getName()); baseType.getName());
oClass.setSuperClasses(oSuperclasses); oClass.setSuperClasses(oSuperclasses);
} }
if (Resource.class.isAssignableFrom(baseType.getTypeClass())) { if(Resource.class.isAssignableFrom(baseType.getTypeClass())) {
Set<Property> properties = typeDefinition.getProperties(); Set<Property> properties = typeDefinition.getProperties();
if (properties != null && properties.size() > 0) { if(properties != null && properties.size() > 0) {
throw new Exception( throw new Exception("A Resource cannot contains any properties.");
"A Resource cannot contains any properties.");
} }
} else { } else {
for (Property property : typeDefinition.getProperties()) { for(Property property : typeDefinition.getProperties()) {
OType oType = OType.getById(property.getType().byteValue()); OType oType = OType.getById(property.getType().byteValue());
switch (oType) { switch(oType) {
case EMBEDDEDLIST: case EMBEDDEDLIST:
throw new UnsupportedDataTypeException(oType.name() + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); throw new UnsupportedDataTypeException(oType.name()
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
case EMBEDDEDSET: case EMBEDDEDSET:
throw new UnsupportedDataTypeException(oType.name() + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354"); throw new UnsupportedDataTypeException(oType.name()
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
default: default:
break; break;
} }
OProperty op = oClass.createProperty(property.getName(), oType); OProperty op = oClass.createProperty(property.getName(), oType);
op.setDescription(property.getDescription()); op.setDescription(property.getDescription());
/* /*
* Mandatory and notNull does not work in distributed mode: * Mandatory and notNull does not work in distributed mode: so that on Type
* so that on Type declaration they are forced to false * declaration they are forced to false
* ovp.setMandatory(property.isMandatory()); * ovp.setMandatory(property.isMandatory());
* ovp.setNotNull(property.isNotnull()); * ovp.setNotNull(property.isNotnull()); This information are persisted in
* * Management Context
* This information are persisted in Management Context
*/ */
op.setMandatory(false); op.setMandatory(false);
op.setNotNull(false); op.setNotNull(false);
op.setReadonly(property.isReadonly()); op.setReadonly(property.isReadonly());
op.setRegexp(property.getRegexp()); op.setRegexp(property.getRegexp());
if (property.getLinkedClass() != null) { if(property.getLinkedClass() != null) {
OClass linkedClass = getOClass(oSchema, OClass linkedClass = getOClass(oSchema, property.getLinkedClass());
property.getLinkedClass()); if(linkedClass == null) {
if (linkedClass == null) { logger.trace("class {} not found in schema", property.getLinkedClass());
logger.trace("class {} not found in schema", throw new Exception("class " + property.getLinkedClass() + " not found in schema");
property.getLinkedClass());
throw new Exception("class "
+ property.getLinkedClass()
+ " not found in schema");
} }
if (linkedClass.isEdgeType() if(linkedClass.isEdgeType() || linkedClass.isVertexType()) {
|| linkedClass.isVertexType()) { throw new Exception("An Embedded Field cannot be an Entity or a Relation");
throw new Exception(
"An Embedded Field cannot be an Entity or a Relation");
} }
op.setLinkedClass(linkedClass); op.setLinkedClass(linkedClass);
} else if (property.getLinkedType() != null) { } else if(property.getLinkedType() != null) {
op.setLinkedType(OType.getById(property.getLinkedType() op.setLinkedType(OType.getById(property.getLinkedType().byteValue()));
.byteValue()));
} }
} }
} }
OClass toBeSerializedOClass = oClass; OClass toBeSerializedOClass = oClass;
if (oClass instanceof OrientElementType) { if(oClass instanceof OrientElementType) {
toBeSerializedOClass = getOClass(oSchema, toBeSerializedOClass = getOClass(oSchema, typeDefinition.getName());
typeDefinition.getName());
} }
/* /*
SchemaContextManagement managementUtility = new SchemaContextManagement(); * SchemaContextManagement managementUtility = new SchemaContextManagement();
String ret = managementUtility.create(jsonSchema, baseType); * String ret = managementUtility.create(jsonSchema, baseType);
*/ */
// TODO Remove when the previous has been implemented // TODO Remove when the previous has been implemented
String ret = getTypeDefinitionAsString(toBeSerializedOClass); String ret = getTypeDefinitionAsString(toBeSerializedOClass);
logger.info("{} type registered successfully: {}", logger.info("{} type registered successfully: {}", baseType.getName(), jsonSchema);
baseType.getName(), jsonSchema);
return ret; return ret;
}catch (Exception e) { } catch(Exception e) {
oSchema.dropClass(typeDefinition.getName()); oSchema.dropClass(typeDefinition.getName());
throw e; throw e;
} }
} catch (OSchemaException ex) { } catch(OSchemaException ex) {
if(ex.getMessage().contains("already exists")){ if(ex.getMessage().contains("already exists")) {
throw new SchemaAlreadyPresentException(ex); throw new SchemaAlreadyPresentException(ex);
} }
throw new SchemaException(ex); throw new SchemaException(ex);
} catch (SchemaException e) { } catch(SchemaException e) {
throw e; throw e;
} catch (Exception ex) { } catch(Exception ex) {
throw new SchemaException(ex); throw new SchemaException(ex);
} finally { } finally {
if (orientGraphNoTx != null) { if(orientGraphNoTx != null) {
orientGraphNoTx.shutdown(); orientGraphNoTx.shutdown();
} }
} }
} }
protected String getSchema(String type, boolean includeSubtypes) protected String getSchema(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
throws SchemaNotFoundException, SchemaException {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
@ -344,61 +317,55 @@ public class SchemaManagementImpl implements SchemaManagement {
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata(); OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema(); OSchema oSchema = oMetadata.getSchema();
OClass baseOClass = getTypeSchema(oSchema, type, null); OClass baseOClass = getTypeSchema(oSchema, type, null);
List<TypeDefinition> typeDefinitions = new ArrayList<>(); List<TypeDefinition> typeDefinitions = new ArrayList<>();
typeDefinitions.add(getTypeDefinition(baseOClass)); typeDefinitions.add(getTypeDefinition(baseOClass));
if(includeSubtypes){ if(includeSubtypes) {
Collection<OClass> subClasses = baseOClass.getAllSubclasses(); Collection<OClass> subClasses = baseOClass.getAllSubclasses();
for (OClass oClass : subClasses) { for(OClass oClass : subClasses) {
typeDefinitions.add(getTypeDefinition(oClass)); typeDefinitions.add(getTypeDefinition(oClass));
} }
} }
/* /*
Collection<OClass> oClasses = oSchema.getClasses(); * Collection<OClass> oClasses = oSchema.getClasses(); for (OClass oClass :
for (OClass oClass : oClasses) { * oClasses) { if (oClass.isSubClassOf(baseOClass)) {
if (oClass.isSubClassOf(baseOClass)) { * typeDefinitions.add(getTypeDefinition(oClass)); } }
typeDefinitions.add(getTypeDefinition(oClass)); */
}
}
*/
return TypeBinder.serializeTypeDefinitions(typeDefinitions); return TypeBinder.serializeTypeDefinitions(typeDefinitions);
} catch (SchemaException e) { } catch(SchemaException e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
throw new SchemaException(e); throw new SchemaException(e);
} finally { } finally {
if (orientGraphNoTx != null) { if(orientGraphNoTx != null) {
orientGraphNoTx.shutdown(); orientGraphNoTx.shutdown();
} }
} }
} }
@Override @Override
public String create(String jsonSchema, AccessType accessType) public String create(String jsonSchema, AccessType accessType) throws SchemaException {
throws SchemaException {
return registerTypeSchema(jsonSchema, accessType); return registerTypeSchema(jsonSchema, accessType);
} }
@Override @Override
public String read(String entityType, boolean includeSubtypes) public String read(String entityType, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
throws SchemaNotFoundException, SchemaException {
return getSchema(entityType, includeSubtypes); return getSchema(entityType, includeSubtypes);
} }
@Override @Override
public String update(String entityType, AccessType accessType, public String update(String entityType, AccessType accessType, String jsonSchema)
String jsonSchema) throws SchemaNotFoundException, SchemaException { throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
@Override @Override
public String delete(String entityType, AccessType accessType) public String delete(String entityType, AccessType accessType) throws SchemaNotFoundException {
throws SchemaNotFoundException {
throw new UnsupportedOperationException("Not Yet implemented"); throw new UnsupportedOperationException("Not Yet implemented");
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.utils; package org.gcube.informationsystem.resourceregistry.utils;
import java.util.Date; import java.util.Date;
@ -14,12 +11,12 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.embedded.Header { public class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.embedded.Header {
public HeaderOrient(){ public HeaderOrient() {
super(Header.NAME); super(Header.NAME);
} }
protected HeaderOrient(String iClassName){ protected HeaderOrient(String iClassName) {
super(iClassName); super(iClassName);
} }
@ -29,16 +26,16 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
} }
@Override @Override
public void setUUID(UUID uuid){ public void setUUID(UUID uuid) {
this.field(Header.UUID_PROPERTY, uuid.toString()); this.field(Header.UUID_PROPERTY, uuid.toString());
} }
@Override @Override
public String getCreator() { public String getCreator() {
return this.field(Header.CREATOR_PROPERTY); return this.field(Header.CREATOR_PROPERTY);
} }
public void setCreator(String creator){ public void setCreator(String creator) {
this.field(Header.CREATOR_PROPERTY, creator); this.field(Header.CREATOR_PROPERTY, creator);
} }
@ -47,7 +44,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
return this.field(Header.CREATION_TIME_PROPERTY); return this.field(Header.CREATION_TIME_PROPERTY);
} }
public void setCreationTime(Date creationTime){ public void setCreationTime(Date creationTime) {
this.field(Header.CREATION_TIME_PROPERTY, creationTime); this.field(Header.CREATION_TIME_PROPERTY, creationTime);
} }
@ -56,7 +53,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
return this.field(Header.MODIFIED_BY_PROPERTY); return this.field(Header.MODIFIED_BY_PROPERTY);
} }
public void setModifiedBy(String modifiedBy){ public void setModifiedBy(String modifiedBy) {
this.field(Header.MODIFIED_BY_PROPERTY, modifiedBy); this.field(Header.MODIFIED_BY_PROPERTY, modifiedBy);
} }
@ -65,8 +62,8 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
return this.field(Header.LAST_UPDATE_TIME_PROPERTY); return this.field(Header.LAST_UPDATE_TIME_PROPERTY);
} }
public void setLastUpdateTime(Date lastUpdateTime){ public void setLastUpdateTime(Date lastUpdateTime) {
this.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); this.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.utils; package org.gcube.informationsystem.resourceregistry.utils;
import java.io.IOException; import java.io.IOException;
@ -31,60 +28,60 @@ import com.tinkerpop.blueprints.Element;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class HeaderUtility { public class HeaderUtility {
private static final Logger logger = LoggerFactory.getLogger(HeaderUtility.class); private static final Logger logger = LoggerFactory.getLogger(HeaderUtility.class);
public static String getUser() { public static String getUser() {
String user = org.gcube.informationsystem.model.embedded.Header.UNKNOWN_USER; String user = org.gcube.informationsystem.model.embedded.Header.UNKNOWN_USER;
try { try {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
if (caller != null) { if(caller != null) {
ClientInfo clientInfo = caller.getClient(); ClientInfo clientInfo = caller.getClient();
String clientId = clientInfo.getId(); String clientId = clientInfo.getId();
if (clientId != null && clientId.compareTo("") != 0) { if(clientId != null && clientId.compareTo("") != 0) {
user = clientId; user = clientId;
} else { } else {
throw new Exception("Username null or empty"); throw new Exception("Username null or empty");
} }
} }
} catch (Exception e) { } catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user); logger.error("Unable to retrieve user. {} will be used", user);
} }
return user; return user;
} }
public static Header createHeader(UUID uuid) { public static Header createHeader(UUID uuid) {
HeaderOrient header = new HeaderOrient(); HeaderOrient header = new HeaderOrient();
if (uuid == null) { if(uuid == null) {
uuid = UUID.randomUUID(); uuid = UUID.randomUUID();
} }
header.setUUID(uuid); header.setUUID(uuid);
String creator = getUser(); String creator = getUser();
header.setCreator(creator); header.setCreator(creator);
header.setModifiedBy(creator); header.setModifiedBy(creator);
Date date = Calendar.getInstance().getTime(); Date date = Calendar.getInstance().getTime();
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
logger.trace("Setting Last Update and Creation Time to " + ft.format(date)); logger.trace("Setting Last Update and Creation Time to " + ft.format(date));
header.setCreationTime(date); header.setCreationTime(date);
header.setLastUpdateTime(date); header.setLastUpdateTime(date);
return header; return header;
} }
public static Header getHeader(JsonNode jsonNode, boolean creation) public static Header getHeader(JsonNode jsonNode, boolean creation)
throws JsonParseException, JsonMappingException, IOException { throws JsonParseException, JsonMappingException, IOException {
if (jsonNode.has(Resource.HEADER_PROPERTY)) { if(jsonNode.has(Resource.HEADER_PROPERTY)) {
JsonNode headerNode = jsonNode.get(Resource.HEADER_PROPERTY); JsonNode headerNode = jsonNode.get(Resource.HEADER_PROPERTY);
if (headerNode.isNull()) { if(headerNode.isNull()) {
return null; return null;
} }
HeaderOrient header = null; HeaderOrient header = null;
if (creation) { if(creation) {
// If an header is provided MUST contains and UUID otherwise is // If an header is provided MUST contains and UUID otherwise is
// an invalid request so that let that an exception is raised // an invalid request so that let that an exception is raised
UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText()); UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText());
@ -97,9 +94,9 @@ public class HeaderUtility {
} }
return null; return null;
} }
public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException { public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException {
if (oDocument instanceof HeaderOrient) { if(oDocument instanceof HeaderOrient) {
return (HeaderOrient) oDocument; return (HeaderOrient) oDocument;
} else { } else {
try { try {
@ -111,29 +108,29 @@ public class HeaderUtility {
headerOrient.setModifiedBy(header.getModifiedBy()); headerOrient.setModifiedBy(header.getModifiedBy());
headerOrient.setLastUpdateTime(header.getLastUpdateTime()); headerOrient.setLastUpdateTime(header.getLastUpdateTime());
return headerOrient; return headerOrient;
} catch (Exception e) { } catch(Exception e) {
throw new ResourceRegistryException( throw new ResourceRegistryException(
"Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE); "Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} }
} }
} }
public static Header addHeader(Element element, UUID uuid) { public static Header addHeader(Element element, UUID uuid) {
Header header = createHeader(uuid); Header header = createHeader(uuid);
element.setProperty(Entity.HEADER_PROPERTY, header); element.setProperty(Entity.HEADER_PROPERTY, header);
return header; return header;
} }
public static Header addHeader(Edge edge, UUID uuid) { public static Header addHeader(Edge edge, UUID uuid) {
Header header = createHeader(uuid); Header header = createHeader(uuid);
edge.setProperty(Entity.HEADER_PROPERTY, header); edge.setProperty(Entity.HEADER_PROPERTY, header);
return header; return header;
} }
public static Header getHeader(Element element) throws ResourceRegistryException { public static Header getHeader(Element element) throws ResourceRegistryException {
return Utility.getEmbedded(Header.class, element, Entity.HEADER_PROPERTY); return Utility.getEmbedded(Header.class, element, Entity.HEADER_PROPERTY);
} }
public static void updateModifiedByAndLastUpdate(Element element) throws ResourceRegistryException { public static void updateModifiedByAndLastUpdate(Element element) throws ResourceRegistryException {
ODocument oDocument = element.getProperty(Entity.HEADER_PROPERTY); ODocument oDocument = element.getProperty(Entity.HEADER_PROPERTY);
String modifiedBy = getUser(); String modifiedBy = getUser();
@ -142,5 +139,5 @@ public class HeaderUtility {
oDocument.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime); oDocument.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
element.setProperty(Entity.HEADER_PROPERTY, oDocument); element.setProperty(Entity.HEADER_PROPERTY, oDocument);
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.utils; package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashSet; import java.util.HashSet;
@ -17,9 +14,9 @@ import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation; import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,115 +37,104 @@ import com.tinkerpop.blueprints.util.io.graphson.GraphSONUtility;
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class Utility { public class Utility {
private static final Logger logger = LoggerFactory.getLogger(Utility.class); private static final Logger logger = LoggerFactory.getLogger(Utility.class);
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator."; public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JSONObject toJsonObject(OrientElement element, boolean raw) public static JSONObject toJsonObject(OrientElement element, boolean raw) throws ResourceRegistryException {
throws ResourceRegistryException {
try { try {
return new JSONObject(toJsonString(element, raw)); return new JSONObject(toJsonString(element, raw));
}catch(Exception e){ } catch(Exception e) {
throw new ResourceRegistryException(e); throw new ResourceRegistryException(e);
} }
} }
public static String toJsonString(OrientElement element, boolean raw) { public static String toJsonString(OrientElement element, boolean raw) {
ORecord oRecord = element.getRecord(); ORecord oRecord = element.getRecord();
return toJsonString(oRecord, raw); return toJsonString(oRecord, raw);
} }
public static String toJsonString(ORecord oRecord, boolean raw) { public static String toJsonString(ORecord oRecord, boolean raw) {
if (raw) { if(raw) {
return oRecord.toJSON(); return oRecord.toJSON();
} }
return oRecord.toJSON("class"); return oRecord.toJSON("class");
} }
public static JSONObject toJsonObject(Element element, boolean raw) public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException {
throws JSONException { if(raw) {
if (raw) { return GraphSONUtility.jsonFromElement(element, element.getPropertyKeys(), GraphSONMode.EXTENDED);
return GraphSONUtility.jsonFromElement(element,
element.getPropertyKeys(), GraphSONMode.EXTENDED);
} else { } else {
Set<String> keys = new HashSet<>(element.getPropertyKeys()); Set<String> keys = new HashSet<>(element.getPropertyKeys());
for (String key : element.getPropertyKeys()) { for(String key : element.getPropertyKeys()) {
if (key.startsWith("_")) { if(key.startsWith("_")) {
keys.remove(key); keys.remove(key);
} }
} }
return GraphSONUtility.jsonFromElement(element, keys, return GraphSONUtility.jsonFromElement(element, keys, GraphSONMode.EXTENDED);
GraphSONMode.EXTENDED);
} }
} }
public static String toJsonString(Element element, boolean raw) { public static String toJsonString(Element element, boolean raw) {
try { try {
return toJsonObject(element, true).toString(); return toJsonObject(element, true).toString();
} catch (Exception e) { } catch(Exception e) {
return String.valueOf(element); return String.valueOf(element);
} }
} }
public static <El extends Element> El getElementByUUIDAsAdmin(String elementType, UUID uuid, public static <El extends Element> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException { Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
OrientGraphNoTx orientGraphNoTx = null; OrientGraphNoTx orientGraphNoTx = null;
try { try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext(); AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER); orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz); return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz);
} finally { } finally {
if (orientGraphNoTx != null) { if(orientGraphNoTx != null) {
orientGraphNoTx.shutdown(); orientGraphNoTx.shutdown();
} }
} }
} }
public static <El extends Element> El getElementByUUID( public static <El extends Element> El getElementByUUID(Graph graph, String elementType, UUID uuid,
Graph graph, String elementType, UUID uuid,
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException { Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
if (elementType == null || elementType.compareTo("") == 0) { if(elementType == null || elementType.compareTo("") == 0) {
if (Vertex.class.isAssignableFrom(clz)) { if(Vertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME; elementType = Entity.NAME;
} }
if (Edge.class.isAssignableFrom(clz)) { if(Edge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME; elementType = Relation.NAME;
} }
} }
// TODO Rewrite using Gremlin // TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE " String select = "SELECT FROM " + elementType + " WHERE " + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ " = \"" + uuid.toString() + "\""; + " = \"" + uuid.toString() + "\"";
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select); OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute(); Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute();
if (elements == null || !elements.iterator().hasNext()) { if(elements == null || !elements.iterator().hasNext()) {
String error = String.format("No %s with UUID %s was found", String error = String.format("No %s with UUID %s was found", elementType, uuid.toString());
elementType, uuid.toString());
logger.info(error); logger.info(error);
throw new ERNotFoundException(error); throw new ERNotFoundException(error);
} }
Iterator<El> iterator = elements.iterator(); Iterator<El> iterator = elements.iterator();
El element = iterator.next(); El element = iterator.next();
logger.trace("{} with {} is : {}", elementType, uuid.toString(), logger.trace("{} with {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true));
Utility.toJsonString(element, true));
if(iterator.hasNext()) {
if (iterator.hasNext()) { throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
throw new ResourceRegistryException("Found more than one "
+ elementType + " with uuid " + uuid.toString()
+ ". This is a fatal error please contact Admnistrator"); + ". This is a fatal error please contact Admnistrator");
} }
return element; return element;
} }
public static <E extends Embedded> E getEmbedded(Class<E> clz, Element element, String property) public static <E extends Embedded> E getEmbedded(Class<E> clz, Element element, String property)
throws ResourceRegistryException { throws ResourceRegistryException {
@ -156,22 +142,20 @@ public class Utility {
ODocument oDocument = element.getProperty(property); ODocument oDocument = element.getProperty(property);
E e = ISMapper.unmarshal(clz, oDocument.toJSON()); E e = ISMapper.unmarshal(clz, oDocument.toJSON());
return e; return e;
} catch (Exception ex) { } catch(Exception ex) {
String error = String.format("Error while getting %s from %s", String error = String.format("Error while getting %s from %s", property, toJsonString(element, true));
property, toJsonString(element, true));
throw new ResourceRegistryException(error, ex); throw new ResourceRegistryException(error, ex);
} }
} }
public static UUID getUUID(Element element) public static UUID getUUID(Element element) throws ResourceRegistryException {
throws ResourceRegistryException {
/* /*
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY); * ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String
* String contextID = header.field(Header.UUID_PROPERTY); return * contextID = header.field(Header.UUID_PROPERTY); return
* UUID.fromString(contextID); * UUID.fromString(contextID);
*/ */
Header header = HeaderUtility.getHeader(element); Header header = HeaderUtility.getHeader(element);
return header.getUUID(); return header.getUUID();
} }
} }

View File

@ -30,6 +30,9 @@ public class ScopedTest {
protected static final String PROPERTIES_FILENAME = "token.properties"; protected static final String PROPERTIES_FILENAME = "token.properties";
private static final String GCUBE_VARNAME = "GCUBE";
public static final String GCUBE;
private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT"; private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT";
public static final String GCUBE_DEVNEXT; public static final String GCUBE_DEVNEXT;
@ -47,6 +50,7 @@ public class ScopedTest {
public static final String GCUBE_DEVNEXT_ANOTHER_USER; public static final String GCUBE_DEVNEXT_ANOTHER_USER;
public static final String DEFAULT_TEST_SCOPE; public static final String DEFAULT_TEST_SCOPE;
public static final String PARENT_DEFAULT_TEST_SCOPE;
public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER; public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER;
public static final String ALTERNATIVE_TEST_SCOPE; public static final String ALTERNATIVE_TEST_SCOPE;
@ -60,7 +64,9 @@ public class ScopedTest {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
GCUBE = properties.getProperty(GCUBE_VARNAME);
GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME); GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME);
GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME); GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME);
@ -71,8 +77,11 @@ public class ScopedTest {
DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT; DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT;
PARENT_DEFAULT_TEST_SCOPE = GCUBE;
DEFAULT_TEST_SCOPE_ANOTHER_USER = GCUBE_DEVNEXT_ANOTHER_USER; DEFAULT_TEST_SCOPE_ANOTHER_USER = GCUBE_DEVNEXT_ANOTHER_USER;
ALTERNATIVE_TEST_SCOPE = GCUBE_DEVNEXT_NEXTNEXT; ALTERNATIVE_TEST_SCOPE = GCUBE_DEVNEXT_NEXTNEXT;
} }
public static String getCurrentScope(String token) throws ObjectNotFound, Exception{ public static String getCurrentScope(String token) throws ObjectNotFound, Exception{

View File

@ -16,8 +16,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode; import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.SecurityType; import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -69,7 +71,8 @@ public class ContextManagementTest extends ScopedTest {
public static final String CTX_NAME_B = "B"; public static final String CTX_NAME_B = "B";
public static final String CTX_NAME_C = "C"; public static final String CTX_NAME_C = "C";
protected void assertions(Context pre, Context post, boolean checkParent, boolean create) throws ResourceRegistryException { protected void assertions(Context pre, Context post, boolean checkParent, boolean create)
throws ResourceRegistryException {
if (checkParent) { if (checkParent) {
if (pre.getHeader() != null) { if (pre.getHeader() != null) {
FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create); FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create);
@ -84,32 +87,34 @@ public class ContextManagementTest extends ScopedTest {
Context postParent = post.getParent().getSource(); Context postParent = post.getParent().getSource();
assertions(preParent, postParent, false, false); assertions(preParent, postParent, false, false);
} }
} }
protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException { protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException {
ContextSecurityContext contextSecurityContext = new ContextSecurityContext(); ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext); ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(),
contextSecurityContext);
OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER); OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER);
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph(); ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity(); OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
SecurityContext securityContext = new SecurityContext(uuid); SecurityContext securityContext = new SecurityContext(uuid);
for(PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, false); boolean[] booleanArray = new boolean[] { false, true };
ORole oRole = oSecurity.getRole(role); for (boolean hierarchic : booleanArray) {
Assert.assertEquals(oRole==null, deleted); for (PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false); ORole oRole = oSecurity.getRole(role);
OUser oUser = oSecurity.getUser(user); Assert.assertEquals(oRole == null, deleted);
Assert.assertEquals(oUser==null, deleted);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
OUser oUser = oSecurity.getUser(user);
Assert.assertEquals(oUser == null, deleted);
}
} }
} }
protected Context read(UUID uuid) throws ResourceRegistryException, IOException { protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
@ -366,15 +371,15 @@ public class ContextManagementTest extends ScopedTest {
delete(contextA1); delete(contextA1);
logger.debug("The DB should be now clean"); logger.debug("The DB should be now clean");
} }
@Test @Test
public void testGetAll() throws Exception { public void testGetAll() throws Exception {
ContextManagement contextManagement = new ContextManagement(); ContextManagement contextManagement = new ContextManagement();
String all = contextManagement.all(false); String all = contextManagement.all(false);
logger.trace(all); logger.trace(all);
List<Context> contexts = ISMapper.unmarshalList(Context.class, all); List<Context> contexts = ISMapper.unmarshalList(Context.class, all);
for(Context context : contexts){ for (Context context : contexts) {
logger.trace(ISMapper.marshal(context)); logger.trace(ISMapper.marshal(context));
List<IsParentOf<Context, Context>> children = context.getChildren(); List<IsParentOf<Context, Context>> children = context.getChildren();
for (IsParentOf<Context, Context> child : children) { for (IsParentOf<Context, Context> child : children) {
Assert.assertTrue(child.getSource() == context); Assert.assertTrue(child.getSource() == context);
@ -384,7 +389,7 @@ public class ContextManagementTest extends ScopedTest {
roleUserAssertions(context.getHeader().getUUID(), false); roleUserAssertions(context.getHeader().getUUID(), false);
} }
} }
// @Test // @Test
public void deleteContext() throws ResourceRegistryException, IOException { public void deleteContext() throws ResourceRegistryException, IOException {
Context context = read(UUID.fromString("")); Context context = read(UUID.fromString(""));
@ -435,14 +440,14 @@ public class ContextManagementTest extends ScopedTest {
Context parthenosRegistry = new ContextImpl("PARTHENOS_Registry"); Context parthenosRegistry = new ContextImpl("PARTHENOS_Registry");
parthenosRegistry.setParent(parthenosVO); parthenosRegistry.setParent(parthenosVO);
create(parthenosRegistry); create(parthenosRegistry);
} }
// @Test // @Test
public void createProductionMissingContext() throws Exception { public void createProductionMissingContext() throws Exception {
UUID d4ResearchUUID = UUID.fromString("8b926d1c-4460-4d7a-adab-c75ad2770a21"); UUID d4ResearchUUID = UUID.fromString("8b926d1c-4460-4d7a-adab-c75ad2770a21");
UUID farmUUID = UUID.fromString("dbafdb3e-f7f9-4039-ad1c-3432c041f53c"); UUID farmUUID = UUID.fromString("dbafdb3e-f7f9-4039-ad1c-3432c041f53c");
Map<String, UUID> contexts = new HashMap<>(); Map<String, UUID> contexts = new HashMap<>();
contexts.put("ICES_FIACO2017", d4ResearchUUID); contexts.put("ICES_FIACO2017", d4ResearchUUID);
contexts.put("D4STeam", farmUUID); contexts.put("D4STeam", farmUUID);

View File

@ -0,0 +1,15 @@
package org.gcube.informationsystem.resourceregistry.er;
import org.gcube.informationsystem.model.ER;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
public abstract class AbstractERManagementTest<Er extends ER> {
public abstract Er create(Er er) throws ResourceRegistryException;
public abstract Er update(Er er) throws ResourceRegistryException;
public abstract Er read(Er er) throws ResourceRegistryException;
public abstract boolean delete(Er er) throws ResourceRegistryException;
}

View File

@ -5,10 +5,14 @@ import java.util.UUID;
import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl; import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl;
import org.gcube.informationsystem.impl.utils.ISMapper; import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.model.ER; import org.gcube.informationsystem.model.ER;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.facet.SoftwareFacet; import org.gcube.informationsystem.model.entity.facet.SoftwareFacet;
import org.gcube.informationsystem.resourceregistry.ScopedTest; import org.gcube.informationsystem.resourceregistry.ScopedTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.utils.Utility;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.er.ERManagementTest; import org.gcube.informationsystem.resourceregistry.er.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility; import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.junit.Assert; import org.junit.Assert;
@ -16,8 +20,11 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class FacetManagementTest extends ScopedTest { public class FacetManagementTest extends ScopedTest {
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class); private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
public static final String GROUP = "InformationSystem"; public static final String GROUP = "InformationSystem";
@ -33,134 +40,276 @@ public class FacetManagementTest extends ScopedTest {
return softwareFacet; return softwareFacet;
} }
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, String version) {
Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP) == 0);
Assert.assertTrue(softwareFacet.getName().compareTo(NAME) == 0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(version) == 0);
}
public static void checkHeader(ER er, UUID uuid, boolean create) { public static void checkHeader(ER er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader()!=null); Assert.assertTrue(er.getHeader() != null);
Assert.assertTrue(er.getHeader().getUUID()!=null); Assert.assertTrue(er.getHeader().getUUID() != null);
if(uuid!=null) { if(uuid != null) {
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid)==0); Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0);
} }
String user = HeaderUtility.getUser(); String user = HeaderUtility.getUser();
Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user)==0); Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user) == 0);
if(create){ if(create) {
Assert.assertTrue(er.getHeader().getCreator().compareTo(user)==0); Assert.assertTrue(er.getHeader().getCreator().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime())==0); Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
}else { } else {
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime())); Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
} }
} }
public static void checkAssertion(SoftwareFacet softwareFacet, String version, UUID uuid, boolean create) { public static void checkAssertion(Facet facet, UUID uuid, boolean create) {
checkHeader(softwareFacet, uuid, create); checkHeader(facet, uuid, create);
Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP)==0);
Assert.assertTrue(softwareFacet.getName().compareTo(NAME)==0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(version)==0);
} }
protected <F extends Facet> F create(F facet) throws Exception {
FacetManagement facetManagement = new FacetManagement();
String facetType = Utility.getType(facet);
facetManagement.setElementType(facetType);
facetManagement.setJSON(ISMapper.marshal(facet));
String json = facetManagement.create();
logger.debug("Created : {}", json);
@SuppressWarnings("unchecked")
F createdFacet = (F) ISMapper.unmarshal(facet.getClass(), json);
logger.debug("Unmarshalled {}", createdFacet);
UUID uuid = null;
if(facet.getHeader() != null) {
uuid = facet.getHeader().getUUID();
}
checkAssertion(createdFacet, uuid, true);
return createdFacet;
}
protected <F extends Facet> F update(F facet) throws Exception {
FacetManagement facetManagement = new FacetManagement();
String facetType = Utility.getType(facet);
facetManagement.setElementType(facetType);
facetManagement.setJSON(ISMapper.marshal(facet));
String json = facetManagement.update();
logger.debug("Updated : {}", json);
@SuppressWarnings("unchecked")
F updatedFacet = (F) ISMapper.unmarshal(facet.getClass(), json);
logger.debug("Unmarshalled {}", updatedFacet);
UUID uuid = facet.getHeader().getUUID();
checkAssertion(updatedFacet, uuid, false);
return updatedFacet;
}
protected <F extends Facet> F read(F facet) throws Exception {
UUID uuid = facet.getHeader().getUUID();
FacetManagement facetManagement = new FacetManagement();
String facetType = Utility.getType(facet);
facetManagement.setElementType(facetType);
facetManagement.setUUID(uuid);
String json = facetManagement.read();
logger.debug("Read : {}", json);
@SuppressWarnings("unchecked")
F readFacet = (F) ISMapper.unmarshal(facet.getClass(), json);
logger.debug("Unmarshalled {}", readFacet);
checkAssertion(readFacet, uuid, false);
return readFacet;
}
protected <F extends Facet> boolean delete(F facet) throws Exception {
FacetManagement facetManagement = new FacetManagement();
String facetType = Utility.getType(facet);
facetManagement.setElementType(facetType);
facetManagement.setUUID(facet.getHeader().getUUID());
boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted);
try {
read(facet);
} catch(FacetNotFoundException e) {
logger.info("Facet not found as expected");
}
return deleted;
}
protected <F extends Facet> boolean addToContext(F facet) throws Exception {
FacetManagement facetManagement = new FacetManagement();
String facetType = Utility.getType(facet);
facetManagement.setElementType(facetType);
facetManagement.setUUID(facet.getHeader().getUUID());
boolean added = facetManagement.addToContext();
Assert.assertTrue(added);
return added;
}
protected <F extends Facet> boolean removeFromContext(F facet) throws Exception {
FacetManagement facetManagement = new FacetManagement();
String facetType = Utility.getType(facet);
facetManagement.setElementType(facetType);
facetManagement.setUUID(facet.getHeader().getUUID());
boolean added = facetManagement.removeFromContext();
Assert.assertTrue(added);
return added;
}
interface ActionFunction<F extends Facet> {
void call(F facet) throws Exception;
}
protected <F extends Facet, C extends Exception, E extends Exception> void assertThrow(F facet, Class<C> c,
ActionFunction<F> action) throws Exception {
try {
action.call(facet);
throw new RuntimeException("Expected " + c.getName());
} catch(Exception e) {
if(c.isAssignableFrom(e.getClass())) {
logger.debug("As expected {} has been thrown", c.getName());
return;
}
throw e;
}
}
@Test @Test
public void createUpdateReadDelete() throws Exception { public void createUpdateReadDelete() throws Exception {
SoftwareFacet softwareFacet = getSoftwareFacet(); SoftwareFacet softwareFacet = getSoftwareFacet();
/* Testing Create */ /* Testing Create */
FacetManagement facetManagement = new FacetManagement(); softwareFacet = create(softwareFacet);
facetManagement.setElementType(SoftwareFacet.NAME); checkSoftwareFacetAssertion(softwareFacet, VERSION);
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
String json = facetManagement.create();
logger.debug("Created : {}", json);
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
logger.debug("Unmarshalled {}", softwareFacet);
checkAssertion(softwareFacet, VERSION, null, true);
UUID uuid = softwareFacet.getHeader().getUUID();
/* Testing Update */ /* Testing Update */
softwareFacet.setVersion(NEW_VERSION); softwareFacet.setVersion(NEW_VERSION);
softwareFacet = update(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
json = facetManagement.update();
logger.debug("Updated : {}", json);
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
logger.debug("Unmarshalled {}", softwareFacet);
checkAssertion(softwareFacet, NEW_VERSION, uuid, false);
/* Testing Read */ /* Testing Read */
facetManagement = new FacetManagement(); softwareFacet = read(softwareFacet);
facetManagement.setElementType(SoftwareFacet.NAME); checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
facetManagement.setUUID(uuid);
json = facetManagement.read(); assertThrow(softwareFacet, FacetAlreadyPresentException.class, (SoftwareFacet s) -> {
logger.debug("Read : {}", json); create(s);
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json); });
logger.debug("Unmarshalled {}", softwareFacet);
checkAssertion(softwareFacet, NEW_VERSION, uuid, false);
/* Testing Create the facet with the same UUID */
facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
try {
facetManagement.create();
}catch (FacetAlreadyPresentException e) {
logger.info("Facet already present as expected");
}
/* Testing Delete */
boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted);
facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setUUID(uuid);
try {
facetManagement.read();
}catch (FacetNotFoundException e) {
logger.info("Facet not found as expected");
}
/* Testing Delete */
delete(softwareFacet);
/* Testing new Create to check creation with provided UUID */ /* Testing new Create to check creation with provided UUID */
facetManagement = new FacetManagement(); softwareFacet = create(softwareFacet);
facetManagement.setElementType(SoftwareFacet.NAME); checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
json = facetManagement.create();
logger.debug("Created : {}", json);
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
logger.debug("Unmarshalled {}", softwareFacet);
checkAssertion(softwareFacet, NEW_VERSION, uuid, true); delete(softwareFacet);
}
@Test
public void testHierarchy() throws Exception {
/* Setting scope /gcube/devNext/NextNext */
ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT);
/* Testing Delete */ SoftwareFacet softwareFacet = getSoftwareFacet();
deleted = facetManagement.delete();
Assert.assertTrue(deleted);
facetManagement = new FacetManagement(); /* Testing Create */
facetManagement.setElementType(SoftwareFacet.NAME); softwareFacet = create(softwareFacet);
facetManagement.setUUID(uuid); checkSoftwareFacetAssertion(softwareFacet, VERSION);
try { softwareFacet = update(softwareFacet);
facetManagement.read(); checkSoftwareFacetAssertion(softwareFacet, VERSION);
}catch (FacetNotFoundException e) {
logger.info("Facet not found as expected"); /* Testing Read */
} softwareFacet = read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
/* Setting (parent) scope /gcube/devNext */
ScopedTest.setContext(GCUBE_DEVNEXT);
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
read(s);
});
/* Entering hierarchic mode */
ContextUtility.getHierarchicMode().set(true);
softwareFacet = read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
/* Setting (parent of parent) scope /gcube */
ScopedTest.setContext(GCUBE);
softwareFacet = read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
/* Leaving hierarchic mode */
ContextUtility.getHierarchicMode().set(false);
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
read(s);
});
/* Adding to /gcube. The context are now /gcube and /gcube/devNext/NextNext */
addToContext(softwareFacet);
softwareFacet = read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
softwareFacet.setVersion(NEW_VERSION);
softwareFacet = update(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
/* Restoring scope /gcube/devNext/NextNext */
ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT);
read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
/* Removing from /gcube/devNext/NextNext. The context is now /gcube */
removeFromContext(softwareFacet);
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
read(s);
});
/* Setting (parent) scope /gcube/devNext */
ScopedTest.setContext(GCUBE_DEVNEXT);
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
read(s);
});
/* Entering hierarchic mode */
ContextUtility.getHierarchicMode().set(true);
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
read(s);
});
/* Setting (parent of parent) scope /gcube */
ScopedTest.setContext(GCUBE);
// The facet must be readable in hierarchic mode in /gcube because the context
// has been explicitly added
read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
/* Leaving hierarchic mode */
ContextUtility.getHierarchicMode().set(false);
read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
delete(softwareFacet);
} }
} }

View File

@ -27,12 +27,11 @@ public class ResourceManagementTest extends ScopedTest {
private static Logger logger = LoggerFactory.getLogger(ResourceManagementTest.class); private static Logger logger = LoggerFactory.getLogger(ResourceManagementTest.class);
public static void checkAssertion(EService eService, String version, UUID eServiceUUID, boolean create) { public static void checkAssertion(EService eService, UUID eServiceUUID, boolean create) {
FacetManagementTest.checkHeader(eService, eServiceUUID, create); FacetManagementTest.checkHeader(eService, eServiceUUID, create);
SoftwareFacet softwareFacet = eService.getFacets(SoftwareFacet.class).get(0); SoftwareFacet softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
FacetManagementTest.checkAssertion(softwareFacet, version, null, create); FacetManagementTest.checkAssertion(softwareFacet, null, create);
} }
@ -55,7 +54,8 @@ public class ResourceManagementTest extends ScopedTest {
logger.trace("Created {}", json); logger.trace("Created {}", json);
eService = ISMapper.unmarshal(EService.class, json); eService = ISMapper.unmarshal(EService.class, json);
checkAssertion(eService, FacetManagementTest.VERSION, null, true); checkAssertion(eService, null, true);
FacetManagementTest.checkSoftwareFacetAssertion(softwareFacet, FacetManagementTest.VERSION);
UUID uuid = eService.getHeader().getUUID(); UUID uuid = eService.getHeader().getUUID();
softwareFacet = eService.getFacets(SoftwareFacet.class).get(0); softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
@ -72,7 +72,9 @@ public class ResourceManagementTest extends ScopedTest {
logger.trace("Updated {}", json); logger.trace("Updated {}", json);
eService = ISMapper.unmarshal(EService.class, json); eService = ISMapper.unmarshal(EService.class, json);
checkAssertion(eService, FacetManagementTest.NEW_VERSION, uuid, false); checkAssertion(eService, uuid, false);
softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
FacetManagementTest.checkSoftwareFacetAssertion(softwareFacet, FacetManagementTest.NEW_VERSION);
resourceManagement = new ResourceManagement(); resourceManagement = new ResourceManagement();

View File

@ -8,7 +8,6 @@ import java.net.URL;
import java.util.Calendar; import java.util.Calendar;
import java.util.UUID; import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.impl.embedded.PropagationConstraintImpl; import org.gcube.informationsystem.impl.embedded.PropagationConstraintImpl;
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl; import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl; import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl;
@ -25,11 +24,9 @@ import org.gcube.informationsystem.impl.relation.consistsof.HasPersistentMemoryI
import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl; import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl;
import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl; import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl;
import org.gcube.informationsystem.impl.utils.ISMapper; import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.model.embedded.Header;
import org.gcube.informationsystem.model.embedded.PropagationConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint;
import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint; import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.entity.Facet; import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.facet.AccessPointFacet; import org.gcube.informationsystem.model.entity.facet.AccessPointFacet;
import org.gcube.informationsystem.model.entity.facet.CPUFacet; import org.gcube.informationsystem.model.entity.facet.CPUFacet;
@ -53,6 +50,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.er.SmartgearResourcesTest; import org.gcube.informationsystem.resourceregistry.er.SmartgearResourcesTest;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement; import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement; import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -85,10 +83,9 @@ public class BasicTest extends ScopedTest {
String json = facetManagement.create(); String json = facetManagement.create();
logger.debug("Created : {}", json); logger.debug("Created : {}", json);
JSONObject jsonObject = new JSONObject(json); CPUFacet createdCPUFacet = ISMapper.unmarshal(CPUFacet.class, json);
JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY); UUID uuid = createdCPUFacet.getHeader().getUUID();
UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY));
facetManagement = new FacetManagement(); facetManagement = new FacetManagement();
facetManagement.setUUID(uuid); facetManagement.setUUID(uuid);
@ -98,7 +95,7 @@ public class BasicTest extends ScopedTest {
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
logger.debug("Switching to another scope"); logger.debug("Switching to another scope");
ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE); ScopedTest.setContext(ScopedTest.PARENT_DEFAULT_TEST_SCOPE);
try { try {
facetManagement = new FacetManagement(); facetManagement = new FacetManagement();
facetManagement.setUUID(uuid); facetManagement.setUUID(uuid);
@ -111,6 +108,19 @@ public class BasicTest extends ScopedTest {
logger.debug("Good the facet created in the default context is not visible in an alternative context"); logger.debug("Good the facet created in the default context is not visible in an alternative context");
} }
/* ---------------- entering hierarchic mode */
ContextUtility.getHierarchicMode().set(true);
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
readJson = facetManagement.read();
logger.debug("You should be able to read it {}", readJson);
ContextUtility.getHierarchicMode().set(false);
/* ---------------- leaving hierarchic mode */
cpuFacet.setAdditionalProperty("My", "Test"); cpuFacet.setAdditionalProperty("My", "Test");
try { try {
@ -126,20 +136,6 @@ public class BasicTest extends ScopedTest {
logger.debug("Good the Facet created in the default context cannot be updated in an alternative context"); logger.debug("Good the Facet created in the default context cannot be updated in an alternative context");
} }
/* Commented because the behavior has been changed
try {
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
facetManagement.delete();
logger.debug("You should not be able to delete Facet with UUID {}",
uuid);
throw new Exception(
"You should not be able to delete Facet with UUID " + uuid);
} catch (FacetAvailableInAnotherContextException e) {
logger.debug("Good the Facet created in the default context cannot be deleted in an alternative context");
}
*/
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
logger.debug("Setting back default scope"); logger.debug("Setting back default scope");
@ -158,6 +154,7 @@ public class BasicTest extends ScopedTest {
facetManagement = new FacetManagement(); facetManagement = new FacetManagement();
facetManagement.setUUID(uuid); facetManagement.setUUID(uuid);
boolean deleted = facetManagement.delete(); boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted); Assert.assertTrue(deleted);
} }