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@158879 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2017-11-28 16:34:43 +00:00
parent d79b91361e
commit f754bf7dda
29 changed files with 1185 additions and 1239 deletions

View File

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

View File

@ -18,6 +18,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
@ -39,11 +40,8 @@ public class ContextManagement extends EntityManagement<Context> {
protected String name;
private void init() {
this.forceAdmin = true;
this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY);
this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY);
this.erType = Context.NAME;
}
@ -52,9 +50,10 @@ public class ContextManagement extends EntityManagement<Context> {
init();
}
public ContextManagement(OrientGraph orientGraph) {
super(AccessType.CONTEXT, orientGraph);
init();
public ContextManagement(OrientGraph orientGraph) throws ResourceRegistryException {
this();
this.orientGraph = orientGraph;
getWorkingContext();
}
public String getName() {
@ -70,6 +69,13 @@ public class ContextManagement extends EntityManagement<Context> {
return name;
}
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
return workingContext;
}
@Override
protected ContextNotFoundException getSpecificElementNotFoundException(ERNotFoundException e) {
return new ContextNotFoundException(e.getMessage(), e.getCause());
@ -190,6 +196,8 @@ public class ContextManagement extends EntityManagement<Context> {
@Override
protected Vertex reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null;
try {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
@ -203,7 +211,6 @@ public class ContextManagement extends EntityManagement<Context> {
if(uuid==null){
uuid = UUID.randomUUID();
}
SecurityContext.createSecurityContext(orientGraph, uuid, true);
createVertex();
@ -216,14 +223,18 @@ public class ContextManagement extends EntityManagement<Context> {
}else {
checkContext(null);
SecurityContext.createSecurityContext(orientGraph, uuid, true);
createVertex();
}
securityContext = new SecurityContext(uuid);
securityContext.create(orientGraph);
return getElement();
}catch (Exception e) {
orientGraph.rollback();
SecurityContext.deleteSecurityContext(orientGraph, uuid, true);
if(securityContext!=null) {
securityContext.delete(orientGraph);
}
throw e;
}
}
@ -303,7 +314,7 @@ public class ContextManagement extends EntityManagement<Context> {
element = (Vertex) ERManagement.updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ContextUtility.invalidContextUUIDCache(uuid);
ContextUtility.getInstace().removeFromCache(uuid);
return element;
}
@ -351,8 +362,11 @@ public class ContextManagement extends EntityManagement<Context> {
element.remove();
ContextUtility.invalidContextUUIDCache(uuid);
SecurityContext.deleteSecurityContext(orientGraph, uuid, false);
ContextUtility contextUtility = ContextUtility.getInstace();
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(orientGraph);
contextUtility.removeFromCache(uuid);
return true;

View File

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

View File

@ -6,6 +6,7 @@ package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import org.gcube.common.authorization.client.Constants;
@ -14,21 +15,19 @@ import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
/**
* @author Luca Frosini (ISTI - CNR)
@ -36,60 +35,26 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
*/
public class ContextUtility {
private static final Logger logger = LoggerFactory
.getLogger(ContextUtility.class);
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
private static Map<String, UUID> contextUUIDCache;
private Map<String, UUID> contextUUIDs;
private Map<UUID, SecurityContext> contexts;
static {
contextUUIDCache = new HashMap<>();
private static ContextUtility contextUtility;
public static ContextUtility getInstace() {
if (contextUtility == null) {
contextUtility = new ContextUtility();
}
return contextUtility;
}
protected static void invalidContextUUIDCache(){
contextUUIDCache = new HashMap<>();
private ContextUtility() {
contextUUIDs = new HashMap<>();
contexts = new HashMap<>();
}
protected static void invalidContextUUIDCache(UUID uuid){
for(String scope : contextUUIDCache.keySet()){
UUID gotUUID = contextUUIDCache.get(scope);
if(gotUUID.compareTo(uuid)==0){
contextUUIDCache.remove(scope);
return;
}
}
}
public static UUID addToActualContext(OrientGraph orientGraph, Element element)
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.addToSecurityContext(orientGraph, element, contextUUID);
return contextUUID;
}
public static UUID addToActualContex(OSecurity oSecurity, Element element)
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.addToSecurityContext(oSecurity, element, contextUUID);
return contextUUID;
}
public static UUID removeFromActualContext(OrientGraph orientGraph, Element element)
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.removeFromSecurityContext(orientGraph, element, contextUUID);
return contextUUID;
}
public static UUID removeFromActualContext(OSecurity oSecurity, Element element)
throws ContextException {
UUID contextUUID = ContextUtility.getActualContextUUID();
SecurityContext.removeFromSecurityContext(oSecurity, element, contextUUID);
return contextUUID;
}
public static String getCurrentContext(){
private static String getCurrentContextFullName() {
String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null;
try {
@ -100,99 +65,105 @@ public class ContextUtility {
return authorizationEntry.getContext();
}
public static UUID getActualContextUUID() throws ContextException {
OrientGraph orientGraph = null;
try {
String scope = getCurrentContext();
if(scope==null){
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
String fullName = getCurrentContextFullName();
if (fullName == null) {
throw new ContextException("Null Token and Scope. Please set your token first.");
}
logger.trace("Trying to get context UUID for scope {}", scope);
UUID uuid = contextUUIDCache.get(scope);
if(uuid == null){
logger.trace("UUID for scope {} is not in cache. Going to query it", scope);
orientGraph = SecurityContextMapper
.getSecurityContextGraph(
SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID,
PermissionMode.READER);
Vertex context = ContextUtility.getContextVertexByFullName(
orientGraph, scope);
uuid = Utility.getUUID(context);
contextUUIDCache.put(scope, uuid);
return ContextUtility.getInstace().getSecurityContextByFullName(fullName);
}
return uuid;
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
AdminSecurityContext adminSecurityContext = (AdminSecurityContext) ContextUtility.getInstace().
getSecurityContextByUUID(DatabaseEnvironment.ADMIN_SECURITY_CONTEXT_UUID);
return adminSecurityContext;
}
public synchronized void removeFromCache(UUID uuid) throws ResourceRegistryException {
for (String fullName : contextUUIDs.keySet()) {
UUID uuidKey = contextUUIDs.get(fullName);
if (uuidKey.compareTo(uuid) == 0) {
contextUUIDs.remove(fullName);
contexts.remove(uuid);
return;
}
}
}
public synchronized void addSecurityContext(String fullname, SecurityContext securityContext) {
contextUUIDs.put(fullname, securityContext.getUUID());
contexts.put(securityContext.getUUID(), securityContext);
}
private synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException {
try {
SecurityContext securityContext = null;
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
UUID uuid = contextUUIDs.get(fullName);
if (uuid == null) {
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
fullName);
Vertex contextVertex = getContextVertexByFullName(fullName);
uuid = Utility.getUUID(contextVertex);
securityContext = getSecurityContextByUUID(uuid, contextVertex);
addSecurityContext(fullName, securityContext);
} else {
securityContext = contexts.get(uuid);
}
return securityContext;
} catch (ContextException e) {
throw e;
} catch (Exception e) {
throw new ContextException(
"Unable to restrive Context UUID from current Context", e);
} finally{
if(orientGraph!=null){
orientGraph.shutdown();
}
throw new ContextException("Unable to restrive Context UUID from current Context", e);
}
}
public static OrientGraph getActualSecurityContextGraph(
PermissionMode permissionMode, boolean forceAdmin) throws ResourceRegistryException {
protected SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException {
return getSecurityContextByUUID(uuid, null);
}
private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
return Utility.getElementByUUID(getAdminSecurityContext().getGraph(PermissionMode.READER), Context.NAME, uuid,
Vertex.class);
}
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid);
if (securityContext == null) {
securityContext = new SecurityContext(uuid);
try {
UUID contextUUID = null;
if(forceAdmin) {
contextUUID = SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID;
}else {
contextUUID = getActualContextUUID();
}
return SecurityContextMapper.getSecurityContextGraph(contextUUID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
if (contextVertex == null) {
contextVertex = getContextVertexByUUID(uuid);
}
Vertex parentVertex = contextVertex.getVertices(Direction.IN, IsParentOf.NAME).iterator().next();
if (parentVertex != null) {
UUID parentUUID = Utility.getUUID(parentVertex);
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
}
public static OrientGraphNoTx getActualSecurityContextGraphNoTx(
PermissionMode permissionMode, boolean forceAdmin) throws ResourceRegistryException {
try {
UUID contextUUID = null;
if(forceAdmin) {
contextUUID = SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID;
}else {
contextUUID = getActualContextUUID();
}
return SecurityContextMapper.getSecurityContextGraphNoTx(contextUUID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
} catch (NoSuchElementException e) {
// No parent
}
public static ODatabaseDocumentTx getActualSecurityContextDatabaseTx(
PermissionMode permissionMode) throws ResourceRegistryException {
try {
UUID contextUUID = getActualContextUUID();
return SecurityContextMapper.getSecurityContextDatabaseDocumentTx(contextUUID, permissionMode);
} catch (ContextException ce) {
logger.error("Unable to retrieve context.", ce);
throw ce;
} catch (Exception e) {
logger.error("Unable to retrieve context.", e);
throw new ResourceRegistryException(e);
}
contexts.put(uuid, securityContext);
}
public static Vertex getContextVertexByFullName(OrientGraph orientGraph,
String fullName) throws ContextNotFoundException {
return securityContext;
}
private Vertex getContextVertexByFullName(String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} from full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName);
@ -202,42 +173,29 @@ public class ContextUtility {
// TODO Rewrite the query using Gremlin
// Please note that this query works because all the scope parts has a
// different name
String select = "SELECT FROM " + Context.class.getSimpleName()
+ " WHERE " + Context.NAME_PROPERTY + " = \"" + name + "\"";
String select = "SELECT FROM " + Context.class.getSimpleName() + " WHERE " + Context.NAME_PROPERTY + " = \""
+ name + "\"";
;
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(
select);
Iterable<Vertex> vertexes = orientGraph.command(osqlSynchQuery)
OSQLSynchQuery<Vertex> osqlSynchQuery = new OSQLSynchQuery<Vertex>(select);
Iterable<Vertex> vertexes = getAdminSecurityContext().getGraph(PermissionMode.READER).command(osqlSynchQuery)
.execute();
if (vertexes == null || !vertexes.iterator().hasNext()) {
throw new ContextNotFoundException(
"Error retrieving context with name " + fullName);
throw new ContextNotFoundException("Error retrieving context with name " + fullName);
}
Iterator<Vertex> iterator = vertexes.iterator();
Vertex context = iterator.next();
logger.trace("Context Representing Vertex : {}",
Utility.toJsonString(context, true));
logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
if (iterator.hasNext()) {
throw new ContextNotFoundException(
"Found more than one context with name " + name
+ "but required the one with path" + fullName
+ ". Please Reimplement the query");
throw new ContextNotFoundException("Found more than one context with name " + name
+ "but required the one with path" + fullName + ". Please Reimplement the query");
}
return context;
}
public static String getActualSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode permissionMode,
SecurityContextMapper.SecurityType securityType)
throws ContextException {
UUID contextUUID = getActualContextUUID();
return SecurityContextMapper.getSecurityRoleOrUserName(permissionMode,
securityType, contextUUID);
}
}

View File

@ -16,6 +16,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
@ -34,8 +35,18 @@ public class IsParentOfManagement extends RelationManagement<IsParentOf, Context
super(AccessType.IS_PARENT_OF);
}
public IsParentOfManagement(OrientGraph orientGraph) {
super(AccessType.IS_PARENT_OF, orientGraph);
public IsParentOfManagement(OrientGraph orientGraph) throws ResourceRegistryException {
this();
this.orientGraph = orientGraph;
getWorkingContext();
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getInstace().getSecurityContextByUUID(DatabaseEnvironment.CONTEXT_SECURITY_CONTEXT_UUID);
}
return workingContext;
}
@Override

View File

@ -3,8 +3,12 @@
*/
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;
@ -19,6 +23,8 @@ 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)
@ -26,194 +32,270 @@ import com.tinkerpop.blueprints.impls.orient.OrientGraph;
*/
public class SecurityContext {
private static Logger logger = LoggerFactory
.getLogger(SecurityContext.class);
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 static void addToSecurityContext(OrientGraph orientGraph,
Element element, UUID context) {
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
SecurityContext.addToSecurityContext(oSecurity, element, context);
public enum SecurityType {
ROLE("Role"), USER("User");
private final String name;
private SecurityType(String name) {
this.name = name;
}
public static void addToSecurityContext(OSecurity oSecurity, Element element,
UUID context) {
OrientElement orientElement = (OrientElement) element;
SecurityContext.allowSecurityContextRoles(oSecurity,
orientElement.getRecord(), context);
orientElement.save();
public String toString() {
return name;
}
}
public static void removeFromSecurityContext(OrientGraph orientGraph,
Element element, UUID context) {
OSecurity oSecurity = orientGraph.getRawGraph().getMetadata()
.getSecurity();
SecurityContext.removeFromSecurityContext(oSecurity, element, context);
public enum PermissionMode {
READER("Reader"), WRITER("Writer");
private final String name;
private PermissionMode(String name) {
this.name = name;
}
public static void removeFromSecurityContext(OSecurity oSecurity, Element element,
UUID context) {
OrientElement orientElement = (OrientElement) element;
SecurityContext.disallowSecurityContextRoles(oSecurity,
orientElement.getRecord(), context);
orientElement.save();
public String toString() {
return name;
}
}
protected static void disallowSecurityContextRoles(OSecurity oSecurity,
ODocument oDocument, UUID context) {
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, context));
protected final UUID context;
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context));
protected final Map<PermissionMode, OrientGraphFactory> factories;
oDocument.save();
// oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL,
// DEFAULT_WRITER_ROLE);
// oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ,
// DEFAULT_READER_ROLE);
protected SecurityContext parentSecurityContext;
public void setParentSecurityContext(SecurityContext parentSecurityContext) {
this.parentSecurityContext = parentSecurityContext;
}
protected static void allowSecurityContextRoles(OSecurity oSecurity,
ODocument oDocument, UUID context) {
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, context));
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context));
oDocument.save();
// oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL,
// DEFAULT_WRITER_ROLE);
// oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ,
// DEFAULT_READER_ROLE);
public SecurityContext(UUID context) throws ResourceRegistryException {
this.context = context;
this.factories = new HashMap<>();
}
public static void createSecurityContext(OrientGraph orientGraph,
UUID context, boolean commit) {
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 writeRoleName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, context);
ORole writerRole = oSecurity.createRole(writeRoleName,
writer, ALLOW_MODES.DENY_ALL_BUT);
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);
String readerRoleName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context);
ORole readerRole = oSecurity.createRole(readerRoleName,
reader, ALLOW_MODES.DENY_ALL_BUT);
ORole readerRole = oSecurity.createRole(readerRoleName, reader, ALLOW_MODES.DENY_ALL_BUT);
readerRole.save();
logger.trace("{} created", readerRole);
String writerUserName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.USER, context);
OUser writerUser = oSecurity.createUser(writerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS
.get(SecurityContextMapper.PermissionMode.WRITER),
writerRole);
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.WRITER), writerRole);
writerUser.save();
logger.trace("{} created", writerUser);
String readerUserName = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.USER, context);
OUser readerUser = oSecurity.createUser(readerUserName,
DatabaseEnvironment.DEFAULT_PASSWORDS
.get(SecurityContextMapper.PermissionMode.READER),
readerRole);
DatabaseEnvironment.DEFAULT_PASSWORDS.get(PermissionMode.READER), readerRole);
readerUser.save();
logger.trace("{} created", readerUser);
if(commit) {
oDatabaseDocumentTx.commit();
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
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;
}
public static void deleteSecurityContext(OrientGraph orientGraph,
UUID context, boolean commit) {
logger.trace(
"Going to remove Security Context (roles and users) with UUID {}",
context.toString());
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
String user = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.USER, context);
boolean dropped = oSecurity.dropUser(user);
if (dropped) {
logger.trace("{} successfully dropped", user);
logger.trace("{} successfully dropped", name);
} else {
logger.error("{} was not dropped successfully", user);
logger.error("{} was not dropped successfully", name);
}
}
user = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.USER, context);
dropped = oSecurity.dropUser(user);
if (dropped) {
logger.trace("{} successfully dropped", user);
} else {
logger.error("{} was not dropped successfully", user);
public void delete() throws ResourceRegistryException {
OrientGraph orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
delete(orientGraph);
orientGraph.commit();
orientGraph.shutdown();
}
String role = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.READER,
SecurityContextMapper.SecurityType.ROLE, context);
dropped = oSecurity.dropRole(role);
if (dropped) {
logger.trace("{} successfully dropped", role);
} else {
logger.error("{} was not dropped successfully", role);
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());
}
role = SecurityContextMapper.getSecurityRoleOrUserName(
SecurityContextMapper.PermissionMode.WRITER,
SecurityContextMapper.SecurityType.ROLE, context);
dropped = oSecurity.dropRole(role);
if (dropped) {
logger.trace("{} successfully dropped", role);
} else {
logger.error("{} was not dropped successfully", role);
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;
}
if(commit) {
oDatabaseDocumentTx.commit();
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;
}
logger.trace(
"Security Context (roles and users) with UUID {} successfully removed",
context.toString());
public ODatabaseDocumentTx getDatabaseDocumentTx(PermissionMode permissionMode) {
OrientGraphFactory factory = getFactory(permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if (databaseDocumentTx.isClosed()) {
factory = getFactory(permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
@Override
public String toString() {
return String.format("%s %s", Context.NAME, getUUID().toString());
}
}

View File

@ -1,193 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.context;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseIntializator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
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 abstract class SecurityContextMapper {
private static Logger logger = LoggerFactory
.getLogger(SecurityContextMapper.class);
// Used to persist Schemas
protected static final String ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
protected static final UUID ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
// Used to Persist Context and their relations
public static final String MANAGEMENT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
public static final UUID MANAGEMENT_SECURITY_CONTEXT_UUID = UUID.fromString(MANAGEMENT_SECURITY_CONTEXT);
private static final Map<PermissionMode, Map<UUID, OrientGraphFactory>> securityContextFactories;
static {
try {
boolean created = DatabaseIntializator.initGraphDB();
logger.trace("Creating factory for {} connecting as {}",
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.CHANGED_ADMIN_USERNAME);
securityContextFactories = new HashMap<>();
OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.CHANGED_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD)
.setupPool(1, 10);
factory.setConnectionStrategy(DatabaseIntializator.CONNECTION_STRATEGY_PARAMETER.toString());
OrientGraph orientGraph = factory.getTx();
if (created) {
SecurityContext.createSecurityContext(orientGraph, ADMIN_SECURITY_CONTEXT_UUID, true);
SecurityContext.createSecurityContext(orientGraph, MANAGEMENT_SECURITY_CONTEXT_UUID, true);
}
for (PermissionMode p : PermissionMode.values()) {
Map<UUID, OrientGraphFactory> map = new HashMap<>();
securityContextFactories.put(p, map);
getSecurityContextFactory(ADMIN_SECURITY_CONTEXT_UUID, p, false);
getSecurityContextFactory(MANAGEMENT_SECURITY_CONTEXT_UUID, p, false);
}
if(created) {
DatabaseIntializator.createEntitiesAndRelations();
}
} catch (Exception e) {
logger.error("Error initializing database connection", e);
throw new RuntimeException(
"Error initializing database connection", e);
}
}
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;
}
}
/**
* @param context Context UUID. For ADMIN operation uses SecurityContextMapper.ADMIN_SECURITY_CONTEXT_UUID
* @return
*/
private static OrientGraphFactory getSecurityContextFactory(
UUID context, PermissionMode permissionMode, boolean recreate) {
OrientGraphFactory factory = null;
Map<UUID, OrientGraphFactory> permissionSecurityContextFactories = securityContextFactories.get(permissionMode);
if(recreate) {
permissionSecurityContextFactories.remove(context);
}else {
factory = permissionSecurityContextFactories.get(context);
}
if (factory == null) {
String username = null;
String password = null;
if(context.compareTo(ADMIN_SECURITY_CONTEXT_UUID)==0){
username = DatabaseEnvironment.CHANGED_ADMIN_USERNAME;
password = DatabaseEnvironment.CHANGED_ADMIN_PASSWORD;
}else {
username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, context);
password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
}
factory = new OrientGraphFactory(DatabaseEnvironment.DB_URI,
username, password).setupPool(1, 10);
factory.setConnectionStrategy(DatabaseIntializator.CONNECTION_STRATEGY_PARAMETER.toString());
permissionSecurityContextFactories.put(context, factory);
}
return factory;
}
protected static OrientGraph getSecurityContextGraph(
UUID context, PermissionMode permissionMode) {
OrientGraphFactory factory = getSecurityContextFactory(context, permissionMode, false);
OrientGraph orientGraph = factory.getTx();
if(orientGraph.isClosed()) {
factory = getSecurityContextFactory(context, permissionMode, true);
orientGraph = factory.getTx();
}
return orientGraph;
}
protected static OrientGraphNoTx getSecurityContextGraphNoTx(
UUID context, PermissionMode permissionMode) {
OrientGraphFactory factory = getSecurityContextFactory(context, permissionMode, false);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
if(orientGraphNoTx.isClosed()) {
factory = getSecurityContextFactory(context, permissionMode, true);
orientGraphNoTx = factory.getNoTx();
}
return orientGraphNoTx;
}
public static ODatabaseDocumentTx getSecurityContextDatabaseDocumentTx(
UUID context, PermissionMode permissionMode) {
OrientGraphFactory factory = getSecurityContextFactory(context, permissionMode, false);
ODatabaseDocumentTx databaseDocumentTx = factory.getDatabase();
if(databaseDocumentTx.isClosed()) {
factory = getSecurityContextFactory(context, permissionMode, true);
databaseDocumentTx = factory.getDatabase();
}
return databaseDocumentTx;
}
public static String getSecurityRoleOrUserName(
PermissionMode permissionMode, SecurityType securityType,
UUID context) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(permissionMode);
stringBuilder.append(securityType);
stringBuilder.append("_");
stringBuilder.append(context.toString());
return stringBuilder.toString();
}
}

