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:
parent
d1fe6daa64
commit
1fcdccd7af
|
@ -10,11 +10,11 @@ import org.glassfish.jersey.server.ResourceConfig;
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
@ApplicationPath("/")
|
@ApplicationPath("/")
|
||||||
public class ResourceInitializer extends ResourceConfig {
|
public class ResourceInitializer extends ResourceConfig {
|
||||||
|
|
||||||
public static final String APPLICATION_JSON_CHARSET_UTF_8 = MediaType.APPLICATION_JSON + ";charset=UTF-8";
|
public static final String APPLICATION_JSON_CHARSET_UTF_8 = MediaType.APPLICATION_JSON + ";charset=UTF-8";
|
||||||
|
|
||||||
public ResourceInitializer(){
|
public ResourceInitializer() {
|
||||||
packages(Access.class.getPackage().toString());
|
packages(Access.class.getPackage().toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -18,6 +18,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
|
||||||
|
@ -33,6 +34,9 @@ import com.tinkerpop.blueprints.Edge;
|
||||||
import com.tinkerpop.blueprints.Vertex;
|
import com.tinkerpop.blueprints.Vertex;
|
||||||
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class ContextManagement extends EntityManagement<Context> {
|
public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
|
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
|
||||||
|
@ -57,12 +61,12 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
if(name==null) {
|
if(name == null) {
|
||||||
if(element==null) {
|
if(element == null) {
|
||||||
if(jsonNode!=null) {
|
if(jsonNode != null) {
|
||||||
name = jsonNode.get(Context.NAME_PROPERTY).asText();
|
name = jsonNode.get(Context.NAME_PROPERTY).asText();
|
||||||
}
|
}
|
||||||
}else {
|
} else {
|
||||||
name = element.getProperty(Context.NAME_PROPERTY);
|
name = element.getProperty(Context.NAME_PROPERTY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -71,7 +75,8 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
||||||
if(workingContext == null) {
|
if(workingContext == null) {
|
||||||
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
|
workingContext = ContextUtility.getInstace()
|
||||||
|
.getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingContext;
|
||||||
}
|
}
|
||||||
|
@ -91,18 +96,16 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
return new ContextAlreadyPresentException(message);
|
return new ContextAlreadyPresentException(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void checkContext(ContextManagement parentContext) throws ContextNotFoundException,
|
protected void checkContext(ContextManagement parentContext)
|
||||||
ContextAlreadyPresentException, ResourceRegistryException {
|
throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException {
|
||||||
|
|
||||||
if (parentContext != null) {
|
if(parentContext != null) {
|
||||||
String parentId = parentContext.getElement().getId().toString();
|
String parentId = parentContext.getElement().getId().toString();
|
||||||
|
|
||||||
// TODO Rewrite using Gremlin
|
// TODO Rewrite using Gremlin
|
||||||
String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME
|
String select = "SELECT FROM (TRAVERSE out(" + IsParentOf.NAME + ") FROM " + parentId
|
||||||
+ ") FROM " + parentId + " MAXDEPTH 1) WHERE "
|
+ " MAXDEPTH 1) WHERE " + Context.NAME_PROPERTY + "=\"" + getName() + "\" AND "
|
||||||
+ Context.NAME_PROPERTY + "=\"" + getName() + "\" AND "
|
+ Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY + "<>\"" + parentContext.uuid + "\"";
|
||||||
+ Context.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
|
|
||||||
+ "<>\"" + parentContext.uuid + "\"";
|
|
||||||
|
|
||||||
logger.trace(select);
|
logger.trace(select);
|
||||||
|
|
||||||
|
@ -114,38 +117,31 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
logger.trace("Checking if {} -> {}", message, select);
|
logger.trace("Checking if {} -> {}", message, select);
|
||||||
|
|
||||||
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(
|
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
|
||||||
select);
|
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery).execute();
|
||||||
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
if (vertexes != null && vertexes.iterator().hasNext()) {
|
if(vertexes != null && vertexes.iterator().hasNext()) {
|
||||||
throw new ContextAlreadyPresentException(message.toString());
|
throw new ContextAlreadyPresentException(message.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// TODO Rewrite using Gremlin
|
// TODO Rewrite using Gremlin
|
||||||
String select = "SELECT FROM "
|
String select = "SELECT FROM " + org.gcube.informationsystem.model.entity.Context.NAME + " WHERE "
|
||||||
+ org.gcube.informationsystem.model.entity.Context.NAME
|
+ Context.NAME_PROPERTY + " = \"" + getName() + "\"" + " AND in(\"" + IsParentOf.NAME
|
||||||
+ " WHERE " + Context.NAME_PROPERTY + " = \"" + getName()
|
+ "\").size() = 0";
|
||||||
+ "\"" + " AND in(\"" + IsParentOf.NAME + "\").size() = 0";
|
|
||||||
|
|
||||||
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(
|
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
|
||||||
select);
|
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery).execute();
|
||||||
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
if (vertexes != null && vertexes.iterator().hasNext()) {
|
if(vertexes != null && vertexes.iterator().hasNext()) {
|
||||||
throw new ContextAlreadyPresentException(
|
throw new ContextAlreadyPresentException(
|
||||||
"A root context with the same name (" + this.getName()
|
"A root context with the same name (" + this.getName() + ") already exist");
|
||||||
+ ") already exist");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String serialize() throws ResourceRegistryException {
|
public String serialize() throws ResourceRegistryException {
|
||||||
return serializeAsJson().toString();
|
return serializeAsJson().toString();
|
||||||
|
@ -156,36 +152,35 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
JSONObject context = serializeSelfOnly();
|
JSONObject context = serializeSelfOnly();
|
||||||
|
|
||||||
int count=0;
|
int count = 0;
|
||||||
Iterable<Edge> parents = getElement().getEdges(Direction.IN);
|
Iterable<Edge> parents = getElement().getEdges(Direction.IN);
|
||||||
for(Edge edge : parents){
|
for(Edge edge : parents) {
|
||||||
if(++count>1) {
|
if(++count > 1) {
|
||||||
throw new ContextException("A " + Context.NAME + " can not have more than one parent");
|
throw new ContextException("A " + Context.NAME + " can not have more than one parent");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
|
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
|
||||||
isParentOfManagement.setElement(edge);
|
isParentOfManagement.setElement(edge);
|
||||||
JSONObject isParentOf = isParentOfManagement.serializeAsJson(true,false);
|
JSONObject isParentOf = isParentOfManagement.serializeAsJson(true, false);
|
||||||
context.putOpt(Context.PARENT_PROPERTY, isParentOf);
|
context.putOpt(Context.PARENT_PROPERTY, isParentOf);
|
||||||
} catch (JSONException e) {
|
} catch(JSONException e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ContextException("");
|
throw new ContextException("");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Iterable<Edge> childrenEdges = getElement().getEdges(Direction.OUT);
|
Iterable<Edge> childrenEdges = getElement().getEdges(Direction.OUT);
|
||||||
for (Edge edge : childrenEdges) {
|
for(Edge edge : childrenEdges) {
|
||||||
|
|
||||||
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
|
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
|
||||||
isParentOfManagement.setElement(edge);
|
isParentOfManagement.setElement(edge);
|
||||||
try {
|
try {
|
||||||
JSONObject isParentOf = isParentOfManagement.serializeAsJson();
|
JSONObject isParentOf = isParentOfManagement.serializeAsJson();
|
||||||
context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY);
|
context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY);
|
||||||
}catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw e;
|
throw e;
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
@ -201,14 +196,14 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
try {
|
try {
|
||||||
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
||||||
|
|
||||||
if (isParentOfJsonNode!=null && !(isParentOfJsonNode instanceof NullNode)) {
|
if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
|
||||||
|
|
||||||
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
|
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
|
||||||
ContextManagement parentContext = new ContextManagement(orientGraph);
|
ContextManagement parentContext = new ContextManagement(orientGraph);
|
||||||
parentContext.setJSON(parentJsonNode);
|
parentContext.setJSON(parentJsonNode);
|
||||||
|
|
||||||
checkContext(parentContext);
|
checkContext(parentContext);
|
||||||
if(uuid==null){
|
if(uuid == null) {
|
||||||
uuid = UUID.randomUUID();
|
uuid = UUID.randomUUID();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -221,7 +216,7 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
isParentOfManagement.internalCreate();
|
isParentOfManagement.internalCreate();
|
||||||
|
|
||||||
}else {
|
} else {
|
||||||
checkContext(null);
|
checkContext(null);
|
||||||
createVertex();
|
createVertex();
|
||||||
}
|
}
|
||||||
|
@ -230,9 +225,9 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
securityContext.create(orientGraph);
|
securityContext.create(orientGraph);
|
||||||
|
|
||||||
return getElement();
|
return getElement();
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
if(securityContext!=null) {
|
if(securityContext != null) {
|
||||||
securityContext.delete(orientGraph);
|
securityContext.delete(orientGraph);
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
|
@ -250,7 +245,7 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
Iterable<Vertex> iterable = getElement().getVertices(Direction.IN, IsParentOf.NAME);
|
Iterable<Vertex> iterable = getElement().getVertices(Direction.IN, IsParentOf.NAME);
|
||||||
for(Vertex p : iterable) {
|
for(Vertex p : iterable) {
|
||||||
if(found){
|
if(found) {
|
||||||
String message = String.format("{} has more than one parent. {}", Context.NAME,
|
String message = String.format("{} has more than one parent. {}", Context.NAME,
|
||||||
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(message.toString());
|
throw new ResourceRegistryException(message.toString());
|
||||||
|
@ -259,9 +254,8 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
found = true;
|
found = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
ContextManagement actualParentContextManagement = null;
|
ContextManagement actualParentContextManagement = null;
|
||||||
if(parent!=null) {
|
if(parent != null) {
|
||||||
actualParentContextManagement = new ContextManagement(orientGraph);
|
actualParentContextManagement = new ContextManagement(orientGraph);
|
||||||
actualParentContextManagement.setElement(parent);
|
actualParentContextManagement.setElement(parent);
|
||||||
}
|
}
|
||||||
|
@ -270,27 +264,26 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
||||||
JsonNode parentContextJsonNode = null;
|
JsonNode parentContextJsonNode = null;
|
||||||
if (isParentOfJsonNode!=null && !(isParentOfJsonNode instanceof NullNode)) {
|
if(isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
|
||||||
parentContextJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
|
parentContextJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(parentContextJsonNode != null && !(parentContextJsonNode instanceof NullNode)) {
|
||||||
if(parentContextJsonNode!=null && !(parentContextJsonNode instanceof NullNode)) {
|
|
||||||
UUID parentUUID = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode);
|
UUID parentUUID = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode);
|
||||||
if(actualParentContextManagement!=null){
|
if(actualParentContextManagement != null) {
|
||||||
if(parentUUID.compareTo(actualParentContextManagement.uuid)!=0) {
|
if(parentUUID.compareTo(actualParentContextManagement.uuid) != 0) {
|
||||||
parentChanged = true;
|
parentChanged = true;
|
||||||
}
|
}
|
||||||
}else {
|
} else {
|
||||||
parentChanged = true;
|
parentChanged = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(parentChanged){
|
if(parentChanged) {
|
||||||
newParentContextManagement = new ContextManagement(orientGraph);
|
newParentContextManagement = new ContextManagement(orientGraph);
|
||||||
newParentContextManagement.setJSON(parentContextJsonNode);
|
newParentContextManagement.setJSON(parentContextJsonNode);
|
||||||
}
|
}
|
||||||
}else{
|
} else {
|
||||||
if(actualParentContextManagement!=null) {
|
if(actualParentContextManagement != null) {
|
||||||
parentChanged = true;
|
parentChanged = true;
|
||||||
newParentContextManagement = null;
|
newParentContextManagement = null;
|
||||||
}
|
}
|
||||||
|
@ -299,7 +292,7 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
|
|
||||||
String oldName = getElement().getProperty(Context.NAME_PROPERTY);
|
String oldName = getElement().getProperty(Context.NAME_PROPERTY);
|
||||||
String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
|
String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
|
||||||
if(oldName.compareTo(newName)!=0){
|
if(oldName.compareTo(newName) != 0) {
|
||||||
nameChanged = true;
|
nameChanged = true;
|
||||||
name = newName;
|
name = newName;
|
||||||
}
|
}
|
||||||
|
@ -312,36 +305,36 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
move(newParentContextManagement, false);
|
move(newParentContextManagement, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
|
element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys,
|
||||||
|
ignoreStartWithKeys);
|
||||||
|
|
||||||
ContextUtility.getInstace().removeFromCache(uuid);
|
ContextUtility.getInstace().removeFromCache(uuid);
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private void move(ContextManagement newParentContextManagement, boolean check)
|
private void move(ContextManagement newParentContextManagement, boolean check)
|
||||||
throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException {
|
throws ContextNotFoundException, ContextAlreadyPresentException, ResourceRegistryException {
|
||||||
if(check){
|
if(check) {
|
||||||
checkContext(newParentContextManagement);
|
checkContext(newParentContextManagement);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Removing the old parent relationship if any
|
// Removing the old parent relationship if any
|
||||||
Iterable<Edge> edges = getElement().getEdges(Direction.IN, IsParentOf.NAME);
|
Iterable<Edge> edges = getElement().getEdges(Direction.IN, IsParentOf.NAME);
|
||||||
if (edges != null && edges.iterator().hasNext()) {
|
if(edges != null && edges.iterator().hasNext()) {
|
||||||
Iterator<Edge> edgeIterator = edges.iterator();
|
Iterator<Edge> edgeIterator = edges.iterator();
|
||||||
Edge edge = edgeIterator.next();
|
Edge edge = edgeIterator.next();
|
||||||
IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
|
IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
|
||||||
isParentOfManagement.setElement(edge);
|
isParentOfManagement.setElement(edge);
|
||||||
isParentOfManagement.internalDelete();
|
isParentOfManagement.internalDelete();
|
||||||
|
|
||||||
if (edgeIterator.hasNext()) {
|
if(edgeIterator.hasNext()) {
|
||||||
throw new ContextException("Seems that the Context has more than one Parent. "
|
throw new ContextException(
|
||||||
+ Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
"Seems that the Context has more than one Parent. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(newParentContextManagement!=null){
|
if(newParentContextManagement != null) {
|
||||||
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
||||||
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
|
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(orientGraph);
|
||||||
isParentOfManagement.setJSON(isParentOfJsonNode);
|
isParentOfManagement.setJSON(isParentOfJsonNode);
|
||||||
|
@ -356,7 +349,7 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
protected boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException {
|
protected boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException {
|
||||||
Iterable<Edge> iterable = getElement().getEdges(Direction.OUT);
|
Iterable<Edge> iterable = getElement().getEdges(Direction.OUT);
|
||||||
Iterator<Edge> iterator = iterable.iterator();
|
Iterator<Edge> iterator = iterable.iterator();
|
||||||
while (iterator.hasNext()) {
|
while(iterator.hasNext()) {
|
||||||
throw new ContextException("Cannot remove a " + Context.NAME + " having children");
|
throw new ContextException("Cannot remove a " + Context.NAME + " having children");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -376,13 +369,13 @@ public class ContextManagement extends EntityManagement<Context> {
|
||||||
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
||||||
JSONArray jsonArray = new JSONArray();
|
JSONArray jsonArray = new JSONArray();
|
||||||
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
|
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
|
||||||
for(Vertex vertex : iterable){
|
for(Vertex vertex : iterable) {
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setElement(vertex);
|
contextManagement.setElement(vertex);
|
||||||
try {
|
try {
|
||||||
JSONObject jsonObject = contextManagement.serializeAsJson();
|
JSONObject jsonObject = contextManagement.serializeAsJson();
|
||||||
jsonArray.put(jsonObject);
|
jsonArray.put(jsonObject);
|
||||||
}catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
||||||
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
|
@ -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());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.context;
|
package org.gcube.informationsystem.resourceregistry.context;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
@ -19,7 +16,9 @@ import org.gcube.informationsystem.model.relation.IsParentOf;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.Utility;
|
import org.gcube.informationsystem.resourceregistry.utils.Utility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
@ -31,19 +30,18 @@ import com.tinkerpop.blueprints.Vertex;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ContextUtility {
|
public class ContextUtility {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
|
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
|
||||||
|
|
||||||
private Map<String, UUID> contextUUIDs;
|
private Map<String,UUID> contextUUIDs;
|
||||||
private Map<UUID, SecurityContext> contexts;
|
private Map<UUID,SecurityContext> contexts;
|
||||||
|
|
||||||
private static ContextUtility contextUtility;
|
private static ContextUtility contextUtility;
|
||||||
|
|
||||||
public static ContextUtility getInstace() {
|
public static ContextUtility getInstace() {
|
||||||
if (contextUtility == null) {
|
if(contextUtility == null) {
|
||||||
contextUtility = new ContextUtility();
|
contextUtility = new ContextUtility();
|
||||||
}
|
}
|
||||||
return contextUtility;
|
return contextUtility;
|
||||||
|
@ -54,12 +52,25 @@ public class ContextUtility {
|
||||||
contexts = new HashMap<>();
|
contexts = new HashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final InheritableThreadLocal<Boolean> hierarchicMode = new InheritableThreadLocal<Boolean>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Boolean initialValue() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
public static InheritableThreadLocal<Boolean> getHierarchicMode() {
|
||||||
|
return hierarchicMode;
|
||||||
|
}
|
||||||
|
|
||||||
private static String getCurrentContextFullName() {
|
private static String getCurrentContextFullName() {
|
||||||
String token = SecurityTokenProvider.instance.get();
|
String token = SecurityTokenProvider.instance.get();
|
||||||
AuthorizationEntry authorizationEntry = null;
|
AuthorizationEntry authorizationEntry = null;
|
||||||
try {
|
try {
|
||||||
authorizationEntry = Constants.authorizationService().get(token);
|
authorizationEntry = Constants.authorizationService().get(token);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
return ScopeProvider.instance.get();
|
return ScopeProvider.instance.get();
|
||||||
}
|
}
|
||||||
return authorizationEntry.getContext();
|
return authorizationEntry.getContext();
|
||||||
|
@ -67,23 +78,22 @@ public class ContextUtility {
|
||||||
|
|
||||||
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
|
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
|
||||||
String fullName = getCurrentContextFullName();
|
String fullName = getCurrentContextFullName();
|
||||||
if (fullName == null) {
|
if(fullName == null) {
|
||||||
throw new ContextException("Null Token and Scope. Please set your token first.");
|
throw new ContextException("Null Token and Scope. Please set your token first.");
|
||||||
}
|
}
|
||||||
return ContextUtility.getInstace().getSecurityContextByFullName(fullName);
|
return ContextUtility.getInstace().getSecurityContextByFullName(fullName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
|
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
|
||||||
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace().
|
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace()
|
||||||
getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
|
.getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
|
||||||
return adminSecurityContext;
|
return adminSecurityContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException {
|
public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException {
|
||||||
for (String fullName : contextUUIDs.keySet()) {
|
for(String fullName : contextUUIDs.keySet()) {
|
||||||
UUID uuidKey = contextUUIDs.get(fullName);
|
UUID uuidKey = contextUUIDs.get(fullName);
|
||||||
if (uuidKey.compareTo(uuid) == 0) {
|
if(uuidKey.compareTo(uuid) == 0) {
|
||||||
contextUUIDs.remove(fullName);
|
contextUUIDs.remove(fullName);
|
||||||
contexts.remove(uuid);
|
contexts.remove(uuid);
|
||||||
return;
|
return;
|
||||||
|
@ -103,7 +113,7 @@ public class ContextUtility {
|
||||||
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
|
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
|
||||||
UUID uuid = contextUUIDs.get(fullName);
|
UUID uuid = contextUUIDs.get(fullName);
|
||||||
|
|
||||||
if (uuid == null) {
|
if(uuid == null) {
|
||||||
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
|
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
|
||||||
fullName);
|
fullName);
|
||||||
|
|
||||||
|
@ -120,9 +130,9 @@ public class ContextUtility {
|
||||||
|
|
||||||
return securityContext;
|
return securityContext;
|
||||||
|
|
||||||
} catch (ContextException e) {
|
} catch(ContextException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ContextException("Unable to restrive Context UUID from current Context", e);
|
throw new ContextException("Unable to restrive Context UUID from current Context", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -138,22 +148,22 @@ public class ContextUtility {
|
||||||
|
|
||||||
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
|
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
|
||||||
SecurityContext securityContext = contexts.get(uuid);
|
SecurityContext securityContext = contexts.get(uuid);
|
||||||
if (securityContext == null) {
|
if(securityContext == null) {
|
||||||
|
|
||||||
securityContext = new SecurityContext(uuid);
|
securityContext = new SecurityContext(uuid);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (contextVertex == null) {
|
if(contextVertex == null) {
|
||||||
contextVertex = getContextVertexByUUID(uuid);
|
contextVertex = getContextVertexByUUID(uuid);
|
||||||
}
|
}
|
||||||
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next();
|
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next();
|
||||||
|
|
||||||
if (parentVertex != null) {
|
if(parentVertex != null) {
|
||||||
UUID parentUUID = Utility.getUUID(parentVertex);
|
UUID parentUUID = Utility.getUUID(parentVertex);
|
||||||
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
|
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (NoSuchElementException e) {
|
} catch(NoSuchElementException e) {
|
||||||
// No parent
|
// No parent
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -181,7 +191,7 @@ public class ContextUtility {
|
||||||
Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
|
Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
if (vertexes == null || !vertexes.iterator().hasNext()) {
|
if(vertexes == null || !vertexes.iterator().hasNext()) {
|
||||||
throw new ContextNotFoundException("Error retrieving context with name " + fullName);
|
throw new ContextNotFoundException("Error retrieving context with name " + fullName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -190,7 +200,7 @@ public class ContextUtility {
|
||||||
|
|
||||||
logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
|
logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
|
||||||
|
|
||||||
if (iterator.hasNext()) {
|
if(iterator.hasNext()) {
|
||||||
throw new ContextNotFoundException("Found more than one context with name " + name
|
throw new ContextNotFoundException("Found more than one context with name " + name
|
||||||
+ "but required the one with path" + fullName + ". Please Reimplement the query");
|
+ "but required the one with path" + fullName + ". Please Reimplement the query");
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.context;
|
package org.gcube.informationsystem.resourceregistry.context;
|
||||||
|
|
||||||
import org.codehaus.jettison.json.JSONObject;
|
import org.codehaus.jettison.json.JSONObject;
|
||||||
|
@ -16,6 +13,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
|
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.Utility;
|
import org.gcube.informationsystem.resourceregistry.utils.Utility;
|
||||||
|
@ -29,7 +27,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
public class IsParentOfManagement extends RelationManagement<IsParentOf, ContextManagement, ContextManagement> {
|
public class IsParentOfManagement extends RelationManagement<IsParentOf,ContextManagement,ContextManagement> {
|
||||||
|
|
||||||
public IsParentOfManagement() {
|
public IsParentOfManagement() {
|
||||||
super(AccessType.IS_PARENT_OF);
|
super(AccessType.IS_PARENT_OF);
|
||||||
|
@ -44,7 +42,8 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
||||||
if(workingContext == null) {
|
if(workingContext == null) {
|
||||||
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
|
workingContext = ContextUtility.getInstace()
|
||||||
|
.getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingContext;
|
||||||
}
|
}
|
||||||
|
@ -60,7 +59,7 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
|
||||||
if(propagationConstraint.has(PropagationConstraint.REMOVE_PROPERTY)) {
|
if(propagationConstraint.has(PropagationConstraint.REMOVE_PROPERTY)) {
|
||||||
String removeProperty = propagationConstraint.get(PropagationConstraint.REMOVE_PROPERTY).asText();
|
String removeProperty = propagationConstraint.get(PropagationConstraint.REMOVE_PROPERTY).asText();
|
||||||
RemoveConstraint removeConstraint = RemoveConstraint.valueOf(removeProperty);
|
RemoveConstraint removeConstraint = RemoveConstraint.valueOf(removeProperty);
|
||||||
if(removeConstraint!=RemoveConstraint.keep){
|
if(removeConstraint != RemoveConstraint.keep) {
|
||||||
message = new StringBuilder();
|
message = new StringBuilder();
|
||||||
message.append(RemoveConstraint.class.getSimpleName());
|
message.append(RemoveConstraint.class.getSimpleName());
|
||||||
message.append(" can only be ");
|
message.append(" can only be ");
|
||||||
|
@ -71,10 +70,10 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
|
||||||
if(propagationConstraint.has(PropagationConstraint.ADD_PROPERTY)) {
|
if(propagationConstraint.has(PropagationConstraint.ADD_PROPERTY)) {
|
||||||
String addProperty = propagationConstraint.get(PropagationConstraint.ADD_PROPERTY).asText();
|
String addProperty = propagationConstraint.get(PropagationConstraint.ADD_PROPERTY).asText();
|
||||||
AddConstraint addConstraint = AddConstraint.valueOf(addProperty);
|
AddConstraint addConstraint = AddConstraint.valueOf(addProperty);
|
||||||
if(addConstraint!=AddConstraint.unpropagate){
|
if(addConstraint != AddConstraint.unpropagate) {
|
||||||
if(message==null) {
|
if(message == null) {
|
||||||
message = new StringBuilder();
|
message = new StringBuilder();
|
||||||
}else {
|
} else {
|
||||||
message.append(" and ");
|
message.append(" and ");
|
||||||
}
|
}
|
||||||
message.append(AddConstraint.class.getSimpleName());
|
message.append(AddConstraint.class.getSimpleName());
|
||||||
|
@ -83,7 +82,7 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(message!=null) {
|
if(message != null) {
|
||||||
throw new ResourceRegistryException(message.toString());
|
throw new ResourceRegistryException(message.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -118,21 +117,21 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
|
||||||
Vertex source = element.getVertex(Direction.OUT);
|
Vertex source = element.getVertex(Direction.OUT);
|
||||||
ContextManagement sourceContextManagement = new ContextManagement(orientGraph);
|
ContextManagement sourceContextManagement = new ContextManagement(orientGraph);
|
||||||
sourceContextManagement.setElement(source);
|
sourceContextManagement.setElement(source);
|
||||||
if (includeSource) {
|
if(includeSource) {
|
||||||
relation.put(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
|
relation.put(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
|
||||||
}
|
}
|
||||||
|
|
||||||
Vertex target = element.getVertex(Direction.IN);
|
Vertex target = element.getVertex(Direction.IN);
|
||||||
ContextManagement targetContextManagement = new ContextManagement(orientGraph);
|
ContextManagement targetContextManagement = new ContextManagement(orientGraph);
|
||||||
targetContextManagement.setElement(target);
|
targetContextManagement.setElement(target);
|
||||||
if (includeTarget) {
|
if(includeTarget) {
|
||||||
relation.put(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly());
|
relation.put(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly());
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
|
|
@ -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());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.dbinitialization;
|
package org.gcube.informationsystem.resourceregistry.dbinitialization;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
@ -14,11 +11,11 @@ import org.gcube.informationsystem.impl.utils.discovery.ERDiscovery;
|
||||||
import org.gcube.informationsystem.model.ISConstants;
|
import org.gcube.informationsystem.model.ISConstants;
|
||||||
import org.gcube.informationsystem.model.embedded.Embedded;
|
import org.gcube.informationsystem.model.embedded.Embedded;
|
||||||
import org.gcube.informationsystem.model.embedded.ValueSchema;
|
import org.gcube.informationsystem.model.embedded.ValueSchema;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextSecurityContext;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SchemaSecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -40,7 +37,6 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class DatabaseEnvironment {
|
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;
|
||||||
private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD";
|
private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD";
|
||||||
|
|
||||||
public static final Map<PermissionMode, String> DEFAULT_PASSWORDS;
|
public static final Map<PermissionMode,String> DEFAULT_PASSWORDS;
|
||||||
|
|
||||||
private static final String HOSTS;
|
private static final String HOSTS;
|
||||||
|
|
||||||
|
@ -135,12 +131,12 @@ public class DatabaseEnvironment {
|
||||||
String changedAdminUsername = null;
|
String changedAdminUsername = null;
|
||||||
try {
|
try {
|
||||||
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
|
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
|
||||||
if (changedAdminUsername == null) {
|
if(changedAdminUsername == null) {
|
||||||
// To be compliant with old configuration.properties which does not have
|
// To be compliant with old configuration.properties which does not have
|
||||||
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
|
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
|
||||||
changedAdminUsername = DB;
|
changedAdminUsername = DB;
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
// To be compliant with old configuration.properties which does not have
|
// To be compliant with old configuration.properties which does not have
|
||||||
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
|
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
|
||||||
changedAdminUsername = DB;
|
changedAdminUsername = DB;
|
||||||
|
@ -155,18 +151,16 @@ public class DatabaseEnvironment {
|
||||||
DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME);
|
DEFAULT_ADMIN_USERNAME = properties.getProperty(DEFAULT_ADMIN_USERNAME_VARNAME);
|
||||||
DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME);
|
DEFAULT_ADMIN_PASSWORD = properties.getProperty(DEFAULT_ADMIN_PASSWORD_VARNAME);
|
||||||
|
|
||||||
DEFAULT_PASSWORDS = new HashMap<PermissionMode, String>();
|
DEFAULT_PASSWORDS = new HashMap<PermissionMode,String>();
|
||||||
|
|
||||||
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD);
|
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD);
|
||||||
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
|
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
|
logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
|
||||||
throw new RuntimeException("Unable to load properties", e);
|
throw new RuntimeException("Unable to load properties", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
|
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
|
||||||
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
|
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
|
||||||
|
|
||||||
|
@ -178,7 +172,6 @@ public class DatabaseEnvironment {
|
||||||
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
|
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
|
||||||
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
|
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
boolean created = initGraphDB();
|
boolean created = initGraphDB();
|
||||||
|
|
||||||
|
@ -190,10 +183,10 @@ public class DatabaseEnvironment {
|
||||||
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
|
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
|
||||||
contextUtility.addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
|
contextUtility.addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
|
||||||
|
|
||||||
SecurityContext schemaSecurityContext = new SecurityContext(SCHEMA_SECURITY_CONTEXT_UUID);
|
SchemaSecurityContext schemaSecurityContext = new SchemaSecurityContext();
|
||||||
contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext);
|
contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext);
|
||||||
|
|
||||||
if (created) {
|
if(created) {
|
||||||
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME,
|
OrientGraphFactory factory = new OrientGraphFactory(DB_URI, CHANGED_ADMIN_USERNAME,
|
||||||
CHANGED_ADMIN_PASSWORD).setupPool(1, 10);
|
CHANGED_ADMIN_PASSWORD).setupPool(1, 10);
|
||||||
OrientGraph orientGraph = factory.getTx();
|
OrientGraph orientGraph = factory.getTx();
|
||||||
|
@ -209,7 +202,7 @@ public class DatabaseEnvironment {
|
||||||
createEntitiesAndRelations();
|
createEntitiesAndRelations();
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Error initializing database connection", e);
|
logger.error("Error initializing database connection", e);
|
||||||
throw new RuntimeException("Error initializing database connection", e);
|
throw new RuntimeException("Error initializing database connection", e);
|
||||||
}
|
}
|
||||||
|
@ -225,7 +218,7 @@ public class DatabaseEnvironment {
|
||||||
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
|
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
|
||||||
OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD);
|
OServerAdmin serverAdmin = new OServerAdmin(SERVER_URI).connect(ROOT_USERNAME, ROOT_PASSWORD);
|
||||||
|
|
||||||
if (!serverAdmin.existsDatabase(DB, STORAGE_MODE)) {
|
if(!serverAdmin.existsDatabase(DB, STORAGE_MODE)) {
|
||||||
|
|
||||||
logger.info("The database {} does not exist. Going to create it.", DB_URI);
|
logger.info("The database {} does not exist. Going to create it.", DB_URI);
|
||||||
serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE);
|
serverAdmin.createDatabase(DB, DATABASE_TYPE, STORAGE_MODE);
|
||||||
|
@ -263,7 +256,7 @@ public class DatabaseEnvironment {
|
||||||
OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
|
OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
|
||||||
newAdminUser.save();
|
newAdminUser.save();
|
||||||
|
|
||||||
for (PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
|
for(PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
|
||||||
OUser oUser = oSecurity.getUser(permissionMode.toString());
|
OUser oUser = oSecurity.getUser(permissionMode.toString());
|
||||||
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
|
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
|
||||||
oUser.save();
|
oUser.save();
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.dbinitialization;
|
package org.gcube.informationsystem.resourceregistry.dbinitialization;
|
||||||
|
|
||||||
import org.gcube.informationsystem.impl.utils.discovery.SchemaAction;
|
import org.gcube.informationsystem.impl.utils.discovery.SchemaAction;
|
||||||
|
@ -18,53 +15,52 @@ import org.gcube.informationsystem.types.TypeBinder;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
public class SchemaActionImpl implements SchemaAction {
|
public class SchemaActionImpl implements SchemaAction {
|
||||||
|
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SchemaActionImpl.class);
|
private static Logger logger = LoggerFactory.getLogger(SchemaActionImpl.class);
|
||||||
|
|
||||||
protected SchemaManagement schemaManagement;
|
protected SchemaManagement schemaManagement;
|
||||||
|
|
||||||
public SchemaActionImpl(){
|
public SchemaActionImpl() {
|
||||||
this.schemaManagement = new SchemaManagementImpl();
|
this.schemaManagement = new SchemaManagementImpl();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <R extends Relation<? extends Entity, ? extends Entity>> void manageRelationClass(
|
public <R extends Relation<? extends Entity,? extends Entity>> void manageRelationClass(Class<R> r)
|
||||||
Class<R> r) throws Exception {
|
throws Exception {
|
||||||
try{
|
try {
|
||||||
String json = TypeBinder.serializeType(r);
|
String json = TypeBinder.serializeType(r);
|
||||||
logger.trace(json);
|
logger.trace(json);
|
||||||
if (ConsistsOf.class.isAssignableFrom(r)) {
|
if(ConsistsOf.class.isAssignableFrom(r)) {
|
||||||
schemaManagement.create(json, AccessType.CONSISTS_OF);
|
schemaManagement.create(json, AccessType.CONSISTS_OF);
|
||||||
} else if(IsRelatedTo.class.isAssignableFrom(r)){
|
} else if(IsRelatedTo.class.isAssignableFrom(r)) {
|
||||||
schemaManagement.create(json, AccessType.IS_RELATED_TO);
|
schemaManagement.create(json, AccessType.IS_RELATED_TO);
|
||||||
} else {
|
} else {
|
||||||
schemaManagement.create(json, AccessType.RELATION);
|
schemaManagement.create(json, AccessType.RELATION);
|
||||||
}
|
}
|
||||||
} catch(Exception ex){
|
} catch(Exception ex) {
|
||||||
logger.error("Error creating schema for {} type {} : {}", Relation.NAME, r.getSimpleName(), ex.getMessage());
|
logger.error("Error creating schema for {} type {} : {}", Relation.NAME, r.getSimpleName(),
|
||||||
|
ex.getMessage());
|
||||||
throw ex;
|
throw ex;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <E extends Entity> void manageEntityClass(Class<E> e) throws Exception {
|
public <E extends Entity> void manageEntityClass(Class<E> e) throws Exception {
|
||||||
try{
|
try {
|
||||||
String json = TypeBinder.serializeType(e);
|
String json = TypeBinder.serializeType(e);
|
||||||
logger.trace(json);
|
logger.trace(json);
|
||||||
if (Facet.class.isAssignableFrom(e)) {
|
if(Facet.class.isAssignableFrom(e)) {
|
||||||
schemaManagement.create(json, AccessType.FACET);
|
schemaManagement.create(json, AccessType.FACET);
|
||||||
} else if(Resource.class.isAssignableFrom(e)){
|
} else if(Resource.class.isAssignableFrom(e)) {
|
||||||
schemaManagement.create(json, AccessType.RESOURCE);
|
schemaManagement.create(json, AccessType.RESOURCE);
|
||||||
} else {
|
} else {
|
||||||
schemaManagement.create(json, AccessType.ENTITY);
|
schemaManagement.create(json, AccessType.ENTITY);
|
||||||
}
|
}
|
||||||
} catch(Exception ex){
|
} catch(Exception ex) {
|
||||||
logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage());
|
logger.error("Error creating schema for {} type {} : {}", Entity.NAME, e.getSimpleName(), ex.getMessage());
|
||||||
throw ex;
|
throw ex;
|
||||||
}
|
}
|
||||||
|
@ -76,9 +72,8 @@ public class SchemaActionImpl implements SchemaAction {
|
||||||
String json = TypeBinder.serializeType(e);
|
String json = TypeBinder.serializeType(e);
|
||||||
logger.trace(json);
|
logger.trace(json);
|
||||||
schemaManagement.create(json, AccessType.EMBEDDED);
|
schemaManagement.create(json, AccessType.EMBEDDED);
|
||||||
} catch (Exception ex) {
|
} catch(Exception ex) {
|
||||||
logger.error("Error creating schema for {} type {} : {}",
|
logger.error("Error creating schema for {} type {} : {}", Embedded.NAME, e.getSimpleName(),
|
||||||
Embedded.NAME, e.getSimpleName(),
|
|
||||||
ex.getMessage());
|
ex.getMessage());
|
||||||
throw ex;
|
throw ex;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er;
|
package org.gcube.informationsystem.resourceregistry.er;
|
||||||
|
|
||||||
import java.io.IOException;
|
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.er.ERNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
|
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient;
|
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 {
|
public void setUUID(UUID uuid) throws ResourceRegistryException {
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
if (jsonNode != null) {
|
if(jsonNode != null) {
|
||||||
checkUUIDMatch();
|
checkUUIDMatch();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -143,15 +140,15 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
try {
|
try {
|
||||||
this.jsonNode = mapper.readTree(jsonRepresentation);
|
this.jsonNode = mapper.readTree(jsonRepresentation);
|
||||||
} catch (IOException e) {
|
} catch(IOException e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
checkJSON();
|
checkJSON();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected OClass getOClass() throws SchemaException, ResourceRegistryException {
|
protected OClass getOClass() throws SchemaException, ResourceRegistryException {
|
||||||
if (oClass == null) {
|
if(oClass == null) {
|
||||||
if (element != null) {
|
if(element != null) {
|
||||||
OrientElement orientElement = (OrientElement) element;
|
OrientElement orientElement = (OrientElement) element;
|
||||||
OMetadata oMetadata = orientElement.getGraph().getRawGraph().getMetadata();
|
OMetadata oMetadata = orientElement.getGraph().getRawGraph().getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
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 {
|
public void setElementType(String erType) throws ResourceRegistryException {
|
||||||
this.erType = erType;
|
this.erType = erType;
|
||||||
if (erType == null || erType.compareTo("") == 0) {
|
if(erType == null || erType.compareTo("") == 0) {
|
||||||
erType = accessType.getName();
|
erType = accessType.getName();
|
||||||
}
|
}
|
||||||
if (jsonNode != null) {
|
if(jsonNode != null) {
|
||||||
checkERMatch();
|
checkERMatch();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void checkJSON() throws ResourceRegistryException {
|
protected void checkJSON() throws ResourceRegistryException {
|
||||||
if (uuid == null) {
|
if(uuid == null) {
|
||||||
try {
|
try {
|
||||||
uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode);
|
uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
checkUUIDMatch();
|
checkUUIDMatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.erType == null) {
|
if(this.erType == null) {
|
||||||
this.erType = getClassProperty(jsonNode);
|
this.erType = getClassProperty(jsonNode);
|
||||||
getOClass();
|
getOClass();
|
||||||
} else {
|
} else {
|
||||||
|
@ -193,9 +190,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void checkERMatch() throws ResourceRegistryException {
|
protected void checkERMatch() throws ResourceRegistryException {
|
||||||
if (jsonNode != null) {
|
if(jsonNode != null) {
|
||||||
String type = getClassProperty(jsonNode);
|
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",
|
String error = String.format("Declared resourceType does not match with json representation %s!=%s",
|
||||||
erType, type);
|
erType, type);
|
||||||
logger.trace(error);
|
logger.trace(error);
|
||||||
|
@ -209,13 +206,13 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
Header header = null;
|
Header header = null;
|
||||||
try {
|
try {
|
||||||
header = HeaderUtility.getHeader(jsonNode, false);
|
header = HeaderUtility.getHeader(jsonNode, false);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (header != null) {
|
if(header != null) {
|
||||||
UUID resourceUUID = header.getUUID();
|
UUID resourceUUID = header.getUUID();
|
||||||
if (resourceUUID.compareTo(uuid) != 0) {
|
if(resourceUUID.compareTo(uuid) != 0) {
|
||||||
String error = String.format(
|
String error = String.format(
|
||||||
"UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
|
"UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
|
||||||
resourceUUID.toString(), uuid.toString(), erType);
|
resourceUUID.toString(), uuid.toString(), erType);
|
||||||
|
@ -228,7 +225,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
public JSONObject serializeSelfOnly() throws ResourceRegistryException {
|
public JSONObject serializeSelfOnly() throws ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
return toJSONObject();
|
return toJSONObject();
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -244,7 +241,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
reallyCreate();
|
reallyCreate();
|
||||||
|
|
||||||
Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
|
Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
|
||||||
if (entityHeader != null) {
|
if(entityHeader != null) {
|
||||||
element.setProperty(Entity.HEADER_PROPERTY, entityHeader);
|
element.setProperty(Entity.HEADER_PROPERTY, entityHeader);
|
||||||
} else {
|
} else {
|
||||||
entityHeader = HeaderUtility.addHeader(element, null);
|
entityHeader = HeaderUtility.addHeader(element, null);
|
||||||
|
@ -255,9 +252,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
((OrientElement) element).save();
|
((OrientElement) element).save();
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause());
|
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();
|
((OrientElement) element).save();
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException("Error Updating " + erType + " with " + jsonNode, e.getCause());
|
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 {
|
public El internalCreateOrUdate() throws ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
return internalUpdate();
|
return internalUpdate();
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
return internalCreate();
|
return internalCreate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -303,9 +300,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
HeaderUtility.updateModifiedByAndLastUpdate(element);
|
HeaderUtility.updateModifiedByAndLastUpdate(element);
|
||||||
((OrientElement) element).save();
|
((OrientElement) element).save();
|
||||||
return ret && true;
|
return ret && true;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException("Error Adding " + erType + " to Current Context ", e.getCause());
|
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);
|
HeaderUtility.updateModifiedByAndLastUpdate(element);
|
||||||
((OrientElement) element).save();
|
((OrientElement) element).save();
|
||||||
return ret && true;
|
return ret && true;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause());
|
throw new ResourceRegistryException("Error Removing " + erType + " from Current Context ", e.getCause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setElement(El element) throws ResourceRegistryException {
|
public void setElement(El element) throws ResourceRegistryException {
|
||||||
if (element == null) {
|
if(element == null) {
|
||||||
throw new ResourceRegistryException("Trying to set null " + elementClass.getSimpleName() + " in " + this);
|
throw new ResourceRegistryException("Trying to set null " + elementClass.getSimpleName() + " in " + this);
|
||||||
}
|
}
|
||||||
this.element = element;
|
this.element = element;
|
||||||
|
@ -341,28 +338,28 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message);
|
protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message);
|
||||||
|
|
||||||
public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
|
public El getElement() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
|
||||||
if (element == null) {
|
if(element == null) {
|
||||||
try {
|
try {
|
||||||
element = retrieveElement();
|
element = retrieveElement();
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
try {
|
try {
|
||||||
retrieveElementFromAnyContext();
|
retrieveElementFromAnyContext();
|
||||||
throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName()
|
throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName()
|
||||||
: erType + " with UUID " + uuid + " is available in another "
|
: erType + " with UUID " + uuid + " is available in another "
|
||||||
+ Context.class.getSimpleName());
|
+ Context.class.getSimpleName());
|
||||||
} catch (ERAvailableInAnotherContextException e1) {
|
} catch(ERAvailableInAnotherContextException e1) {
|
||||||
throw e1;
|
throw e1;
|
||||||
} catch (Exception e1) {
|
} catch(Exception e1) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
if (reload) {
|
if(reload) {
|
||||||
((OrientElement) element).reload();
|
((OrientElement) element).reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -371,16 +368,16 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
public El retrieveElement() throws ERNotFoundException, ResourceRegistryException {
|
public El retrieveElement() throws ERNotFoundException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
if (uuid == null) {
|
if(uuid == null) {
|
||||||
throw new ERNotFoundException("null UUID does not allow to retrieve the Element");
|
throw new ERNotFoundException("null UUID does not allow to retrieve the Element");
|
||||||
}
|
}
|
||||||
return Utility.getElementByUUID(orientGraph, erType == null ? accessType.getName() : erType, uuid,
|
return Utility.getElementByUUID(orientGraph, erType == null ? accessType.getName() : erType, uuid,
|
||||||
elementClass);
|
elementClass);
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
throw getSpecificElementNotFoundException(e);
|
throw getSpecificElementNotFoundException(e);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(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 {
|
public El retrieveElementFromAnyContext() throws ERNotFoundException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass);
|
return Utility.getElementByUUIDAsAdmin(erType == null ? accessType.getName() : erType, uuid, elementClass);
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
throw getSpecificElementNotFoundException(e);
|
throw getSpecificElementNotFoundException(e);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -405,12 +402,12 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
|
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
|
||||||
|
|
||||||
return reallyGetAll(polymorphic);
|
return reallyGetAll(polymorphic);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -424,14 +421,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
getElement();
|
getElement();
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid);
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e);
|
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e);
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -450,20 +447,20 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
return serialize();
|
return serialize();
|
||||||
|
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to create {}", accessType.getName());
|
logger.error("Unable to create {}", accessType.getName());
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to create {}", accessType.getName(), e);
|
logger.error("Unable to create {}", accessType.getName(), e);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -476,14 +473,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
getElement();
|
getElement();
|
||||||
|
|
||||||
return serialize();
|
return serialize();
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid);
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e);
|
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e);
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -498,24 +495,25 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
orientGraph.commit();
|
orientGraph.commit();
|
||||||
|
|
||||||
setReload(true);
|
setReload(true);
|
||||||
|
|
||||||
// TODO Notify to subscriptionNotification
|
// TODO Notify to subscriptionNotification
|
||||||
|
|
||||||
return serialize();
|
return serialize();
|
||||||
|
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e);
|
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -531,7 +529,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
boolean deleted = reallyDelete();
|
boolean deleted = reallyDelete();
|
||||||
|
|
||||||
if (deleted) {
|
if(deleted) {
|
||||||
orientGraph.commit();
|
orientGraph.commit();
|
||||||
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
|
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
|
||||||
} else {
|
} else {
|
||||||
|
@ -541,27 +539,28 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
return deleted;
|
return deleted;
|
||||||
|
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e);
|
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid, e);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException {
|
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 {
|
try {
|
||||||
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
|
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);
|
logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
|
||||||
|
|
||||||
return added;
|
return added;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid);
|
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
|
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new ContextException(e);
|
throw new ContextException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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);
|
logger.info("{} with UUID {} successfully removed from actual Context", accessType.getName(), uuid);
|
||||||
|
|
||||||
return removed;
|
return removed;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid);
|
logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid, e);
|
logger.error("Unable to remove {} with UUID {} from actual Context", accessType.getName(), uuid, e);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new ContextException(e);
|
throw new ContextException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getClassProperty(JsonNode jsonNode) {
|
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 jsonNode.get(ISManageable.CLASS_PROPERTY).asText();
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
@ -634,84 +633,90 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
throws UnsupportedDataTypeException, ResourceRegistryException {
|
throws UnsupportedDataTypeException, ResourceRegistryException {
|
||||||
JsonNodeType jsonNodeType = value.getNodeType();
|
JsonNodeType jsonNodeType = value.getNodeType();
|
||||||
|
|
||||||
switch (jsonNodeType) {
|
switch(jsonNodeType) {
|
||||||
case OBJECT:
|
case OBJECT:
|
||||||
return EmbeddedMangement.getEmbeddedType(value);
|
return EmbeddedMangement.getEmbeddedType(value);
|
||||||
|
|
||||||
case ARRAY:
|
case ARRAY:
|
||||||
/*
|
/*
|
||||||
* List<Object> list = new ArrayList<Object>(); Iterator<JsonNode> arrayElement
|
List<Object> list = new ArrayList<Object>();
|
||||||
* = value.elements(); while (arrayElement.hasNext()) { JsonNode arrayNode =
|
Iterator<JsonNode> arrayElement = value.elements();
|
||||||
* arrayElement.next(); Object objectNode = getObjectFromElement(arrayNode); if
|
while(arrayElement.hasNext()) {
|
||||||
* (objectNode != null) { list.add(objectNode); } } return list;
|
JsonNode arrayNode = arrayElement.next();
|
||||||
*/
|
Object objectNode = getObjectFromElement(arrayNode);
|
||||||
throw new UnsupportedDataTypeException(
|
if(objectNode != null) {
|
||||||
"List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
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");
|
||||||
|
|
||||||
case BINARY:
|
case BINARY:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case BOOLEAN:
|
case BOOLEAN:
|
||||||
return value.asBoolean();
|
return value.asBoolean();
|
||||||
|
|
||||||
case NULL:
|
case NULL:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case NUMBER:
|
case NUMBER:
|
||||||
if (value.isDouble() || value.isFloat()) {
|
if(value.isDouble() || value.isFloat()) {
|
||||||
return value.asDouble();
|
return value.asDouble();
|
||||||
}
|
}
|
||||||
if (value.isBigInteger() || value.isShort() || value.isInt()) {
|
if(value.isBigInteger() || value.isShort() || value.isInt()) {
|
||||||
return value.asInt();
|
return value.asInt();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (value.isLong()) {
|
if(value.isLong()) {
|
||||||
return value.asLong();
|
return value.asLong();
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case STRING:
|
case STRING:
|
||||||
return value.asText();
|
return value.asText();
|
||||||
|
|
||||||
case MISSING:
|
case MISSING:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case POJO:
|
case POJO:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
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 {
|
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<>();
|
ignoreKeys = new HashSet<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ignoreStartWith == null) {
|
if(ignoreStartWith == null) {
|
||||||
ignoreStartWith = new HashSet<>();
|
ignoreStartWith = new HashSet<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
|
Iterator<Entry<String,JsonNode>> fields = jsonNode.fields();
|
||||||
|
|
||||||
OUTER_WHILE: while (fields.hasNext()) {
|
OUTER_WHILE: while(fields.hasNext()) {
|
||||||
Entry<String, JsonNode> entry = fields.next();
|
Entry<String,JsonNode> entry = fields.next();
|
||||||
|
|
||||||
String key = entry.getKey();
|
String key = entry.getKey();
|
||||||
|
|
||||||
if (ignoreKeys.contains(key)) {
|
if(ignoreKeys.contains(key)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (String prefix : ignoreStartWith) {
|
for(String prefix : ignoreStartWith) {
|
||||||
if (key.startsWith(prefix)) {
|
if(key.startsWith(prefix)) {
|
||||||
continue OUTER_WHILE;
|
continue OUTER_WHILE;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -720,10 +725,10 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
Object object = null;
|
Object object = null;
|
||||||
try {
|
try {
|
||||||
object = getObjectFromElement(value);
|
object = getObjectFromElement(value);
|
||||||
if (object != null) {
|
if(object != null) {
|
||||||
map.put(key, object);
|
map.put(key, object);
|
||||||
}
|
}
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
staticLogger.warn("An invalidy property has been provided. It will be ignored.");
|
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();
|
Set<String> oldKeys = element.getPropertyKeys();
|
||||||
|
|
||||||
Map<String, Object> properties;
|
Map<String,Object> properties;
|
||||||
if (element instanceof Vertex || element instanceof Edge) {
|
if(element instanceof Vertex || element instanceof Edge) {
|
||||||
try {
|
try {
|
||||||
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
|
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
|
||||||
} catch (IOException e) {
|
} catch(IOException e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -751,15 +756,15 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
oldKeys.removeAll(properties.keySet());
|
oldKeys.removeAll(properties.keySet());
|
||||||
|
|
||||||
for (String key : properties.keySet()) {
|
for(String key : properties.keySet()) {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
Object object = properties.get(key);
|
Object object = properties.get(key);
|
||||||
if (!oClass.existsProperty(key)) {
|
if(!oClass.existsProperty(key)) {
|
||||||
|
|
||||||
boolean set = false;
|
boolean set = false;
|
||||||
|
|
||||||
if (object instanceof ODocument) {
|
if(object instanceof ODocument) {
|
||||||
ODocument oDocument = (ODocument) object;
|
ODocument oDocument = (ODocument) object;
|
||||||
((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED);
|
((OrientElement) element).setProperty(key, oDocument, OType.EMBEDDED);
|
||||||
set = true;
|
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,
|
* if(object instanceof Set){ ((OrientElement) element).setProperty(key, object,
|
||||||
* OType.EMBEDDEDSET); set = true; }
|
* OType.EMBEDDEDSET); set = true; } if(object instanceof List){
|
||||||
*
|
* ((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST); set =
|
||||||
* if(object instanceof List){ ((OrientElement) element).setProperty(key,
|
* true; }
|
||||||
* object, OType.EMBEDDEDLIST); set = true; }
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
if (!set) {
|
if(!set) {
|
||||||
element.setProperty(key, object);
|
element.setProperty(key, object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -781,7 +785,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
element.setProperty(key, object);
|
element.setProperty(key, object);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String error = String.format("Error while setting property %s : %s (%s)", key,
|
String error = String.format("Error while setting property %s : %s (%s)", key,
|
||||||
properties.get(key).toString(), e.getMessage());
|
properties.get(key).toString(), e.getMessage());
|
||||||
staticLogger.error(error);
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (String prefix : ignoreStartWithKeys) {
|
for(String prefix : ignoreStartWithKeys) {
|
||||||
if (key.startsWith(prefix)) {
|
if(key.startsWith(prefix)) {
|
||||||
continue OUTER_FOR;
|
continue OUTER_FOR;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -811,53 +815,53 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException {
|
protected Object getPropertyForJson(String key, Object object) throws ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
if (key.compareTo(ER.HEADER_PROPERTY) == 0) {
|
if(key.compareTo(ER.HEADER_PROPERTY) == 0) {
|
||||||
// Keeping the header
|
// Keeping the header
|
||||||
HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object);
|
HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object);
|
||||||
JSONObject headerObject = new JSONObject(headerOrient.toJSON("class"));
|
JSONObject headerObject = new JSONObject(headerOrient.toJSON("class"));
|
||||||
return headerObject;
|
return headerObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ignoreKeys.contains(key)) {
|
if(ignoreKeys.contains(key)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (String prefix : ignoreStartWithKeys) {
|
for(String prefix : ignoreStartWithKeys) {
|
||||||
if (key.startsWith(prefix)) {
|
if(key.startsWith(prefix)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (object instanceof ODocument) {
|
if(object instanceof ODocument) {
|
||||||
String json = ((ODocument) object).toJSON("class");
|
String json = ((ODocument) object).toJSON("class");
|
||||||
JSONObject jsonObject = new JSONObject(json);
|
JSONObject jsonObject = new JSONObject(json);
|
||||||
return jsonObject;
|
return jsonObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (object instanceof Date) {
|
if(object instanceof Date) {
|
||||||
OProperty oProperty = getOClass().getProperty(key);
|
OProperty oProperty = getOClass().getProperty(key);
|
||||||
OType oType = oProperty.getType();
|
OType oType = oProperty.getType();
|
||||||
DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance();
|
DateFormat dateFormat = ODateHelper.getDateTimeFormatInstance();
|
||||||
switch (oType) {
|
switch(oType) {
|
||||||
case DATE:
|
case DATE:
|
||||||
dateFormat = ODateHelper.getDateFormatInstance();
|
dateFormat = ODateHelper.getDateFormatInstance();
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case DATETIME:
|
case DATETIME:
|
||||||
dateFormat = ODateHelper.getDateTimeFormatInstance();
|
dateFormat = ODateHelper.getDateTimeFormatInstance();
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return dateFormat.format((Date) object);
|
return dateFormat.format((Date) object);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (object instanceof Collection) {
|
if(object instanceof Collection) {
|
||||||
Collection<?> collection = (Collection<?>) object;
|
Collection<?> collection = (Collection<?>) object;
|
||||||
JSONArray jsonArray = new JSONArray();
|
JSONArray jsonArray = new JSONArray();
|
||||||
for (Object o : collection) {
|
for(Object o : collection) {
|
||||||
Object obj = getPropertyForJson("PLACEHOLDER", o);
|
Object obj = getPropertyForJson("PLACEHOLDER", o);
|
||||||
jsonArray.put(obj);
|
jsonArray.put(obj);
|
||||||
}
|
}
|
||||||
|
@ -867,7 +871,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
|
|
||||||
return object.toString();
|
return object.toString();
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
"Error while serializing " + key + "=" + object.toString() + " in " + getElement().toString(), e);
|
"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 {
|
protected Collection<String> getSuperclasses() throws SchemaException, ResourceRegistryException {
|
||||||
Collection<OClass> allSuperClasses = getOClass().getAllSuperClasses();
|
Collection<OClass> allSuperClasses = getOClass().getAllSuperClasses();
|
||||||
Collection<String> superClasses = new HashSet<>();
|
Collection<String> superClasses = new HashSet<>();
|
||||||
for (OClass oSuperClass : allSuperClasses) {
|
for(OClass oSuperClass : allSuperClasses) {
|
||||||
String name = oSuperClass.getName();
|
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) {
|
|| name.compareTo(DatabaseEnvironment.O_RESTRICTED_CLASS) == 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
@ -892,11 +896,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
try {
|
try {
|
||||||
OrientElement orientElement = (OrientElement) getElement();
|
OrientElement orientElement = (OrientElement) getElement();
|
||||||
|
|
||||||
Map<String, Object> properties = orientElement.getProperties();
|
Map<String,Object> properties = orientElement.getProperties();
|
||||||
for (String key : orientElement.getPropertyKeys()) {
|
for(String key : orientElement.getPropertyKeys()) {
|
||||||
Object object = properties.get(key);
|
Object object = properties.get(key);
|
||||||
object = getPropertyForJson(key, object);
|
object = getPropertyForJson(key, object);
|
||||||
if (object != null) {
|
if(object != null) {
|
||||||
properties.put(key, object);
|
properties.put(key, object);
|
||||||
} else {
|
} else {
|
||||||
properties.remove(key);
|
properties.remove(key);
|
||||||
|
@ -913,9 +917,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
|
||||||
jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray);
|
jsonObject.put(ISManageable.SUPERCLASSES_PROPERTY, jsonArray);
|
||||||
|
|
||||||
return jsonObject;
|
return jsonObject;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException("Error while serializing " + getElement().toString(), e);
|
throw new ResourceRegistryException("Error while serializing " + getElement().toString(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,7 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo;
|
||||||
import org.gcube.informationsystem.model.relation.Relation;
|
import org.gcube.informationsystem.model.relation.Relation;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
||||||
|
@ -32,6 +32,9 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
|
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
|
||||||
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
|
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class ERManagementUtility {
|
public class ERManagementUtility {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(EntityManagement.class);
|
private static Logger logger = LoggerFactory.getLogger(EntityManagement.class);
|
||||||
|
@ -42,17 +45,17 @@ public class ERManagementUtility {
|
||||||
OClass oClass = SchemaManagementImpl.getTypeSchema(type, null);
|
OClass oClass = SchemaManagementImpl.getTypeSchema(type, null);
|
||||||
ERManagement erManagement = null;
|
ERManagement erManagement = null;
|
||||||
|
|
||||||
if (oClass.isSubClassOf(Resource.NAME)) {
|
if(oClass.isSubClassOf(Resource.NAME)) {
|
||||||
erManagement = new ResourceManagement();
|
erManagement = new ResourceManagement();
|
||||||
} else if (oClass.isSubClassOf(Facet.NAME)) {
|
} else if(oClass.isSubClassOf(Facet.NAME)) {
|
||||||
erManagement = new FacetManagement();
|
erManagement = new FacetManagement();
|
||||||
} else if (oClass.isSubClassOf(ConsistsOf.NAME)) {
|
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
|
||||||
erManagement = new ConsistsOfManagement();
|
erManagement = new ConsistsOfManagement();
|
||||||
} else if (oClass.isSubClassOf(IsRelatedTo.NAME)) {
|
} else if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
|
||||||
erManagement = new IsRelatedToManagement();
|
erManagement = new IsRelatedToManagement();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (erManagement == null) {
|
if(erManagement == null) {
|
||||||
throw new ResourceRegistryException(String.format("%s is not querable", type.toString()));
|
throw new ResourceRegistryException(String.format("%s is not querable", type.toString()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -61,11 +64,11 @@ public class ERManagementUtility {
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element)
|
private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph,
|
||||||
throws ResourceRegistryException {
|
Element element) throws ResourceRegistryException {
|
||||||
if (element instanceof Vertex) {
|
if(element instanceof Vertex) {
|
||||||
return getEntityManagement(workingContext, orientGraph, (Vertex) element);
|
return getEntityManagement(workingContext, orientGraph, (Vertex) element);
|
||||||
} else if (element instanceof Edge) {
|
} else if(element instanceof Edge) {
|
||||||
return getRelationManagement(workingContext, orientGraph, (Edge) element);
|
return getRelationManagement(workingContext, orientGraph, (Edge) element);
|
||||||
}
|
}
|
||||||
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
|
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
|
||||||
|
@ -75,11 +78,11 @@ public class ERManagementUtility {
|
||||||
public static Element getAnyElementByUUID(UUID uuid) throws ERNotFoundException, ResourceRegistryException {
|
public static Element getAnyElementByUUID(UUID uuid) throws ERNotFoundException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
return Utility.getElementByUUIDAsAdmin(null, uuid, Vertex.class);
|
return Utility.getElementByUUIDAsAdmin(null, uuid, Vertex.class);
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
return Utility.getElementByUUIDAsAdmin(null, uuid, Edge.class);
|
return Utility.getElementByUUIDAsAdmin(null, uuid, Edge.class);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -88,90 +91,89 @@ public class ERManagementUtility {
|
||||||
throws ERNotFoundException, ResourceRegistryException {
|
throws ERNotFoundException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
return Utility.getElementByUUID(orientGraph, null, uuid, Vertex.class);
|
return Utility.getElementByUUID(orientGraph, null, uuid, Vertex.class);
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
return Utility.getElementByUUID(orientGraph, null, uuid, Edge.class);
|
return Utility.getElementByUUID(orientGraph, null, uuid, Edge.class);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, UUID uuid)
|
public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph,
|
||||||
throws ResourceRegistryException {
|
UUID uuid) throws ResourceRegistryException {
|
||||||
Element element;
|
Element element;
|
||||||
try {
|
try {
|
||||||
element = getAnyElementByUUID(orientGraph, uuid);
|
element = getAnyElementByUUID(orientGraph, uuid);
|
||||||
return getERManagement(workingContext, orientGraph, element);
|
return getERManagement(workingContext, orientGraph, element);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
|
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
|
||||||
uuid.toString(), Entity.NAME, Relation.NAME));
|
uuid.toString(), Entity.NAME, Relation.NAME));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||||
public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, Vertex vertex)
|
public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph,
|
||||||
throws ResourceRegistryException {
|
Vertex vertex) throws ResourceRegistryException {
|
||||||
|
|
||||||
if (orientGraph == null) {
|
if(orientGraph == null) {
|
||||||
throw new ResourceRegistryException(OrientGraph.class.getSimpleName()
|
throw new ResourceRegistryException(
|
||||||
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (vertex == null) {
|
if(vertex == null) {
|
||||||
throw new ResourceRegistryException(Vertex.class.getSimpleName()
|
throw new ResourceRegistryException(
|
||||||
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Vertex.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
OrientVertexType orientVertexType = null;
|
OrientVertexType orientVertexType = null;
|
||||||
try {
|
try {
|
||||||
orientVertexType = ((OrientVertex) vertex).getType();
|
orientVertexType = ((OrientVertex) vertex).getType();
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String error = String.format(
|
String error = String.format("Unable to detect type of %s. %s", vertex.toString(),
|
||||||
"Unable to detect type of %s. %s",
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
logger.error(error, e);
|
logger.error(error, e);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
EntityManagement entityManagement = null;
|
EntityManagement entityManagement = null;
|
||||||
if (orientVertexType.isSubClassOf(Resource.NAME)) {
|
if(orientVertexType.isSubClassOf(Resource.NAME)) {
|
||||||
entityManagement = new ResourceManagement(workingContext, orientGraph);
|
entityManagement = new ResourceManagement(workingContext, orientGraph);
|
||||||
} else if (orientVertexType.isSubClassOf(Facet.NAME)) {
|
} else if(orientVertexType.isSubClassOf(Facet.NAME)) {
|
||||||
entityManagement = new FacetManagement(workingContext, orientGraph);
|
entityManagement = new FacetManagement(workingContext, orientGraph);
|
||||||
} else {
|
} else {
|
||||||
String error = String.format("{%s is not a %s nor a %s. %s",
|
String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME,
|
||||||
vertex, Resource.NAME, Facet.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
entityManagement.setElement(vertex);
|
entityManagement.setElement(vertex);
|
||||||
return entityManagement;
|
return entityManagement;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, Edge edge)
|
public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph,
|
||||||
throws ResourceRegistryException {
|
Edge edge) throws ResourceRegistryException {
|
||||||
|
|
||||||
if (orientGraph == null) {
|
if(orientGraph == null) {
|
||||||
throw new ResourceRegistryException(OrientGraph.class.getSimpleName()
|
throw new ResourceRegistryException(
|
||||||
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
OrientGraph.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (edge == null) {
|
if(edge == null) {
|
||||||
throw new ResourceRegistryException(Edge.class.getSimpleName()
|
throw new ResourceRegistryException(
|
||||||
+ "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Edge.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
|
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
|
||||||
RelationManagement relationManagement = null;
|
RelationManagement relationManagement = null;
|
||||||
if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
|
if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
|
||||||
relationManagement = new ConsistsOfManagement(workingContext, orientGraph);
|
relationManagement = new ConsistsOfManagement(workingContext, orientGraph);
|
||||||
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
|
} else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
|
||||||
relationManagement = new IsRelatedToManagement(workingContext, orientGraph);
|
relationManagement = new IsRelatedToManagement(workingContext, orientGraph);
|
||||||
} else {
|
} else {
|
||||||
String error = String.format("{%s is not a %s nor a %s. %s",
|
String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME,
|
||||||
edge, ConsistsOf.NAME, IsRelatedTo.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
relationManagement.setElement(edge);
|
relationManagement.setElement(edge);
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er;
|
package org.gcube.informationsystem.resourceregistry.er;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
@ -24,8 +21,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
|
||||||
*/
|
*/
|
||||||
public class EmbeddedMangement {
|
public class EmbeddedMangement {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory
|
private static Logger logger = LoggerFactory.getLogger(EmbeddedMangement.class);
|
||||||
.getLogger(EmbeddedMangement.class);
|
|
||||||
|
|
||||||
public static final Set<String> EMBEDDED_IGNORE_KEYS;
|
public static final Set<String> EMBEDDED_IGNORE_KEYS;
|
||||||
public static final Set<String> EMBEDDED_IGNORE_START_WITH_KEYS;
|
public static final Set<String> EMBEDDED_IGNORE_START_WITH_KEYS;
|
||||||
|
@ -42,16 +38,14 @@ public class EmbeddedMangement {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static ODocument getEmbeddedType(JsonNode jsonNode) throws ResourceRegistryException {
|
||||||
public static ODocument getEmbeddedType(JsonNode jsonNode)
|
if(jsonNode.has(ISManageable.CLASS_PROPERTY)) {
|
||||||
throws ResourceRegistryException {
|
|
||||||
if (jsonNode.has(ISManageable.CLASS_PROPERTY)) {
|
|
||||||
// Complex type
|
// Complex type
|
||||||
String type = ERManagement.getClassProperty(jsonNode);
|
String type = ERManagement.getClassProperty(jsonNode);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED);
|
SchemaManagementImpl.getTypeSchema(type, AccessType.EMBEDDED);
|
||||||
} catch (SchemaNotFoundException e) {
|
} catch(SchemaNotFoundException e) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,12 +53,12 @@ public class EmbeddedMangement {
|
||||||
try {
|
try {
|
||||||
header = HeaderUtility.getHeader(jsonNode, false);
|
header = HeaderUtility.getHeader(jsonNode, false);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.warn("An invalid Header has been provided. Anyway embedded object cannot have an Header.");
|
logger.warn("An invalid Header has been provided. Anyway embedded object cannot have an Header.");
|
||||||
throw new ResourceRegistryException("An embedded object cannot have an Header");
|
throw new ResourceRegistryException("An embedded object cannot have an Header");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (header != null) {
|
if(header != null) {
|
||||||
throw new ResourceRegistryException("An embedded object cannot have an Header");
|
throw new ResourceRegistryException("An embedded object cannot have an Header");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er.entity;
|
package org.gcube.informationsystem.resourceregistry.er.entity;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
@ -16,7 +13,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
|
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
|
||||||
|
@ -32,30 +29,24 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertex;
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
public abstract class EntityManagement<E extends Entity> extends
|
public abstract class EntityManagement<E extends Entity> extends ERManagement<E,Vertex> {
|
||||||
ERManagement<E, Vertex> {
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provide a cache edge-internal-id -> RelationManagement
|
* Provide a cache edge-internal-id -> RelationManagement
|
||||||
* this avoid to recreate the relationManagement of already visited
|
* this avoid to recreate the relationManagement of already visited edges
|
||||||
* edges
|
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
protected Map<String, RelationManagement> relationManagements;
|
protected Map<String,RelationManagement> relationManagements;
|
||||||
|
|
||||||
protected EntityManagement(AccessType accessType) {
|
protected EntityManagement(AccessType accessType) {
|
||||||
super(accessType);
|
super(accessType);
|
||||||
|
|
||||||
this.ignoreKeys.add(Entity.HEADER_PROPERTY);
|
this.ignoreKeys.add(Entity.HEADER_PROPERTY);
|
||||||
|
|
||||||
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX
|
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toLowerCase());
|
||||||
.toLowerCase());
|
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toLowerCase());
|
||||||
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
|
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX.toUpperCase());
|
||||||
.toLowerCase());
|
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX.toUpperCase());
|
||||||
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_IN_PREFIX
|
|
||||||
.toUpperCase());
|
|
||||||
this.ignoreStartWithKeys.add(OrientVertex.CONNECTION_OUT_PREFIX
|
|
||||||
.toUpperCase());
|
|
||||||
|
|
||||||
this.relationManagements = new HashMap<>();
|
this.relationManagements = new HashMap<>();
|
||||||
|
|
||||||
|
@ -69,24 +60,26 @@ public abstract class EntityManagement<E extends Entity> extends
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
/*
|
/*
|
||||||
* It works perfectly in case of any kind of update.
|
* It works perfectly in case of any kind of update. In case of use from create
|
||||||
* In case of use from create the cache does not work by using the ID because until commit the edge has a fake id
|
* the cache does not work by using the ID because until commit the edge has a
|
||||||
* starting with - (minus) sign. This not imply any collateral effect but a better solution is a desiderata.
|
* fake id starting with - (minus) sign. This not imply any collateral effect
|
||||||
|
* but a better solution is a desiderata.
|
||||||
*/
|
*/
|
||||||
protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException {
|
protected RelationManagement getRelationManagement(Edge edge) throws ResourceRegistryException {
|
||||||
String id = edge.getId().toString();
|
String id = edge.getId().toString();
|
||||||
RelationManagement relationManagement = relationManagements.get(id);
|
RelationManagement relationManagement = relationManagements.get(id);
|
||||||
if(relationManagement==null) {
|
if(relationManagement == null) {
|
||||||
relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
|
relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
}
|
}
|
||||||
return relationManagement;
|
return relationManagement;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement) throws ResourceRegistryException {
|
protected void addToRelationManagement(@SuppressWarnings("rawtypes") RelationManagement relationManagement)
|
||||||
|
throws ResourceRegistryException {
|
||||||
Element elem = relationManagement.getElement();
|
Element elem = relationManagement.getElement();
|
||||||
String id = elem.getId().toString();
|
String id = elem.getId().toString();
|
||||||
if(relationManagements.get(id)!=null && relationManagements.get(id)!=relationManagement) {
|
if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) {
|
||||||
StringBuilder errorMessage = new StringBuilder();
|
StringBuilder errorMessage = new StringBuilder();
|
||||||
errorMessage.append("Two different instance of ");
|
errorMessage.append("Two different instance of ");
|
||||||
errorMessage.append(relationManagement.getClass().getSimpleName());
|
errorMessage.append(relationManagement.getClass().getSimpleName());
|
||||||
|
@ -99,12 +92,11 @@ public abstract class EntityManagement<E extends Entity> extends
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static JSONObject addRelation(JSONObject sourceResource,
|
protected static JSONObject addRelation(JSONObject sourceResource, JSONObject relation, String arrayKey)
|
||||||
JSONObject relation, String arrayKey)
|
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
JSONArray relationArray = null;
|
JSONArray relationArray = null;
|
||||||
try {
|
try {
|
||||||
if (sourceResource.has(arrayKey)) {
|
if(sourceResource.has(arrayKey)) {
|
||||||
relationArray = sourceResource.getJSONArray(arrayKey);
|
relationArray = sourceResource.getJSONArray(arrayKey);
|
||||||
} else {
|
} else {
|
||||||
relationArray = new JSONArray();
|
relationArray = new JSONArray();
|
||||||
|
@ -112,22 +104,22 @@ public abstract class EntityManagement<E extends Entity> extends
|
||||||
|
|
||||||
relationArray.put(relation);
|
relationArray.put(relation);
|
||||||
sourceResource.putOpt(arrayKey, relationArray);
|
sourceResource.putOpt(arrayKey, relationArray);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
return sourceResource;
|
return sourceResource;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Vertex createVertex() throws EntityAlreadyPresentException,
|
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
|
||||||
ResourceRegistryException {
|
|
||||||
|
|
||||||
logger.trace("Going to create {} for {} ({}) using {}",
|
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
|
||||||
Vertex.class.getSimpleName(), accessType.getName(), erType, jsonNode);
|
erType, jsonNode);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if(oClass.isAbstract()){
|
if(oClass.isAbstract()) {
|
||||||
String error = String.format("Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
|
String error = String.format(
|
||||||
|
"Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
|
||||||
accessType.getName(), erType);
|
accessType.getName(), erType);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
|
@ -135,63 +127,57 @@ public abstract class EntityManagement<E extends Entity> extends
|
||||||
Vertex vertexEntity = orientGraph.addVertex("class:" + erType);
|
Vertex vertexEntity = orientGraph.addVertex("class:" + erType);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if(uuid!=null){
|
if(uuid != null) {
|
||||||
Vertex v = getElement();
|
Vertex v = getElement();
|
||||||
if (v != null) {
|
if(v != null) {
|
||||||
String error = String.format(
|
String error = String.format("A %s with UUID %s already exist", erType, uuid.toString());
|
||||||
"A %s with UUID %s already exist", erType,
|
|
||||||
uuid.toString());
|
|
||||||
throw getSpecificERAlreadyPresentException(error);
|
throw getSpecificERAlreadyPresentException(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
try {
|
try {
|
||||||
Element el = ERManagementUtility.getAnyElementByUUID(uuid);
|
Element el = ERManagementUtility.getAnyElementByUUID(uuid);
|
||||||
String error = String.format(
|
String error = String.format("UUID %s is already used by another %s. This is not allowed.",
|
||||||
"UUID %s is already used by another %s. This is not allowed.",
|
|
||||||
uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME);
|
uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME);
|
||||||
throw getSpecificERAvailableInAnotherContextException(error);
|
throw getSpecificERAvailableInAnotherContextException(error);
|
||||||
|
|
||||||
}catch (ERNotFoundException e1) {
|
} catch(ERNotFoundException e1) {
|
||||||
// OK the UUID is not already used.
|
// OK the UUID is not already used.
|
||||||
}
|
}
|
||||||
} catch (ERAvailableInAnotherContextException e) {
|
} catch(ERAvailableInAnotherContextException e) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.element = vertexEntity;
|
this.element = vertexEntity;
|
||||||
|
|
||||||
if (accessType==AccessType.RESOURCE) {
|
if(accessType == AccessType.RESOURCE) {
|
||||||
// Facet and relation are created in calling method
|
// Facet and relation are created in calling method
|
||||||
} else {
|
} else {
|
||||||
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys,
|
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
|
||||||
ignoreStartWithKeys);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("Created {} is {}", Vertex.class.getSimpleName(),
|
logger.info("Created {} is {}", Vertex.class.getSimpleName(),
|
||||||
Utility.toJsonString((OrientVertex) element, true));
|
Utility.toJsonString((OrientVertex) element, true));
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.trace("Error while creating {} for {} ({}) using {}",
|
logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
|
||||||
Vertex.class.getSimpleName(), accessType.getName(), erType, jsonNode, e);
|
accessType.getName(), erType, jsonNode, e);
|
||||||
throw new ResourceRegistryException("Error Creating " + erType
|
throw new ResourceRegistryException("Error Creating " + erType + " with " + jsonNode, e.getCause());
|
||||||
+ " with " + jsonNode, e.getCause());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean reallyAddToContext() throws ContextException,
|
protected boolean reallyAddToContext() throws ContextException, ResourceRegistryException {
|
||||||
ResourceRegistryException {
|
|
||||||
|
|
||||||
getWorkingContext().addElement(getElement(), orientGraph);
|
getWorkingContext().addElement(getElement(), orientGraph);
|
||||||
|
|
||||||
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
|
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
|
||||||
|
|
||||||
for (Edge edge : edges) {
|
for(Edge edge : edges) {
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
RelationManagement relationManagement = getRelationManagement(edge);
|
RelationManagement relationManagement = getRelationManagement(edge);
|
||||||
relationManagement.internalAddToContext();
|
relationManagement.internalAddToContext();
|
||||||
|
@ -201,12 +187,11 @@ public abstract class EntityManagement<E extends Entity> extends
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean reallyRemoveFromContext() throws ContextException,
|
protected boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException {
|
||||||
ResourceRegistryException {
|
|
||||||
|
|
||||||
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
|
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
|
||||||
|
|
||||||
for (Edge edge : edges) {
|
for(Edge edge : edges) {
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
RelationManagement relationManagement = getRelationManagement(edge);
|
RelationManagement relationManagement = getRelationManagement(edge);
|
||||||
relationManagement.internalRemoveFromContext();
|
relationManagement.internalRemoveFromContext();
|
||||||
|
@ -217,19 +202,18 @@ public abstract class EntityManagement<E extends Entity> extends
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
||||||
JSONArray jsonArray = new JSONArray();
|
JSONArray jsonArray = new JSONArray();
|
||||||
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
|
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
|
||||||
for(Vertex vertex : iterable){
|
for(Vertex vertex : iterable) {
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
|
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
|
||||||
|
orientGraph, vertex);
|
||||||
try {
|
try {
|
||||||
JSONObject jsonObject = entityManagement.serializeAsJson();
|
JSONObject jsonObject = entityManagement.serializeAsJson();
|
||||||
jsonArray.put(jsonObject);
|
jsonArray.put(jsonObject);
|
||||||
}catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
||||||
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er.entity;
|
package org.gcube.informationsystem.resourceregistry.er.entity;
|
||||||
|
|
||||||
import org.codehaus.jettison.json.JSONObject;
|
import org.codehaus.jettison.json.JSONObject;
|
||||||
|
@ -11,7 +8,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
||||||
|
|
||||||
import com.tinkerpop.blueprints.Vertex;
|
import com.tinkerpop.blueprints.Vertex;
|
||||||
|
@ -19,7 +16,6 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class FacetManagement extends EntityManagement<Facet> {
|
public class FacetManagement extends EntityManagement<Facet> {
|
||||||
|
|
||||||
|
|
|
@ -15,8 +15,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
|
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
|
||||||
|
@ -46,7 +46,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) {
|
public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) {
|
||||||
super(AccessType.RESOURCE, workingContext, orientGraph);
|
super(AccessType.RESOURCE, workingContext, orientGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -55,7 +55,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message) {
|
protected ResourceAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
|
||||||
|
String message) {
|
||||||
return new ResourceAvailableInAnotherContextException(message);
|
return new ResourceAvailableInAnotherContextException(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -77,24 +78,22 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Cannot get ConsistsOf edge only because is not polymorphic for a
|
* Cannot get ConsistsOf edge only because is not polymorphic for a
|
||||||
* com.tinkerpop.blueprints.Vertex
|
* com.tinkerpop.blueprints.Vertex vertex.getEdges(Direction.OUT,
|
||||||
* vertex.getEdges(Direction.OUT, ConsistsOf.NAME);
|
* ConsistsOf.NAME); TODO Looks for a different query
|
||||||
* TODO Looks for a different query
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
|
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
|
||||||
for (Edge edge : edges) {
|
for(Edge edge : edges) {
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
RelationManagement relationManagement = getRelationManagement(edge);
|
RelationManagement relationManagement = getRelationManagement(edge);
|
||||||
relationManagement.setReload(reload);
|
relationManagement.setReload(reload);
|
||||||
|
|
||||||
if(relationManagement.giveMeSourceEntityManagementAsIs()==null) {
|
if(relationManagement.giveMeSourceEntityManagementAsIs() == null) {
|
||||||
relationManagement.setSourceEntityManagement(this);
|
relationManagement.setSourceEntityManagement(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(relationManagement.giveMeSourceEntityManagementAsIs() != this) {
|
||||||
if(relationManagement.giveMeSourceEntityManagementAsIs()!=this) {
|
|
||||||
StringBuilder errorMessage = new StringBuilder();
|
StringBuilder errorMessage = new StringBuilder();
|
||||||
errorMessage.append("SourceEntityManagement for ");
|
errorMessage.append("SourceEntityManagement for ");
|
||||||
errorMessage.append(relationManagement.getClass().getSimpleName());
|
errorMessage.append(relationManagement.getClass().getSimpleName());
|
||||||
|
@ -103,53 +102,51 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
throw new ResourceRegistryException(errorMessage.toString());
|
throw new ResourceRegistryException(errorMessage.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (relationManagement instanceof ConsistsOfManagement) {
|
if(relationManagement instanceof ConsistsOfManagement) {
|
||||||
try {
|
try {
|
||||||
JSONObject consistsOf = relationManagement.serializeAsJson(true, true);
|
JSONObject consistsOf = relationManagement.serializeAsJson(true, true);
|
||||||
sourceResource = addConsistsOf(sourceResource, consistsOf);
|
sourceResource = addConsistsOf(sourceResource, consistsOf);
|
||||||
}catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw e;
|
throw e;
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
* This comment is just to show that IsRelatedTo is not serialized
|
* This comment is just to show that IsRelatedTo is not serialized by default as
|
||||||
* by default as design choice and not because forget
|
* design choice and not because forget
|
||||||
*
|
*
|
||||||
* else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){
|
* else if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)){ JSONObject
|
||||||
* JSONObject isRelatedTo = relationManagement.serializeAsJson(true, true);
|
* isRelatedTo = relationManagement.serializeAsJson(true, true); sourceResource
|
||||||
* sourceResource = addIsRelatedTo(sourceResource, isRelatedTo);
|
* = addIsRelatedTo(sourceResource, isRelatedTo); }
|
||||||
* }
|
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
return sourceResource;
|
return sourceResource;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static JSONObject addConsistsOf(JSONObject sourceResource,
|
public static JSONObject addConsistsOf(JSONObject sourceResource, JSONObject consistsOf)
|
||||||
JSONObject consistsOf) throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter());
|
return addRelation(sourceResource, consistsOf, AccessType.CONSISTS_OF.lowerCaseFirstCharacter());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static JSONObject addIsRelatedTo(JSONObject sourceResource,
|
public static JSONObject addIsRelatedTo(JSONObject sourceResource, JSONObject isRelatedTo)
|
||||||
JSONObject isRelatedTo) throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter());
|
return addRelation(sourceResource, isRelatedTo, AccessType.IS_RELATED_TO.lowerCaseFirstCharacter());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Vertex reallyCreate() throws ResourceAlreadyPresentException,
|
protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
|
||||||
ResourceRegistryException {
|
|
||||||
|
|
||||||
createVertex();
|
createVertex();
|
||||||
|
|
||||||
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
|
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
|
||||||
if (jsonNode.has(property)) {
|
if(jsonNode.has(property)) {
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for (JsonNode consistOfJsonNode : jsonNodeArray) {
|
for(JsonNode consistOfJsonNode : jsonNodeArray) {
|
||||||
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
|
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
|
||||||
com.setJSON(consistOfJsonNode);
|
com.setJSON(consistOfJsonNode);
|
||||||
com.setSourceEntityManagement(this);
|
com.setSourceEntityManagement(this);
|
||||||
|
@ -159,9 +156,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
}
|
}
|
||||||
|
|
||||||
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
|
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
|
||||||
if (jsonNode.has(property)) {
|
if(jsonNode.has(property)) {
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for (JsonNode relationJsonNode : jsonNodeArray) {
|
for(JsonNode relationJsonNode : jsonNodeArray) {
|
||||||
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
|
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
|
||||||
irtm.setJSON(relationJsonNode);
|
irtm.setJSON(relationJsonNode);
|
||||||
irtm.setSourceEntityManagement(this);
|
irtm.setSourceEntityManagement(this);
|
||||||
|
@ -179,9 +176,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
getElement();
|
getElement();
|
||||||
|
|
||||||
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
|
String property = AccessType.CONSISTS_OF.lowerCaseFirstCharacter();
|
||||||
if (jsonNode.has(property)) {
|
if(jsonNode.has(property)) {
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for (JsonNode relationJsonNode : jsonNodeArray) {
|
for(JsonNode relationJsonNode : jsonNodeArray) {
|
||||||
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
|
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
|
||||||
com.setJSON(relationJsonNode);
|
com.setJSON(relationJsonNode);
|
||||||
com.internalCreateOrUdate();
|
com.internalCreateOrUdate();
|
||||||
|
@ -190,9 +187,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
}
|
}
|
||||||
|
|
||||||
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
|
property = AccessType.IS_RELATED_TO.lowerCaseFirstCharacter();
|
||||||
if (jsonNode.has(property)) {
|
if(jsonNode.has(property)) {
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for (JsonNode relationJsonNode : jsonNodeArray) {
|
for(JsonNode relationJsonNode : jsonNodeArray) {
|
||||||
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
|
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
|
||||||
irtm.setJSON(relationJsonNode);
|
irtm.setJSON(relationJsonNode);
|
||||||
irtm.internalUpdate();
|
irtm.internalUpdate();
|
||||||
|
@ -205,30 +202,28 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
protected boolean reallyDelete() throws ResourceNotFoundException,
|
protected boolean reallyDelete() throws ResourceNotFoundException, ResourceRegistryException {
|
||||||
ResourceRegistryException {
|
|
||||||
// internalDeleteResource(orientGraph, uuid, null);
|
// internalDeleteResource(orientGraph, uuid, null);
|
||||||
|
|
||||||
getElement();
|
getElement();
|
||||||
|
|
||||||
Iterable<Edge> iterable = element.getEdges(Direction.OUT);
|
Iterable<Edge> iterable = element.getEdges(Direction.OUT);
|
||||||
Iterator<Edge> iterator = iterable.iterator();
|
Iterator<Edge> iterator = iterable.iterator();
|
||||||
while (iterator.hasNext()) {
|
while(iterator.hasNext()) {
|
||||||
|
|
||||||
Edge edge = iterator.next();
|
Edge edge = iterator.next();
|
||||||
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
|
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
RelationManagement relationManagement = null;
|
RelationManagement relationManagement = null;
|
||||||
if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
|
if(orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
|
||||||
relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph);
|
relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph);
|
||||||
} else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
|
} else if(orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
|
||||||
relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph);
|
relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph);
|
||||||
} else {
|
} else {
|
||||||
logger.warn("{} is not a {} nor a {}. {}",
|
logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME,
|
||||||
Utility.toJsonString(edge, true), IsRelatedTo.NAME,
|
|
||||||
ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
if (relationManagement != null) {
|
if(relationManagement != null) {
|
||||||
relationManagement.setElement(edge);
|
relationManagement.setElement(edge);
|
||||||
relationManagement.internalDelete();
|
relationManagement.internalDelete();
|
||||||
}
|
}
|
||||||
|
@ -240,24 +235,23 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String all(boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
||||||
public String all(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException {
|
|
||||||
try {
|
try {
|
||||||
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
|
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
|
||||||
|
|
||||||
return reallyGetAll(polymorphic, constraint);
|
return reallyGetAll(polymorphic, constraint);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String reallyGetAll(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException{
|
public String reallyGetAll(boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
||||||
JSONArray jsonArray = new JSONArray();
|
JSONArray jsonArray = new JSONArray();
|
||||||
|
|
||||||
String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART);
|
String relationType = constraint.get(AccessPath.RELATION_TYPE_PATH_PART);
|
||||||
|
@ -268,10 +262,10 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
// TODO check types
|
// TODO check types
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService')
|
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
|
||||||
* FROM (SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
|
* FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
|
||||||
*
|
*
|
||||||
* WHERE @class='EService' // Only is not polymorphic
|
* WHERE @class='EService' // Only is not polymorphic
|
||||||
*/
|
*/
|
||||||
|
|
||||||
boolean first = true;
|
boolean first = true;
|
||||||
|
@ -282,11 +276,11 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
selectStringBuilder.append(erType);
|
selectStringBuilder.append(erType);
|
||||||
selectStringBuilder.append("') FROM (SELECT FROM ");
|
selectStringBuilder.append("') FROM (SELECT FROM ");
|
||||||
selectStringBuilder.append(facetType);
|
selectStringBuilder.append(facetType);
|
||||||
for(String key : constraint.keySet()){
|
for(String key : constraint.keySet()) {
|
||||||
if(first){
|
if(first) {
|
||||||
selectStringBuilder.append(" WHERE ");
|
selectStringBuilder.append(" WHERE ");
|
||||||
first = false;
|
first = false;
|
||||||
}else{
|
} else {
|
||||||
selectStringBuilder.append(" AND ");
|
selectStringBuilder.append(" AND ");
|
||||||
}
|
}
|
||||||
selectStringBuilder.append(key);
|
selectStringBuilder.append(key);
|
||||||
|
@ -298,7 +292,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
}
|
}
|
||||||
selectStringBuilder.append(" ))");
|
selectStringBuilder.append(" ))");
|
||||||
|
|
||||||
if(!polymorphic){
|
if(!polymorphic) {
|
||||||
selectStringBuilder.append(" WHERE @class='");
|
selectStringBuilder.append(" WHERE @class='");
|
||||||
selectStringBuilder.append(erType);
|
selectStringBuilder.append(erType);
|
||||||
selectStringBuilder.append("'");
|
selectStringBuilder.append("'");
|
||||||
|
@ -307,54 +301,49 @@ public class ResourceManagement extends EntityManagement<Resource> {
|
||||||
String select = selectStringBuilder.toString();
|
String select = selectStringBuilder.toString();
|
||||||
logger.trace(select);
|
logger.trace(select);
|
||||||
|
|
||||||
|
OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>(select);
|
||||||
|
Iterable<Element> elements = orientGraph.command(osqlSynchQuery).execute();
|
||||||
|
|
||||||
OSQLSynchQuery<Element> osqlSynchQuery = new OSQLSynchQuery<Element>(
|
for(Element element : elements) {
|
||||||
select);
|
|
||||||
Iterable<Element> elements = orientGraph.command(osqlSynchQuery)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
for(Element element : elements){
|
if(polymorphic) {
|
||||||
|
|
||||||
if(polymorphic){
|
|
||||||
OrientVertexType orientVertexType = null;
|
OrientVertexType orientVertexType = null;
|
||||||
try {
|
try {
|
||||||
OrientElement orientElement = ((OrientElement) element);
|
OrientElement orientElement = ((OrientElement) element);
|
||||||
if(orientElement instanceof OrientEdge){
|
if(orientElement instanceof OrientEdge) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
orientVertexType = ((OrientVertex) orientElement).getType();
|
orientVertexType = ((OrientVertex) orientElement).getType();
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String error = String.format("Unable to detect type of %s. %s",
|
String error = String.format("Unable to detect type of %s. %s", element.toString(),
|
||||||
element.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
logger.error(error, e);
|
logger.error(error, e);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(orientVertexType.getName().compareTo(erType)!=0){
|
if(orientVertexType.getName().compareTo(erType) != 0) {
|
||||||
if(!orientVertexType.isSubClassOf(erType) ) {
|
if(!orientVertexType.isSubClassOf(erType)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Vertex vertex = (Vertex) element;
|
Vertex vertex = (Vertex) element;
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
|
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(),
|
||||||
|
orientGraph, vertex);
|
||||||
try {
|
try {
|
||||||
JSONObject jsonObject = entityManagement.serializeAsJson();
|
JSONObject jsonObject = entityManagement.serializeAsJson();
|
||||||
jsonArray.put(jsonObject);
|
jsonArray.put(jsonObject);
|
||||||
}catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
||||||
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return jsonArray.toString();
|
return jsonArray.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er.relation;
|
package org.gcube.informationsystem.resourceregistry.er.relation;
|
||||||
|
|
||||||
import org.gcube.informationsystem.model.AccessType;
|
import org.gcube.informationsystem.model.AccessType;
|
||||||
|
@ -10,7 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
||||||
|
|
||||||
|
@ -20,7 +17,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
public class ConsistsOfManagement extends RelationManagement<ConsistsOf, ResourceManagement, FacetManagement> {
|
public class ConsistsOfManagement extends RelationManagement<ConsistsOf,ResourceManagement,FacetManagement> {
|
||||||
|
|
||||||
public ConsistsOfManagement() {
|
public ConsistsOfManagement() {
|
||||||
super(AccessType.CONSISTS_OF);
|
super(AccessType.CONSISTS_OF);
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er.relation;
|
package org.gcube.informationsystem.resourceregistry.er.relation;
|
||||||
|
|
||||||
import org.gcube.informationsystem.model.AccessType;
|
import org.gcube.informationsystem.model.AccessType;
|
||||||
|
@ -10,7 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
||||||
|
|
||||||
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
|
@ -19,7 +16,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, ResourceManagement, ResourceManagement> {
|
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo,ResourceManagement,ResourceManagement> {
|
||||||
|
|
||||||
public IsRelatedToManagement() {
|
public IsRelatedToManagement() {
|
||||||
super(AccessType.IS_RELATED_TO);
|
super(AccessType.IS_RELATED_TO);
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.er.relation;
|
package org.gcube.informationsystem.resourceregistry.er.relation;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
@ -27,8 +24,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
|
||||||
|
@ -49,7 +46,7 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
public abstract class RelationManagement<R extends Relation, S extends EntityManagement, T extends EntityManagement>
|
public abstract class RelationManagement<R extends Relation, S extends EntityManagement, T extends EntityManagement>
|
||||||
extends ERManagement<R, Edge> {
|
extends ERManagement<R,Edge> {
|
||||||
|
|
||||||
protected final Class<? extends Entity> targetEntityClass;
|
protected final Class<? extends Entity> targetEntityClass;
|
||||||
|
|
||||||
|
@ -67,18 +64,18 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase());
|
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_IN.toUpperCase());
|
||||||
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase());
|
this.ignoreKeys.add(OrientBaseGraph.CONNECTION_OUT.toUpperCase());
|
||||||
|
|
||||||
switch (accessType) {
|
switch(accessType) {
|
||||||
case CONSISTS_OF:
|
case CONSISTS_OF:
|
||||||
this.targetEntityClass = Facet.class;
|
this.targetEntityClass = Facet.class;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case IS_RELATED_TO:
|
case IS_RELATED_TO:
|
||||||
this.targetEntityClass = Resource.class;
|
this.targetEntityClass = Resource.class;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
this.targetEntityClass = Resource.class;
|
this.targetEntityClass = Resource.class;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
sourceEntityManagement = null;
|
sourceEntityManagement = null;
|
||||||
|
@ -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
|
* Needed for ResourceManagement.serializeAsJson() function to check that
|
||||||
* the instance is creating this RelationManagement. TODO Look for a workaround
|
* sourceEntityManagement is the same of the instance is creating this
|
||||||
|
* RelationManagement. TODO Look for a workaround
|
||||||
*/
|
*/
|
||||||
public S giveMeSourceEntityManagementAsIs() throws ResourceRegistryException {
|
public S giveMeSourceEntityManagementAsIs() throws ResourceRegistryException {
|
||||||
return sourceEntityManagement;
|
return sourceEntityManagement;
|
||||||
|
@ -102,7 +100,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public S getSourceEntityManagement() throws ResourceRegistryException {
|
public S getSourceEntityManagement() throws ResourceRegistryException {
|
||||||
if (sourceEntityManagement == null) {
|
if(sourceEntityManagement == null) {
|
||||||
Vertex source = getElement().getVertex(Direction.OUT);
|
Vertex source = getElement().getVertex(Direction.OUT);
|
||||||
sourceEntityManagement = newSourceEntityManagement();
|
sourceEntityManagement = newSourceEntityManagement();
|
||||||
sourceEntityManagement.setElement(source);
|
sourceEntityManagement.setElement(source);
|
||||||
|
@ -113,7 +111,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public T getTargetEntityManagement() throws ResourceRegistryException {
|
public T getTargetEntityManagement() throws ResourceRegistryException {
|
||||||
if (targetEntityManagement == null) {
|
if(targetEntityManagement == null) {
|
||||||
Vertex target = getElement().getVertex(Direction.IN);
|
Vertex target = getElement().getVertex(Direction.IN);
|
||||||
targetEntityManagement = newTargetEntityManagement();
|
targetEntityManagement = newTargetEntityManagement();
|
||||||
targetEntityManagement.setElement(target);
|
targetEntityManagement.setElement(target);
|
||||||
|
@ -144,20 +142,20 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
JSONObject relation = serializeSelfOnly();
|
JSONObject relation = serializeSelfOnly();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (includeSource) {
|
if(includeSource) {
|
||||||
EntityManagement sourceEntityManagement = getSourceEntityManagement();
|
EntityManagement sourceEntityManagement = getSourceEntityManagement();
|
||||||
relation.put(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly());
|
relation.put(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (includeTarget) {
|
if(includeTarget) {
|
||||||
EntityManagement targetEntityManagement = getTargetEntityManagement();
|
EntityManagement targetEntityManagement = getTargetEntityManagement();
|
||||||
relation.put(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson());
|
relation.put(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
@ -165,7 +163,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
return relation;
|
return relation;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Map<String, JSONObject> fullSerialize(Map<String, JSONObject> visitedSourceResources)
|
protected Map<String,JSONObject> fullSerialize(Map<String,JSONObject> visitedSourceResources)
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
|
|
||||||
Vertex source = getElement().getVertex(Direction.OUT);
|
Vertex source = getElement().getVertex(Direction.OUT);
|
||||||
|
@ -175,30 +173,28 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
JSONObject sourceResource = visitedSourceResources.get(id);
|
JSONObject sourceResource = visitedSourceResources.get(id);
|
||||||
ResourceManagement resourceManagement = null;
|
ResourceManagement resourceManagement = null;
|
||||||
|
|
||||||
if (sourceResource == null) {
|
if(sourceResource == null) {
|
||||||
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, source);
|
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(),
|
||||||
if (this instanceof IsRelatedToManagement) {
|
orientGraph, source);
|
||||||
|
if(this instanceof IsRelatedToManagement) {
|
||||||
sourceResource = resourceManagement.serializeAsJson();
|
sourceResource = resourceManagement.serializeAsJson();
|
||||||
} else if (this instanceof ConsistsOfManagement) {
|
} else if(this instanceof ConsistsOfManagement) {
|
||||||
sourceResource = resourceManagement.serializeSelfOnly();
|
sourceResource = resourceManagement.serializeSelfOnly();
|
||||||
} else {
|
} else {
|
||||||
String error = String.format(
|
String error = String.format("{%s is not a %s nor a %s. %s", this,
|
||||||
"{%s is not a %s nor a %s. %s",
|
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
|
||||||
this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
|
|
||||||
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(this instanceof IsRelatedToManagement) {
|
||||||
if (this instanceof IsRelatedToManagement) {
|
|
||||||
sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson());
|
sourceResource = ResourceManagement.addIsRelatedTo(sourceResource, serializeAsJson());
|
||||||
} else if (this instanceof ConsistsOfManagement) {
|
} else if(this instanceof ConsistsOfManagement) {
|
||||||
sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson());
|
sourceResource = ResourceManagement.addConsistsOf(sourceResource, serializeAsJson());
|
||||||
} else {
|
} else {
|
||||||
String error = String.format(
|
String error = String.format("{%s is not a %s nor a %s. %s", this,
|
||||||
"{%s is not a %s nor a %s. %s",
|
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
|
||||||
this, IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
|
|
||||||
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
|
@ -211,9 +207,9 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
@Override
|
@Override
|
||||||
protected Edge reallyCreate() throws ResourceRegistryException {
|
protected Edge reallyCreate() throws ResourceRegistryException {
|
||||||
|
|
||||||
if (sourceEntityManagement == null) {
|
if(sourceEntityManagement == null) {
|
||||||
|
|
||||||
if (!jsonNode.has(Relation.SOURCE_PROPERTY)) {
|
if(!jsonNode.has(Relation.SOURCE_PROPERTY)) {
|
||||||
throw new ResourceRegistryException("Error while creating relation. No source definition found");
|
throw new ResourceRegistryException("Error while creating relation. No source definition found");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -224,16 +220,16 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
sourceEntityManagement.setUUID(sourceUUID);
|
sourceEntityManagement.setUUID(sourceUUID);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (targetEntityManagement == null) {
|
if(targetEntityManagement == null) {
|
||||||
targetEntityManagement = newTargetEntityManagement();
|
targetEntityManagement = newTargetEntityManagement();
|
||||||
|
|
||||||
if (!jsonNode.has(Relation.TARGET_PROPERTY)) {
|
if(!jsonNode.has(Relation.TARGET_PROPERTY)) {
|
||||||
throw new ResourceRegistryException("Error while creating " + erType + ". No target definition found");
|
throw new ResourceRegistryException("Error while creating " + erType + ". No target definition found");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
|
targetEntityManagement.setJSON(jsonNode.get(Relation.TARGET_PROPERTY));
|
||||||
} catch (SchemaException e) {
|
} catch(SchemaException e) {
|
||||||
StringBuilder errorMessage = new StringBuilder();
|
StringBuilder errorMessage = new StringBuilder();
|
||||||
errorMessage.append("A ");
|
errorMessage.append("A ");
|
||||||
errorMessage.append(erType);
|
errorMessage.append(erType);
|
||||||
|
@ -246,7 +242,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
|
|
||||||
try {
|
try {
|
||||||
targetEntityManagement.getElement();
|
targetEntityManagement.getElement();
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
targetEntityManagement.internalCreate();
|
targetEntityManagement.internalCreate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -278,9 +274,9 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
Edge edge = getElement();
|
Edge edge = getElement();
|
||||||
ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
|
ERManagement.updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
|
||||||
|
|
||||||
if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
|
if(accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
|
||||||
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
|
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
|
||||||
if (target != null) {
|
if(target != null) {
|
||||||
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph);
|
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph);
|
||||||
fm.setJSON(target);
|
fm.setJSON(target);
|
||||||
fm.internalUpdate();
|
fm.internalUpdate();
|
||||||
|
@ -302,42 +298,40 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
try {
|
try {
|
||||||
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
|
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
|
||||||
Relation.PROPAGATION_CONSTRAINT);
|
Relation.PROPAGATION_CONSTRAINT);
|
||||||
if (propagationConstraint.getAddConstraint() != null) {
|
if(propagationConstraint.getAddConstraint() != null) {
|
||||||
addConstraint = propagationConstraint.getAddConstraint();
|
addConstraint = propagationConstraint.getAddConstraint();
|
||||||
} else {
|
} else {
|
||||||
String error = String.format(
|
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
|
||||||
"%s.%s in %s is null. %s",
|
PropagationConstraint.ADD_PROPERTY, Utility.toJsonString(element, true),
|
||||||
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.ADD_PROPERTY,
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String error = String.format(
|
String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
|
||||||
"Error while getting %s from %s while performing AddToContext. %s",
|
|
||||||
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
|
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
|
||||||
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
logger.warn(error);
|
logger.warn(error);
|
||||||
throw new ResourceRegistryException(error, e);
|
throw new ResourceRegistryException(error, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (addConstraint) {
|
switch(addConstraint) {
|
||||||
case propagate:
|
case propagate:
|
||||||
/*
|
/*
|
||||||
* The relation must be added only in the case the target vertex must be added.
|
* The relation must be added only in the case the target vertex must be added.
|
||||||
* Otherwise we have a relation which point to an entity outside of the context.
|
* Otherwise we have a relation which point to an entity outside of the context.
|
||||||
*/
|
*/
|
||||||
getTargetEntityManagement().internalAddToContext();
|
getTargetEntityManagement().internalAddToContext();
|
||||||
|
|
||||||
getWorkingContext().addElement(getElement(), orientGraph);
|
getWorkingContext().addElement(getElement(), orientGraph);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case unpropagate:
|
case unpropagate:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
@ -367,19 +361,17 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
try {
|
try {
|
||||||
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
|
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
|
||||||
Relation.PROPAGATION_CONSTRAINT);
|
Relation.PROPAGATION_CONSTRAINT);
|
||||||
if (propagationConstraint.getRemoveConstraint() != null) {
|
if(propagationConstraint.getRemoveConstraint() != null) {
|
||||||
removeConstraint = propagationConstraint.getRemoveConstraint();
|
removeConstraint = propagationConstraint.getRemoveConstraint();
|
||||||
} else {
|
} else {
|
||||||
String error = String.format(
|
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
|
||||||
"%s.%s in %s is null. %s",
|
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
|
||||||
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY,
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String error = String.format(
|
String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
|
||||||
"Error while getting %s from %s while performing RemoveFromContext. %s",
|
|
||||||
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
|
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true),
|
||||||
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
|
@ -393,46 +385,46 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
*/
|
*/
|
||||||
getWorkingContext().removeElement(getElement(), orientGraph);
|
getWorkingContext().removeElement(getElement(), orientGraph);
|
||||||
|
|
||||||
switch (removeConstraint) {
|
switch(removeConstraint) {
|
||||||
case cascade:
|
case cascade:
|
||||||
getTargetEntityManagement().internalRemoveFromContext();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case cascadeWhenOrphan:
|
|
||||||
Vertex target = (Vertex) getTargetEntityManagement().getElement();
|
|
||||||
|
|
||||||
Iterable<Edge> iterable = target.getEdges(Direction.IN);
|
|
||||||
Iterator<Edge> iterator = iterable.iterator();
|
|
||||||
int count = 0;
|
|
||||||
OrientEdge edge = null;
|
|
||||||
while (iterator.hasNext()) {
|
|
||||||
edge = (OrientEdge) iterator.next();
|
|
||||||
OrientEdge thisOrientEdge = (OrientEdge) getElement();
|
|
||||||
if (edge.compareTo(thisOrientEdge) != 0) {
|
|
||||||
if (thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
|
|
||||||
count++;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
/*
|
|
||||||
* else{ ContextUtility.removeFromActualContext(orientGraph, edge); }
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (count > 0) {
|
|
||||||
logger.trace(
|
|
||||||
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.",
|
|
||||||
element, target, edge, removeConstraint);
|
|
||||||
} else {
|
|
||||||
getTargetEntityManagement().internalRemoveFromContext();
|
getTargetEntityManagement().internalRemoveFromContext();
|
||||||
}
|
break;
|
||||||
break;
|
|
||||||
|
|
||||||
case keep:
|
case cascadeWhenOrphan:
|
||||||
break;
|
Vertex target = (Vertex) getTargetEntityManagement().getElement();
|
||||||
|
|
||||||
default:
|
Iterable<Edge> iterable = target.getEdges(Direction.IN);
|
||||||
break;
|
Iterator<Edge> iterator = iterable.iterator();
|
||||||
|
int count = 0;
|
||||||
|
OrientEdge edge = null;
|
||||||
|
while(iterator.hasNext()) {
|
||||||
|
edge = (OrientEdge) iterator.next();
|
||||||
|
OrientEdge thisOrientEdge = (OrientEdge) getElement();
|
||||||
|
if(edge.compareTo(thisOrientEdge) != 0) {
|
||||||
|
if(thisOrientEdge.getOutVertex().compareTo(edge.getOutVertex()) != 0) {
|
||||||
|
count++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* else{ ContextUtility.removeFromActualContext(orientGraph, edge); }
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(count > 0) {
|
||||||
|
logger.trace(
|
||||||
|
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from current context.",
|
||||||
|
element, target, edge, removeConstraint);
|
||||||
|
} else {
|
||||||
|
getTargetEntityManagement().internalRemoveFromContext();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case keep:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
@ -450,47 +442,44 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
try {
|
try {
|
||||||
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
|
PropagationConstraint propagationConstraint = Utility.getEmbedded(PropagationConstraint.class, element,
|
||||||
Relation.PROPAGATION_CONSTRAINT);
|
Relation.PROPAGATION_CONSTRAINT);
|
||||||
if (propagationConstraint.getRemoveConstraint() != null) {
|
if(propagationConstraint.getRemoveConstraint() != null) {
|
||||||
removeConstraint = propagationConstraint.getRemoveConstraint();
|
removeConstraint = propagationConstraint.getRemoveConstraint();
|
||||||
} else {
|
} else {
|
||||||
String error = String.format(
|
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT,
|
||||||
"%s.%s in %s is null. %s",
|
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
|
||||||
Relation.PROPAGATION_CONSTRAINT, PropagationConstraint.REMOVE_PROPERTY,
|
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
Utility.toJsonString(element, true), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.warn(
|
logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT,
|
||||||
"Error while getting {} from {}. Assuming {}. {}",
|
Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
Relation.PROPAGATION_CONSTRAINT, Utility.toJsonString(element, true), removeConstraint,
|
|
||||||
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Vertex target = (Vertex) getTargetEntityManagement().getElement();
|
Vertex target = (Vertex) getTargetEntityManagement().getElement();
|
||||||
element.remove();
|
element.remove();
|
||||||
|
|
||||||
switch (removeConstraint) {
|
switch(removeConstraint) {
|
||||||
case cascade:
|
case cascade:
|
||||||
getTargetEntityManagement().internalDelete();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case cascadeWhenOrphan:
|
|
||||||
Iterable<Edge> iterable = target.getEdges(Direction.IN);
|
|
||||||
Iterator<Edge> iterator = iterable.iterator();
|
|
||||||
if (iterator.hasNext()) {
|
|
||||||
logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
|
|
||||||
target, removeConstraint);
|
|
||||||
} else {
|
|
||||||
getTargetEntityManagement().internalDelete();
|
getTargetEntityManagement().internalDelete();
|
||||||
}
|
break;
|
||||||
break;
|
|
||||||
|
|
||||||
case keep:
|
case cascadeWhenOrphan:
|
||||||
break;
|
Iterable<Edge> iterable = target.getEdges(Direction.IN);
|
||||||
|
Iterator<Edge> iterator = iterable.iterator();
|
||||||
|
if(iterator.hasNext()) {
|
||||||
|
logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
|
||||||
|
target, removeConstraint);
|
||||||
|
} else {
|
||||||
|
getTargetEntityManagement().internalDelete();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
default:
|
case keep:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
@ -499,12 +488,13 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
|
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
Map<String, JSONObject> visitedSourceResources = new HashMap<>();
|
Map<String,JSONObject> visitedSourceResources = new HashMap<>();
|
||||||
for (Edge edge : edges) {
|
for(Edge edge : edges) {
|
||||||
if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
|
if(postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
|
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(),
|
||||||
|
orientGraph, edge);
|
||||||
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
|
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
|
||||||
}
|
}
|
||||||
return visitedSourceResources.values();
|
return visitedSourceResources.values();
|
||||||
|
@ -526,10 +516,11 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
EntityManagement entityManagement = null;
|
EntityManagement entityManagement = null;
|
||||||
try {
|
try {
|
||||||
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), orientGraph, uuid);
|
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(),
|
||||||
} catch (ResourceRegistryException e) {
|
orientGraph, uuid);
|
||||||
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME));
|
String.format("Provided UUID %s does not belogn to any %s", uuid.toString(), Entity.NAME));
|
||||||
}
|
}
|
||||||
|
@ -549,12 +540,12 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
|
||||||
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
|
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
|
||||||
|
|
||||||
return reallyGetAllFrom(uuid, direction, polymorphic);
|
return reallyGetAllFrom(uuid, direction, polymorphic);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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);
|
logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
|
||||||
|
|
||||||
return added;
|
return added;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
|
logger.error("Unable to add {} with UUID {} to actual Context", accessType.getName(), uuid, e);
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new ContextException(e);
|
throw new ContextException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,9 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.query;
|
package org.gcube.informationsystem.resourceregistry.query;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public interface Query {
|
public interface Query {
|
||||||
|
|
||||||
|
@ -17,10 +13,9 @@ public interface Query {
|
||||||
* @param fetchPlan
|
* @param fetchPlan
|
||||||
* @return
|
* @return
|
||||||
* @throws InvalidQueryException
|
* @throws InvalidQueryException
|
||||||
* http://orientdb.com/docs/last/OrientDB-REST.html#query
|
* http://orientdb.com/docs/last/OrientDB-REST.html#query
|
||||||
*/
|
*/
|
||||||
public String query(String query, Integer limit, String fetchPlan)
|
public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException;
|
||||||
throws InvalidQueryException;
|
|
||||||
|
|
||||||
public String gremlinQuery(String query) throws InvalidQueryException;
|
public String gremlinQuery(String query) throws InvalidQueryException;
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.query;
|
package org.gcube.informationsystem.resourceregistry.query;
|
||||||
|
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
|
@ -10,8 +7,8 @@ import java.util.List;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.Utility;
|
import org.gcube.informationsystem.resourceregistry.utils.Utility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -22,110 +19,14 @@ import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class QueryImpl implements Query {
|
public class QueryImpl implements Query {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(QueryImpl.class);
|
private static Logger logger = LoggerFactory.getLogger(QueryImpl.class);
|
||||||
|
|
||||||
/*
|
|
||||||
private static final String QUERY = "query/";
|
|
||||||
private static final String SQL = "sql/";
|
|
||||||
|
|
||||||
private static final String DEFAULT_LIMIT = DEFAULT_LIMIT_INT + "/";
|
|
||||||
|
|
||||||
private static final URL BASE_QUERY_URL;
|
|
||||||
|
|
||||||
static {
|
|
||||||
try {
|
|
||||||
URL url = new URL(DatabaseEnvironment.HTTP_URL_STRINGS[0]);
|
|
||||||
URL urlQuery = new URL(url, QUERY);
|
|
||||||
URL urlDB = new URL(urlQuery, DatabaseEnvironment.DB + "/");
|
|
||||||
BASE_QUERY_URL = new URL(urlDB, SQL);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private void checkStatus(HttpURLConnection connection) throws Exception {
|
|
||||||
int statusCode = connection.getResponseCode();
|
|
||||||
switch (statusCode) {
|
|
||||||
case 200:
|
|
||||||
case 201:
|
|
||||||
return;
|
|
||||||
default:
|
|
||||||
throw new Exception(connection.getResponseMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String execute(String query, String fetchPlan)
|
public String query(String query, Integer limit, String fetchPlan) throws InvalidQueryException {
|
||||||
throws InvalidQueryException {
|
if(limit == null) {
|
||||||
|
|
||||||
|
|
||||||
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){
|
|
||||||
limit = AccessPath.DEFAULT_LIMIT;
|
limit = AccessPath.DEFAULT_LIMIT;
|
||||||
}
|
}
|
||||||
limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit;
|
limit = (limit <= 0) ? AccessPath.UNBOUNDED : limit;
|
||||||
|
@ -141,29 +42,28 @@ public class QueryImpl implements Query {
|
||||||
osqlSynchQuery.setFetchPlan(fetchPlan);
|
osqlSynchQuery.setFetchPlan(fetchPlan);
|
||||||
osqlSynchQuery.setCacheableResult(true);
|
osqlSynchQuery.setCacheableResult(true);
|
||||||
|
|
||||||
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}",
|
logger.debug("Going to execute query : \"{}\", fetchPlan : \"{}\", limit : {}", osqlSynchQuery.getText(),
|
||||||
osqlSynchQuery.getText(), osqlSynchQuery.getFetchPlan(),
|
osqlSynchQuery.getFetchPlan(), osqlSynchQuery.getLimit());
|
||||||
osqlSynchQuery.getLimit());
|
|
||||||
|
|
||||||
List<Object> records = oDatabaseDocumentTx.query(osqlSynchQuery);
|
List<Object> records = oDatabaseDocumentTx.query(osqlSynchQuery);
|
||||||
|
|
||||||
Writer writer = new StringWriter();
|
Writer writer = new StringWriter();
|
||||||
writer.append("{\"result\":[");
|
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);
|
ODocument oDocument = (ODocument) records.get(i);
|
||||||
writer.append(Utility.toJsonString(oDocument, false));
|
writer.append(Utility.toJsonString(oDocument, false));
|
||||||
if( i<(records.size()-1) ){
|
if(i < (records.size() - 1)) {
|
||||||
writer.append(",");
|
writer.append(",");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writer.append("]}");
|
writer.append("]}");
|
||||||
|
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new InvalidQueryException(e.getMessage());
|
throw new InvalidQueryException(e.getMessage());
|
||||||
} finally {
|
} finally {
|
||||||
if (oDatabaseDocumentTx != null) {
|
if(oDatabaseDocumentTx != null) {
|
||||||
oDatabaseDocumentTx.close();
|
oDatabaseDocumentTx.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -173,14 +73,13 @@ public class QueryImpl implements Query {
|
||||||
@Override
|
@Override
|
||||||
public String gremlinQuery(String query) throws InvalidQueryException {
|
public String gremlinQuery(String query) throws InvalidQueryException {
|
||||||
throw new UnsupportedOperationException();
|
throw new UnsupportedOperationException();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
OGremlinHelper.global().create();
|
OGremlinHelper.global().create();
|
||||||
|
|
||||||
ODatabaseDocumentTx oDatabaseDocumentTx = null;
|
ODatabaseDocumentTx oDatabaseDocumentTx = null;
|
||||||
try {
|
try {
|
||||||
oDatabaseDocumentTx = ContextUtility
|
oDatabaseDocumentTx = ContextUtility.getActualSecurityContextDatabaseTx(PermissionMode.READER);
|
||||||
.getActualSecurityContextDatabaseTx(PermissionMode.READER);
|
|
||||||
|
|
||||||
|
|
||||||
String finalQuery = String.format("select gremlin('%s')", query);
|
String finalQuery = String.format("select gremlin('%s')", query);
|
||||||
OCommandSQL OCommandSQL = new OCommandSQL(finalQuery);
|
OCommandSQL OCommandSQL = new OCommandSQL(finalQuery);
|
||||||
|
@ -189,22 +88,21 @@ public class QueryImpl implements Query {
|
||||||
|
|
||||||
Iterator iterator = res.iterator();
|
Iterator iterator = res.iterator();
|
||||||
|
|
||||||
while(iterator.hasNext()){
|
while(iterator.hasNext()) {
|
||||||
ODocument oDocument = (ODocument) iterator.next();
|
ODocument oDocument = (ODocument) iterator.next();
|
||||||
logger.debug("{}", oDocument);
|
logger.debug("{}", oDocument);
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.toString();
|
return res.toString();
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new InvalidQueryException(e.getMessage());
|
throw new InvalidQueryException(e.getMessage());
|
||||||
} finally {
|
} finally {
|
||||||
if (oDatabaseDocumentTx != null) {
|
if(oDatabaseDocumentTx != null) {
|
||||||
oDatabaseDocumentTx.close();
|
oDatabaseDocumentTx.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -57,26 +57,26 @@ public class Access {
|
||||||
public static final String TYPE_PATH_PARAM = "type";
|
public static final String TYPE_PATH_PARAM = "type";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It includeSubtypesows to query Entities and Relations in the current
|
* It includeSubtypes to query Entities and Relations in the current Context.<br />
|
||||||
* Context.<br />
|
|
||||||
* It accepts idempotent query only.. <br />
|
* It accepts idempotent query only.. <br />
|
||||||
* <br />
|
* <br />
|
||||||
* For query syntax please refer to<br />
|
* For query syntax please refer to<br />
|
||||||
|
*
|
||||||
* <a href="https://orientdb.com/docs/last/SQL-Syntax.html" target="_blank">
|
* <a href="https://orientdb.com/docs/last/SQL-Syntax.html" target="_blank">
|
||||||
* https://orientdb.com/docs/last/SQL-Syntax.html </a> <br />
|
* https://orientdb.com/docs/last/SQL-Syntax.html </a> <br />
|
||||||
* <br />
|
* <br />
|
||||||
|
*
|
||||||
* e.g. GET /resource-registry/access?query=SELECT FROM V
|
* e.g. GET /resource-registry/access?query=SELECT FROM V
|
||||||
*
|
*
|
||||||
* @param query
|
* @param query
|
||||||
* Defines the query to send to the backend.
|
* Defines the query to send to the backend.
|
||||||
* @param limit
|
* @param limit
|
||||||
* Defines the number of results you want returned, defaults to
|
* Defines the number of results you want returned, defaults to includeSubtypes results.
|
||||||
* includeSubtypes results.
|
|
||||||
* @param fetchPlan
|
* @param fetchPlan
|
||||||
* Defines the fetching strategy you want to use. See <a
|
* Defines the fetching strategy you want to use. See
|
||||||
* href="https://orientdb.com/docs/last/Fetching-Strategies.html"
|
* <a href="https://orientdb.com/docs/last/Fetching-Strategies.html" target="_blank">
|
||||||
* target="_blank">
|
* https://orientdb.com/docs/last/Fetching-Strategies.html
|
||||||
* https://orientdb.com/docs/last/Fetching-Strategies.html </a>
|
* </a>
|
||||||
* @return The JSON representation of the result
|
* @return The JSON representation of the result
|
||||||
* @throws InvalidQueryException
|
* @throws InvalidQueryException
|
||||||
* if the query is invalid or no idempotent
|
* if the query is invalid or no idempotent
|
||||||
|
@ -85,23 +85,18 @@ public class Access {
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String query(@QueryParam(AccessPath.QUERY_PARAM) String query,
|
public String query(@QueryParam(AccessPath.QUERY_PARAM) String query,
|
||||||
@QueryParam(AccessPath.LIMIT_PARAM) Integer limit,
|
@QueryParam(AccessPath.LIMIT_PARAM) Integer limit,
|
||||||
@QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan)
|
@QueryParam(AccessPath.FETCH_PLAN_PARAM) String fetchPlan) throws InvalidQueryException {
|
||||||
throws InvalidQueryException {
|
logger.info("Requested query (fetch plan {}, limit : {}):\n{}", fetchPlan, limit, query);
|
||||||
logger.info("Requested query (fetch plan {}, limit : {}):\n{}",
|
|
||||||
fetchPlan, limit, query);
|
|
||||||
Query queryManager = new QueryImpl();
|
Query queryManager = new QueryImpl();
|
||||||
return queryManager.query(query, limit, fetchPlan);
|
return queryManager.query(query, limit, fetchPlan);
|
||||||
}
|
}
|
||||||
|
|
||||||
@HEAD
|
@HEAD
|
||||||
@Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}"
|
@Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/{" + ID_PATH_PARAM + "}")
|
||||||
+ "/{" + ID_PATH_PARAM + "}")
|
public Response exists(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(ID_PATH_PARAM) String id)
|
||||||
public Response exists(@PathParam(TYPE_PATH_PARAM) String type,
|
throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
|
||||||
@PathParam(ID_PATH_PARAM) String id) throws ERNotFoundException,
|
CalledMethodProvider.instance.set(HTTPMETHOD.HEAD.name() + " /" + AccessPath.ACCESS_PATH_PART + "/"
|
||||||
ERAvailableInAnotherContextException, ResourceRegistryException {
|
+ AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
|
||||||
CalledMethodProvider.instance.set(
|
|
||||||
HTTPMETHOD.HEAD.name() + " /" + AccessPath.ACCESS_PATH_PART +
|
|
||||||
"/" + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
|
|
||||||
logger.info("Requested to check if {} with id {} exists", type, id);
|
logger.info("Requested to check if {} with id {} exists", type, id);
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
|
@ -109,44 +104,40 @@ public class Access {
|
||||||
UUID uuid = null;
|
UUID uuid = null;
|
||||||
try {
|
try {
|
||||||
uuid = UUID.fromString(id);
|
uuid = UUID.fromString(id);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
erManagement.setUUID(uuid);
|
erManagement.setUUID(uuid);
|
||||||
try {
|
try {
|
||||||
boolean found = erManagement.exists();
|
boolean found = erManagement.exists();
|
||||||
if(found){
|
if(found) {
|
||||||
return Response.status(Status.NO_CONTENT).build();
|
return Response.status(Status.NO_CONTENT).build();
|
||||||
}else{
|
} else {
|
||||||
// This code should never be reached due to exception management
|
// This code should never be reached due to exception management
|
||||||
// anyway adding it for safety reason
|
// anyway adding it for safety reason
|
||||||
return Response.status(Status.NOT_FOUND).build();
|
return Response.status(Status.NOT_FOUND).build();
|
||||||
}
|
}
|
||||||
} catch (ERNotFoundException e) {
|
} catch(ERNotFoundException e) {
|
||||||
return Response.status(Status.NOT_FOUND).build();
|
return Response.status(Status.NOT_FOUND).build();
|
||||||
} catch (ERAvailableInAnotherContextException e) {
|
} catch(ERAvailableInAnotherContextException e) {
|
||||||
return Response.status(Status.FORBIDDEN).build();
|
return Response.status(Status.FORBIDDEN).build();
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* e.g. GET
|
* e.g. GET
|
||||||
* /resource-registry/access/instance/ContactFacet/4d28077b-566d-4132-b073-
|
* /resource-registry/access/instance/ContactFacet/4d28077b-566d-4132-b073-f4edaf61dcb9
|
||||||
* f4edaf61dcb9
|
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}"
|
@Path(AccessPath.INSTANCE_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/{" + ID_PATH_PARAM + "}")
|
||||||
+ "/{" + ID_PATH_PARAM + "}")
|
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String getInstance(@PathParam(TYPE_PATH_PARAM) String type,
|
public String getInstance(@PathParam(TYPE_PATH_PARAM) String type, @PathParam(ID_PATH_PARAM) String id)
|
||||||
@PathParam(ID_PATH_PARAM) String id)
|
|
||||||
throws ERNotFoundException, ResourceRegistryException {
|
throws ERNotFoundException, ResourceRegistryException {
|
||||||
|
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.GET.name() + " /" + AccessPath.ACCESS_PATH_PART + "/"
|
||||||
HTTPMETHOD.GET.name() + " /" + AccessPath.ACCESS_PATH_PART +
|
+ AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + AccessPath.INSTANCE_PATH_PART + "/" + type + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
|
|
||||||
logger.info("Requested {} with id {}", type, id);
|
logger.info("Requested {} with id {}", type, id);
|
||||||
|
|
||||||
|
@ -155,7 +146,7 @@ public class Access {
|
||||||
UUID uuid = null;
|
UUID uuid = null;
|
||||||
try {
|
try {
|
||||||
uuid = UUID.fromString(id);
|
uuid = UUID.fromString(id);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
erManagement.setUUID(uuid);
|
erManagement.setUUID(uuid);
|
||||||
|
@ -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)
|
* &reference=4d28077b-566d-4132-b073-f4edaf61dcb9 &direction=(in|out|both)
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "rawtypes" })
|
@SuppressWarnings({"rawtypes"})
|
||||||
@GET
|
@GET
|
||||||
@Path(AccessPath.INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}")
|
@Path(AccessPath.INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}")
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String getInstances(@PathParam(TYPE_PATH_PARAM) String type,
|
public String getInstances(@PathParam(TYPE_PATH_PARAM) String type,
|
||||||
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic,
|
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic,
|
||||||
@QueryParam(AccessPath.REFERENCE) String reference,
|
@QueryParam(AccessPath.REFERENCE) String reference,
|
||||||
@QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction)
|
@QueryParam(AccessPath.DIRECTION) @DefaultValue("both") String direction) throws ResourceRegistryException {
|
||||||
throws ResourceRegistryException {
|
logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic);
|
||||||
logger.info("Requested {} ({}={}) instances", type,
|
|
||||||
AccessPath.POLYMORPHIC_PARAM, polymorphic);
|
|
||||||
|
|
||||||
ERManagement erManagement = ERManagementUtility.getERManagement(type);
|
ERManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
|
|
||||||
if (erManagement instanceof EntityManagement) {
|
if(erManagement instanceof EntityManagement) {
|
||||||
return erManagement.all(polymorphic);
|
return erManagement.all(polymorphic);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (erManagement instanceof RelationManagement) {
|
if(erManagement instanceof RelationManagement) {
|
||||||
if (reference != null) {
|
if(reference != null) {
|
||||||
UUID uuid = null;
|
UUID uuid = null;
|
||||||
try {
|
try {
|
||||||
uuid = UUID.fromString(reference);
|
uuid = UUID.fromString(reference);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String errror = String.format(
|
String errror = String.format("Provided %s (%s) is not a valid %s", AccessPath.REFERENCE, reference,
|
||||||
"Provided %s (%s) is not a valid %s",
|
|
||||||
AccessPath.REFERENCE, reference,
|
|
||||||
UUID.class.getSimpleName());
|
UUID.class.getSimpleName());
|
||||||
throw new ResourceRegistryException(errror);
|
throw new ResourceRegistryException(errror);
|
||||||
}
|
}
|
||||||
|
|
||||||
Direction directionEnum;
|
Direction directionEnum;
|
||||||
if (direction == null) {
|
if(direction == null) {
|
||||||
directionEnum = Direction.BOTH;
|
directionEnum = Direction.BOTH;
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
directionEnum = Enum.valueOf(Direction.class, direction
|
directionEnum = Enum.valueOf(Direction.class, direction.trim().toUpperCase());
|
||||||
.trim().toUpperCase());
|
} catch(Exception e) {
|
||||||
} catch (Exception e) {
|
String errror = String.format("Provided %s (%s) is not valid. Allowed values are %s",
|
||||||
String errror = String
|
AccessPath.DIRECTION, direction, Arrays.toString(Direction.values()).toLowerCase());
|
||||||
.format("Provided %s (%s) is not valid. Allowed values are %s",
|
|
||||||
AccessPath.DIRECTION, direction,
|
|
||||||
Arrays.toString(Direction.values()).toLowerCase());
|
|
||||||
throw new ResourceRegistryException(errror);
|
throw new ResourceRegistryException(errror);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ((RelationManagement) erManagement).allFrom(uuid,
|
return ((RelationManagement) erManagement).allFrom(uuid, directionEnum, polymorphic);
|
||||||
directionEnum, polymorphic);
|
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return erManagement.all(polymorphic);
|
return erManagement.all(polymorphic);
|
||||||
|
@ -225,36 +208,33 @@ public class Access {
|
||||||
throw new ResourceRegistryException("Invalid Request");
|
throw new ResourceRegistryException("Invalid Request");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet?polymorphic=true
|
* e.g. GET /resource-registry/access/resourceInstances/EService/isIdentifiedBy/SoftwareFacet
|
||||||
|
* ?polymorphic=true
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({ "rawtypes" })
|
@SuppressWarnings({"rawtypes"})
|
||||||
@GET
|
@GET
|
||||||
@Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" +
|
@Path(AccessPath.RESOURCE_INSTANCES_PATH_PART + "/" + "{" + TYPE_PATH_PARAM + "}" + "/" + "{"
|
||||||
"/" + "{" + AccessPath.RELATION_TYPE_PATH_PART + "}"+ "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}")
|
+ AccessPath.RELATION_TYPE_PATH_PART + "}" + "/" + "{" + AccessPath.FACET_TYPE_PATH_PART + "}")
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String getFilteredInstances(
|
public String getFilteredInstances(@PathParam(TYPE_PATH_PARAM) String type,
|
||||||
@PathParam(TYPE_PATH_PARAM) String type,
|
|
||||||
@PathParam(AccessPath.RELATION_TYPE_PATH_PART) @DefaultValue(ConsistsOf.NAME) String relationType,
|
@PathParam(AccessPath.RELATION_TYPE_PATH_PART) @DefaultValue(ConsistsOf.NAME) String relationType,
|
||||||
@PathParam(AccessPath.FACET_TYPE_PATH_PART) @DefaultValue(Facet.NAME) String facetType,
|
@PathParam(AccessPath.FACET_TYPE_PATH_PART) @DefaultValue(Facet.NAME) String facetType,
|
||||||
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic,
|
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic,
|
||||||
@Context UriInfo uriInfo)
|
@Context UriInfo uriInfo) throws ResourceRegistryException {
|
||||||
throws ResourceRegistryException {
|
logger.info("Requested {} ({}={}) instances", type, AccessPath.POLYMORPHIC_PARAM, polymorphic);
|
||||||
logger.info("Requested {} ({}={}) instances", type,
|
|
||||||
AccessPath.POLYMORPHIC_PARAM, polymorphic);
|
|
||||||
|
|
||||||
MultivaluedMap<String, String> multivaluedMap = uriInfo.getQueryParameters();
|
MultivaluedMap<String,String> multivaluedMap = uriInfo.getQueryParameters();
|
||||||
|
|
||||||
Map<String, String> constraint = new HashMap<>();
|
Map<String,String> constraint = new HashMap<>();
|
||||||
for(String key : multivaluedMap.keySet()){
|
for(String key : multivaluedMap.keySet()) {
|
||||||
if(key.compareTo(AccessPath.POLYMORPHIC_PARAM)==0){
|
if(key.compareTo(AccessPath.POLYMORPHIC_PARAM) == 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if(key.compareTo("gcube-token")==0){
|
if(key.compareTo("gcube-token") == 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if(key.compareTo("gcube-scope")==0){
|
if(key.compareTo("gcube-scope") == 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
constraint.put(key, multivaluedMap.getFirst(key));
|
constraint.put(key, multivaluedMap.getFirst(key));
|
||||||
|
@ -264,15 +244,13 @@ public class Access {
|
||||||
|
|
||||||
ERManagement erManagement = ERManagementUtility.getERManagement(type);
|
ERManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
|
|
||||||
if (erManagement instanceof ResourceManagement) {
|
if(erManagement instanceof ResourceManagement) {
|
||||||
return ((ResourceManagement) erManagement).all(polymorphic, constraint);
|
return ((ResourceManagement) erManagement).all(polymorphic, constraint);
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new ResourceRegistryException("Invalid Request");
|
throw new ResourceRegistryException("Invalid Request");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* e.g. GET /resource-registry/access/schema/ContactFacet?polymorphic=true
|
* e.g. GET /resource-registry/access/schema/ContactFacet?polymorphic=true
|
||||||
*/
|
*/
|
||||||
|
@ -287,7 +265,6 @@ public class Access {
|
||||||
return schemaManagement.read(type, polymorphic);
|
return schemaManagement.read(type, polymorphic);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* e.g. GET /resource-registry/access/context/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
* e.g. GET /resource-registry/access/context/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.rest;
|
package org.gcube.informationsystem.resourceregistry.rest;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
|
@ -54,13 +54,12 @@ public class ERManager {
|
||||||
*/
|
*/
|
||||||
@PUT
|
@PUT
|
||||||
@Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
@Path(ERPath.FACET_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
public Response createFacet(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
||||||
throws FacetAlreadyPresentException, ResourceRegistryException {
|
throws FacetAlreadyPresentException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance
|
||||||
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
|
.set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/" + type);
|
||||||
"/" + ERPath.FACET_PATH_PART + "/" + type);
|
|
||||||
logger.info("Requested to create {} of type {}", Facet.NAME, type);
|
logger.info("Requested to create {} of type {}", Facet.NAME, type);
|
||||||
logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json);
|
logger.trace("Requested to create {} of type {} defined by {} ", Facet.NAME, type, json);
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
@ -79,13 +78,12 @@ public class ERManager {
|
||||||
*/
|
*/
|
||||||
@POST
|
@POST
|
||||||
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json)
|
public String updateFacet(@PathParam(ID_PATH_PARAM) String uuid, String json)
|
||||||
throws FacetNotFoundException, ResourceRegistryException {
|
throws FacetNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to update {} with id {}", Facet.NAME, uuid);
|
logger.info("Requested to update {} with id {}", Facet.NAME, uuid);
|
||||||
logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json);
|
logger.trace("Requested to update {} with id {} with json {}", Facet.NAME, uuid, json);
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
@ -95,16 +93,15 @@ public class ERManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86
|
* e.g. DELETE /resource-registry/er/facet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
@DELETE
|
@DELETE
|
||||||
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid)
|
public boolean deleteFacet(@PathParam(ID_PATH_PARAM) String uuid)
|
||||||
throws FacetNotFoundException, ResourceRegistryException {
|
throws FacetNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to delete {} with id {}", Facet.NAME, uuid);
|
logger.info("Requested to delete {} with id {}", Facet.NAME, uuid);
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
facetManagement.setUUID(UUID.fromString(uuid));
|
facetManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
@ -121,13 +118,12 @@ public class ERManager {
|
||||||
*/
|
*/
|
||||||
@PUT
|
@PUT
|
||||||
@Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
@Path(ERPath.RESOURCE_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
public Response createResource(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
||||||
throws ResourceAlreadyPresentException, ResourceRegistryException {
|
throws ResourceAlreadyPresentException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance
|
||||||
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
|
.set(HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/" + type);
|
||||||
"/" + ERPath.RESOURCE_PATH_PART + "/" + type);
|
|
||||||
logger.info("Requested to create {} of type {}", Resource.NAME, type);
|
logger.info("Requested to create {} of type {}", Resource.NAME, type);
|
||||||
logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json);
|
logger.trace("Requested to create {} of type {} with json {}", Resource.NAME, type, json);
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
|
@ -146,13 +142,12 @@ public class ERManager {
|
||||||
*/
|
*/
|
||||||
@POST
|
@POST
|
||||||
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json)
|
public String updateResource(@PathParam(ID_PATH_PARAM) String uuid, String json)
|
||||||
throws ResourceNotFoundException, ResourceRegistryException {
|
throws ResourceNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to update {} with id {}", Resource.NAME, uuid);
|
logger.info("Requested to update {} with id {}", Resource.NAME, uuid);
|
||||||
logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json);
|
logger.trace("Requested to update {} with id {} with json {}", Resource.NAME, uuid, json);
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
|
@ -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
|
@DELETE
|
||||||
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception {
|
public boolean deleteResource(@PathParam(ID_PATH_PARAM) String uuid) throws ResourceNotFoundException, Exception {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to delete {} with id {}", Resource.NAME, uuid);
|
logger.info("Requested to delete {} with id {}", Resource.NAME, uuid);
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setUUID(UUID.fromString(uuid));
|
resourceManagement.setUUID(UUID.fromString(uuid));
|
||||||
return resourceManagement.delete();
|
return resourceManagement.delete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy
|
* e.g. PUT /resource-registry/er/consistsOf/IsIdentifiedBy
|
||||||
*
|
*
|
||||||
|
@ -186,13 +180,12 @@ public class ERManager {
|
||||||
*/
|
*/
|
||||||
@PUT
|
@PUT
|
||||||
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
public Response createConsistsOf(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
||||||
throws ResourceAlreadyPresentException, ResourceRegistryException {
|
throws ResourceAlreadyPresentException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(
|
||||||
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
|
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type);
|
||||||
"/" + ERPath.CONSISTS_OF_PATH_PART + "/" + type);
|
|
||||||
logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type);
|
logger.info("Requested to create {} of type {}", ConsistsOf.NAME, type);
|
||||||
logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json);
|
logger.trace("Requested to create {} of type {} with json {}", ConsistsOf.NAME, type, json);
|
||||||
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
|
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
|
||||||
|
@ -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
|
@DELETE
|
||||||
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException {
|
public boolean detachFacet(@PathParam(ID_PATH_PARAM) String consistOfUUID) throws ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.CONSISTS_OF_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID);
|
logger.info("Requested to delete {} with id {}", ConsistsOf.NAME, consistOfUUID);
|
||||||
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
|
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
|
||||||
consistsOfManagement.setUUID(UUID.fromString(consistOfUUID));
|
consistsOfManagement.setUUID(UUID.fromString(consistOfUUID));
|
||||||
|
@ -227,13 +220,12 @@ public class ERManager {
|
||||||
*/
|
*/
|
||||||
@PUT
|
@PUT
|
||||||
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + TYPE_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
public Response createIsRelatedTo(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
||||||
throws ResourceAlreadyPresentException, ResourceRegistryException {
|
throws ResourceAlreadyPresentException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(
|
||||||
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART +
|
HTTPMETHOD.PUT.name() + " /" + ERPath.ER_PATH_PART + "/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type);
|
||||||
"/" + ERPath.IS_RELATED_TO_PATH_PART + "/" + type);
|
|
||||||
logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json);
|
logger.info("Requested to create {} of type {} with json {}", IsRelatedTo.NAME, type, json);
|
||||||
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
|
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
|
||||||
isRelatedToManagement.setElementType(type);
|
isRelatedToManagement.setElementType(type);
|
||||||
|
@ -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
|
@DELETE
|
||||||
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException {
|
public boolean detachResource(@PathParam(ID_PATH_PARAM) String relatedToUUID) throws ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.DELETE.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.IS_RELATED_TO_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID);
|
logger.info("Requested to delete {} with id {}", IsRelatedTo.NAME, relatedToUUID);
|
||||||
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
|
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
|
||||||
isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID));
|
isRelatedToManagement.setUUID(UUID.fromString(relatedToUUID));
|
||||||
|
@ -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
|
@POST
|
||||||
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid)
|
public boolean addResourceToContext(@PathParam(ID_PATH_PARAM) String uuid)
|
||||||
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME);
|
logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME);
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setUUID(UUID.fromString(uuid));
|
resourceManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
@ -284,9 +276,8 @@ public class ERManager {
|
||||||
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid)
|
public boolean addFacetToContext(@PathParam(ID_PATH_PARAM) String uuid)
|
||||||
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME);
|
logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME);
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
facetManagement.setUUID(UUID.fromString(uuid));
|
facetManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
@ -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
|
@POST
|
||||||
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid)
|
public boolean removeResourceFromContext(@PathParam(ID_PATH_PARAM) String uuid)
|
||||||
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME);
|
logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME);
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setUUID(UUID.fromString(uuid));
|
resourceManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
@ -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
|
@POST
|
||||||
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
@Path(ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}")
|
||||||
public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid)
|
public boolean removeFacetFromContext(@PathParam(ID_PATH_PARAM) String uuid)
|
||||||
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws FacetNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
CalledMethodProvider.instance.set(
|
CalledMethodProvider.instance.set(HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART + "/"
|
||||||
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
|
+ ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
||||||
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
|
|
||||||
logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME);
|
logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME);
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
facetManagement.setUUID(UUID.fromString(uuid));
|
facetManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
|
|
@ -15,28 +15,29 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
@Provider
|
@Provider
|
||||||
public class ResourceRegistryExceptionMapper implements ExceptionMapper<ResourceRegistryException>{
|
public class ResourceRegistryExceptionMapper implements ExceptionMapper<ResourceRegistryException> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(ResourceRegistryException exception) {
|
public Response toResponse(ResourceRegistryException exception) {
|
||||||
|
|
||||||
Status status = Status.BAD_REQUEST;
|
Status status = Status.BAD_REQUEST;
|
||||||
|
|
||||||
if(ERNotFoundException.class.isAssignableFrom(exception.getClass())){
|
if(ERNotFoundException.class.isAssignableFrom(exception.getClass())) {
|
||||||
status = Status.NOT_FOUND;
|
status = Status.NOT_FOUND;
|
||||||
} else if(ERAlreadyPresentException.class.isAssignableFrom(exception.getClass())){
|
} else if(ERAlreadyPresentException.class.isAssignableFrom(exception.getClass())) {
|
||||||
status = Status.CONFLICT;
|
status = Status.CONFLICT;
|
||||||
} else if(ERAvailableInAnotherContextException.class.isAssignableFrom(exception.getClass())){
|
} else if(ERAvailableInAnotherContextException.class.isAssignableFrom(exception.getClass())) {
|
||||||
status = Status.FORBIDDEN;
|
status = Status.FORBIDDEN;
|
||||||
} else if(exception.getClass() == ResourceRegistryException.class){
|
} else if(exception.getClass() == ResourceRegistryException.class) {
|
||||||
status = Status.INTERNAL_SERVER_ERROR;
|
status = Status.INTERNAL_SERVER_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
String entity = org.gcube.informationsystem.resourceregistry.api.exceptions.ExceptionMapper.marshal(exception);
|
String entity = org.gcube.informationsystem.resourceregistry.api.exceptions.ExceptionMapper
|
||||||
|
.marshal(exception);
|
||||||
MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
|
MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
|
||||||
return Response.status(status).entity(entity).type(mediaType).build();
|
return Response.status(status).entity(entity).type(mediaType).build();
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String entity = exception.getMessage();
|
String entity = exception.getMessage();
|
||||||
MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
|
MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
|
||||||
return Response.status(status).entity(entity).type(mediaType).build();
|
return Response.status(status).entity(entity).type(mediaType).build();
|
||||||
|
|
|
@ -46,7 +46,7 @@ public class SchemaManager {
|
||||||
*/
|
*/
|
||||||
@PUT
|
@PUT
|
||||||
@Path("{" + TYPE_PATH_PARAM + "}")
|
@Path("{" + TYPE_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public Response create(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
public Response create(@PathParam(TYPE_PATH_PARAM) String type, String json)
|
||||||
throws SchemaException, ResourceRegistryException {
|
throws SchemaException, ResourceRegistryException {
|
||||||
|
@ -55,27 +55,27 @@ public class SchemaManager {
|
||||||
AccessType accessType = null;
|
AccessType accessType = null;
|
||||||
try {
|
try {
|
||||||
accessType = AccessType.valueOf(type);
|
accessType = AccessType.valueOf(type);
|
||||||
switch (accessType) {
|
switch(accessType) {
|
||||||
case EMBEDDED:
|
case EMBEDDED:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case FACET:
|
case FACET:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RESOURCE:
|
case RESOURCE:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case IS_RELATED_TO:
|
case IS_RELATED_TO:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case CONSISTS_OF:
|
case CONSISTS_OF:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new Exception();
|
throw new Exception();
|
||||||
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
String error = String.format("Cannot register %s schema", type);
|
String error = String.format("Cannot register %s schema", type);
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
|
@ -91,7 +91,7 @@ public class SchemaManager {
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("{" + TYPE_PATH_PARAM + "}")
|
@Path("{" + TYPE_PATH_PARAM + "}")
|
||||||
@Consumes({ MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8 })
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String read(@PathParam(TYPE_PATH_PARAM) String type,
|
public String read(@PathParam(TYPE_PATH_PARAM) String type,
|
||||||
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic)
|
@QueryParam(AccessPath.POLYMORPHIC_PARAM) @DefaultValue("false") Boolean polymorphic)
|
||||||
|
|
|
@ -8,9 +8,9 @@ import org.gcube.informationsystem.model.entity.Entity;
|
||||||
import org.gcube.informationsystem.model.relation.Relation;
|
import org.gcube.informationsystem.model.relation.Relation;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
|
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -28,12 +28,12 @@ public class SchemaContextManagement implements SchemaManagement {
|
||||||
|
|
||||||
public static final String SCHEMA = "__SCHEMA";
|
public static final String SCHEMA = "__SCHEMA";
|
||||||
|
|
||||||
protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception{
|
protected Vertex getVertex(OrientGraph orientGraph, String vertexType) throws Exception {
|
||||||
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(vertexType, false);
|
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(vertexType, false);
|
||||||
Iterator<Vertex> iterator = iterable.iterator();
|
Iterator<Vertex> iterator = iterable.iterator();
|
||||||
|
|
||||||
Vertex vertex = null;
|
Vertex vertex = null;
|
||||||
if(iterator.hasNext()){
|
if(iterator.hasNext()) {
|
||||||
vertex = iterator.next();
|
vertex = iterator.next();
|
||||||
} else {
|
} else {
|
||||||
String error = String.format("%s is not a registered type", vertexType);
|
String error = String.format("%s is not a registered type", vertexType);
|
||||||
|
@ -41,8 +41,10 @@ public class SchemaContextManagement implements SchemaManagement {
|
||||||
throw new Exception(error);
|
throw new Exception(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(iterator.hasNext()){
|
if(iterator.hasNext()) {
|
||||||
String error = String.format("More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.", vertexType);
|
String error = String.format(
|
||||||
|
"More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.",
|
||||||
|
vertexType);
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
throw new Exception(error);
|
throw new Exception(error);
|
||||||
}
|
}
|
||||||
|
@ -62,11 +64,11 @@ public class SchemaContextManagement implements SchemaManagement {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class);
|
TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class);
|
||||||
|
|
||||||
if (Entity.class.isAssignableFrom(baseType.getTypeClass())) {
|
if(Entity.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
OrientVertex orientVertex = orientGraph.addVertex("class:" + typeDefinition.getName());
|
OrientVertex orientVertex = orientGraph.addVertex("class:" + typeDefinition.getName());
|
||||||
orientVertex.setProperty(SCHEMA, json);
|
orientVertex.setProperty(SCHEMA, json);
|
||||||
orientVertex.save();
|
orientVertex.save();
|
||||||
} else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) {
|
} else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
String sourceClass = typeDefinition.getSourceType();
|
String sourceClass = typeDefinition.getSourceType();
|
||||||
Vertex source = getVertex(orientGraph, sourceClass);
|
Vertex source = getVertex(orientGraph, sourceClass);
|
||||||
|
|
||||||
|
@ -77,7 +79,7 @@ public class SchemaContextManagement implements SchemaManagement {
|
||||||
orientEdge.setProperty(SCHEMA, json);
|
orientEdge.setProperty(SCHEMA, json);
|
||||||
orientEdge.save();
|
orientEdge.save();
|
||||||
|
|
||||||
} else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
|
} else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
ODocument doc = new ODocument(typeDefinition.getName());
|
ODocument doc = new ODocument(typeDefinition.getName());
|
||||||
doc.field(SCHEMA, json);
|
doc.field(SCHEMA, json);
|
||||||
doc.save();
|
doc.save();
|
||||||
|
@ -86,13 +88,13 @@ public class SchemaContextManagement implements SchemaManagement {
|
||||||
orientGraph.commit();
|
orientGraph.commit();
|
||||||
return json;
|
return json;
|
||||||
|
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.rollback();
|
orientGraph.rollback();
|
||||||
}
|
}
|
||||||
throw new SchemaException(e);
|
throw new SchemaException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraph != null) {
|
if(orientGraph != null) {
|
||||||
orientGraph.shutdown();
|
orientGraph.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,8 +7,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
*
|
||||||
* For JSON schema see
|
* For JSON schema see http://orientdb.com/docs/last/OrientDB-REST.html#class
|
||||||
* http://orientdb.com/docs/last/OrientDB-REST.html#class
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public interface SchemaManagement {
|
public interface SchemaManagement {
|
||||||
|
@ -17,7 +16,8 @@ public interface SchemaManagement {
|
||||||
|
|
||||||
public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException;
|
public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException;
|
||||||
|
|
||||||
public String update(String type, AccessType accessType, String json) throws SchemaNotFoundException, SchemaException;
|
public String update(String type, AccessType accessType, String json)
|
||||||
|
throws SchemaNotFoundException, SchemaException;
|
||||||
|
|
||||||
public String delete(String type, AccessType accessType) throws SchemaNotFoundException;
|
public String delete(String type, AccessType accessType) throws SchemaNotFoundException;
|
||||||
|
|
||||||
|
|
|
@ -19,9 +19,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.gcube.informationsystem.types.TypeBinder;
|
import org.gcube.informationsystem.types.TypeBinder;
|
||||||
import org.gcube.informationsystem.types.TypeBinder.Property;
|
import org.gcube.informationsystem.types.TypeBinder.Property;
|
||||||
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
|
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
|
||||||
|
@ -44,44 +44,40 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*
|
*
|
||||||
* TODO Create an instance for each Registered Type in a management
|
* TODO Create an instance for each Registered Type in a management SecurityContext so that that management context
|
||||||
* SecurityContext so that that management context can be used to see
|
* can be used to see Entity and Relations as graph.
|
||||||
* Entity and Relations as graph.
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class SchemaManagementImpl implements SchemaManagement {
|
public class SchemaManagementImpl implements SchemaManagement {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory
|
private static Logger logger = LoggerFactory.getLogger(SchemaManagementImpl.class);
|
||||||
.getLogger(SchemaManagementImpl.class);
|
|
||||||
|
|
||||||
protected static OClass getOClass(OSchema oSchema, String type)
|
protected static OClass getOClass(OSchema oSchema, String type) throws SchemaException {
|
||||||
throws SchemaException {
|
|
||||||
return oSchema.getClass(type);
|
return oSchema.getClass(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph,
|
public static OClass getTypeSchema(OrientBaseGraph orientBaseGraph, String type, AccessType accessType)
|
||||||
String type, AccessType accessType) throws SchemaException {
|
throws SchemaException {
|
||||||
OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata();
|
OMetadata oMetadata = orientBaseGraph.getRawGraph().getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
return getTypeSchema(oSchema, type, accessType);
|
return getTypeSchema(oSchema, type, accessType);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static OClass getTypeSchema(OSchema oSchema, String type,
|
public static OClass getTypeSchema(OSchema oSchema, String type, AccessType accessType) throws SchemaException {
|
||||||
AccessType accessType) throws SchemaException {
|
|
||||||
try {
|
try {
|
||||||
OClass oClass = oSchema.getClass(type);
|
OClass oClass = oSchema.getClass(type);
|
||||||
if (oClass == null) {
|
if(oClass == null) {
|
||||||
throw new SchemaNotFoundException(type + " was not registered");
|
throw new SchemaNotFoundException(type + " was not registered");
|
||||||
}
|
}
|
||||||
if(accessType!=null && type.compareTo(accessType.getName())!= 0) {
|
if(accessType != null && type.compareTo(accessType.getName()) != 0) {
|
||||||
if (!oClass.isSubClassOf(accessType.getName())) {
|
if(!oClass.isSubClassOf(accessType.getName())) {
|
||||||
throw new SchemaException(type + " is not a " + accessType.getName());
|
throw new SchemaException(type + " is not a " + accessType.getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return oClass;
|
return oClass;
|
||||||
} catch (SchemaNotFoundException snfe) {
|
} catch(SchemaNotFoundException snfe) {
|
||||||
throw snfe;
|
throw snfe;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new SchemaException(e.getMessage());
|
throw new SchemaException(e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -90,54 +86,49 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
throws SchemaException, ResourceRegistryException {
|
throws SchemaException, ResourceRegistryException {
|
||||||
OrientGraphNoTx orientGraphNoTx = null;
|
OrientGraphNoTx orientGraphNoTx = null;
|
||||||
try {
|
try {
|
||||||
logger.debug("Getting {} Type {} schema",
|
logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type);
|
||||||
accessType != null ? accessType.getName() : "", type);
|
|
||||||
|
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
||||||
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
|
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
|
||||||
|
|
||||||
return getTypeSchema(orientGraphNoTx, type, accessType);
|
return getTypeSchema(orientGraphNoTx, type, accessType);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraphNoTx != null) {
|
if(orientGraphNoTx != null) {
|
||||||
orientGraphNoTx.shutdown();
|
orientGraphNoTx.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static TypeDefinition getTypeDefinition(OClass oClass)
|
protected static TypeDefinition getTypeDefinition(OClass oClass) throws SchemaException {
|
||||||
throws SchemaException {
|
|
||||||
ODocument oDocument = ((OClassImpl) oClass).toStream();
|
ODocument oDocument = ((OClassImpl) oClass).toStream();
|
||||||
String json = oDocument.toJSON();
|
String json = oDocument.toJSON();
|
||||||
try {
|
try {
|
||||||
return TypeBinder.deserializeTypeDefinition(json);
|
return TypeBinder.deserializeTypeDefinition(json);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new SchemaException(e);
|
throw new SchemaException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static String getTypeDefinitionAsString(OClass oClass)
|
protected static String getTypeDefinitionAsString(OClass oClass) throws SchemaException {
|
||||||
throws SchemaException {
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
TypeDefinition typeDefinition = getTypeDefinition(oClass);
|
TypeDefinition typeDefinition = getTypeDefinition(oClass);
|
||||||
return TypeBinder.serializeTypeDefinition(typeDefinition);
|
return TypeBinder.serializeTypeDefinition(typeDefinition);
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new SchemaException(e);
|
throw new SchemaException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected List<OClass> getSuperclassesAndCheckCompliancy(
|
protected List<OClass> getSuperclassesAndCheckCompliancy(OrientGraphNoTx orientGraphNoTx,
|
||||||
OrientGraphNoTx orientGraphNoTx, TypeDefinition typeDefinition,
|
TypeDefinition typeDefinition, String baseType) throws SchemaException {
|
||||||
String baseType) throws SchemaException {
|
|
||||||
|
|
||||||
Set<String> superClasses = typeDefinition.getSuperClasses();
|
Set<String> superClasses = typeDefinition.getSuperClasses();
|
||||||
if (baseType != null) {
|
if(baseType != null) {
|
||||||
if (superClasses == null || superClasses.size() == 0) {
|
if(superClasses == null || superClasses.size() == 0) {
|
||||||
throw new RuntimeException(
|
throw new RuntimeException(
|
||||||
String.format(
|
String.format("No Superclass found in schema %s. The Type Definition must extend %s",
|
||||||
"No Superclass found in schema %s. The Type Definition must extend %s",
|
|
||||||
typeDefinition, baseType));
|
typeDefinition, baseType));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -146,18 +137,16 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
|
|
||||||
List<OClass> oSuperclasses = new ArrayList<>();
|
List<OClass> oSuperclasses = new ArrayList<>();
|
||||||
for (String superClass : superClasses) {
|
for(String superClass : superClasses) {
|
||||||
OClass oSuperClass = getOClass(oSchema, superClass);
|
OClass oSuperClass = getOClass(oSchema, superClass);
|
||||||
if(oSuperClass==null){
|
if(oSuperClass == null) {
|
||||||
throw new SchemaNotFoundException("Superclass "+ superClass + " does not exists");
|
throw new SchemaNotFoundException("Superclass " + superClass + " does not exists");
|
||||||
}
|
}
|
||||||
if (baseType != null) {
|
if(baseType != null) {
|
||||||
if (typeDefinition.getName().compareTo(baseType) != 0) {
|
if(typeDefinition.getName().compareTo(baseType) != 0) {
|
||||||
if (!oSuperClass.isSubClassOf(baseType)) {
|
if(!oSuperClass.isSubClassOf(baseType)) {
|
||||||
throw new RuntimeException(superClass
|
throw new RuntimeException(superClass + " is not a subsclass of " + baseType
|
||||||
+ " is not a subsclass of " + baseType
|
+ ". Each Superclass MUST be a subclass of " + baseType);
|
||||||
+ ". Each Superclass MUST be a subclass of "
|
|
||||||
+ baseType);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -167,17 +156,14 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
return oSuperclasses;
|
return oSuperclasses;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String registerTypeSchema(String jsonSchema, AccessType baseType)
|
protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException {
|
||||||
throws SchemaException {
|
|
||||||
|
|
||||||
OrientGraphNoTx orientGraphNoTx = null;
|
OrientGraphNoTx orientGraphNoTx = null;
|
||||||
try {
|
try {
|
||||||
logger.info("Trying to register {} {}", baseType.getName(),
|
logger.info("Trying to register {} {}", baseType.getName(), jsonSchema);
|
||||||
jsonSchema);
|
|
||||||
|
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
TypeDefinition typeDefinition = mapper.readValue(jsonSchema,
|
TypeDefinition typeDefinition = mapper.readValue(jsonSchema, TypeDefinition.class);
|
||||||
TypeDefinition.class);
|
|
||||||
|
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
||||||
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
|
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
|
||||||
|
@ -187,70 +173,68 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
|
|
||||||
OClass oClass = null;
|
OClass oClass = null;
|
||||||
|
|
||||||
if (Entity.class.isAssignableFrom(baseType.getTypeClass())) {
|
if(Entity.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
oClass = orientGraphNoTx.createVertexType(typeDefinition
|
oClass = orientGraphNoTx.createVertexType(typeDefinition.getName());
|
||||||
.getName());
|
} else if(Relation.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
} else if (Relation.class.isAssignableFrom(baseType.getTypeClass())) {
|
oClass = orientGraphNoTx.createEdgeType(typeDefinition.getName());
|
||||||
oClass = orientGraphNoTx.createEdgeType(typeDefinition
|
|
||||||
.getName());
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This information are persisted in Management Context
|
* This information are persisted in Management Context String outBaseType =
|
||||||
*
|
* typeDefinition.getOutBaseType(); String inBaseType =
|
||||||
* String outBaseType = typeDefinition.getOutBaseType();
|
* typeDefinition.getInBaseType();
|
||||||
* String inBaseType = typeDefinition.getInBaseType();
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
} else if (Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
|
} else if(Embedded.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
oClass = oSchema.createClass(typeDefinition.getName());
|
oClass = oSchema.createClass(typeDefinition.getName());
|
||||||
} else {
|
} else {
|
||||||
String error = String
|
String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.",
|
||||||
.format("Allowed superclass are %s, %s, %s, or any subclasses of them.",
|
Entity.NAME, Relation.NAME, Embedded.NAME);
|
||||||
Entity.NAME, Relation.NAME, Embedded.NAME);
|
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (typeDefinition.getDescription() != null) {
|
if(typeDefinition.getDescription() != null) {
|
||||||
try {
|
try {
|
||||||
oClass.setDescription(typeDefinition.getDescription());
|
oClass.setDescription(typeDefinition.getDescription());
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.warn("Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
|
logger.warn(
|
||||||
|
"Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// oClass.setAbstract(false); // Used to allow to persist Schema in Context Management
|
// oClass.setAbstract(false); // Used to allow to persist Schema in Context
|
||||||
|
// Management
|
||||||
oClass.setAbstract(typeDefinition.isAbstract());
|
oClass.setAbstract(typeDefinition.isAbstract());
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error(
|
logger.error(
|
||||||
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
|
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
|
||||||
typeDefinition.getName());
|
typeDefinition.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeDefinition.getName().compareTo(Embedded.NAME) != 0) {
|
if(typeDefinition.getName().compareTo(Embedded.NAME) != 0) {
|
||||||
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(
|
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(orientGraphNoTx, typeDefinition,
|
||||||
orientGraphNoTx, typeDefinition, baseType.getName());
|
baseType.getName());
|
||||||
oClass.setSuperClasses(oSuperclasses);
|
oClass.setSuperClasses(oSuperclasses);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Resource.class.isAssignableFrom(baseType.getTypeClass())) {
|
if(Resource.class.isAssignableFrom(baseType.getTypeClass())) {
|
||||||
Set<Property> properties = typeDefinition.getProperties();
|
Set<Property> properties = typeDefinition.getProperties();
|
||||||
if (properties != null && properties.size() > 0) {
|
if(properties != null && properties.size() > 0) {
|
||||||
throw new Exception(
|
throw new Exception("A Resource cannot contains any properties.");
|
||||||
"A Resource cannot contains any properties.");
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (Property property : typeDefinition.getProperties()) {
|
for(Property property : typeDefinition.getProperties()) {
|
||||||
|
|
||||||
OType oType = OType.getById(property.getType().byteValue());
|
OType oType = OType.getById(property.getType().byteValue());
|
||||||
switch (oType) {
|
switch(oType) {
|
||||||
case EMBEDDEDLIST:
|
case EMBEDDEDLIST:
|
||||||
throw new UnsupportedDataTypeException(oType.name() + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
throw new UnsupportedDataTypeException(oType.name()
|
||||||
|
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
||||||
case EMBEDDEDSET:
|
case EMBEDDEDSET:
|
||||||
throw new UnsupportedDataTypeException(oType.name() + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
throw new UnsupportedDataTypeException(oType.name()
|
||||||
|
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -259,12 +243,11 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
op.setDescription(property.getDescription());
|
op.setDescription(property.getDescription());
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Mandatory and notNull does not work in distributed mode:
|
* Mandatory and notNull does not work in distributed mode: so that on Type
|
||||||
* so that on Type declaration they are forced to false
|
* declaration they are forced to false
|
||||||
* ovp.setMandatory(property.isMandatory());
|
* ovp.setMandatory(property.isMandatory());
|
||||||
* ovp.setNotNull(property.isNotnull());
|
* ovp.setNotNull(property.isNotnull()); This information are persisted in
|
||||||
*
|
* Management Context
|
||||||
* This information are persisted in Management Context
|
|
||||||
*/
|
*/
|
||||||
op.setMandatory(false);
|
op.setMandatory(false);
|
||||||
op.setNotNull(false);
|
op.setNotNull(false);
|
||||||
|
@ -272,70 +255,60 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
op.setReadonly(property.isReadonly());
|
op.setReadonly(property.isReadonly());
|
||||||
op.setRegexp(property.getRegexp());
|
op.setRegexp(property.getRegexp());
|
||||||
|
|
||||||
if (property.getLinkedClass() != null) {
|
if(property.getLinkedClass() != null) {
|
||||||
OClass linkedClass = getOClass(oSchema,
|
OClass linkedClass = getOClass(oSchema, property.getLinkedClass());
|
||||||
property.getLinkedClass());
|
if(linkedClass == null) {
|
||||||
if (linkedClass == null) {
|
logger.trace("class {} not found in schema", property.getLinkedClass());
|
||||||
logger.trace("class {} not found in schema",
|
throw new Exception("class " + property.getLinkedClass() + " not found in schema");
|
||||||
property.getLinkedClass());
|
|
||||||
throw new Exception("class "
|
|
||||||
+ property.getLinkedClass()
|
|
||||||
+ " not found in schema");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (linkedClass.isEdgeType()
|
if(linkedClass.isEdgeType() || linkedClass.isVertexType()) {
|
||||||
|| linkedClass.isVertexType()) {
|
throw new Exception("An Embedded Field cannot be an Entity or a Relation");
|
||||||
throw new Exception(
|
|
||||||
"An Embedded Field cannot be an Entity or a Relation");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
op.setLinkedClass(linkedClass);
|
op.setLinkedClass(linkedClass);
|
||||||
} else if (property.getLinkedType() != null) {
|
} else if(property.getLinkedType() != null) {
|
||||||
op.setLinkedType(OType.getById(property.getLinkedType()
|
op.setLinkedType(OType.getById(property.getLinkedType().byteValue()));
|
||||||
.byteValue()));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
OClass toBeSerializedOClass = oClass;
|
OClass toBeSerializedOClass = oClass;
|
||||||
if (oClass instanceof OrientElementType) {
|
if(oClass instanceof OrientElementType) {
|
||||||
toBeSerializedOClass = getOClass(oSchema,
|
toBeSerializedOClass = getOClass(oSchema, typeDefinition.getName());
|
||||||
typeDefinition.getName());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
SchemaContextManagement managementUtility = new SchemaContextManagement();
|
* SchemaContextManagement managementUtility = new SchemaContextManagement();
|
||||||
String ret = managementUtility.create(jsonSchema, baseType);
|
* String ret = managementUtility.create(jsonSchema, baseType);
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// TODO Remove when the previous has been implemented
|
// TODO Remove when the previous has been implemented
|
||||||
String ret = getTypeDefinitionAsString(toBeSerializedOClass);
|
String ret = getTypeDefinitionAsString(toBeSerializedOClass);
|
||||||
|
|
||||||
logger.info("{} type registered successfully: {}",
|
logger.info("{} type registered successfully: {}", baseType.getName(), jsonSchema);
|
||||||
baseType.getName(), jsonSchema);
|
|
||||||
return ret;
|
return ret;
|
||||||
}catch (Exception e) {
|
} catch(Exception e) {
|
||||||
oSchema.dropClass(typeDefinition.getName());
|
oSchema.dropClass(typeDefinition.getName());
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
} catch (OSchemaException ex) {
|
} catch(OSchemaException ex) {
|
||||||
if(ex.getMessage().contains("already exists")){
|
if(ex.getMessage().contains("already exists")) {
|
||||||
throw new SchemaAlreadyPresentException(ex);
|
throw new SchemaAlreadyPresentException(ex);
|
||||||
}
|
}
|
||||||
throw new SchemaException(ex);
|
throw new SchemaException(ex);
|
||||||
} catch (SchemaException e) {
|
} catch(SchemaException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception ex) {
|
} catch(Exception ex) {
|
||||||
throw new SchemaException(ex);
|
throw new SchemaException(ex);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraphNoTx != null) {
|
if(orientGraphNoTx != null) {
|
||||||
orientGraphNoTx.shutdown();
|
orientGraphNoTx.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String getSchema(String type, boolean includeSubtypes)
|
protected String getSchema(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
|
||||||
throws SchemaNotFoundException, SchemaException {
|
|
||||||
OrientGraphNoTx orientGraphNoTx = null;
|
OrientGraphNoTx orientGraphNoTx = null;
|
||||||
try {
|
try {
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
||||||
|
@ -348,29 +321,26 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
List<TypeDefinition> typeDefinitions = new ArrayList<>();
|
List<TypeDefinition> typeDefinitions = new ArrayList<>();
|
||||||
typeDefinitions.add(getTypeDefinition(baseOClass));
|
typeDefinitions.add(getTypeDefinition(baseOClass));
|
||||||
|
|
||||||
if(includeSubtypes){
|
if(includeSubtypes) {
|
||||||
Collection<OClass> subClasses = baseOClass.getAllSubclasses();
|
Collection<OClass> subClasses = baseOClass.getAllSubclasses();
|
||||||
for (OClass oClass : subClasses) {
|
for(OClass oClass : subClasses) {
|
||||||
typeDefinitions.add(getTypeDefinition(oClass));
|
typeDefinitions.add(getTypeDefinition(oClass));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Collection<OClass> oClasses = oSchema.getClasses();
|
* Collection<OClass> oClasses = oSchema.getClasses(); for (OClass oClass :
|
||||||
for (OClass oClass : oClasses) {
|
* oClasses) { if (oClass.isSubClassOf(baseOClass)) {
|
||||||
if (oClass.isSubClassOf(baseOClass)) {
|
* typeDefinitions.add(getTypeDefinition(oClass)); } }
|
||||||
typeDefinitions.add(getTypeDefinition(oClass));
|
*/
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
return TypeBinder.serializeTypeDefinitions(typeDefinitions);
|
return TypeBinder.serializeTypeDefinitions(typeDefinitions);
|
||||||
} catch (SchemaException e) {
|
} catch(SchemaException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new SchemaException(e);
|
throw new SchemaException(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraphNoTx != null) {
|
if(orientGraphNoTx != null) {
|
||||||
orientGraphNoTx.shutdown();
|
orientGraphNoTx.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -378,26 +348,23 @@ public class SchemaManagementImpl implements SchemaManagement {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String create(String jsonSchema, AccessType accessType)
|
public String create(String jsonSchema, AccessType accessType) throws SchemaException {
|
||||||
throws SchemaException {
|
|
||||||
return registerTypeSchema(jsonSchema, accessType);
|
return registerTypeSchema(jsonSchema, accessType);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String read(String entityType, boolean includeSubtypes)
|
public String read(String entityType, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
|
||||||
throws SchemaNotFoundException, SchemaException {
|
|
||||||
return getSchema(entityType, includeSubtypes);
|
return getSchema(entityType, includeSubtypes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String update(String entityType, AccessType accessType,
|
public String update(String entityType, AccessType accessType, String jsonSchema)
|
||||||
String jsonSchema) throws SchemaNotFoundException, SchemaException {
|
throws SchemaNotFoundException, SchemaException {
|
||||||
throw new UnsupportedOperationException("Not Yet implemented");
|
throw new UnsupportedOperationException("Not Yet implemented");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String delete(String entityType, AccessType accessType)
|
public String delete(String entityType, AccessType accessType) throws SchemaNotFoundException {
|
||||||
throws SchemaNotFoundException {
|
|
||||||
throw new UnsupportedOperationException("Not Yet implemented");
|
throw new UnsupportedOperationException("Not Yet implemented");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.utils;
|
package org.gcube.informationsystem.resourceregistry.utils;
|
||||||
|
|
||||||
import java.util.Date;
|
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 class HeaderOrient extends ODocument implements org.gcube.informationsystem.model.embedded.Header {
|
||||||
|
|
||||||
public HeaderOrient(){
|
public HeaderOrient() {
|
||||||
super(Header.NAME);
|
super(Header.NAME);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected HeaderOrient(String iClassName){
|
protected HeaderOrient(String iClassName) {
|
||||||
super(iClassName);
|
super(iClassName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -29,7 +26,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setUUID(UUID uuid){
|
public void setUUID(UUID uuid) {
|
||||||
this.field(Header.UUID_PROPERTY, uuid.toString());
|
this.field(Header.UUID_PROPERTY, uuid.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -38,7 +35,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
|
||||||
return this.field(Header.CREATOR_PROPERTY);
|
return this.field(Header.CREATOR_PROPERTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCreator(String creator){
|
public void setCreator(String creator) {
|
||||||
this.field(Header.CREATOR_PROPERTY, creator);
|
this.field(Header.CREATOR_PROPERTY, creator);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -47,7 +44,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
|
||||||
return this.field(Header.CREATION_TIME_PROPERTY);
|
return this.field(Header.CREATION_TIME_PROPERTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCreationTime(Date creationTime){
|
public void setCreationTime(Date creationTime) {
|
||||||
this.field(Header.CREATION_TIME_PROPERTY, creationTime);
|
this.field(Header.CREATION_TIME_PROPERTY, creationTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -56,7 +53,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
|
||||||
return this.field(Header.MODIFIED_BY_PROPERTY);
|
return this.field(Header.MODIFIED_BY_PROPERTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setModifiedBy(String modifiedBy){
|
public void setModifiedBy(String modifiedBy) {
|
||||||
this.field(Header.MODIFIED_BY_PROPERTY, modifiedBy);
|
this.field(Header.MODIFIED_BY_PROPERTY, modifiedBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -65,7 +62,7 @@ public class HeaderOrient extends ODocument implements org.gcube.informationsyst
|
||||||
return this.field(Header.LAST_UPDATE_TIME_PROPERTY);
|
return this.field(Header.LAST_UPDATE_TIME_PROPERTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLastUpdateTime(Date lastUpdateTime){
|
public void setLastUpdateTime(Date lastUpdateTime) {
|
||||||
this.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
|
this.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.utils;
|
package org.gcube.informationsystem.resourceregistry.utils;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
@ -38,16 +35,16 @@ public class HeaderUtility {
|
||||||
String user = org.gcube.informationsystem.model.embedded.Header.UNKNOWN_USER;
|
String user = org.gcube.informationsystem.model.embedded.Header.UNKNOWN_USER;
|
||||||
try {
|
try {
|
||||||
Caller caller = AuthorizationProvider.instance.get();
|
Caller caller = AuthorizationProvider.instance.get();
|
||||||
if (caller != null) {
|
if(caller != null) {
|
||||||
ClientInfo clientInfo = caller.getClient();
|
ClientInfo clientInfo = caller.getClient();
|
||||||
String clientId = clientInfo.getId();
|
String clientId = clientInfo.getId();
|
||||||
if (clientId != null && clientId.compareTo("") != 0) {
|
if(clientId != null && clientId.compareTo("") != 0) {
|
||||||
user = clientId;
|
user = clientId;
|
||||||
} else {
|
} else {
|
||||||
throw new Exception("Username null or empty");
|
throw new Exception("Username null or empty");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to retrieve user. {} will be used", user);
|
logger.error("Unable to retrieve user. {} will be used", user);
|
||||||
}
|
}
|
||||||
return user;
|
return user;
|
||||||
|
@ -56,7 +53,7 @@ public class HeaderUtility {
|
||||||
public static Header createHeader(UUID uuid) {
|
public static Header createHeader(UUID uuid) {
|
||||||
HeaderOrient header = new HeaderOrient();
|
HeaderOrient header = new HeaderOrient();
|
||||||
|
|
||||||
if (uuid == null) {
|
if(uuid == null) {
|
||||||
uuid = UUID.randomUUID();
|
uuid = UUID.randomUUID();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -78,13 +75,13 @@ public class HeaderUtility {
|
||||||
|
|
||||||
public static Header getHeader(JsonNode jsonNode, boolean creation)
|
public static Header getHeader(JsonNode jsonNode, boolean creation)
|
||||||
throws JsonParseException, JsonMappingException, IOException {
|
throws JsonParseException, JsonMappingException, IOException {
|
||||||
if (jsonNode.has(Resource.HEADER_PROPERTY)) {
|
if(jsonNode.has(Resource.HEADER_PROPERTY)) {
|
||||||
JsonNode headerNode = jsonNode.get(Resource.HEADER_PROPERTY);
|
JsonNode headerNode = jsonNode.get(Resource.HEADER_PROPERTY);
|
||||||
if (headerNode.isNull()) {
|
if(headerNode.isNull()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
HeaderOrient header = null;
|
HeaderOrient header = null;
|
||||||
if (creation) {
|
if(creation) {
|
||||||
// If an header is provided MUST contains and UUID otherwise is
|
// If an header is provided MUST contains and UUID otherwise is
|
||||||
// an invalid request so that let that an exception is raised
|
// an invalid request so that let that an exception is raised
|
||||||
UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText());
|
UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText());
|
||||||
|
@ -99,7 +96,7 @@ public class HeaderUtility {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException {
|
public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException {
|
||||||
if (oDocument instanceof HeaderOrient) {
|
if(oDocument instanceof HeaderOrient) {
|
||||||
return (HeaderOrient) oDocument;
|
return (HeaderOrient) oDocument;
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
|
@ -111,7 +108,7 @@ public class HeaderUtility {
|
||||||
headerOrient.setModifiedBy(header.getModifiedBy());
|
headerOrient.setModifiedBy(header.getModifiedBy());
|
||||||
headerOrient.setLastUpdateTime(header.getLastUpdateTime());
|
headerOrient.setLastUpdateTime(header.getLastUpdateTime());
|
||||||
return headerOrient;
|
return headerOrient;
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
"Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
"Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.utils;
|
package org.gcube.informationsystem.resourceregistry.utils;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
@ -17,9 +14,9 @@ import org.gcube.informationsystem.model.entity.Entity;
|
||||||
import org.gcube.informationsystem.model.relation.Relation;
|
import org.gcube.informationsystem.model.relation.Relation;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.AdminSecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -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 final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
|
||||||
|
|
||||||
public static JSONObject toJsonObject(OrientElement element, boolean raw)
|
public static JSONObject toJsonObject(OrientElement element, boolean raw) throws ResourceRegistryException {
|
||||||
throws ResourceRegistryException {
|
|
||||||
try {
|
try {
|
||||||
return new JSONObject(toJsonString(element, raw));
|
return new JSONObject(toJsonString(element, raw));
|
||||||
}catch(Exception e){
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -60,38 +56,34 @@ public class Utility {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJsonString(ORecord oRecord, boolean raw) {
|
public static String toJsonString(ORecord oRecord, boolean raw) {
|
||||||
if (raw) {
|
if(raw) {
|
||||||
return oRecord.toJSON();
|
return oRecord.toJSON();
|
||||||
}
|
}
|
||||||
return oRecord.toJSON("class");
|
return oRecord.toJSON("class");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static JSONObject toJsonObject(Element element, boolean raw)
|
public static JSONObject toJsonObject(Element element, boolean raw) throws JSONException {
|
||||||
throws JSONException {
|
if(raw) {
|
||||||
if (raw) {
|
return GraphSONUtility.jsonFromElement(element, element.getPropertyKeys(), GraphSONMode.EXTENDED);
|
||||||
return GraphSONUtility.jsonFromElement(element,
|
|
||||||
element.getPropertyKeys(), GraphSONMode.EXTENDED);
|
|
||||||
} else {
|
} else {
|
||||||
Set<String> keys = new HashSet<>(element.getPropertyKeys());
|
Set<String> keys = new HashSet<>(element.getPropertyKeys());
|
||||||
for (String key : element.getPropertyKeys()) {
|
for(String key : element.getPropertyKeys()) {
|
||||||
if (key.startsWith("_")) {
|
if(key.startsWith("_")) {
|
||||||
keys.remove(key);
|
keys.remove(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return GraphSONUtility.jsonFromElement(element, keys,
|
return GraphSONUtility.jsonFromElement(element, keys, GraphSONMode.EXTENDED);
|
||||||
GraphSONMode.EXTENDED);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String toJsonString(Element element, boolean raw) {
|
public static String toJsonString(Element element, boolean raw) {
|
||||||
try {
|
try {
|
||||||
return toJsonObject(element, true).toString();
|
return toJsonObject(element, true).toString();
|
||||||
} catch (Exception e) {
|
} catch(Exception e) {
|
||||||
return String.valueOf(element);
|
return String.valueOf(element);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static <El extends Element> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
|
public static <El extends Element> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
|
||||||
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
|
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
|
||||||
OrientGraphNoTx orientGraphNoTx = null;
|
OrientGraphNoTx orientGraphNoTx = null;
|
||||||
|
@ -100,36 +92,33 @@ public class Utility {
|
||||||
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
|
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
|
||||||
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz);
|
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz);
|
||||||
} finally {
|
} finally {
|
||||||
if (orientGraphNoTx != null) {
|
if(orientGraphNoTx != null) {
|
||||||
orientGraphNoTx.shutdown();
|
orientGraphNoTx.shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <El extends Element> El getElementByUUID(
|
public static <El extends Element> El getElementByUUID(Graph graph, String elementType, UUID uuid,
|
||||||
Graph graph, String elementType, UUID uuid,
|
|
||||||
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
|
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
|
||||||
|
|
||||||
if (elementType == null || elementType.compareTo("") == 0) {
|
if(elementType == null || elementType.compareTo("") == 0) {
|
||||||
if (Vertex.class.isAssignableFrom(clz)) {
|
if(Vertex.class.isAssignableFrom(clz)) {
|
||||||
elementType = Entity.NAME;
|
elementType = Entity.NAME;
|
||||||
}
|
}
|
||||||
if (Edge.class.isAssignableFrom(clz)) {
|
if(Edge.class.isAssignableFrom(clz)) {
|
||||||
elementType = Relation.NAME;
|
elementType = Relation.NAME;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO Rewrite using Gremlin
|
// TODO Rewrite using Gremlin
|
||||||
String select = "SELECT FROM " + elementType + " WHERE "
|
String select = "SELECT FROM " + elementType + " WHERE " + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
|
||||||
+ Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
|
|
||||||
+ " = \"" + uuid.toString() + "\"";
|
+ " = \"" + uuid.toString() + "\"";
|
||||||
|
|
||||||
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
|
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
|
||||||
|
|
||||||
Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute();
|
Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute();
|
||||||
if (elements == null || !elements.iterator().hasNext()) {
|
if(elements == null || !elements.iterator().hasNext()) {
|
||||||
String error = String.format("No %s with UUID %s was found",
|
String error = String.format("No %s with UUID %s was found", elementType, uuid.toString());
|
||||||
elementType, uuid.toString());
|
|
||||||
logger.info(error);
|
logger.info(error);
|
||||||
throw new ERNotFoundException(error);
|
throw new ERNotFoundException(error);
|
||||||
}
|
}
|
||||||
|
@ -137,37 +126,32 @@ public class Utility {
|
||||||
Iterator<El> iterator = elements.iterator();
|
Iterator<El> iterator = elements.iterator();
|
||||||
El element = iterator.next();
|
El element = iterator.next();
|
||||||
|
|
||||||
logger.trace("{} with {} is : {}", elementType, uuid.toString(),
|
logger.trace("{} with {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true));
|
||||||
Utility.toJsonString(element, true));
|
|
||||||
|
|
||||||
if (iterator.hasNext()) {
|
if(iterator.hasNext()) {
|
||||||
throw new ResourceRegistryException("Found more than one "
|
throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
|
||||||
+ elementType + " with uuid " + uuid.toString()
|
|
||||||
+ ". This is a fatal error please contact Admnistrator");
|
+ ". This is a fatal error please contact Admnistrator");
|
||||||
}
|
}
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static <E extends Embedded> E getEmbedded(Class<E> clz, Element element, String property)
|
public static <E extends Embedded> E getEmbedded(Class<E> clz, Element element, String property)
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
ODocument oDocument = element.getProperty(property);
|
ODocument oDocument = element.getProperty(property);
|
||||||
E e = ISMapper.unmarshal(clz, oDocument.toJSON());
|
E e = ISMapper.unmarshal(clz, oDocument.toJSON());
|
||||||
return e;
|
return e;
|
||||||
} catch (Exception ex) {
|
} catch(Exception ex) {
|
||||||
String error = String.format("Error while getting %s from %s",
|
String error = String.format("Error while getting %s from %s", property, toJsonString(element, true));
|
||||||
property, toJsonString(element, true));
|
|
||||||
throw new ResourceRegistryException(error, ex);
|
throw new ResourceRegistryException(error, ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static UUID getUUID(Element element)
|
public static UUID getUUID(Element element) throws ResourceRegistryException {
|
||||||
throws ResourceRegistryException {
|
|
||||||
/*
|
/*
|
||||||
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY);
|
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String
|
||||||
* String contextID = header.field(Header.UUID_PROPERTY); return
|
* contextID = header.field(Header.UUID_PROPERTY); return
|
||||||
* UUID.fromString(contextID);
|
* UUID.fromString(contextID);
|
||||||
*/
|
*/
|
||||||
Header header = HeaderUtility.getHeader(element);
|
Header header = HeaderUtility.getHeader(element);
|
||||||
|
|
|
@ -30,6 +30,9 @@ public class ScopedTest {
|
||||||
|
|
||||||
protected static final String PROPERTIES_FILENAME = "token.properties";
|
protected static final String PROPERTIES_FILENAME = "token.properties";
|
||||||
|
|
||||||
|
private static final String GCUBE_VARNAME = "GCUBE";
|
||||||
|
public static final String GCUBE;
|
||||||
|
|
||||||
private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT";
|
private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT";
|
||||||
public static final String GCUBE_DEVNEXT;
|
public static final String GCUBE_DEVNEXT;
|
||||||
|
|
||||||
|
@ -47,6 +50,7 @@ public class ScopedTest {
|
||||||
public static final String GCUBE_DEVNEXT_ANOTHER_USER;
|
public static final String GCUBE_DEVNEXT_ANOTHER_USER;
|
||||||
|
|
||||||
public static final String DEFAULT_TEST_SCOPE;
|
public static final String DEFAULT_TEST_SCOPE;
|
||||||
|
public static final String PARENT_DEFAULT_TEST_SCOPE;
|
||||||
public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER;
|
public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER;
|
||||||
public static final String ALTERNATIVE_TEST_SCOPE;
|
public static final String ALTERNATIVE_TEST_SCOPE;
|
||||||
|
|
||||||
|
@ -61,6 +65,8 @@ public class ScopedTest {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
GCUBE = properties.getProperty(GCUBE_VARNAME);
|
||||||
|
|
||||||
GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME);
|
GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME);
|
||||||
GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME);
|
GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME);
|
||||||
|
|
||||||
|
@ -71,8 +77,11 @@ public class ScopedTest {
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT;
|
DEFAULT_TEST_SCOPE = GCUBE_DEVNEXT;
|
||||||
|
PARENT_DEFAULT_TEST_SCOPE = GCUBE;
|
||||||
|
|
||||||
DEFAULT_TEST_SCOPE_ANOTHER_USER = GCUBE_DEVNEXT_ANOTHER_USER;
|
DEFAULT_TEST_SCOPE_ANOTHER_USER = GCUBE_DEVNEXT_ANOTHER_USER;
|
||||||
ALTERNATIVE_TEST_SCOPE = GCUBE_DEVNEXT_NEXTNEXT;
|
ALTERNATIVE_TEST_SCOPE = GCUBE_DEVNEXT_NEXTNEXT;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getCurrentScope(String token) throws ObjectNotFound, Exception{
|
public static String getCurrentScope(String token) throws ObjectNotFound, Exception{
|
||||||
|
|
|
@ -16,8 +16,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.context.security.ContextSecurityContext;
|
||||||
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.SecurityType;
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.PermissionMode;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.security.SecurityContext.SecurityType;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest;
|
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
@ -69,7 +71,8 @@ public class ContextManagementTest extends ScopedTest {
|
||||||
public static final String CTX_NAME_B = "B";
|
public static final String CTX_NAME_B = "B";
|
||||||
public static final String CTX_NAME_C = "C";
|
public static final String CTX_NAME_C = "C";
|
||||||
|
|
||||||
protected void assertions(Context pre, Context post, boolean checkParent, boolean create) throws ResourceRegistryException {
|
protected void assertions(Context pre, Context post, boolean checkParent, boolean create)
|
||||||
|
throws ResourceRegistryException {
|
||||||
if (checkParent) {
|
if (checkParent) {
|
||||||
if (pre.getHeader() != null) {
|
if (pre.getHeader() != null) {
|
||||||
FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create);
|
FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create);
|
||||||
|
@ -89,28 +92,30 @@ public class ContextManagementTest extends ScopedTest {
|
||||||
|
|
||||||
protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException {
|
protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException {
|
||||||
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
|
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
|
||||||
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
|
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(),
|
||||||
|
contextSecurityContext);
|
||||||
|
|
||||||
OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER);
|
OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER);
|
||||||
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
|
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
|
||||||
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
|
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
|
||||||
|
|
||||||
SecurityContext securityContext = new SecurityContext(uuid);
|
SecurityContext securityContext = new SecurityContext(uuid);
|
||||||
for(PermissionMode permissionMode : PermissionMode.values()) {
|
|
||||||
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, false);
|
|
||||||
ORole oRole = oSecurity.getRole(role);
|
|
||||||
Assert.assertEquals(oRole==null, deleted);
|
|
||||||
|
|
||||||
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false);
|
boolean[] booleanArray = new boolean[] { false, true };
|
||||||
OUser oUser = oSecurity.getUser(user);
|
for (boolean hierarchic : booleanArray) {
|
||||||
Assert.assertEquals(oUser==null, deleted);
|
for (PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
|
||||||
|
ORole oRole = oSecurity.getRole(role);
|
||||||
|
Assert.assertEquals(oRole == null, deleted);
|
||||||
|
|
||||||
|
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
|
||||||
|
OUser oUser = oSecurity.getUser(user);
|
||||||
|
Assert.assertEquals(oUser == null, deleted);
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
|
protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setUUID(uuid);
|
contextManagement.setUUID(uuid);
|
||||||
|
@ -373,7 +378,7 @@ public class ContextManagementTest extends ScopedTest {
|
||||||
String all = contextManagement.all(false);
|
String all = contextManagement.all(false);
|
||||||
logger.trace(all);
|
logger.trace(all);
|
||||||
List<Context> contexts = ISMapper.unmarshalList(Context.class, all);
|
List<Context> contexts = ISMapper.unmarshalList(Context.class, all);
|
||||||
for(Context context : contexts){
|
for (Context context : contexts) {
|
||||||
logger.trace(ISMapper.marshal(context));
|
logger.trace(ISMapper.marshal(context));
|
||||||
List<IsParentOf<Context, Context>> children = context.getChildren();
|
List<IsParentOf<Context, Context>> children = context.getChildren();
|
||||||
for (IsParentOf<Context, Context> child : children) {
|
for (IsParentOf<Context, Context> child : children) {
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
|
@ -5,10 +5,14 @@ import java.util.UUID;
|
||||||
import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl;
|
import org.gcube.informationsystem.impl.entity.facet.SoftwareFacetImpl;
|
||||||
import org.gcube.informationsystem.impl.utils.ISMapper;
|
import org.gcube.informationsystem.impl.utils.ISMapper;
|
||||||
import org.gcube.informationsystem.model.ER;
|
import org.gcube.informationsystem.model.ER;
|
||||||
|
import org.gcube.informationsystem.model.entity.Facet;
|
||||||
import org.gcube.informationsystem.model.entity.facet.SoftwareFacet;
|
import org.gcube.informationsystem.model.entity.facet.SoftwareFacet;
|
||||||
import org.gcube.informationsystem.resourceregistry.ScopedTest;
|
import org.gcube.informationsystem.resourceregistry.ScopedTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAlreadyPresentException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.utils.Utility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.ERManagementTest;
|
import org.gcube.informationsystem.resourceregistry.er.ERManagementTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
|
@ -16,6 +20,9 @@ import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class FacetManagementTest extends ScopedTest {
|
public class FacetManagementTest extends ScopedTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
|
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
|
||||||
|
@ -33,134 +40,276 @@ public class FacetManagementTest extends ScopedTest {
|
||||||
return softwareFacet;
|
return softwareFacet;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkHeader(ER er, UUID uuid, boolean create) {
|
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, String version) {
|
||||||
Assert.assertTrue(er.getHeader()!=null);
|
Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP) == 0);
|
||||||
Assert.assertTrue(er.getHeader().getUUID()!=null);
|
Assert.assertTrue(softwareFacet.getName().compareTo(NAME) == 0);
|
||||||
|
Assert.assertTrue(softwareFacet.getVersion().compareTo(version) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
if(uuid!=null) {
|
public static void checkHeader(ER er, UUID uuid, boolean create) {
|
||||||
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid)==0);
|
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();
|
String user = HeaderUtility.getUser();
|
||||||
Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user)==0);
|
Assert.assertTrue(er.getHeader().getModifiedBy().compareTo(user) == 0);
|
||||||
|
|
||||||
if(create){
|
if(create) {
|
||||||
Assert.assertTrue(er.getHeader().getCreator().compareTo(user)==0);
|
Assert.assertTrue(er.getHeader().getCreator().compareTo(user) == 0);
|
||||||
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime())==0);
|
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
|
||||||
}else {
|
} else {
|
||||||
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
|
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkAssertion(SoftwareFacet softwareFacet, String version, UUID uuid, boolean create) {
|
public static void checkAssertion(Facet facet, UUID uuid, boolean create) {
|
||||||
checkHeader(softwareFacet, uuid, create);
|
checkHeader(facet, uuid, create);
|
||||||
|
|
||||||
Assert.assertTrue(softwareFacet.getGroup().compareTo(GROUP)==0);
|
|
||||||
Assert.assertTrue(softwareFacet.getName().compareTo(NAME)==0);
|
|
||||||
Assert.assertTrue(softwareFacet.getVersion().compareTo(version)==0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet> F create(F facet) throws Exception {
|
||||||
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
String facetType = Utility.getType(facet);
|
||||||
|
facetManagement.setElementType(facetType);
|
||||||
|
facetManagement.setJSON(ISMapper.marshal(facet));
|
||||||
|
|
||||||
|
String json = facetManagement.create();
|
||||||
|
logger.debug("Created : {}", json);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
F createdFacet = (F) ISMapper.unmarshal(facet.getClass(), json);
|
||||||
|
logger.debug("Unmarshalled {}", createdFacet);
|
||||||
|
|
||||||
|
UUID uuid = null;
|
||||||
|
if(facet.getHeader() != null) {
|
||||||
|
uuid = facet.getHeader().getUUID();
|
||||||
|
}
|
||||||
|
checkAssertion(createdFacet, uuid, true);
|
||||||
|
return createdFacet;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet> F update(F facet) throws Exception {
|
||||||
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
String facetType = Utility.getType(facet);
|
||||||
|
facetManagement.setElementType(facetType);
|
||||||
|
facetManagement.setJSON(ISMapper.marshal(facet));
|
||||||
|
|
||||||
|
String json = facetManagement.update();
|
||||||
|
logger.debug("Updated : {}", json);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
F updatedFacet = (F) ISMapper.unmarshal(facet.getClass(), json);
|
||||||
|
logger.debug("Unmarshalled {}", updatedFacet);
|
||||||
|
|
||||||
|
UUID uuid = facet.getHeader().getUUID();
|
||||||
|
checkAssertion(updatedFacet, uuid, false);
|
||||||
|
|
||||||
|
return updatedFacet;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet> F read(F facet) throws Exception {
|
||||||
|
UUID uuid = facet.getHeader().getUUID();
|
||||||
|
|
||||||
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
String facetType = Utility.getType(facet);
|
||||||
|
facetManagement.setElementType(facetType);
|
||||||
|
facetManagement.setUUID(uuid);
|
||||||
|
|
||||||
|
String json = facetManagement.read();
|
||||||
|
logger.debug("Read : {}", json);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
F readFacet = (F) ISMapper.unmarshal(facet.getClass(), json);
|
||||||
|
logger.debug("Unmarshalled {}", readFacet);
|
||||||
|
|
||||||
|
checkAssertion(readFacet, uuid, false);
|
||||||
|
|
||||||
|
return readFacet;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet> boolean delete(F facet) throws Exception {
|
||||||
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
String facetType = Utility.getType(facet);
|
||||||
|
facetManagement.setElementType(facetType);
|
||||||
|
facetManagement.setUUID(facet.getHeader().getUUID());
|
||||||
|
|
||||||
|
boolean deleted = facetManagement.delete();
|
||||||
|
Assert.assertTrue(deleted);
|
||||||
|
|
||||||
|
try {
|
||||||
|
read(facet);
|
||||||
|
} catch(FacetNotFoundException e) {
|
||||||
|
logger.info("Facet not found as expected");
|
||||||
|
}
|
||||||
|
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet> boolean addToContext(F facet) throws Exception {
|
||||||
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
String facetType = Utility.getType(facet);
|
||||||
|
facetManagement.setElementType(facetType);
|
||||||
|
facetManagement.setUUID(facet.getHeader().getUUID());
|
||||||
|
|
||||||
|
boolean added = facetManagement.addToContext();
|
||||||
|
Assert.assertTrue(added);
|
||||||
|
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet> boolean removeFromContext(F facet) throws Exception {
|
||||||
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
|
String facetType = Utility.getType(facet);
|
||||||
|
facetManagement.setElementType(facetType);
|
||||||
|
facetManagement.setUUID(facet.getHeader().getUUID());
|
||||||
|
|
||||||
|
boolean added = facetManagement.removeFromContext();
|
||||||
|
Assert.assertTrue(added);
|
||||||
|
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ActionFunction<F extends Facet> {
|
||||||
|
void call(F facet) throws Exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <F extends Facet, C extends Exception, E extends Exception> void assertThrow(F facet, Class<C> c,
|
||||||
|
ActionFunction<F> action) throws Exception {
|
||||||
|
try {
|
||||||
|
action.call(facet);
|
||||||
|
throw new RuntimeException("Expected " + c.getName());
|
||||||
|
} catch(Exception e) {
|
||||||
|
if(c.isAssignableFrom(e.getClass())) {
|
||||||
|
logger.debug("As expected {} has been thrown", c.getName());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void createUpdateReadDelete() throws Exception {
|
public void createUpdateReadDelete() throws Exception {
|
||||||
SoftwareFacet softwareFacet = getSoftwareFacet();
|
SoftwareFacet softwareFacet = getSoftwareFacet();
|
||||||
|
|
||||||
|
|
||||||
/* Testing Create */
|
/* Testing Create */
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
softwareFacet = create(softwareFacet);
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
|
|
||||||
|
|
||||||
String json = facetManagement.create();
|
|
||||||
logger.debug("Created : {}", json);
|
|
||||||
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
|
|
||||||
logger.debug("Unmarshalled {}", softwareFacet);
|
|
||||||
|
|
||||||
checkAssertion(softwareFacet, VERSION, null, true);
|
|
||||||
UUID uuid = softwareFacet.getHeader().getUUID();
|
|
||||||
|
|
||||||
/* Testing Update */
|
/* Testing Update */
|
||||||
softwareFacet.setVersion(NEW_VERSION);
|
softwareFacet.setVersion(NEW_VERSION);
|
||||||
|
softwareFacet = update(softwareFacet);
|
||||||
facetManagement = new FacetManagement();
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
|
||||||
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
|
|
||||||
|
|
||||||
json = facetManagement.update();
|
|
||||||
logger.debug("Updated : {}", json);
|
|
||||||
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
|
|
||||||
logger.debug("Unmarshalled {}", softwareFacet);
|
|
||||||
|
|
||||||
checkAssertion(softwareFacet, NEW_VERSION, uuid, false);
|
|
||||||
|
|
||||||
|
|
||||||
/* Testing Read */
|
/* Testing Read */
|
||||||
facetManagement = new FacetManagement();
|
softwareFacet = read(softwareFacet);
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
facetManagement.setUUID(uuid);
|
|
||||||
|
|
||||||
json = facetManagement.read();
|
assertThrow(softwareFacet, FacetAlreadyPresentException.class, (SoftwareFacet s) -> {
|
||||||
logger.debug("Read : {}", json);
|
create(s);
|
||||||
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
|
});
|
||||||
logger.debug("Unmarshalled {}", softwareFacet);
|
|
||||||
|
|
||||||
checkAssertion(softwareFacet, NEW_VERSION, uuid, false);
|
|
||||||
|
|
||||||
|
|
||||||
/* Testing Create the facet with the same UUID */
|
|
||||||
facetManagement = new FacetManagement();
|
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
|
||||||
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
|
|
||||||
|
|
||||||
try {
|
|
||||||
facetManagement.create();
|
|
||||||
}catch (FacetAlreadyPresentException e) {
|
|
||||||
logger.info("Facet already present as expected");
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Testing Delete */
|
/* Testing Delete */
|
||||||
boolean deleted = facetManagement.delete();
|
delete(softwareFacet);
|
||||||
Assert.assertTrue(deleted);
|
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
|
||||||
facetManagement.setUUID(uuid);
|
|
||||||
|
|
||||||
try {
|
|
||||||
facetManagement.read();
|
|
||||||
}catch (FacetNotFoundException e) {
|
|
||||||
logger.info("Facet not found as expected");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/* Testing new Create to check creation with provided UUID */
|
/* Testing new Create to check creation with provided UUID */
|
||||||
facetManagement = new FacetManagement();
|
softwareFacet = create(softwareFacet);
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
facetManagement.setJSON(ISMapper.marshal(softwareFacet));
|
|
||||||
|
|
||||||
json = facetManagement.create();
|
delete(softwareFacet);
|
||||||
logger.debug("Created : {}", json);
|
|
||||||
softwareFacet = ISMapper.unmarshal(SoftwareFacet.class, json);
|
|
||||||
logger.debug("Unmarshalled {}", softwareFacet);
|
|
||||||
|
|
||||||
checkAssertion(softwareFacet, NEW_VERSION, uuid, true);
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHierarchy() throws Exception {
|
||||||
|
/* Setting scope /gcube/devNext/NextNext */
|
||||||
|
ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT);
|
||||||
|
|
||||||
/* Testing Delete */
|
SoftwareFacet softwareFacet = getSoftwareFacet();
|
||||||
deleted = facetManagement.delete();
|
|
||||||
Assert.assertTrue(deleted);
|
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
/* Testing Create */
|
||||||
facetManagement.setElementType(SoftwareFacet.NAME);
|
softwareFacet = create(softwareFacet);
|
||||||
facetManagement.setUUID(uuid);
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
|
|
||||||
try {
|
softwareFacet = update(softwareFacet);
|
||||||
facetManagement.read();
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
}catch (FacetNotFoundException e) {
|
|
||||||
logger.info("Facet not found as expected");
|
/* Testing Read */
|
||||||
}
|
softwareFacet = read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
|
|
||||||
|
/* Setting (parent) scope /gcube/devNext */
|
||||||
|
ScopedTest.setContext(GCUBE_DEVNEXT);
|
||||||
|
|
||||||
|
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
|
||||||
|
read(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* Entering hierarchic mode */
|
||||||
|
ContextUtility.getHierarchicMode().set(true);
|
||||||
|
|
||||||
|
softwareFacet = read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
|
|
||||||
|
/* Setting (parent of parent) scope /gcube */
|
||||||
|
ScopedTest.setContext(GCUBE);
|
||||||
|
|
||||||
|
softwareFacet = read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
|
|
||||||
|
/* Leaving hierarchic mode */
|
||||||
|
ContextUtility.getHierarchicMode().set(false);
|
||||||
|
|
||||||
|
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
|
||||||
|
read(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* Adding to /gcube. The context are now /gcube and /gcube/devNext/NextNext */
|
||||||
|
addToContext(softwareFacet);
|
||||||
|
softwareFacet = read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, VERSION);
|
||||||
|
|
||||||
|
softwareFacet.setVersion(NEW_VERSION);
|
||||||
|
softwareFacet = update(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
|
|
||||||
|
/* Restoring scope /gcube/devNext/NextNext */
|
||||||
|
ScopedTest.setContext(GCUBE_DEVNEXT_NEXTNEXT);
|
||||||
|
read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
|
|
||||||
|
/* Removing from /gcube/devNext/NextNext. The context is now /gcube */
|
||||||
|
removeFromContext(softwareFacet);
|
||||||
|
|
||||||
|
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
|
||||||
|
read(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* Setting (parent) scope /gcube/devNext */
|
||||||
|
ScopedTest.setContext(GCUBE_DEVNEXT);
|
||||||
|
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
|
||||||
|
read(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* Entering hierarchic mode */
|
||||||
|
ContextUtility.getHierarchicMode().set(true);
|
||||||
|
|
||||||
|
assertThrow(softwareFacet, FacetAvailableInAnotherContextException.class, (SoftwareFacet s) -> {
|
||||||
|
read(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* Setting (parent of parent) scope /gcube */
|
||||||
|
ScopedTest.setContext(GCUBE);
|
||||||
|
// The facet must be readable in hierarchic mode in /gcube because the context
|
||||||
|
// has been explicitly added
|
||||||
|
read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
|
|
||||||
|
/* Leaving hierarchic mode */
|
||||||
|
ContextUtility.getHierarchicMode().set(false);
|
||||||
|
|
||||||
|
read(softwareFacet);
|
||||||
|
checkSoftwareFacetAssertion(softwareFacet, NEW_VERSION);
|
||||||
|
|
||||||
|
delete(softwareFacet);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,12 +27,11 @@ public class ResourceManagementTest extends ScopedTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ResourceManagementTest.class);
|
private static Logger logger = LoggerFactory.getLogger(ResourceManagementTest.class);
|
||||||
|
|
||||||
public static void checkAssertion(EService eService, String version, UUID eServiceUUID, boolean create) {
|
public static void checkAssertion(EService eService, UUID eServiceUUID, boolean create) {
|
||||||
FacetManagementTest.checkHeader(eService, eServiceUUID, create);
|
FacetManagementTest.checkHeader(eService, eServiceUUID, create);
|
||||||
|
|
||||||
SoftwareFacet softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
|
SoftwareFacet softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
|
||||||
FacetManagementTest.checkAssertion(softwareFacet, version, null, create);
|
FacetManagementTest.checkAssertion(softwareFacet, null, create);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -55,7 +54,8 @@ public class ResourceManagementTest extends ScopedTest {
|
||||||
logger.trace("Created {}", json);
|
logger.trace("Created {}", json);
|
||||||
eService = ISMapper.unmarshal(EService.class, json);
|
eService = ISMapper.unmarshal(EService.class, json);
|
||||||
|
|
||||||
checkAssertion(eService, FacetManagementTest.VERSION, null, true);
|
checkAssertion(eService, null, true);
|
||||||
|
FacetManagementTest.checkSoftwareFacetAssertion(softwareFacet, FacetManagementTest.VERSION);
|
||||||
|
|
||||||
UUID uuid = eService.getHeader().getUUID();
|
UUID uuid = eService.getHeader().getUUID();
|
||||||
softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
|
softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
|
||||||
|
@ -72,7 +72,9 @@ public class ResourceManagementTest extends ScopedTest {
|
||||||
logger.trace("Updated {}", json);
|
logger.trace("Updated {}", json);
|
||||||
eService = ISMapper.unmarshal(EService.class, json);
|
eService = ISMapper.unmarshal(EService.class, json);
|
||||||
|
|
||||||
checkAssertion(eService, FacetManagementTest.NEW_VERSION, uuid, false);
|
checkAssertion(eService, uuid, false);
|
||||||
|
softwareFacet = eService.getFacets(SoftwareFacet.class).get(0);
|
||||||
|
FacetManagementTest.checkSoftwareFacetAssertion(softwareFacet, FacetManagementTest.NEW_VERSION);
|
||||||
|
|
||||||
|
|
||||||
resourceManagement = new ResourceManagement();
|
resourceManagement = new ResourceManagement();
|
||||||
|
|
|
@ -8,7 +8,6 @@ import java.net.URL;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.codehaus.jettison.json.JSONObject;
|
|
||||||
import org.gcube.informationsystem.impl.embedded.PropagationConstraintImpl;
|
import org.gcube.informationsystem.impl.embedded.PropagationConstraintImpl;
|
||||||
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
|
import org.gcube.informationsystem.impl.entity.facet.AccessPointFacetImpl;
|
||||||
import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl;
|
import org.gcube.informationsystem.impl.entity.facet.CPUFacetImpl;
|
||||||
|
@ -25,11 +24,9 @@ import org.gcube.informationsystem.impl.relation.consistsof.HasPersistentMemoryI
|
||||||
import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl;
|
import org.gcube.informationsystem.impl.relation.consistsof.HasVolatileMemoryImpl;
|
||||||
import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl;
|
import org.gcube.informationsystem.impl.relation.isrelatedto.HostsImpl;
|
||||||
import org.gcube.informationsystem.impl.utils.ISMapper;
|
import org.gcube.informationsystem.impl.utils.ISMapper;
|
||||||
import org.gcube.informationsystem.model.embedded.Header;
|
|
||||||
import org.gcube.informationsystem.model.embedded.PropagationConstraint;
|
import org.gcube.informationsystem.model.embedded.PropagationConstraint;
|
||||||
import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint;
|
import org.gcube.informationsystem.model.embedded.PropagationConstraint.AddConstraint;
|
||||||
import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint;
|
import org.gcube.informationsystem.model.embedded.PropagationConstraint.RemoveConstraint;
|
||||||
import org.gcube.informationsystem.model.entity.Entity;
|
|
||||||
import org.gcube.informationsystem.model.entity.Facet;
|
import org.gcube.informationsystem.model.entity.Facet;
|
||||||
import org.gcube.informationsystem.model.entity.facet.AccessPointFacet;
|
import org.gcube.informationsystem.model.entity.facet.AccessPointFacet;
|
||||||
import org.gcube.informationsystem.model.entity.facet.CPUFacet;
|
import org.gcube.informationsystem.model.entity.facet.CPUFacet;
|
||||||
|
@ -53,6 +50,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.SmartgearResourcesTest;
|
import org.gcube.informationsystem.resourceregistry.er.SmartgearResourcesTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
|
||||||
|
@ -85,9 +83,8 @@ public class BasicTest extends ScopedTest {
|
||||||
String json = facetManagement.create();
|
String json = facetManagement.create();
|
||||||
logger.debug("Created : {}", json);
|
logger.debug("Created : {}", json);
|
||||||
|
|
||||||
JSONObject jsonObject = new JSONObject(json);
|
CPUFacet createdCPUFacet = ISMapper.unmarshal(CPUFacet.class, json);
|
||||||
JSONObject header = jsonObject.getJSONObject(Entity.HEADER_PROPERTY);
|
UUID uuid = createdCPUFacet.getHeader().getUUID();
|
||||||
UUID uuid = UUID.fromString(header.getString(Header.UUID_PROPERTY));
|
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
facetManagement = new FacetManagement();
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
|
@ -98,7 +95,7 @@ public class BasicTest extends ScopedTest {
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
logger.debug("Switching to another scope");
|
logger.debug("Switching to another scope");
|
||||||
ScopedTest.setContext(ScopedTest.ALTERNATIVE_TEST_SCOPE);
|
ScopedTest.setContext(ScopedTest.PARENT_DEFAULT_TEST_SCOPE);
|
||||||
try {
|
try {
|
||||||
facetManagement = new FacetManagement();
|
facetManagement = new FacetManagement();
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
|
@ -111,6 +108,19 @@ public class BasicTest extends ScopedTest {
|
||||||
logger.debug("Good the facet created in the default context is not visible in an alternative context");
|
logger.debug("Good the facet created in the default context is not visible in an alternative context");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------------- entering hierarchic mode */
|
||||||
|
|
||||||
|
ContextUtility.getHierarchicMode().set(true);
|
||||||
|
|
||||||
|
facetManagement = new FacetManagement();
|
||||||
|
facetManagement.setUUID(uuid);
|
||||||
|
readJson = facetManagement.read();
|
||||||
|
logger.debug("You should be able to read it {}", readJson);
|
||||||
|
|
||||||
|
ContextUtility.getHierarchicMode().set(false);
|
||||||
|
|
||||||
|
/* ---------------- leaving hierarchic mode */
|
||||||
|
|
||||||
cpuFacet.setAdditionalProperty("My", "Test");
|
cpuFacet.setAdditionalProperty("My", "Test");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
@ -126,20 +136,6 @@ public class BasicTest extends ScopedTest {
|
||||||
logger.debug("Good the Facet created in the default context cannot be updated in an alternative context");
|
logger.debug("Good the Facet created in the default context cannot be updated in an alternative context");
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Commented because the behavior has been changed
|
|
||||||
try {
|
|
||||||
facetManagement = new FacetManagement();
|
|
||||||
facetManagement.setUUID(uuid);
|
|
||||||
facetManagement.delete();
|
|
||||||
logger.debug("You should not be able to delete Facet with UUID {}",
|
|
||||||
uuid);
|
|
||||||
throw new Exception(
|
|
||||||
"You should not be able to delete Facet with UUID " + uuid);
|
|
||||||
} catch (FacetAvailableInAnotherContextException e) {
|
|
||||||
logger.debug("Good the Facet created in the default context cannot be deleted in an alternative context");
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
logger.debug("Setting back default scope");
|
logger.debug("Setting back default scope");
|
||||||
|
@ -158,6 +154,7 @@ public class BasicTest extends ScopedTest {
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
facetManagement = new FacetManagement();
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
|
|
||||||
boolean deleted = facetManagement.delete();
|
boolean deleted = facetManagement.delete();
|
||||||
Assert.assertTrue(deleted);
|
Assert.assertTrue(deleted);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue