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

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

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;
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.context.ContextException;
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.utils.Utility;
import org.slf4j.Logger;
@ -31,19 +30,18 @@ import com.tinkerpop.blueprints.Vertex;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class ContextUtility {
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
private Map<String, UUID> contextUUIDs;
private Map<UUID, SecurityContext> contexts;
private Map<String,UUID> contextUUIDs;
private Map<UUID,SecurityContext> contexts;
private static ContextUtility contextUtility;
public static ContextUtility getInstace() {
if (contextUtility == null) {
if(contextUtility == null) {
contextUtility = new ContextUtility();
}
return contextUtility;
@ -54,12 +52,25 @@ public class ContextUtility {
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() {
String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null;
try {
authorizationEntry = Constants.authorizationService().get(token);
} catch (Exception e) {
} catch(Exception e) {
return ScopeProvider.instance.get();
}
return authorizationEntry.getContext();
@ -67,23 +78,22 @@ public class ContextUtility {
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
String fullName = getCurrentContextFullName();
if (fullName == null) {
if(fullName == null) {
throw new ContextException("Null Token and Scope. Please set your token first.");
}
return ContextUtility.getInstace().getSecurityContextByFullName(fullName);
}
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace().
getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace()
.getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
return adminSecurityContext;
}
public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException {
for (String fullName : contextUUIDs.keySet()) {
for(String fullName : contextUUIDs.keySet()) {
UUID uuidKey = contextUUIDs.get(fullName);
if (uuidKey.compareTo(uuid) == 0) {
if(uuidKey.compareTo(uuid) == 0) {
contextUUIDs.remove(fullName);
contexts.remove(uuid);
return;
@ -103,7 +113,7 @@ public class ContextUtility {
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), 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(),
fullName);
@ -120,9 +130,9 @@ public class ContextUtility {
return securityContext;
} catch (ContextException e) {
} catch(ContextException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ContextException("Unable to restrive Context UUID from current Context", e);
}
}
@ -138,22 +148,22 @@ public class ContextUtility {
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid);
if (securityContext == null) {
if(securityContext == null) {
securityContext = new SecurityContext(uuid);
try {
if (contextVertex == null) {
if(contextVertex == null) {
contextVertex = getContextVertexByUUID(uuid);
}
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next();
if (parentVertex != null) {
if(parentVertex != null) {
UUID parentUUID = Utility.getUUID(parentVertex);
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
}
} catch (NoSuchElementException e) {
} catch(NoSuchElementException e) {
// No parent
}
@ -181,7 +191,7 @@ public class ContextUtility {
Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
.execute();
if (vertexes == null || !vertexes.iterator().hasNext()) {
if(vertexes == null || !vertexes.iterator().hasNext()) {
throw new ContextNotFoundException("Error retrieving context with name " + fullName);
}
@ -190,7 +200,7 @@ public class ContextUtility {
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
+ "but required the one with path" + fullName + ". Please Reimplement the query");
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context;
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.isparentof.IsParentOfAlreadyPresentException;
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.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
@ -29,7 +27,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("rawtypes")
public class IsParentOfManagement extends RelationManagement<IsParentOf, ContextManagement, ContextManagement> {
public class IsParentOfManagement extends RelationManagement<IsParentOf,ContextManagement,ContextManagement> {
public IsParentOfManagement() {
super(AccessType.IS_PARENT_OF);
@ -44,7 +42,8 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
workingContext = ContextUtility.getInstace()
.getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
return workingContext;
}
@ -60,7 +59,7 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
if(propagationConstraint.has(PropagationConstraint.REMOVE_PROPERTY)) {
String removeProperty = propagationConstraint.get(PropagationConstraint.REMOVE_PROPERTY).asText();
RemoveConstraint removeConstraint = RemoveConstraint.valueOf(removeProperty);
if(removeConstraint!=RemoveConstraint.keep){
if(removeConstraint != RemoveConstraint.keep) {
message = new StringBuilder();
message.append(RemoveConstraint.class.getSimpleName());
message.append(" can only be ");
@ -71,10 +70,10 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
if(propagationConstraint.has(PropagationConstraint.ADD_PROPERTY)) {
String addProperty = propagationConstraint.get(PropagationConstraint.ADD_PROPERTY).asText();
AddConstraint addConstraint = AddConstraint.valueOf(addProperty);
if(addConstraint!=AddConstraint.unpropagate){
if(message==null) {
if(addConstraint != AddConstraint.unpropagate) {
if(message == null) {
message = new StringBuilder();
}else {
} else {
message.append(" and ");
}
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());
}
}
@ -118,21 +117,21 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
Vertex source = element.getVertex(Direction.OUT);
ContextManagement sourceContextManagement = new ContextManagement(orientGraph);
sourceContextManagement.setElement(source);
if (includeSource) {
if(includeSource) {
relation.put(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
}
Vertex target = element.getVertex(Direction.IN);
ContextManagement targetContextManagement = new ContextManagement(orientGraph);
targetContextManagement.setElement(target);
if (includeTarget) {
if(includeTarget) {
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);
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}

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;
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.embedded.Embedded;
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.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SchemaSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -40,7 +37,6 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class DatabaseEnvironment {
@ -82,7 +78,7 @@ public class DatabaseEnvironment {
private static final String 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;
@ -135,12 +131,12 @@ public class DatabaseEnvironment {
String changedAdminUsername = null;
try {
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
if (changedAdminUsername == null) {
if(changedAdminUsername == null) {
// To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB;
}
} catch (Exception e) {
} catch(Exception e) {
// To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB;
@ -155,18 +151,16 @@ public class DatabaseEnvironment {
DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_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.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
throw new RuntimeException("Unable to load properties", e);
}
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
@ -178,7 +172,6 @@ public class DatabaseEnvironment {
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
try {
boolean created = initGraphDB();
@ -190,10 +183,10 @@ public class DatabaseEnvironment {
ContextSecurityContext contextSecurityContext = new 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);
if (created) {
if(created) {
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD).setupPool(1, 10);
OrientGraph orientGraph = factory.getTx();
@ -209,7 +202,7 @@ public class DatabaseEnvironment {
createEntitiesAndRelations();
}
} catch (Exception e) {
} catch(Exception e) {
logger.error("Error initializing database connection", e);
throw new RuntimeException("Error initializing database connection", e);
}
@ -225,7 +218,7 @@ public class DatabaseEnvironment {
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
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);
serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE);
@ -263,7 +256,7 @@ public class DatabaseEnvironment {
OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
newAdminUser.save();
for (PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
for(PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
oUser.save();

View File

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

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er;
import java.io.IOException;
@ -32,8 +29,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailabl
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
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.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient;
@ -129,7 +126,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public void setUUID(UUID uuid) throws ResourceRegistryException {
this.uuid = uuid;
if (jsonNode != null) {
if(jsonNode != null) {
checkUUIDMatch();
}
}
@ -143,15 +140,15 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
ObjectMapper mapper = new ObjectMapper();
try {
this.jsonNode = mapper.readTree(jsonRepresentation);
} catch (IOException e) {
} catch(IOException e) {
throw new ResourceRegistryException(e);
}
checkJSON();
}
protected OClass getOClass() throws SchemaException, ResourceRegistryException {
if (oClass == null) {
if (element != null) {
if(oClass == null) {
if(element != null) {
OrientElement orientElement = (OrientElement) element;
OMetadata oMetadata = orientElement.getGraph().getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema();
@ -166,25 +163,25 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public void setElementType(String erType) throws ResourceRegistryException {
this.erType = erType;
if (erType == null || erType.compareTo("") == 0) {
if(erType == null || erType.compareTo("") == 0) {
erType = accessType.getName();
}
if (jsonNode != null) {
if(jsonNode != null) {
checkERMatch();
}
}
protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) {
if(uuid == null) {
try {
uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {
} catch(Exception e) {
}
} else {
checkUUIDMatch();
}
if (this.erType == null) {
if(this.erType == null) {
this.erType = getClassProperty(jsonNode);
getOClass();
} else {
@ -193,9 +190,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
protected void checkERMatch() throws ResourceRegistryException {
if (jsonNode != null) {
if(jsonNode != null) {
String type = getClassProperty(jsonNode);
if (type != null && type.compareTo(erType) != 0) {
if(type != null && type.compareTo(erType) != 0) {
String error = String.format("Declared resourceType does not match with json representation %s!=%s",
erType, type);
logger.trace(error);
@ -209,13 +206,13 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
if (header != null) {
if(header != null) {
UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) {
if(resourceUUID.compareTo(uuid) != 0) {
String error = String.format(
"UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(), erType);
@ -228,7 +225,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public JSONObject serializeSelfOnly() throws ResourceRegistryException {
try {
return toJSONObject();
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@ -244,7 +241,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
reallyCreate();
Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
if (entityHeader != null) {
if(entityHeader != null) {
element.setProperty(Entity.HEADER_PROPERTY, entityHeader);
} else {
entityHeader = HeaderUtility.addHeader(element, null);
@ -255,9 +252,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
((OrientElement) element).save();
return element;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause());
}
}
@ -273,9 +270,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
((OrientElement) element).save();
return element;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException("Error Updating " + erType + " with " + jsonNode, e.getCause());
}
}
@ -283,7 +280,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public El internalCreateOrUdate() throws ResourceRegistryException {
try {
return internalUpdate();
} catch (ERNotFoundException e) {
} catch(ERNotFoundException e) {
return internalCreate();
}
}
@ -303,9 +300,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save();
return ret && true;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException("Error Adding " + erType + " to Current Context ", e.getCause());
}
}
@ -318,15 +315,15 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
HeaderUtility.updateModifiedByAndLastUpdate(element);
((OrientElement) element).save();
return ret && true;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause());
}
}
public void setElement(El element) throws ResourceRegistryException {
if (element == null) {
if(element == null) {
throw new ResourceRegistryException("Trying to set null " + elementClass.getSimpleName() + " in " + this);
}
this.element = element;
@ -341,28 +338,28 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message);
public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
if (element == null) {
if(element == null) {
try {
element = retrieveElement();
} catch (ERNotFoundException e) {
} catch(ERNotFoundException e) {
try {
retrieveElementFromAnyContext();
throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName()
: erType + " with UUID " + uuid + " is available in another "
+ Context.class.getSimpleName());
} catch (ERAvailableInAnotherContextException e1) {
} catch(ERAvailableInAnotherContextException e1) {
throw e1;
} catch (Exception e1) {
} catch(Exception e1) {
throw e;
}
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
} else {
if (reload) {
if(reload) {
((OrientElement) element).reload();
}
}
@ -371,16 +368,16 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public El retrieveElement() throws ERNotFoundException, ResourceRegistryException {
try {
if (uuid == null) {
if(uuid == null) {
throw new ERNotFoundException("null UUID does not allow to retrieve the Element");
}
return Utility.getElementByUUID(orientGraph, erType == null ? accessType.getName() : erType, uuid,
elementClass);
} catch (ERNotFoundException e) {
} catch(ERNotFoundException e) {
throw getSpecificElementNotFoundException(e);
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@ -388,11 +385,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public El retrieveElementFromAnyContext() throws ERNotFoundException, ResourceRegistryException {
try {
return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass);
} catch (ERNotFoundException e) {
} catch(ERNotFoundException e) {
throw getSpecificElementNotFoundException(e);
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@ -405,12 +402,12 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAll(polymorphic);
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -424,14 +421,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
getElement();
return true;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid);
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e);
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -450,20 +447,20 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return serialize();
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to create {}", accessType.getName());
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to create {}", accessType.getName(), e);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -476,14 +473,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
getElement();
return serialize();
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid);
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e);
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -498,24 +495,25 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
orientGraph.commit();
setReload(true);
// TODO Notify to subscriptionNotification
return serialize();
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -531,7 +529,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
boolean deleted = reallyDelete();
if (deleted) {
if(deleted) {
orientGraph.commit();
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
} else {
@ -541,27 +539,28 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return deleted;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
}
public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException {
logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid, getWorkingContext().toString());
logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid,
getWorkingContext().toString());
try {
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
@ -572,20 +571,20 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
return added;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -604,27 +603,27 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
logger.info("{} with UUID {} successfully removed from actual Context", accessType.getName(), uuid);
return removed;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid, e);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
}
public static String getClassProperty(JsonNode jsonNode) {
if (jsonNode.has(ISManageable.CLASS_PROPERTY)) {
if(jsonNode.has(ISManageable.CLASS_PROPERTY)) {
return jsonNode.get(ISManageable.CLASS_PROPERTY).asText();
}
return null;
@ -634,16 +633,22 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
throws UnsupportedDataTypeException, ResourceRegistryException {
JsonNodeType jsonNodeType = value.getNodeType();
switch (jsonNodeType) {
switch(jsonNodeType) {
case OBJECT:
return EmbeddedMangement.getEmbeddedType(value);
case ARRAY:
/*
* List<Object> list = new ArrayList<Object>(); Iterator<JsonNode> arrayElement
* = value.elements(); while (arrayElement.hasNext()) { JsonNode arrayNode =
* arrayElement.next(); Object objectNode = getObjectFromElement(arrayNode); if
* (objectNode != null) { list.add(objectNode); } } return list;
List<Object> list = new ArrayList<Object>();
Iterator<JsonNode> arrayElement = value.elements();
while(arrayElement.hasNext()) {
JsonNode arrayNode = arrayElement.next();
Object objectNode = getObjectFromElement(arrayNode);
if(objectNode != null) {
list.add(objectNode);
}
}
return list;
*/
throw new UnsupportedDataTypeException(
"List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
@ -658,14 +663,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
break;
case NUMBER:
if (value.isDouble() || value.isFloat()) {
if(value.isDouble() || value.isFloat()) {
return value.asDouble();
}
if (value.isBigInteger() || value.isShort() || value.isInt()) {
if(value.isBigInteger() || value.isShort() || value.isInt()) {
return value.asInt();
}
if (value.isLong()) {
if(value.isLong()) {
return value.asLong();
}
break;
@ -686,32 +691,32 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return null;
}
public static Map<String, Object> getPropertyMap(JsonNode jsonNode, Set<String> ignoreKeys,
public static Map<String,Object> getPropertyMap(JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreStartWith) throws JsonProcessingException, IOException {
Map<String, Object> map = new HashMap<>();
Map<String,Object> map = new HashMap<>();
if (ignoreKeys == null) {
if(ignoreKeys == null) {
ignoreKeys = new HashSet<>();
}
if (ignoreStartWith == null) {
if(ignoreStartWith == null) {
ignoreStartWith = new HashSet<>();
}
Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
Iterator<Entry<String,JsonNode>> fields = jsonNode.fields();
OUTER_WHILE: while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
OUTER_WHILE: while(fields.hasNext()) {
Entry<String,JsonNode> entry = fields.next();
String key = entry.getKey();
if (ignoreKeys.contains(key)) {
if(ignoreKeys.contains(key)) {
continue;
}
for (String prefix : ignoreStartWith) {
if (key.startsWith(prefix)) {
for(String prefix : ignoreStartWith) {
if(key.startsWith(prefix)) {
continue OUTER_WHILE;
}
}
@ -720,10 +725,10 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
Object object = null;
try {
object = getObjectFromElement(value);
if (object != null) {
if(object != null) {
map.put(key, object);
}
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
staticLogger.warn("An invalidy property has been provided. It will be ignored.");
}
@ -737,11 +742,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
Set<String> oldKeys = element.getPropertyKeys();
Map<String, Object> properties;
if (element instanceof Vertex || element instanceof Edge) {
Map<String,Object> properties;
if(element instanceof Vertex || element instanceof Edge) {
try {
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
} catch (IOException e) {
} catch(IOException e) {
throw new ResourceRegistryException(e);
}
} else {
@ -751,15 +756,15 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
oldKeys.removeAll(properties.keySet());
for (String key : properties.keySet()) {
for(String key : properties.keySet()) {
try {
Object object = properties.get(key);
if (!oClass.existsProperty(key)) {
if(!oClass.existsProperty(key)) {
boolean set = false;
if (object instanceof ODocument) {
if(object instanceof ODocument) {
ODocument oDocument = (ODocument) object;
((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED);
set = true;
@ -767,13 +772,12 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
/*
* if(object instanceof Set){ ((OrientElement) element).setProperty(key, object,
* OType.EMBEDDEDSET); set = true; }
*
* if(object instanceof List){ ((OrientElement) element).setProperty(key,
* object, OType.EMBEDDEDLIST); set = true; }
* OType.EMBEDDEDSET); set = true; } if(object instanceof List){
* ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); set =
* true; }
*/
if (!set) {
if(!set) {
element.setProperty(key, object);
}
@ -781,7 +785,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
element.setProperty(key, object);
}
} catch (Exception e) {
} catch(Exception e) {
String error = String.format("Error while setting property %s : %s (%s)", key,
properties.get(key).toString(), e.getMessage());
staticLogger.error(error);
@ -789,14 +793,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
OUTER_FOR: for (String key : oldKeys) {
OUTER_FOR: for(String key : oldKeys) {
if (ignoreKeys.contains(key)) {
if(ignoreKeys.contains(key)) {
continue;
}
for (String prefix : ignoreStartWithKeys) {
if (key.startsWith(prefix)) {
for(String prefix : ignoreStartWithKeys) {
if(key.startsWith(prefix)) {
continue OUTER_FOR;
}
}
@ -811,34 +815,34 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException {
try {
if (key.compareTo(ER.HEADER_PROPERTY) == 0) {
if(key.compareTo(ER.HEADER_PROPERTY) == 0) {
// Keeping the header
HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object);
JSONObject headerObject = new JSONObject(headerOrient.toJSON("class"));
return headerObject;
}
if (ignoreKeys.contains(key)) {
if(ignoreKeys.contains(key)) {
return null;
}
for (String prefix : ignoreStartWithKeys) {
if (key.startsWith(prefix)) {
for(String prefix : ignoreStartWithKeys) {
if(key.startsWith(prefix)) {
return null;
}
}
if (object instanceof ODocument) {
if(object instanceof ODocument) {
String json = ((ODocument) object).toJSON("class");
JSONObject jsonObject = new JSONObject(json);
return jsonObject;
}
if (object instanceof Date) {
if(object instanceof Date) {
OProperty oProperty = getOClass().getProperty(key);
OType oType = oProperty.getType();
DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance();
switch (oType) {
switch(oType) {
case DATE:
dateFormat = ODateHelper.getDateFormatInstance();
break;
@ -854,10 +858,10 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return dateFormat.format((Date) object);
}
if (object instanceof Collection) {
if(object instanceof Collection) {
Collection<?> collection = (Collection<?>) object;
JSONArray jsonArray = new JSONArray();
for (Object o : collection) {
for(Object o : collection) {
Object obj = getPropertyForJson("PLACEHOLDER", o);
jsonArray.put(obj);
}
@ -867,7 +871,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return object.toString();
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(
"Error while serializing " + key + "=" + object.toString() + " in " + getElement().toString(), e);
}
@ -876,9 +880,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected Collection<String> getSuperclasses() throws SchemaException, ResourceRegistryException {
Collection<OClass> allSuperClasses = getOClass().getAllSuperClasses();
Collection<String> superClasses = new HashSet<>();
for (OClass oSuperClass : allSuperClasses) {
for(OClass oSuperClass : allSuperClasses) {
String name = oSuperClass.getName();
if (name.compareTo(StringFactory.V.toUpperCase()) == 0 || name.compareTo(StringFactory.E.toUpperCase()) == 0
if(name.compareTo(StringFactory.V.toUpperCase()) == 0 || name.compareTo(StringFactory.E.toUpperCase()) == 0
|| name.compareTo(DatabaseEnvironment.O_RESTRICTED_CLASS) == 0) {
continue;
}
@ -892,11 +896,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
try {
OrientElement orientElement = (OrientElement) getElement();
Map<String, Object> properties = orientElement.getProperties();
for (String key : orientElement.getPropertyKeys()) {
Map<String,Object> properties = orientElement.getProperties();
for(String key : orientElement.getPropertyKeys()) {
Object object = properties.get(key);
object = getPropertyForJson(key, object);
if (object != null) {
if(object != null) {
properties.put(key, object);
} else {
properties.remove(key);
@ -913,9 +917,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray);
return jsonObject;
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException("Error while serializing " + getElement().toString(), e);
}
}

View File

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

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er;
import java.util.HashSet;
@ -24,8 +21,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
*/
public class EmbeddedMangement {
private static Logger logger = LoggerFactory
.getLogger(EmbeddedMangement.class);
private static Logger logger = LoggerFactory.getLogger(EmbeddedMangement.class);
public static final Set<String> EMBEDDED_IGNORE_KEYS;
public static final Set<String> EMBEDDED_IGNORE_START_WITH_KEYS;
@ -42,16 +38,14 @@ public class EmbeddedMangement {
}
public static ODocument getEmbeddedType(JsonNode jsonNode)
throws ResourceRegistryException {
if (jsonNode.has(ISManageable.CLASS_PROPERTY)) {
public static ODocument getEmbeddedType(JsonNode jsonNode) throws ResourceRegistryException {
if(jsonNode.has(ISManageable.CLASS_PROPERTY)) {
// Complex type
String type = ERManagement.getClassProperty(jsonNode);
try {
SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED);
} catch (SchemaNotFoundException e) {
} catch(SchemaNotFoundException e) {
throw e;
}
@ -59,12 +53,12 @@ public class EmbeddedMangement {
try {
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.");
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");
}

View File

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

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.entity;
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.FacetNotFoundException;
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 com.tinkerpop.blueprints.Vertex;
@ -19,7 +16,6 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class FacetManagement extends EntityManagement<Facet> {

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.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
@ -55,7 +55,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
}
@Override
protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message) {
protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message) {
return new ResourceAvailableInAnotherContextException(message);
}
@ -77,24 +78,22 @@ public class ResourceManagement extends EntityManagement<Resource> {
/*
* Cannot get ConsistsOf edge only because is not polymorphic for a
* com.tinkerpop.blueprints.Vertex
* vertex.getEdges(Direction.OUT, ConsistsOf.NAME);
* TODO Looks for a different query
* com.tinkerpop.blueprints.Vertex vertex.getEdges(Direction.OUT,
* ConsistsOf.NAME); TODO Looks for a different query
*/
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
for (Edge edge : edges) {
for(Edge edge : edges) {
@SuppressWarnings("rawtypes")
RelationManagement relationManagement = getRelationManagement(edge);
relationManagement.setReload(reload);
if(relationManagement.giveMeSourceEntityManagementAsIs()==null) {
if(relationManagement.giveMeSourceEntityManagementAsIs() == null) {
relationManagement.setSourceEntityManagement(this);
}
if(relationManagement.giveMeSourceEntityManagementAsIs()!=this) {
if(relationManagement.giveMeSourceEntityManagementAsIs() != this) {
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("SourceEntityManagement for ");
errorMessage.append(relationManagement.getClass().getSimpleName());
@ -103,53 +102,51 @@ public class ResourceManagement extends EntityManagement<Resource> {
throw new ResourceRegistryException(errorMessage.toString());
}
if (relationManagement instanceof ConsistsOfManagement) {
if(relationManagement instanceof ConsistsOfManagement) {
try {
JSONObject consistsOf = relationManagement.serializeAsJson(true, true);
sourceResource = addConsistsOf(sourceResource, consistsOf);
}catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e;
}catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e);
}
}
/*
* This comment is just to show that IsRelatedTo is not serialized
* by default as design choice and not because forget
* This comment is just to show that IsRelatedTo is not serialized by default as
* design choice and not because forget
*
* else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){
* JSONObject isRelatedTo = relationManagement.serializeAsJson(true, true);
* sourceResource = addIsRelatedTo(sourceResource, isRelatedTo);
* }
* else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ JSONObject
* isRelatedTo = relationManagement.serializeAsJson(true, true); sourceResource
* = addIsRelatedTo(sourceResource, isRelatedTo); }
*/
}
return sourceResource;
}
public static JSONObject addConsistsOf(JSONObject sourceResource,
JSONObject consistsOf) throws ResourceRegistryException {
public static JSONObject addConsistsOf(JSONObject sourceResource, JSONObject consistsOf)
throws ResourceRegistryException {
return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter());
}
public static JSONObject addIsRelatedTo(JSONObject sourceResource,
JSONObject isRelatedTo) throws ResourceRegistryException {
public static JSONObject addIsRelatedTo(JSONObject sourceResource, JSONObject isRelatedTo)
throws ResourceRegistryException {
return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter());
}
@Override
protected Vertex reallyCreate() throws ResourceAlreadyPresentException,
ResourceRegistryException {
protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
createVertex();
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
if (jsonNode.has(property)) {
if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode consistOfJsonNode : jsonNodeArray) {
for(JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(consistOfJsonNode);
com.setSourceEntityManagement(this);
@ -159,9 +156,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
}
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
if (jsonNode.has(property)) {
if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
irtm.setJSON(relationJsonNode);
irtm.setSourceEntityManagement(this);
@ -179,9 +176,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
getElement();
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
if (jsonNode.has(property)) {
if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
for(JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(relationJsonNode);
com.internalCreateOrUdate();
@ -190,9 +187,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
}
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
if (jsonNode.has(property)) {
if(jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
irtm.setJSON(relationJsonNode);
irtm.internalUpdate();
@ -205,30 +202,28 @@ public class ResourceManagement extends EntityManagement<Resource> {
@SuppressWarnings("unchecked")
@Override
protected boolean reallyDelete() throws ResourceNotFoundException,
ResourceRegistryException {
protected boolean reallyDelete() throws ResourceNotFoundException, ResourceRegistryException {
// internalDeleteResource(orientGraph, uuid, null);
getElement();
Iterable<Edge> iterable = element.getEdges(Direction.OUT);
Iterator<Edge> iterator = iterable.iterator();
while (iterator.hasNext()) {
while(iterator.hasNext()) {
Edge edge = iterator.next();
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
@SuppressWarnings("rawtypes")
RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph);
} else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
} else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph);
} else {
logger.warn("{} is not a {} nor a {}. {}",
Utility.toJsonString(edge, true), IsRelatedTo.NAME,
logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME,
ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if (relationManagement != null) {
if(relationManagement != null) {
relationManagement.setElement(edge);
relationManagement.internalDelete();
}
@ -240,24 +235,23 @@ public class ResourceManagement extends EntityManagement<Resource> {
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 {
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAll(polymorphic, constraint);
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
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();
String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART);
@ -268,8 +262,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
// TODO check types
/*
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService')
* FROM (SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
* FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
*
* WHERE @class='EService' // Only is not polymorphic
*/
@ -282,11 +276,11 @@ public class ResourceManagement extends EntityManagement<Resource> {
selectStringBuilder.append(erType);
selectStringBuilder.append("') FROM (SELECT FROM ");
selectStringBuilder.append(facetType);
for(String key : constraint.keySet()){
if(first){
for(String key : constraint.keySet()) {
if(first) {
selectStringBuilder.append(" WHERE ");
first = false;
}else{
} else {
selectStringBuilder.append(" AND ");
}
selectStringBuilder.append(key);
@ -298,7 +292,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
}
selectStringBuilder.append(" ))");
if(!polymorphic){
if(!polymorphic) {
selectStringBuilder.append(" WHERE @class='");
selectStringBuilder.append(erType);
selectStringBuilder.append("'");
@ -307,54 +301,49 @@ public class ResourceManagement extends EntityManagement<Resource> {
String select = selectStringBuilder.toString();
logger.trace(select);
OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>(select);
Iterable<Element> elements = orientGraph.command(osqlSynchQuery).execute();
OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>(
select);
Iterable<Element> elements = orientGraph.command(osqlSynchQuery)
.execute();
for(Element element : elements) {
for(Element element : elements){
if(polymorphic){
if(polymorphic) {
OrientVertexType orientVertexType = null;
try {
OrientElement orientElement = ((OrientElement) element);
if(orientElement instanceof OrientEdge){
if(orientElement instanceof OrientEdge) {
continue;
}
orientVertexType = ((OrientVertex) orientElement).getType();
}catch (Exception e) {
String error = String.format("Unable to detect type of %s. %s",
element.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", element.toString(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
if(orientVertexType.getName().compareTo(erType)!=0){
if(!orientVertexType.isSubClassOf(erType) ) {
if(orientVertexType.getName().compareTo(erType) != 0) {
if(!orientVertexType.isSubClassOf(erType)) {
continue;
}
}
}
Vertex vertex = (Vertex) element;
@SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, vertex);
try {
JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject);
}catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
return jsonArray.toString();
}
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.relation;
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.ConsistsOfAvailableInAnotherContextException;
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.ResourceManagement;
@ -20,7 +17,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("rawtypes")
public class ConsistsOfManagement extends RelationManagement<ConsistsOf, ResourceManagement, FacetManagement> {
public class ConsistsOfManagement extends RelationManagement<ConsistsOf,ResourceManagement,FacetManagement> {
public ConsistsOfManagement() {
super(AccessType.CONSISTS_OF);

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.relation;
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.IsRelatedToAvailableInAnotherContextException;
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 com.tinkerpop.blueprints.impls.orient.OrientGraph;
@ -19,7 +16,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("rawtypes")
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, ResourceManagement, ResourceManagement> {
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo,ResourceManagement,ResourceManagement> {
public IsRelatedToManagement() {
super(AccessType.IS_RELATED_TO);

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.er.relation;
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.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
@ -49,7 +46,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
*/
@SuppressWarnings("rawtypes")
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;
@ -67,7 +64,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase());
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase());
switch (accessType) {
switch(accessType) {
case CONSISTS_OF:
this.targetEntityClass = Facet.class;
break;
@ -93,8 +90,9 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
}
/*
* Needed for ResourceManagement.serializeAsJson() function to check that sourceEntityManagement is the same of
* the instance is creating this RelationManagement. TODO Look for a workaround
* Needed for ResourceManagement.serializeAsJson() function to check that
* sourceEntityManagement is the same of the instance is creating this
* RelationManagement. TODO Look for a workaround
*/
public S giveMeSourceEntityManagementAsIs() throws ResourceRegistryException {
return sourceEntityManagement;
@ -102,7 +100,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@SuppressWarnings("unchecked")
public S getSourceEntityManagement() throws ResourceRegistryException {
if (sourceEntityManagement == null) {
if(sourceEntityManagement == null) {
Vertex source = getElement().getVertex(Direction.OUT);
sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElement(source);
@ -113,7 +111,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@SuppressWarnings("unchecked")
public T getTargetEntityManagement() throws ResourceRegistryException {
if (targetEntityManagement == null) {
if(targetEntityManagement == null) {
Vertex target = getElement().getVertex(Direction.IN);
targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElement(target);
@ -144,20 +142,20 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
JSONObject relation = serializeSelfOnly();
try {
if (includeSource) {
if(includeSource) {
EntityManagement sourceEntityManagement = getSourceEntityManagement();
relation.put(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly());
}
if (includeTarget) {
if(includeTarget) {
EntityManagement targetEntityManagement = getTargetEntityManagement();
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);
throw e;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}
@ -165,7 +163,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return relation;
}
protected Map<String, JSONObject> fullSerialize(Map<String, JSONObject> visitedSourceResources)
protected Map<String,JSONObject> fullSerialize(Map<String,JSONObject> visitedSourceResources)
throws ResourceRegistryException {
Vertex source = getElement().getVertex(Direction.OUT);
@ -175,30 +173,28 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
JSONObject sourceResource = visitedSourceResources.get(id);
ResourceManagement resourceManagement = null;
if (sourceResource == null) {
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, source);
if (this instanceof IsRelatedToManagement) {
if(sourceResource == null) {
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(),
orientGraph, source);
if(this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.serializeAsJson();
} else if (this instanceof ConsistsOfManagement) {
} else if(this instanceof ConsistsOfManagement) {
sourceResource = resourceManagement.serializeSelfOnly();
} else {
String error = String.format(
"{%s is not a %s nor a %s. %s",
this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
}
if (this instanceof IsRelatedToManagement) {
if(this instanceof IsRelatedToManagement) {
sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson());
} else if (this instanceof ConsistsOfManagement) {
} else if(this instanceof ConsistsOfManagement) {
sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson());
} else {
String error = String.format(
"{%s is not a %s nor a %s. %s",
this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
@ -211,9 +207,9 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@Override
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");
}
@ -224,16 +220,16 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
sourceEntityManagement.setUUID(sourceUUID);
}
if (targetEntityManagement == null) {
if(targetEntityManagement == null) {
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");
}
try {
targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
} catch (SchemaException e) {
} catch(SchemaException e) {
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("A ");
errorMessage.append(erType);
@ -246,7 +242,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
try {
targetEntityManagement.getElement();
} catch (Exception e) {
} catch(Exception e) {
targetEntityManagement.internalCreate();
}
}
@ -278,9 +274,9 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
Edge edge = getElement();
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);
if (target != null) {
if(target != null) {
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph);
fm.setJSON(target);
fm.internalUpdate();
@ -302,26 +298,24 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
try {
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getAddConstraint() != null) {
if(propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint();
} else {
String error = String.format(
"%s.%s in %s is null. %s",
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.ADD_PROPERTY,
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
PropagationConstraint.ADD_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch (Exception e) {
String error = String.format(
"Error while getting %s from %s while performing AddToContext. %s",
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error);
throw new ResourceRegistryException(error, e);
}
switch (addConstraint) {
switch(addConstraint) {
case propagate:
/*
* The relation must be added only in the case the target vertex must be added.
@ -367,19 +361,17 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
try {
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) {
if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint();
} else {
String error = String.format(
"%s.%s in %s is null. %s",
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY,
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch (Exception e) {
String error = String.format(
"Error while getting %s from %s while performing RemoveFromContext. %s",
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
@ -393,7 +385,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
*/
getWorkingContext().removeElement(getElement(), orientGraph);
switch (removeConstraint) {
switch(removeConstraint) {
case cascade:
getTargetEntityManagement().internalRemoveFromContext();
break;
@ -405,11 +397,11 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
Iterator<Edge> iterator = iterable.iterator();
int count = 0;
OrientEdge edge = null;
while (iterator.hasNext()) {
while(iterator.hasNext()) {
edge = (OrientEdge) iterator.next();
OrientEdge thisOrientEdge = (OrientEdge) getElement();
if (edge.compareTo(thisOrientEdge) != 0) {
if (thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
if(edge.compareTo(thisOrientEdge) != 0) {
if(thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
count++;
break;
}
@ -419,7 +411,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
}
}
if (count > 0) {
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);
@ -450,27 +442,24 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
try {
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT);
if (propagationConstraint.getRemoveConstraint() != null) {
if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint();
} else {
String error = String.format(
"%s.%s in %s is null. %s",
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY,
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch (Exception e) {
logger.warn(
"Error while getting {} from {}. Assuming {}. {}",
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), removeConstraint,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
} catch(Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT,
Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
Vertex target = (Vertex) getTargetEntityManagement().getElement();
element.remove();
switch (removeConstraint) {
switch(removeConstraint) {
case cascade:
getTargetEntityManagement().internalDelete();
break;
@ -478,7 +467,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
case cascadeWhenOrphan:
Iterable<Edge> iterable = target.getEdges(Direction.IN);
Iterator<Edge> iterator = iterable.iterator();
if (iterator.hasNext()) {
if(iterator.hasNext()) {
logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
target, removeConstraint);
} else {
@ -499,12 +488,13 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
@SuppressWarnings("unchecked")
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException {
Map<String, JSONObject> visitedSourceResources = new HashMap<>();
for (Edge edge : edges) {
if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
Map<String,JSONObject> visitedSourceResources = new HashMap<>();
for(Edge edge : edges) {
if(postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
continue;
}
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(),
orientGraph, edge);
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
}
return visitedSourceResources.values();
@ -526,10 +516,11 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
throws ResourceRegistryException {
EntityManagement entityManagement = null;
try {
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), orientGraph, uuid);
} catch (ResourceRegistryException e) {
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(),
orientGraph, uuid);
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(
String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME));
}
@ -549,12 +540,12 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAllFrom(uuid, direction, polymorphic);
} catch (ResourceRegistryException e) {
} catch(ResourceRegistryException e) {
throw e;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}
@ -573,14 +564,14 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
return added;
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new ContextException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}

View File

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

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.query;
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.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -22,110 +19,14 @@ import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class QueryImpl implements Query {
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
public String query(String query, Integer limit, String fetchPlan)
throws InvalidQueryException {
if(limit == null){
public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException {
if(limit == null) {
limit = AccessPath.DEFAULT_LIMIT;
}
limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit;
@ -141,18 +42,17 @@ public class QueryImpl implements Query {
osqlSynchQuery.setFetchPlan(fetchPlan);
osqlSynchQuery.setCacheableResult(true);
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}",
osqlSynchQuery.getText(), osqlSynchQuery.getFetchPlan(),
osqlSynchQuery.getLimit());
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(),
osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit());
List<Object> records = oDatabaseDocumentTx.query(osqlSynchQuery);
Writer writer = new StringWriter();
writer.append("{\"result\":[");
for(int i=0; i<records.size(); i++){
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) ){
if(i < (records.size() - 1)) {
writer.append(",");
}
}
@ -160,10 +60,10 @@ public class QueryImpl implements Query {
return writer.toString();
} catch (Exception e) {
} catch(Exception e) {
throw new InvalidQueryException(e.getMessage());
} finally {
if (oDatabaseDocumentTx != null) {
if(oDatabaseDocumentTx != null) {
oDatabaseDocumentTx.close();
}
}
@ -173,14 +73,13 @@ public class QueryImpl implements Query {
@Override
public String gremlinQuery(String query) throws InvalidQueryException {
throw new UnsupportedOperationException();
/*
OGremlinHelper.global().create();
ODatabaseDocumentTx oDatabaseDocumentTx = null;
try {
oDatabaseDocumentTx = ContextUtility
.getActualSecurityContextDatabaseTx(PermissionMode.READER);
oDatabaseDocumentTx = ContextUtility.getActualSecurityContextDatabaseTx(PermissionMode.READER);
String finalQuery = String.format("select gremlin('%s')", query);
OCommandSQL OCommandSQL = new OCommandSQL(finalQuery);
@ -189,22 +88,21 @@ public class QueryImpl implements Query {
Iterator iterator = res.iterator();
while(iterator.hasNext()){
while(iterator.hasNext()) {
ODocument oDocument = (ODocument) iterator.next();
logger.debug("{}", oDocument);
}
return res.toString();
} catch (Exception e) {
} catch(Exception e) {
throw new InvalidQueryException(e.getMessage());
} finally {
if (oDatabaseDocumentTx != null) {
if(oDatabaseDocumentTx != null) {
oDatabaseDocumentTx.close();
}
}
*/
}
}

View File

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

View File

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

View File

@ -54,13 +54,12 @@ public class ERManager {
*/
@PUT
@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)
public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws FacetAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.FACET_PATH_PART + "/" + type);
CalledMethodProvider.instance
.set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {}", Facet.NAME, type);
logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json);
FacetManagement facetManagement = new FacetManagement();
@ -79,13 +78,12 @@ public class ERManager {
*/
@POST
@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)
public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json)
throws FacetNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
+ ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to update {} with id {}", Facet.NAME, uuid);
logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json);
FacetManagement facetManagement = new FacetManagement();
@ -102,9 +100,8 @@ public class ERManager {
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
+ ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", Facet.NAME, uuid);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
@ -121,13 +118,12 @@ public class ERManager {
*/
@PUT
@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)
public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws ResourceAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.RESOURCE_PATH_PART + "/" + type);
CalledMethodProvider.instance
.set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {}", Resource.NAME, type);
logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json);
ResourceManagement resourceManagement = new ResourceManagement();
@ -146,13 +142,12 @@ public class ERManager {
*/
@POST
@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)
public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json)
throws ResourceNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
+ ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to update {} with id {}", Resource.NAME, uuid);
logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json);
ResourceManagement resourceManagement = new ResourceManagement();
@ -162,22 +157,21 @@ public class ERManager {
}
/**
* 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
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception {
CalledMethodProvider.instance.set(
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
+ ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", Resource.NAME, uuid);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.delete();
}
/**
* e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy
*
@ -186,13 +180,12 @@ public class ERManager {
*/
@PUT
@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)
public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws ResourceAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type);
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type);
logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
@ -204,15 +197,15 @@ public class ERManager {
}
/**
* 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
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
+ ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setUUID(UUID.fromString(consistOfUUID));
@ -227,13 +220,12 @@ public class ERManager {
*/
@PUT
@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)
public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws ResourceAlreadyPresentException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type);
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type);
logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json);
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(type);
@ -244,15 +236,15 @@ public class ERManager {
}
/**
* 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
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
+ ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID);
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID));
@ -260,16 +252,16 @@ public class ERManager {
}
/**
* 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
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
+ 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);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
@ -284,9 +276,8 @@ public class ERManager {
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
+ 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);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
@ -294,16 +285,16 @@ public class ERManager {
}
/**
* 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
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
+ 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);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
@ -311,16 +302,16 @@ public class ERManager {
}
/**
* 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
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid)
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
+ 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);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));

View File

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

View File

@ -46,7 +46,7 @@ public class SchemaManager {
*/
@PUT
@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)
public Response create(@PathParam(TYPE_PATH_PARAM) String type, String json)
throws SchemaException, ResourceRegistryException {
@ -55,7 +55,7 @@ public class SchemaManager {
AccessType accessType = null;
try {
accessType = AccessType.valueOf(type);
switch (accessType) {
switch(accessType) {
case EMBEDDED:
break;
@ -75,7 +75,7 @@ public class SchemaManager {
throw new Exception();
}
} catch (Exception e) {
} catch(Exception e) {
String error = String.format("Cannot register %s schema", type);
throw new ResourceRegistryException(error);
}
@ -91,7 +91,7 @@ public class SchemaManager {
*/
@GET
@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)
public String read(@PathParam(TYPE_PATH_PARAM) String type,
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean 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.resourceregistry.api.exceptions.schema.SchemaException;
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.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -28,12 +28,12 @@ public class SchemaContextManagement implements SchemaManagement {
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);
Iterator<Vertex> iterator = iterable.iterator();
Vertex vertex = null;
if(iterator.hasNext()){
if(iterator.hasNext()) {
vertex = iterator.next();
} else {
String error = String.format("%s is not a registered type", vertexType);
@ -41,8 +41,10 @@ public class SchemaContextManagement implements SchemaManagement {
throw new Exception(error);
}
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);
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);
logger.error(error);
throw new Exception(error);
}
@ -62,11 +64,11 @@ public class SchemaContextManagement implements SchemaManagement {
ObjectMapper mapper = new ObjectMapper();
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.setProperty(SCHEMA, json);
orientVertex.save();
} else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) {
} else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) {
String sourceClass = typeDefinition.getSourceType();
Vertex source = getVertex(orientGraph, sourceClass);
@ -77,7 +79,7 @@ public class SchemaContextManagement implements SchemaManagement {
orientEdge.setProperty(SCHEMA, json);
orientEdge.save();
} else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
} else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
ODocument doc = new ODocument(typeDefinition.getName());
doc.field(SCHEMA, json);
doc.save();
@ -86,13 +88,13 @@ public class SchemaContextManagement implements SchemaManagement {
orientGraph.commit();
return json;
}catch (Exception e) {
if (orientGraph != null) {
} catch(Exception e) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new SchemaException(e);
} finally {
if (orientGraph != null) {
if(orientGraph != null) {
orientGraph.shutdown();
}
}

View File

@ -7,8 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
/**
* @author Luca Frosini (ISTI - CNR)
*
* For JSON schema see
* http://orientdb.com/docs/last/OrientDB-REST.html#class
* For JSON schema see http://orientdb.com/docs/last/OrientDB-REST.html#class
*
*/
public interface SchemaManagement {
@ -17,7 +16,8 @@ public interface SchemaManagement {
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;

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

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.Date;
@ -15,11 +12,11 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
*/
public class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.embedded.Header {
public HeaderOrient(){
public HeaderOrient() {
super(Header.NAME);
}
protected HeaderOrient(String iClassName){
protected HeaderOrient(String iClassName) {
super(iClassName);
}
@ -29,7 +26,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
}
@Override
public void setUUID(UUID uuid){
public void setUUID(UUID uuid) {
this.field(Header.UUID_PROPERTY, uuid.toString());
}
@ -38,7 +35,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
return this.field(Header.CREATOR_PROPERTY);
}
public void setCreator(String creator){
public void setCreator(String 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);
}
public void setCreationTime(Date creationTime){
public void setCreationTime(Date 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);
}
public void setModifiedBy(String modifiedBy){
public void setModifiedBy(String modifiedBy) {
this.field(Header.MODIFIED_BY_PROPERTY, modifiedBy);
}
@ -65,7 +62,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
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);
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.utils;
import java.io.IOException;
@ -38,16 +35,16 @@ public class HeaderUtility {
String user = org.gcube.informationsystem.model.embedded.Header.UNKNOWN_USER;
try {
Caller caller = AuthorizationProvider.instance.get();
if (caller != null) {
if(caller != null) {
ClientInfo clientInfo = caller.getClient();
String clientId = clientInfo.getId();
if (clientId != null && clientId.compareTo("") != 0) {
if(clientId != null && clientId.compareTo("") != 0) {
user = clientId;
} else {
throw new Exception("Username null or empty");
}
}
} catch (Exception e) {
} catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user);
}
return user;
@ -56,7 +53,7 @@ public class HeaderUtility {
public static Header createHeader(UUID uuid) {
HeaderOrient header = new HeaderOrient();
if (uuid == null) {
if(uuid == null) {
uuid = UUID.randomUUID();
}
@ -78,13 +75,13 @@ public class HeaderUtility {
public static Header getHeader(JsonNode jsonNode, boolean creation)
throws JsonParseException, JsonMappingException, IOException {
if (jsonNode.has(Resource.HEADER_PROPERTY)) {
if(jsonNode.has(Resource.HEADER_PROPERTY)) {
JsonNode headerNode = jsonNode.get(Resource.HEADER_PROPERTY);
if (headerNode.isNull()) {
if(headerNode.isNull()) {
return null;
}
HeaderOrient header = null;
if (creation) {
if(creation) {
// If an header is provided MUST contains and UUID otherwise is
// an invalid request so that let that an exception is raised
UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText());
@ -99,7 +96,7 @@ public class HeaderUtility {
}
public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException {
if (oDocument instanceof HeaderOrient) {
if(oDocument instanceof HeaderOrient) {
return (HeaderOrient) oDocument;
} else {
try {
@ -111,7 +108,7 @@ public class HeaderUtility {
headerOrient.setModifiedBy(header.getModifiedBy());
headerOrient.setLastUpdateTime(header.getLastUpdateTime());
return headerOrient;
} catch (Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(
"Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.utils;
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.resourceregistry.api.exceptions.ResourceRegistryException;
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.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.LoggerFactory;
@ -45,11 +42,10 @@ public class Utility {
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JSONObject toJsonObject(OrientElement element, boolean raw)
throws ResourceRegistryException {
public static JSONObject toJsonObject(OrientElement element, boolean raw) throws ResourceRegistryException {
try {
return new JSONObject(toJsonString(element, raw));
}catch(Exception e){
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@ -60,38 +56,34 @@ public class Utility {
}
public static String toJsonString(ORecord oRecord, boolean raw) {
if (raw) {
if(raw) {
return oRecord.toJSON();
}
return oRecord.toJSON("class");
}
public static JSONObject toJsonObject(Element element, boolean raw)
throws JSONException {
if (raw) {
return GraphSONUtility.jsonFromElement(element,
element.getPropertyKeys(), GraphSONMode.EXTENDED);
public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException {
if(raw) {
return GraphSONUtility.jsonFromElement(element, element.getPropertyKeys(), GraphSONMode.EXTENDED);
} else {
Set<String> keys = new HashSet<>(element.getPropertyKeys());
for (String key : element.getPropertyKeys()) {
if (key.startsWith("_")) {
for(String key : element.getPropertyKeys()) {
if(key.startsWith("_")) {
keys.remove(key);
}
}
return GraphSONUtility.jsonFromElement(element, keys,
GraphSONMode.EXTENDED);
return GraphSONUtility.jsonFromElement(element, keys, GraphSONMode.EXTENDED);
}
}
public static String toJsonString(Element element, boolean raw) {
try {
return toJsonObject(element, true).toString();
} catch (Exception e) {
} catch(Exception e) {
return String.valueOf(element);
}
}
public static <El extends Element> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
OrientGraphNoTx orientGraphNoTx = null;
@ -100,36 +92,33 @@ public class Utility {
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz);
} finally {
if (orientGraphNoTx != null) {
if(orientGraphNoTx != null) {
orientGraphNoTx.shutdown();
}
}
}
public static <El extends Element> El getElementByUUID(
Graph graph, String elementType, UUID uuid,
public static <El extends Element> El getElementByUUID(Graph graph, String elementType, UUID uuid,
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
if (elementType == null || elementType.compareTo("") == 0) {
if (Vertex.class.isAssignableFrom(clz)) {
if(elementType == null || elementType.compareTo("") == 0) {
if(Vertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME;
}
if (Edge.class.isAssignableFrom(clz)) {
if(Edge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME;
}
}
// TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE "
+ Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
String select = "SELECT FROM " + elementType + " WHERE " + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ " = \"" + uuid.toString() + "\"";
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute();
if (elements == null || !elements.iterator().hasNext()) {
String error = String.format("No %s with UUID %s was found",
elementType, uuid.toString());
if(elements == null || !elements.iterator().hasNext()) {
String error = String.format("No %s with UUID %s was found", elementType, uuid.toString());
logger.info(error);
throw new ERNotFoundException(error);
}
@ -137,37 +126,32 @@ public class Utility {
Iterator<El> iterator = elements.iterator();
El element = iterator.next();
logger.trace("{} with {} is : {}", elementType, uuid.toString(),
Utility.toJsonString(element, true));
logger.trace("{} with {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true));
if (iterator.hasNext()) {
throw new ResourceRegistryException("Found more than one "
+ elementType + " with uuid " + uuid.toString()
if(iterator.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
+ ". This is a fatal error please contact Admnistrator");
}
return element;
}
public static <E extends Embedded> E getEmbedded(Class<E> clz, Element element, String property)
throws ResourceRegistryException {
try {
ODocument oDocument = element.getProperty(property);
E e = ISMapper.unmarshal(clz, oDocument.toJSON());
return e;
} catch (Exception ex) {
String error = String.format("Error while getting %s from %s",
property, toJsonString(element, true));
} catch(Exception ex) {
String error = String.format("Error while getting %s from %s", property, toJsonString(element, true));
throw new ResourceRegistryException(error, ex);
}
}
public static UUID getUUID(Element element)
throws ResourceRegistryException {
public static UUID getUUID(Element element) throws ResourceRegistryException {
/*
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY);
* String contextID = header.field(Header.UUID_PROPERTY); return
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String
* contextID = header.field(Header.UUID_PROPERTY); return
* UUID.fromString(contextID);
*/
Header header = HeaderUtility.getHeader(element);

View File

@ -30,6 +30,9 @@ public class ScopedTest {
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";
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 DEFAULT_TEST_SCOPE;
public static final String PARENT_DEFAULT_TEST_SCOPE;
public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER;
public static final String ALTERNATIVE_TEST_SCOPE;
@ -61,6 +65,8 @@ public class ScopedTest {
throw new RuntimeException(e);
}
GCUBE = properties.getProperty(GCUBE_VARNAME);
GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME);
GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME);
@ -71,8 +77,11 @@ public class ScopedTest {
DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT;
PARENT_DEFAULT_TEST_SCOPE = GCUBE;
DEFAULT_TEST_SCOPE_ANOTHER_USER = GCUBE_DEVNEXT_ANOTHER_USER;
ALTERNATIVE_TEST_SCOPE = GCUBE_DEVNEXT_NEXTNEXT;
}
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.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext;
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.junit.Assert;
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_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 (pre.getHeader() != null) {
FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create);
@ -89,27 +92,29 @@ public class ContextManagementTest extends ScopedTest {
protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException {
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(),
contextSecurityContext);
OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER);
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
SecurityContext securityContext = new SecurityContext(uuid);
for(PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, false);
boolean[] booleanArray = new boolean[] { false, true };
for (boolean hierarchic : booleanArray) {
for (PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
ORole oRole = oSecurity.getRole(role);
Assert.assertEquals(oRole==null, deleted);
Assert.assertEquals(oRole == null, deleted);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
OUser oUser = oSecurity.getUser(user);
Assert.assertEquals(oUser==null, deleted);
Assert.assertEquals(oUser == null, deleted);
}
}
}
protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
ContextManagement contextManagement = new ContextManagement();
@ -373,7 +378,7 @@ public class ContextManagementTest extends ScopedTest {
String all = contextManagement.all(false);
logger.trace(all);
List<Context> contexts = ISMapper.unmarshalList(Context.class, all);
for(Context context : contexts){
for (Context context : contexts) {
logger.trace(ISMapper.marshal(context));
List<IsParentOf<Context, Context>> children = context.getChildren();
for (IsParentOf<Context, Context> child : children) {

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.utils.ISMapper;
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.resourceregistry.ScopedTest;
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.utils.Utility;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.er.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.junit.Assert;
@ -16,6 +20,9 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class FacetManagementTest extends ScopedTest {
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
@ -33,134 +40,276 @@ public class FacetManagementTest extends ScopedTest {
return softwareFacet;
}
public static void checkHeader(ER er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader()!=null);
Assert.assertTrue(er.getHeader().getUUID()!=null);
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);
}
if(uuid!=null) {
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid)==0);
public static void checkHeader(ER er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader() != null);
Assert.assertTrue(er.getHeader().getUUID() != null);
if(uuid != null) {
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0);
}
String user = HeaderUtility.getUser();
Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user)==0);
Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user) == 0);
if(create){
Assert.assertTrue(er.getHeader().getCreator().compareTo(user)==0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime())==0);
}else {
if(create) {
Assert.assertTrue(er.getHeader().getCreator().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
} else {
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
}
}
public static void checkAssertion(SoftwareFacet softwareFacet, String version, UUID uuid, boolean create) {
checkHeader(softwareFacet, uuid, create);
Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP)==0);
Assert.assertTrue(softwareFacet.getName().compareTo(NAME)==0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(version)==0);
public static void checkAssertion(Facet facet, UUID uuid, boolean create) {
checkHeader(facet, uuid, create);
}
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
public void createUpdateReadDelete() throws Exception {
SoftwareFacet softwareFacet = getSoftwareFacet();
/* Testing Create */
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
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();
softwareFacet = create(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
/* Testing Update */
softwareFacet.setVersion(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);
softwareFacet = update(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
/* Testing Read */
facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setUUID(uuid);
softwareFacet = read(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
json = facetManagement.read();
logger.debug("Read : {}", json);
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");
}
assertThrow(softwareFacet, FacetAlreadyPresentException.class, (SoftwareFacet s) -> {
create(s);
});
/* 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");
}
delete(softwareFacet);
/* Testing new Create to check creation with provided UUID */
facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
softwareFacet = create(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
json = facetManagement.create();
logger.debug("Created : {}", json);
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
logger.debug("Unmarshalled {}", softwareFacet);
delete(softwareFacet);
checkAssertion(softwareFacet, NEW_VERSION, uuid, true);
/* Testing Delete */
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");
}
@Test
public void testHierarchy() throws Exception {
/* Setting scope /gcube/devNext/NextNext */
ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT);
SoftwareFacet softwareFacet = getSoftwareFacet();
/* Testing Create */
softwareFacet = create(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
softwareFacet = update(softwareFacet);
checkSoftwareFacetAssertion(softwareFacet, VERSION);
/* 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);
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);
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);
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();
softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
@ -72,7 +72,9 @@ public class ResourceManagementTest extends ScopedTest {
logger.trace("Updated {}", 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();

View File

@ -8,7 +8,6 @@ import java.net.URL;
import java.util.Calendar;
import java.util.UUID;
import org.codehaus.jettison.json.JSONObject;
import org.gcube.informationsystem.impl.embedded.PropagationConstraintImpl;
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
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.isrelatedto.HostsImpl;
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.AddConstraint;
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.AccessPointFacet;
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.ResourceNotFoundException;
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.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -85,9 +83,8 @@ public class BasicTest extends ScopedTest {
String json = facetManagement.create();
logger.debug("Created : {}", json);
JSONObject jsonObject = new JSONObject(json);
JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY);
UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY));
CPUFacet createdCPUFacet = ISMapper.unmarshal(CPUFacet.class, json);
UUID uuid = createdCPUFacet.getHeader().getUUID();
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
@ -98,7 +95,7 @@ public class BasicTest extends ScopedTest {
/* ------------------------------------------------------------------ */
logger.debug("Switching to another scope");
ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE);
ScopedTest.setContext(ScopedTest.PARENT_DEFAULT_TEST_SCOPE);
try {
facetManagement = new FacetManagement();
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");
}
/* ---------------- 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");
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");
}
/* 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");
@ -158,6 +154,7 @@ public class BasicTest extends ScopedTest {
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted);
}