View File

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

View File

@ -1,157 +0,0 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.impl.utils.discovery.ERDiscovery;
import org.gcube.informationsystem.model.ISConstants;
import org.gcube.informationsystem.model.embedded.Embedded;
import org.gcube.informationsystem.model.embedded.ValueSchema;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY;
import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class DatabaseIntializator {
private static Logger logger = LoggerFactory
.getLogger(DatabaseIntializator.class);
private static final String DATABASE_TYPE = "graph";
private static final String STORAGE_MODE = "plocal";
public static final String O_RESTRICTED_CLASS = "ORestricted";
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
private static final String ALTER_DATETIME_FORMAT_QUERY_TEMPLATE = "ALTER DATABASE DATETIMEFORMAT \"%s\"";
public static boolean initGraphDB() throws Exception {
OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false);
logger.trace("Connecting to {} as {} to create new DB",
DatabaseEnvironment.SERVER_URI, DatabaseEnvironment.ROOT_USERNAME);
OServerAdmin serverAdmin = new OServerAdmin(DatabaseEnvironment.SERVER_URI)
.connect(DatabaseEnvironment.ROOT_USERNAME,
DatabaseEnvironment.ROOT_PASSWORD);
if (!serverAdmin.existsDatabase(DatabaseEnvironment.DB, STORAGE_MODE)) {
logger.trace("Creating Database {}", DatabaseEnvironment.DB_URI);
serverAdmin.createDatabase(DatabaseEnvironment.DB, DATABASE_TYPE,
STORAGE_MODE);
logger.trace(
"Connecting to newly created database {} as {} with default password",
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME,
DatabaseEnvironment.DEFAULT_ADMIN_PASSWORD)
.setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
/* Updating DateTimeFormat to be aligned with IS model definition */
/*
* This solution does not work
* OStorageConfiguration configuration = orientGraphNoTx.getRawGraph().getStorage().getConfiguration();
* configuration.dateTimeFormat = ISConstants.DATETIME_PATTERN;
* configuration.update();
*/
String query = String.format(ALTER_DATETIME_FORMAT_QUERY_TEMPLATE, ISConstants.DATETIME_PATTERN);
OCommandSQL preparedQuery = new OCommandSQL( query );
orientGraphNoTx.getRawGraph().command( preparedQuery ).execute();
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSecurity oSecurity = oMetadata.getSecurity();
logger.trace("Changing {} password",
DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
OUser admin = oSecurity
.getUser(DatabaseEnvironment.DEFAULT_ADMIN_USERNAME);
admin.setPassword(DatabaseEnvironment.CHANGED_ADMIN_PASSWORD);
admin.save();
logger.trace("Creating new admin named '{}'",
DatabaseEnvironment.CHANGED_ADMIN_USERNAME);
ORole adminRole = oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
OUser newAdminUser = oSecurity.createUser(DatabaseEnvironment.CHANGED_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD, adminRole);
newAdminUser.save();
for (PermissionMode permissionMode : DatabaseEnvironment.DEFAULT_PASSWORDS
.keySet()) {
OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DatabaseEnvironment.DEFAULT_PASSWORDS
.get(permissionMode));
oUser.save();
logger.trace("Updating password for user {}",
permissionMode.toString());
}
logger.trace("Setting Record-level Security (see https://orientdb.com/docs/last/Database-Security.html)");
OSchema oSchema = oMetadata.getSchema();
OClass oRestricted = oSchema.getClass(O_RESTRICTED_CLASS);
OrientVertexType v = orientGraphNoTx.getVertexBaseType();
v.addSuperClass(oRestricted);
OrientEdgeType e = orientGraphNoTx.getEdgeBaseType();
e.addSuperClass(oRestricted);
//orientGraphNoTx.commit();
orientGraphNoTx.shutdown();
factory.close();
return true;
}
serverAdmin.close();
return false;
}
public static void createEntitiesAndRelations() throws Exception {
ERDiscovery erDiscovery = ISMapper.getErdiscovery();
SchemaActionImpl entityRegistrationAction = new SchemaActionImpl();
entityRegistrationAction.manageEmbeddedClass(Embedded.class);
entityRegistrationAction.manageEmbeddedClass(ValueSchema.class);
erDiscovery.manageDiscoveredERTypes(entityRegistrationAction);
}
}

View File

@ -31,11 +31,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAlreadyP
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.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextManagement;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.IsParentOfManagement;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseIntializator;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.schema.SchemaManagementImpl;
import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
@ -97,21 +96,21 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
this.reload = reload;
}
/**
* This boolean is used to force the use of ADMIN user instead of the user of the context
*/
protected boolean forceAdmin;
public AccessType getAccessType() {
return accessType;
}
public boolean isForceAdmin() {
return forceAdmin;
protected SecurityContext workingContext;
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getCurrentSecurityContext();
}
return workingContext;
}
public void setForceAdmin(boolean forceAdmin) {
this.forceAdmin = forceAdmin;
public void setWorkingContext(SecurityContext workingContext) {
this.workingContext = workingContext;
}
protected ERManagement(AccessType accessType) {
@ -125,11 +124,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
this.ignoreStartWithKeys.add(UNDERSCORE);
this.reload = false;
}
protected ERManagement(AccessType accessType, OrientGraph orientGraph) {
this(accessType);
this.orientGraph = orientGraph;
}
public void setUUID(UUID uuid) throws ResourceRegistryException {
@ -144,8 +139,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
checkJSON();
}
public void setJSON(String jsonRepresentation)
throws ResourceRegistryException {
public void setJSON(String jsonRepresentation) throws ResourceRegistryException {
ObjectMapper mapper = new ObjectMapper();
try {
this.jsonNode = mapper.readTree(jsonRepresentation);
@ -183,9 +177,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected void checkJSON() throws ResourceRegistryException {
if (uuid == null) {
try {
uuid = org.gcube.informationsystem.impl.utils.Utility
.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {}
uuid = org.gcube.informationsystem.impl.utils.Utility.getUUIDFromJsonNode(jsonNode);
} catch (Exception e) {
}
} else {
checkUUIDMatch();
}
@ -202,8 +196,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
if (jsonNode != null) {
String type = getClassProperty(jsonNode);
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);
logger.trace(error);
throw new ResourceRegistryException(error);
@ -223,10 +216,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
if (header != null) {
UUID resourceUUID = header.getUUID();
if (resourceUUID.compareTo(uuid) != 0) {
String error = String
.format("UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(),
erType);
String error = String.format(
"UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(), erType);
throw new ResourceRegistryException(error);
}
@ -243,11 +235,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public abstract String serialize() throws ResourceRegistryException;
public abstract JSONObject serializeAsJson()
throws ResourceRegistryException;
public abstract JSONObject serializeAsJson() throws ResourceRegistryException;
protected abstract El reallyCreate() throws ERAlreadyPresentException,
ResourceRegistryException;
protected abstract El reallyCreate() throws ERAlreadyPresentException, ResourceRegistryException;
public El internalCreate() throws ERAlreadyPresentException, ResourceRegistryException {
try {
@ -260,9 +250,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
entityHeader = HeaderUtility.addHeader(element, null);
}
if(!(this instanceof ContextManagement || this instanceof IsParentOfManagement)){
ContextUtility.addToActualContext(orientGraph, element);
}
getWorkingContext().addElement(element, orientGraph);
((OrientElement) element).save();
@ -274,8 +262,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
protected abstract El reallyUpdate() throws ERNotFoundException,
ResourceRegistryException;
protected abstract El reallyUpdate() throws ERNotFoundException, ResourceRegistryException;
public El internalUpdate() throws ERNotFoundException, ResourceRegistryException {
try {
@ -301,16 +288,14 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
protected abstract boolean reallyDelete() throws ERNotFoundException,
ResourceRegistryException;
protected abstract boolean reallyDelete() throws ERNotFoundException, ResourceRegistryException;
public boolean internalDelete() throws ERNotFoundException, ResourceRegistryException {
// Added for consistency with create and update addToContext removeFromContext.
return reallyDelete();
}
protected abstract boolean reallyAddToContext() throws ContextException,
ResourceRegistryException;
protected abstract boolean reallyAddToContext() throws ContextException, ResourceRegistryException;
public boolean internalAddToContext() throws ContextException, ResourceRegistryException {
try {
@ -325,8 +310,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
protected abstract boolean reallyRemoveFromContext() throws ContextException,
ResourceRegistryException;
protected abstract boolean reallyRemoveFromContext() throws ContextException, ResourceRegistryException;
public boolean internalRemoveFromContext() throws ContextException, ResourceRegistryException {
try {
@ -343,8 +327,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public void setElement(El element) throws ResourceRegistryException {
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.uuid = HeaderUtility.getHeader(element).getUUID();
@ -352,7 +335,8 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
protected abstract ERNotFoundException getSpecificElementNotFoundException(ERNotFoundException e);
protected abstract ERAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message);
protected abstract ERAvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(
String message);
protected abstract ERAlreadyPresentException getSpecificERAlreadyPresentException(String message);
@ -363,7 +347,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
} catch (ERNotFoundException e) {
try {
retrieveElementFromAnyContext();
throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName() : erType + " with UUID " + uuid + " is available in another " + Context.class.getSimpleName());
throw getSpecificERAvailableInAnotherContextException(erType == null ? accessType.getName()
: erType + " with UUID " + uuid + " is available in another "
+ Context.class.getSimpleName());
} catch (ERAvailableInAnotherContextException e1) {
throw e1;
} catch (Exception e1) {
@ -388,8 +374,8 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
if (uuid == null) {
throw new ERNotFoundException("null UUID does not allow to retrieve the Element");
}
return Utility.getElementByUUID(orientGraph,
erType == null ? accessType.getName() : erType, uuid, elementClass);
return Utility.getElementByUUID(orientGraph, erType == null ? accessType.getName() : erType, uuid,
elementClass);
} catch (ERNotFoundException e) {
throw getSpecificElementNotFoundException(e);
} catch (ResourceRegistryException e) {
@ -411,13 +397,12 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
public abstract String reallyGetAll(boolean polymorphic)
throws ResourceRegistryException;
public abstract String reallyGetAll(boolean polymorphic) throws ResourceRegistryException;
public String all(boolean polymorphic) throws ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAll(polymorphic);
} catch (ResourceRegistryException e) {
@ -431,10 +416,10 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
public boolean exists() throws ERNotFoundException,
ERAvailableInAnotherContextException, ResourceRegistryException {
public boolean exists()
throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
getElement();
@ -455,7 +440,7 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
public String create() throws ERAlreadyPresentException, ResourceRegistryException {
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER);
element = internalCreate();
@ -484,11 +469,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
public String read() throws ERNotFoundException,
ERAvailableInAnotherContextException, ResourceRegistryException {
public String read() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
getElement();
@ -506,11 +489,9 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
public String update() throws ERNotFoundException,
ERAvailableInAnotherContextException, ResourceRegistryException {
public String update() throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.WRITER);
element = internalUpdate();
@ -520,7 +501,6 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
// TODO Notify to subscriptionNotification
return serialize();
// TODO Serialized resource is the old version. This really strange and should be an orient bug
} catch (ResourceRegistryException e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
@ -541,24 +521,21 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
}
public boolean delete() throws ERNotFoundException,
ERAvailableInAnotherContextException, ResourceRegistryException {
public boolean delete()
throws ERNotFoundException, ERAvailableInAnotherContextException, ResourceRegistryException {
logger.debug("Going to delete {} with UUID {}", accessType.getName(), uuid);
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(
PermissionMode.WRITER, true);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean deleted = reallyDelete();
if (deleted) {
orientGraph.commit();
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(),
uuid);
logger.info("{} with UUID {} was successfully deleted.", accessType.getName(), uuid);
} else {
logger.info("{} with UUID {} was NOT deleted.", accessType.getName(),
uuid);
logger.info("{} with UUID {} was NOT deleted.", accessType.getName(), uuid);
orientGraph.rollback();
}
@ -584,30 +561,25 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
public boolean addToContext() throws ERNotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to add {} with UUID {} to actual Context",
accessType.getName(), uuid);
logger.info("Going to add {} with UUID {} to Context {}", accessType.getName(), uuid, getWorkingContext().toString());
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(
PermissionMode.WRITER, true);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean added = internalAddToContext();
orientGraph.commit();
logger.info("{} with UUID {} successfully added to actual Context",
accessType.getName(), uuid);
logger.info("{} with UUID {} successfully added to actual Context", accessType.getName(), uuid);
return added;
} 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) {
orientGraph.rollback();
}
throw 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) {
orientGraph.rollback();
}
@ -620,32 +592,26 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
public boolean removeFromContext() throws ERNotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {} from actual Context",
accessType.getName(), uuid);
logger.debug("Going to remove {} with UUID {} from actual Context", accessType.getName(), uuid);
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(
PermissionMode.WRITER, true);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean removed = internalRemoveFromContext();
orientGraph.commit();
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;
} 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) {
orientGraph.rollback();
}
throw 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) {
orientGraph.rollback();
}
@ -674,18 +640,13 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
case ARRAY:
/*
List<Object> list = new ArrayList<Object>();
Iterator<JsonNode> arrayElement = value.elements();
while (arrayElement.hasNext()) {
JsonNode arrayNode = arrayElement.next();
Object objectNode = getObjectFromElement(arrayNode);
if (objectNode != null) {
list.add(objectNode);
}
}
return list;
* List<Object> list = new ArrayList<Object>(); Iterator<JsonNode> arrayElement
* = value.elements(); while (arrayElement.hasNext()) { JsonNode arrayNode =
* arrayElement.next(); Object objectNode = getObjectFromElement(arrayNode); if
* (objectNode != null) { list.add(objectNode); } } return list;
*/
throw new UnsupportedDataTypeException("List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
throw new UnsupportedDataTypeException(
"List/Set support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
case BINARY:
break;
@ -725,9 +686,8 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return null;
}
public static Map<String, Object> getPropertyMap(JsonNode jsonNode,
Set<String> ignoreKeys, Set<String> ignoreStartWith)
throws JsonProcessingException, IOException {
public static Map<String, Object> getPropertyMap(JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreStartWith) throws JsonProcessingException, IOException {
Map<String, Object> map = new HashMap<>();
@ -772,23 +732,20 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return map;
}
public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode,
Set<String> ignoreKeys, Set<String> ignoreStartWithKeys)
throws ResourceRegistryException {
public static Element updateProperties(OClass oClass, Element element, JsonNode jsonNode, Set<String> ignoreKeys,
Set<String> ignoreStartWithKeys) throws ResourceRegistryException {
Set<String> oldKeys = element.getPropertyKeys();
Map<String, Object> properties;
if (element instanceof Vertex || element instanceof Edge) {
try {
properties = getPropertyMap(jsonNode, ignoreKeys,
ignoreStartWithKeys);
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
} catch (IOException e) {
throw new ResourceRegistryException(e);
}
} else {
String error = String.format("Error while updating %s properties",
element.toString());
String error = String.format("Error while updating %s properties", element.toString());
throw new ResourceRegistryException(error);
}
@ -809,15 +766,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
/*
if(object instanceof Set){
((OrientElement) element).setProperty(key, object, OType.EMBEDDEDSET);
set = true;
}
if(object instanceof List){
((OrientElement) element).setProperty(key, object, OType.EMBEDDEDLIST);
set = true;
}
* if(object instanceof Set){ ((OrientElement) element).setProperty(key, object,
* OType.EMBEDDEDSET); set = true; }
*
* if(object instanceof List){ ((OrientElement) element).setProperty(key,
* object, OType.EMBEDDEDLIST); set = true; }
*/
if (!set) {
@ -829,9 +782,8 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
}
} catch (Exception e) {
String error = String.format(
"Error while setting property %s : %s (%s)", key, properties
.get(key).toString(), e.getMessage());
String error = String.format("Error while setting property %s : %s (%s)", key,
properties.get(key).toString(), e.getMessage());
staticLogger.error(error);
throw new ResourceRegistryException(error, e);
}
@ -913,12 +865,11 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
return jsonArray;
}
return object.toString();
} catch (Exception e) {
throw new ResourceRegistryException("Error while serializing "
+ key + "=" + object.toString() + " in " + getElement().toString(), e);
throw new ResourceRegistryException(
"Error while serializing " + key + "=" + object.toString() + " in " + getElement().toString(), e);
}
}
@ -927,9 +878,8 @@ public abstract class ERManagement<ERType extends ER, El extends Element> {
Collection<String> superClasses = new HashSet<>();
for (OClass oSuperClass : allSuperClasses) {
String name = oSuperClass.getName();
if(name.compareTo(StringFactory.V.toUpperCase())==0 ||
name.compareTo(StringFactory.E.toUpperCase())==0 ||
name.compareTo(DatabaseIntializator.O_RESTRICTED_CLASS)==0){
if (name.compareTo(StringFactory.V.toUpperCase()) == 0 || name.compareTo(StringFactory.E.toUpperCase()) == 0
|| name.compareTo(DatabaseEnvironment.O_RESTRICTED_CLASS) == 0) {
continue;
}
superClasses.add(name);

View File

@ -10,6 +10,7 @@ import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -60,12 +61,12 @@ public class ERManagementUtility {
}
@SuppressWarnings("rawtypes")
private static ERManagement getERManagement(OrientGraph orientGraph, Element element)
private static ERManagement getERManagement(SecurityContext workingContext, OrientGraph orientGraph, Element element)
throws ResourceRegistryException {
if (element instanceof Vertex) {
return getEntityManagement(orientGraph, (Vertex) element);
return getEntityManagement(workingContext, orientGraph, (Vertex) element);
} else if (element instanceof Edge) {
return getRelationManagement(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(),
Entity.NAME, Relation.NAME));
@ -97,12 +98,12 @@ public class ERManagementUtility {
}
@SuppressWarnings("rawtypes")
public static ERManagement getERManagementFromUUID(OrientGraph orientGraph, UUID uuid)
public static ERManagement getERManagementFromUUID(SecurityContext workingContext, OrientGraph orientGraph, UUID uuid)
throws ResourceRegistryException {
Element element;
try {
element = getAnyElementByUUID(orientGraph, uuid);
return getERManagement(orientGraph, element);
return getERManagement(workingContext, orientGraph, element);
} catch (Exception e) {
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
uuid.toString(), Entity.NAME, Relation.NAME));
@ -110,7 +111,7 @@ public class ERManagementUtility {
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static EntityManagement getEntityManagement(OrientGraph orientGraph, Vertex vertex)
public static EntityManagement getEntityManagement(SecurityContext workingContext, OrientGraph orientGraph, Vertex vertex)
throws ResourceRegistryException {
if (orientGraph == null) {
@ -136,9 +137,9 @@ public class ERManagementUtility {
EntityManagement entityManagement = null;
if (orientVertexType.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement(orientGraph);
entityManagement = new ResourceManagement(workingContext, orientGraph);
} else if (orientVertexType.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement(orientGraph);
entityManagement = new FacetManagement(workingContext, orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. %s",
vertex, Resource.NAME, Facet.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -149,7 +150,7 @@ public class ERManagementUtility {
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static RelationManagement getRelationManagement(OrientGraph orientGraph, Edge edge)
public static RelationManagement getRelationManagement(SecurityContext workingContext, OrientGraph orientGraph, Edge edge)
throws ResourceRegistryException {
if (orientGraph == null) {
@ -165,9 +166,9 @@ public class ERManagementUtility {
OrientEdgeType orientEdgeType = ((OrientEdge) edge).getType();
RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(orientGraph);
relationManagement = new ConsistsOfManagement(workingContext, orientGraph);
} else if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph);
relationManagement = new IsRelatedToManagement(workingContext, orientGraph);
} else {
String error = String.format("{%s is not a %s nor a %s. %s",
edge, ConsistsOf.NAME, IsRelatedTo.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);

View File

@ -16,7 +16,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.context.Conte
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.RelationManagement;
@ -61,6 +61,12 @@ public abstract class EntityManagement<E extends Entity> extends
}
protected EntityManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) {
this(accessType);
this.orientGraph = orientGraph;
setWorkingContext(workingContext);
}
@SuppressWarnings("rawtypes")
/*
* It works perfectly in case of any kind of update.
@ -71,7 +77,7 @@ public abstract class EntityManagement<E extends Entity> extends
String id = edge.getId().toString();
RelationManagement relationManagement = relationManagements.get(id);
if(relationManagement==null) {
relationManagement = ERManagementUtility.getRelationManagement(orientGraph, edge);
relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
relationManagements.put(id, relationManagement);
}
return relationManagement;
@ -93,11 +99,6 @@ public abstract class EntityManagement<E extends Entity> extends
relationManagements.put(id, relationManagement);
}
protected EntityManagement(AccessType accessType, OrientGraph orientGraph) {
this(accessType);
this.orientGraph = orientGraph;
}
protected static JSONObject addRelation(JSONObject sourceResource,
JSONObject relation, String arrayKey)
throws ResourceRegistryException {
@ -186,7 +187,7 @@ public abstract class EntityManagement<E extends Entity> extends
protected boolean reallyAddToContext() throws ContextException,
ResourceRegistryException {
ContextUtility.addToActualContext(orientGraph, getElement());
getWorkingContext().addElement(getElement(), orientGraph);
Iterable<Edge> edges = getElement().getEdges(Direction.OUT);
@ -211,7 +212,7 @@ public abstract class EntityManagement<E extends Entity> extends
relationManagement.internalRemoveFromContext();
}
ContextUtility.removeFromActualContext(orientGraph, getElement());
getWorkingContext().removeElement(getElement(), orientGraph);
return true;
}
@ -224,7 +225,7 @@ public abstract class EntityManagement<E extends Entity> extends
Iterable<Vertex> iterable = orientGraph.getVerticesOfClass(erType, polymorphic);
for(Vertex vertex : iterable){
@SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex);
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
try {
JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject);

View File

@ -11,6 +11,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import com.tinkerpop.blueprints.Vertex;
@ -26,8 +27,8 @@ public class FacetManagement extends EntityManagement<Facet> {
super(AccessType.FACET);
}
public FacetManagement(OrientGraph orientGraph) {
super(AccessType.FACET, orientGraph);
public FacetManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.FACET, workingContext, orientGraph);
}
@Override

View File

@ -15,8 +15,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resour
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.IsRelatedToManagement;
@ -45,8 +45,8 @@ public class ResourceManagement extends EntityManagement<Resource> {
super(AccessType.RESOURCE);
}
public ResourceManagement(OrientGraph orientGraph) {
super(AccessType.RESOURCE, orientGraph);
public ResourceManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.RESOURCE, workingContext, orientGraph);
}
@Override
@ -150,7 +150,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph);
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(consistOfJsonNode);
com.setSourceEntityManagement(this);
com.internalCreate();
@ -162,8 +162,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(
orientGraph);
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
irtm.setJSON(relationJsonNode);
irtm.setSourceEntityManagement(this);
irtm.internalCreate();
@ -183,7 +182,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement(orientGraph);
ConsistsOfManagement com = new ConsistsOfManagement(getWorkingContext(), orientGraph);
com.setJSON(relationJsonNode);
com.internalCreateOrUdate();
addToRelationManagement(com);
@ -194,8 +193,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
if (jsonNode.has(property)) {
JsonNode jsonNodeArray = jsonNode.get(property);
for (JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement(
orientGraph);
IsRelatedToManagement irtm = new IsRelatedToManagement(getWorkingContext(), orientGraph);
irtm.setJSON(relationJsonNode);
irtm.internalUpdate();
addToRelationManagement(irtm);
@ -222,9 +220,9 @@ public class ResourceManagement extends EntityManagement<Resource> {
@SuppressWarnings("rawtypes")
RelationManagement relationManagement = null;
if (orientEdgeType.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement(orientGraph);
relationManagement = new IsRelatedToManagement(getWorkingContext(), orientGraph);
} else if (orientEdgeType.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement(orientGraph);
relationManagement = new ConsistsOfManagement(getWorkingContext(), orientGraph);
} else {
logger.warn("{} is not a {} nor a {}. {}",
Utility.toJsonString(edge, true), IsRelatedTo.NAME,
@ -245,8 +243,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
public String all(boolean polymorphic, Map<String, String> constraint) throws ResourceRegistryException {
try {
orientGraph = ContextUtility
.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAll(polymorphic, constraint);
} catch (ResourceRegistryException e) {
@ -345,7 +342,7 @@ public class ResourceManagement extends EntityManagement<Resource> {
Vertex vertex = (Vertex) element;
@SuppressWarnings("rawtypes")
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(orientGraph, vertex);
EntityManagement entityManagement = ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, vertex);
try {
JSONObject jsonObject = entityManagement.serializeAsJson();
jsonArray.put(jsonObject);

View File

@ -10,6 +10,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
@ -25,8 +26,8 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf, Resourc
super(AccessType.CONSISTS_OF);
}
public ConsistsOfManagement(OrientGraph orientGraph) {
super(AccessType.CONSISTS_OF, orientGraph);
public ConsistsOfManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.CONSISTS_OF, workingContext, orientGraph);
}
@Override
@ -47,12 +48,12 @@ public class ConsistsOfManagement extends RelationManagement<ConsistsOf, Resourc
@Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(orientGraph);
return new ResourceManagement(getWorkingContext(), orientGraph);
}
@Override
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
return new FacetManagement(orientGraph);
return new FacetManagement(getWorkingContext(), orientGraph);
}
}

View File

@ -10,6 +10,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
@ -24,8 +25,8 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, Resou
super(AccessType.IS_RELATED_TO);
}
public IsRelatedToManagement(OrientGraph orientGraph) {
super(AccessType.IS_RELATED_TO, orientGraph);
public IsRelatedToManagement(SecurityContext workingContext, OrientGraph orientGraph) {
super(AccessType.IS_RELATED_TO, workingContext, orientGraph);
}
@Override
@ -46,12 +47,12 @@ public class IsRelatedToManagement extends RelationManagement<IsRelatedTo, Resou
@Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(orientGraph);
return new ResourceManagement(getWorkingContext(), orientGraph);
}
@Override
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ResourceManagement(orientGraph);
return new ResourceManagement(getWorkingContext(), orientGraph);
}
}

View File

@ -27,7 +27,8 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFound
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.er.ERManagement;
import org.gcube.informationsystem.resourceregistry.er.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.EntityManagement;
@ -85,9 +86,10 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
}
protected RelationManagement(AccessType accessType, OrientGraph orientGraph) {
protected RelationManagement(AccessType accessType, SecurityContext workingContext, OrientGraph orientGraph) {
this(accessType);
this.orientGraph = orientGraph;
setWorkingContext(workingContext);
}
/*
@ -174,7 +176,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
ResourceManagement resourceManagement = null;
if (sourceResource == null) {
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(orientGraph, source);
resourceManagement = (ResourceManagement) ERManagementUtility.getEntityManagement(getWorkingContext(), orientGraph, source);
if (this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.serializeAsJson();
} else if (this instanceof ConsistsOfManagement) {
@ -279,7 +281,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
if (accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if (target != null) {
FacetManagement fm = new FacetManagement(orientGraph);
FacetManagement fm = new FacetManagement(getWorkingContext(), orientGraph);
fm.setJSON(target);
fm.internalUpdate();
}
@ -327,7 +329,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
*/
getTargetEntityManagement().internalAddToContext();
ContextUtility.addToActualContext(orientGraph, getElement());
getWorkingContext().addElement(getElement(), orientGraph);
break;
@ -351,7 +353,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
/* Adding target to Context */
getTargetEntityManagement().internalAddToContext();
ContextUtility.addToActualContext(orientGraph, getElement());
getWorkingContext().addElement(getElement(), orientGraph);
return true;
}
@ -389,7 +391,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
* In any removeConstraint value the relation MUST be removed from context to
* avoid to have edge having a source outside of the context.
*/
ContextUtility.removeFromActualContext(orientGraph, element);
getWorkingContext().removeElement(getElement(), orientGraph);
switch (removeConstraint) {
case cascade:
@ -494,37 +496,6 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
return true;
}
@SuppressWarnings("unused")
private String create(UUID sourceUUID, UUID targetUUID) throws ResourceRegistryException {
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, forceAdmin);
getSourceEntityManagement().setUUID(sourceUUID);
getTargetEntityManagement().setUUID(targetUUID);
element = reallyCreate();
orientGraph.commit();
return serialize();
} catch (ResourceRegistryException e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw e;
} catch (Exception e) {
if (orientGraph != null) {
orientGraph.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if (orientGraph != null) {
orientGraph.shutdown();
}
}
}
@SuppressWarnings("unchecked")
protected Collection<JSONObject> serializeEdges(Iterable<Edge> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException {
@ -533,7 +504,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
if (postFilterPolymorphic && edge.getLabel().compareTo(erType) != 0) {
continue;
}
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(orientGraph, edge);
RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), orientGraph, edge);
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
}
return visitedSourceResources.values();
@ -555,7 +526,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
throws ResourceRegistryException {
EntityManagement entityManagement = null;
try {
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(orientGraph, uuid);
entityManagement = (EntityManagement) ERManagementUtility.getERManagementFromUUID(getWorkingContext(), orientGraph, uuid);
} catch (ResourceRegistryException e) {
throw e;
} catch (Exception e) {
@ -575,7 +546,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
public String allFrom(UUID uuid, Direction direction, boolean polymorphic) throws ResourceRegistryException {
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.READER, forceAdmin);
orientGraph = getWorkingContext().getGraph(PermissionMode.READER);
return reallyGetAllFrom(uuid, direction, polymorphic);
} catch (ResourceRegistryException e) {
@ -594,7 +565,7 @@ public abstract class RelationManagement<R extends Relation, S extends EntityMan
logger.debug("Going to add {} with UUID {} to actual Context", accessType.getName(), uuid);
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, true);
orientGraph = ContextUtility.getAdminSecurityContext().getGraph(PermissionMode.WRITER);
boolean added = forcedAddToContext();

View File

@ -10,7 +10,8 @@ import java.util.List;
import org.gcube.informationsystem.resourceregistry.api.exceptions.query.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -132,9 +133,9 @@ public class QueryImpl implements Query {
ODatabaseDocumentTx oDatabaseDocumentTx = null;
try {
oDatabaseDocumentTx = ContextUtility
.getActualSecurityContextDatabaseTx(PermissionMode.READER);
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
oDatabaseDocumentTx = securityContext.getDatabaseDocumentTx(PermissionMode.READER);
OSQLSynchQuery<ODocument> osqlSynchQuery = new OSQLSynchQuery<>(query, limit);
osqlSynchQuery.setFetchPlan(fetchPlan);

View File

@ -14,6 +14,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.relation.ConsistsOf;
@ -27,7 +28,6 @@ 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.rest.ERPath;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall.HTTPMETHOD;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagement;
import org.gcube.informationsystem.resourceregistry.er.entity.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.er.relation.ConsistsOfManagement;
@ -270,8 +270,7 @@ public class ERManager {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to add {} with UUID {} to current context {}", Resource.NAME, uuid,
ContextUtility.getCurrentContext());
logger.info("Requested to add {} with UUID {} to current {}", Resource.NAME, uuid, Context.NAME);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.addToContext();
@ -288,8 +287,7 @@ public class ERManager {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.ADD_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to add {} with UUID {} to current context {}", Facet.NAME, uuid,
ContextUtility.getCurrentContext());
logger.info("Requested to add {} with UUID {} to current {}", Facet.NAME, uuid, Context.NAME);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.addToContext();
@ -306,8 +304,7 @@ public class ERManager {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.RESOURCE_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to remove {} with UUID {} from current context {}", Resource.NAME, uuid,
ContextUtility.getCurrentContext());
logger.info("Requested to remove {} with UUID {} from current {}", Resource.NAME, uuid, Context.NAME);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString(uuid));
return resourceManagement.removeFromContext();
@ -324,8 +321,7 @@ public class ERManager {
CalledMethodProvider.instance.set(
HTTPMETHOD.POST.name() + " /" + ERPath.ER_PATH_PART +
"/" + ERPath.REMOVE_PATH_PART + "/" + ERPath.FACET_PATH_PART + "/{" + ID_PATH_PARAM + "}");
logger.info("Requested to remove {} with UUID {} from current context {}", Facet.NAME, uuid,
ContextUtility.getCurrentContext());
logger.info("Requested to remove {} with UUID {} from current {}", Facet.NAME, uuid, Context.NAME);
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(UUID.fromString(uuid));
return facetManagement.removeFromContext();

View File

@ -8,8 +8,9 @@ import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -55,7 +56,8 @@ public class SchemaContextManagement implements SchemaManagement {
OrientGraph orientGraph = null;
try {
orientGraph = ContextUtility.getActualSecurityContextGraph(PermissionMode.WRITER, true);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraph = adminSecurityContext.getGraph(PermissionMode.WRITER);
ObjectMapper mapper = new ObjectMapper();
TypeDefinition typeDefinition = mapper.readValue(json, TypeDefinition.class);

View File

@ -19,8 +19,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder;
import org.gcube.informationsystem.types.TypeBinder.Property;
import org.gcube.informationsystem.types.TypeBinder.TypeDefinition;
@ -92,8 +93,8 @@ public class SchemaManagementImpl implements SchemaManagement {
logger.debug("Getting {} Type {} schema",
accessType != null ? accessType.getName() : "", type);
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx(
PermissionMode.READER, true);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return getTypeSchema(orientGraphNoTx, type, accessType);
} catch (ResourceRegistryException e) {
@ -178,8 +179,9 @@ public class SchemaManagementImpl implements SchemaManagement {
TypeDefinition typeDefinition = mapper.readValue(jsonSchema,
TypeDefinition.class);
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx(
PermissionMode.WRITER, true);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema();
@ -336,8 +338,8 @@ public class SchemaManagementImpl implements SchemaManagement {
throws SchemaNotFoundException, SchemaException {
OrientGraphNoTx orientGraphNoTx = null;
try {
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx(
PermissionMode.WRITER, true);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.WRITER);
OMetadata oMetadata = orientGraphNoTx.getRawGraph().getMetadata();
OSchema oSchema = oMetadata.getSchema();

View File

@ -17,8 +17,9 @@ import org.gcube.informationsystem.model.entity.Entity;
import org.gcube.informationsystem.model.relation.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.er.ERNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.context.SecurityContextMapper.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -27,6 +28,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
import com.tinkerpop.blueprints.impls.orient.OrientElement;
@ -94,7 +96,8 @@ public class Utility {
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
OrientGraphNoTx orientGraphNoTx = null;
try {
orientGraphNoTx = ContextUtility.getActualSecurityContextGraphNoTx(PermissionMode.READER, true);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraphNoTx = adminSecurityContext.getGraphNoTx(PermissionMode.READER);
return Utility.getElementByUUID(orientGraphNoTx, elementType, uuid, clz);
} finally {
if (orientGraphNoTx != null) {
@ -104,7 +107,7 @@ public class Utility {
}
public static <El extends Element> El getElementByUUID(
OrientBaseGraph orientBaseGraph, String elementType, UUID uuid,
Graph graph, String elementType, UUID uuid,
Class<? extends El> clz) throws ERNotFoundException, ResourceRegistryException {
if (elementType == null || elementType.compareTo("") == 0) {
@ -123,7 +126,7 @@ public class Utility {
OSQLSynchQuery<El> osqlSynchQuery = new OSQLSynchQuery<>(select);
Iterable<El> elements = orientBaseGraph.command(osqlSynchQuery).execute();
Iterable<El> elements = ((OrientBaseGraph) graph).command(osqlSynchQuery).execute();
if (elements == null || !elements.iterator().hasNext()) {
String error = String.format("No %s with UUID %s was found",
elementType, uuid.toString());

View File

@ -11,10 +11,13 @@ import org.gcube.informationsystem.impl.entity.ContextImpl;
import org.gcube.informationsystem.impl.utils.ISMapper;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.relation.IsParentOf;
import org.gcube.informationsystem.resourceregistry.ScopedTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.context.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.er.entity.FacetManagementTest;
import org.junit.Assert;
import org.junit.Test;
@ -22,61 +25,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class ContextManagementTest {
public class ContextManagementTest extends ScopedTest {
private static Logger logger = LoggerFactory.getLogger(ContextManagementTest.class);
@Test
public void get() throws Exception {
// UUID uuid = UUID.fromString("602ce5ea-b263-452a-93e5-ab33db7af979");
UUID uuid = UUID.fromString("4e2b121e-ba5a-41e1-bbed-be9b60370aa3");
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(uuid);
String string = contextManagement.read();
logger.debug(string);
Context context = ISMapper.unmarshal(Context.class, string);
logger.debug("{}", ISMapper.marshal(context));
logger.debug("Parent : {}", ISMapper.marshal(context.getParent().getSource()));
for (IsParentOf<Context, Context> isParentOf : context.getChildren()) {
logger.debug("Children : {}", ISMapper.marshal(isParentOf.getTarget()));
}
Context parent = context.getParent().getSource();
Context sameOfContext = parent.getChildren().get(0).getTarget();
Assert.assertTrue(context == sameOfContext);
List<IsParentOf<Context, Context>> children = context.getChildren();
for (IsParentOf<Context, Context> child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
Assert.assertTrue(childContext.getParent().getSource() == context);
}
}
// @Test
public void test() throws Exception {
UUID uuid = UUID.fromString("4e2b121e-ba5a-41e1-bbed-be9b60370aa3");
Context myTest = new ContextImpl("myTest");
myTest.setParent(uuid);
String contextJsonString = ISMapper.marshal(myTest);
logger.debug("myTest : {}", contextJsonString);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setJSON(contextJsonString);
contextManagement.create();
}
@Test
public void testJava() throws Exception {
Context gcube = new ContextImpl("gcube");
logger.debug("gcube : {}", ISMapper.marshal(gcube));
@ -110,7 +69,7 @@ public class ContextManagementTest {
public static final String CTX_NAME_B = "B";
public static final String CTX_NAME_C = "C";
protected void assertions(Context pre, Context post, boolean checkParent, boolean create) {
protected void assertions(Context pre, Context post, boolean checkParent, boolean create) throws ResourceRegistryException {
if (checkParent) {
if (pre.getHeader() != null) {
FacetManagementTest.checkHeader(post, pre.getHeader().getUUID(), create);
@ -125,13 +84,39 @@ public class ContextManagementTest {
Context postParent = post.getParent().getSource();
assertions(preParent, postParent, false, false);
}
}
protected void roleUserAssertions(UUID uuid, boolean deleted) throws ResourceRegistryException {
ContextSecurityContext contextSecurityContext = new ContextSecurityContext();
ContextUtility.getInstace().addSecurityContext(contextSecurityContext.getUUID().toString(), contextSecurityContext);
OrientGraph orientGraph = contextSecurityContext.getGraph(PermissionMode.READER);
ODatabaseDocumentTx oDatabaseDocumentTx = orientGraph.getRawGraph();
OSecurity oSecurity = oDatabaseDocumentTx.getMetadata().getSecurity();
SecurityContext securityContext = new SecurityContext(uuid);
for(PermissionMode permissionMode : PermissionMode.values()) {
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, false);
ORole oRole = oSecurity.getRole(role);
Assert.assertEquals(oRole==null, deleted);
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, false);
OUser oUser = oSecurity.getUser(user);
Assert.assertEquals(oUser==null, deleted);
}
}
protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(uuid);
String contextString = contextManagement.read();
logger.debug("Read {}", contextString);
roleUserAssertions(uuid, false);
return ISMapper.unmarshal(Context.class, contextString);
}
@ -142,6 +127,7 @@ public class ContextManagementTest {
logger.debug("Created {}", contextString);
Context c = ISMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, true);
roleUserAssertions(c.getHeader().getUUID(), false);
return c;
}
@ -152,6 +138,7 @@ public class ContextManagementTest {
logger.debug("Updated {}", contextString);
Context c = ISMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, false);
roleUserAssertions(c.getHeader().getUUID(), false);
return c;
}
@ -160,6 +147,7 @@ public class ContextManagementTest {
contextManagement.setUUID(uuid);
boolean deleted = contextManagement.delete();
Assert.assertTrue(deleted);
roleUserAssertions(uuid, true);
logger.debug("Deleted {} with UUID {}", Context.NAME, uuid);
return deleted;
}
@ -383,14 +371,27 @@ public class ContextManagementTest {
public void testGetAll() throws Exception {
ContextManagement contextManagement = new ContextManagement();
String all = contextManagement.all(false);
logger.debug(all);
logger.trace(all);
List<Context> contexts = ISMapper.unmarshalList(Context.class, all);
for(Context context : contexts){
logger.debug(ISMapper.marshal(context));
logger.trace(ISMapper.marshal(context));
List<IsParentOf<Context, Context>> children = context.getChildren();
for (IsParentOf<Context, Context> child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
Assert.assertTrue(childContext.getParent().getSource() == context);
}
roleUserAssertions(context.getHeader().getUUID(), false);
}
}
@Test
// @Test
public void deleteContext() throws ResourceRegistryException, IOException {
Context context = read(UUID.fromString(""));
delete(context);
}
// @Test
public void createDevContext() throws Exception {
Context gcube = new ContextImpl("gcube");
gcube = create(gcube);

View File

@ -0,0 +1,16 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatabaseEnvironmentTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironmentTest.class);
@Test
public void createDB() throws Exception{
String db = DatabaseEnvironment.DB_URI;
logger.trace("Created DB is {}", db);
}
}

View File

@ -1,32 +0,0 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
public class DatabaseIntializatorTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseIntializatorTest.class);
//@Test
public void testInitDB() throws Exception{
DatabaseIntializator.initGraphDB();
OrientGraphFactory factory = new OrientGraphFactory(
DatabaseEnvironment.DB_URI,
DatabaseEnvironment.CHANGED_ADMIN_USERNAME,
DatabaseEnvironment.CHANGED_ADMIN_PASSWORD)
.setupPool(1, 10);
OrientGraphNoTx orientGraphNoTx = factory.getNoTx();
/* Updating Datetime Format to be aligned with IS model definition */
OStorageConfiguration configuration = orientGraphNoTx.getRawGraph().getStorage().getConfiguration();
logger.debug("Got DateTimeFormat {}", configuration.getDateTimeFormat());
}
}

View File

@ -292,8 +292,8 @@ public class ERManagementTest extends ScopedTest {
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
//boolean deleted = facetManagement.delete();
//Assert.assertTrue(deleted);
boolean deleted = facetManagement.delete();
Assert.assertTrue(deleted);
}

View File

@ -81,9 +81,6 @@ public class FacetManagementTest extends ScopedTest {
checkAssertion(softwareFacet, VERSION, null, true);
UUID uuid = softwareFacet.getHeader().getUUID();
Thread.sleep(1000);
/* Testing Update */
softwareFacet.setVersion(NEW_VERSION);

View File

@ -117,6 +117,14 @@ public class RuleTest extends ScopedTest {
// TODO continue with checks
eServiceManagement = new ResourceManagement();
eServiceManagement.setElementType(EService.NAME);
eServiceManagement.setJSON(eServiceString);
boolean deleted = eServiceManagement.delete();
Assert.assertTrue(deleted);
}
}

View File

@ -11,6 +11,9 @@
<logger name="org.gcube" level="INFO" />
<logger name="org.gcube.informationsystem" level="TRACE" />
<logger name="org.gcube.informationsystem.types" level="INFO" />
<logger name="org.gcube.informationsystem.resourceregistry.dbinitialization" level="INFO" />
<logger name=" org.gcube.informationsystem.impl.utils.discovery" level="INFO" />
<root level="WARN">
<appender-ref ref="STDOUT" />