Fixing database initializations

This commit is contained in:
Luca Frosini 2019-11-08 12:29:32 +01:00
parent c6ddf6da91
commit f8427ea85b
17 changed files with 802 additions and 390 deletions

View File

@ -196,7 +196,8 @@ public class DatabaseEnvironment {
contextUtility.addSecurityContext(schemaSecurityContext.getUUID().toString(), schemaSecurityContext);
if(created) {
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD);
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD);
ODatabaseDocument oDatabaseDocument = pool.acquire();
adminSecurityContext.create(oDatabaseDocument);
oDatabaseDocument.commit();
@ -207,7 +208,6 @@ public class DatabaseEnvironment {
schemaSecurityContext.create();
List<Package> packages = new ArrayList<Package>();
Class<TypeDefinition> tdClz = TypeDefinition.class;
@ -240,16 +240,17 @@ public class DatabaseEnvironment {
}
protected static Key initDbKey(Properties properties) {
try {
logger.trace("Going to get properties required to load DB key");
String keyFileName = properties.getProperty(DB_KEY_FILENAME_VARNAME);
String keyAlgorithm = properties.getProperty(DB_KEY_ALGORITHM_VARNAME);
logger.debug("Trying to load DB key from file with name {} created for algorithm {}", keyFileName, keyAlgorithm);
logger.debug("Trying to load DB key from file with name {} created for algorithm {}", keyFileName,
keyAlgorithm);
URL keyFileURL = DatabaseEnvironment.class.getClassLoader().getResource(keyFileName);
File keyFile = new File(keyFileURL.toURI());
logger.debug("Trying to load DB key from file {} created for algorithm {}", keyFile.getAbsolutePath(), keyAlgorithm);
logger.debug("Trying to load DB key from file {} created for algorithm {}", keyFile.getAbsolutePath(),
keyAlgorithm);
Key key = SymmetricKey.loadKeyFromFile(keyFile, keyAlgorithm);
logger.info("DB Key has been properly initialized");
return key;
@ -263,9 +264,7 @@ public class DatabaseEnvironment {
oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, ISConstants.DATETIME_PATTERN);
}
private static boolean initGraphDB() throws Exception {
OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false);
@ -273,64 +272,64 @@ public class DatabaseEnvironment {
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
OrientDB orientDB = new OrientDB(SERVER_URI, ROOT_USERNAME, ROOT_PASSWORD, OrientDBConfig.defaultConfig());
try {
if(!orientDB.exists(DB)) {
if(!orientDB.exists(DB)) {
logger.info("The database {} does not exist. Going to create it.", DB_URI);
orientDB.create(DB, ODatabaseType.PLOCAL);
logger.trace("Connecting to newly created database {} as {} with default password", DB_URI,
DEFAULT_ADMIN_USERNAME);
logger.info("The database {} does not exist. Going to create it.", DB_URI);
orientDB.create(DB, ODatabaseType.PLOCAL);
ODatabasePool pool = new ODatabasePool(orientDB, DB, DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD);
ODatabaseSession oDatabaseSession = pool.acquire();
logger.trace("Connecting to newly created database {} as {} with default password", DB_URI,
DEFAULT_ADMIN_USERNAME);
DatabaseEnvironment.setDateTimeFormat(oDatabaseSession);
ODatabasePool pool = new ODatabasePool(orientDB,DB, DEFAULT_ADMIN_USERNAME,DEFAULT_ADMIN_PASSWORD);
ODatabaseSession oDatabaseSession = pool.acquire();
OMetadata oMetadata = oDatabaseSession.getMetadata();
OSecurity oSecurity = oMetadata.getSecurity();
DatabaseEnvironment.setDateTimeFormat(oDatabaseSession);
logger.trace("Changing {} password", DEFAULT_ADMIN_USERNAME);
OUser admin = oSecurity.getUser(DEFAULT_ADMIN_USERNAME);
admin.setPassword(CHANGED_ADMIN_PASSWORD);
admin.save();
OMetadata oMetadata = oDatabaseSession.getMetadata();
OSecurity oSecurity = oMetadata.getSecurity();
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();
logger.trace("Changing {} password", DEFAULT_ADMIN_USERNAME);
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());
}
OUser admin = oSecurity.getUser(DEFAULT_ADMIN_USERNAME);
admin.setPassword(CHANGED_ADMIN_PASSWORD);
admin.save();
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);
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();
OClass v = oSchema.getClass("V");
v.addSuperClass(oRestricted);
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());
OClass e = oSchema.getClass("E");
e.addSuperClass(oRestricted);
oDatabaseSession.commit();
oDatabaseSession.close();
pool.close();
return true;
}
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);
OClass v = oSchema.getClass("V");
v.addSuperClass(oRestricted);
OClass e = oSchema.getClass("E");
e.addSuperClass(oRestricted);
oDatabaseSession.commit();
oDatabaseSession.close();
pool.close();
return true;
return false;
} finally {
orientDB.close();
}
orientDB.close();
return false;
}
public static Key getDatabaseKey() {

View File

@ -51,9 +51,7 @@ import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.util.ODateHelper;
import com.tinkerpop.blueprints.util.StringFactory;
@ -170,6 +168,10 @@ public abstract class ERManagement<El extends OElement> {
}
}
public void setOClass(OClass oClass) {
this.oClass = oClass;
}
protected OClass getOClass() throws SchemaException, ResourceRegistryException {
if(oClass == null) {
if(element != null) {
@ -847,15 +849,10 @@ public abstract class ERManagement<El extends OElement> {
Set<String> oldKeys = element.getPropertyNames();
Map<String,Object> properties;
if(element instanceof OVertex || element instanceof OEdge) {
try {
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
} catch(IOException e) {
throw new ResourceRegistryException(e);
}
} else {
String error = String.format("Error while updating %s properties", element.toString());
throw new ResourceRegistryException(error);
try {
properties = getPropertyMap(jsonNode, ignoreKeys, ignoreStartWithKeys);
} catch(IOException e) {
throw new ResourceRegistryException(e);
}
oldKeys.removeAll(properties.keySet());

View File

@ -125,7 +125,7 @@ public class BasePropertyManagement {
return jsonNode;
}
OClass oClass = SchemaManagementImpl.getTypeSchema(type, AccessType.PROPERTY);
OClass oClass = SchemaManagementImpl.getTypeSchema(type, AccessType.BASE_PROPERTY);
/*
* In case it is an Encrypted type the value is encrypted with the DB Key

View File

@ -4,7 +4,6 @@ import java.util.UUID;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.entities.BaseEntity;
import org.gcube.informationsystem.base.reference.relations.BaseRelation;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationNotFoundException;
@ -25,16 +24,16 @@ import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM extends BaseEntityManagement<S>, TEM extends BaseEntityManagement<T>, S extends BaseEntity, T extends BaseEntity>
public abstract class BaseRelationManagement<SEM extends BaseEntityManagement<? extends BaseEntity>, TEM extends BaseEntityManagement<? extends BaseEntity>>
extends ERManagement<OEdge> {
protected final Class<S> sourceEntityClass;
protected final Class<T> targetEntityClass;
protected final Class<? extends BaseEntity> sourceEntityClass;
protected final Class<? extends BaseEntity> targetEntityClass;
protected SEM sourceEntityManagement;
protected TEM targetEntityManagement;
protected BaseRelationManagement(AccessType accessType, Class<S> sourceEntityClass, Class<T> targetEntityClass) {
protected BaseRelationManagement(AccessType accessType, Class<? extends BaseEntity> sourceEntityClass, Class<? extends BaseEntity> targetEntityClass) {
super(accessType);
this.ignoreKeys.add(Relation.HEADER_PROPERTY);
@ -52,7 +51,7 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
this.targetEntityManagement = null;
}
protected BaseRelationManagement(AccessType accessType, Class<S> sourceEntityClass, Class<T> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) {
protected BaseRelationManagement(AccessType accessType, Class<? extends BaseEntity> sourceEntityClass, Class<? extends BaseEntity> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) {
this(accessType, sourceEntityClass, targetEntityClass);
this.oDatabaseDocument = orientGraph;
setWorkingContext(workingContext);
@ -101,12 +100,12 @@ public abstract class BaseRelationManagement<R extends BaseRelation<S, T>, SEM e
try {
if(includeSource) {
BaseEntityManagement<S> sourceEntityManagement = getSourceEntityManagement();
BaseEntityManagement<? extends BaseEntity> sourceEntityManagement = getSourceEntityManagement();
((ObjectNode) relation).replace(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly());
}
if(includeTarget) {
BaseEntityManagement<T> targetEntityManagement = getTargetEntityManagement();
BaseEntityManagement<? extends BaseEntity> targetEntityManagement = getTargetEntityManagement();
((ObjectNode) relation).replace(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson());
}

View File

@ -2,7 +2,6 @@ package org.gcube.informationsystem.resourceregistry.instances.context.relations
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.context.reference.entities.Context;
import org.gcube.informationsystem.context.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -26,7 +25,7 @@ import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class IsParentOfManagement extends BaseRelationManagement<IsParentOf,ContextManagement,ContextManagement, Context, Context> {
public class IsParentOfManagement extends BaseRelationManagement<ContextManagement,ContextManagement> {
public IsParentOfManagement() {
super(AccessType.IS_PARENT_OF, Context.class, Context.class);

View File

@ -3,11 +3,9 @@ package org.gcube.informationsystem.resourceregistry.instances.model.relations;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.consistsOf.ConsistsOfAlreadyPresentException;
@ -21,7 +19,7 @@ import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ConsistsOfManagement extends RelationManagement<ConsistsOf<Resource, Facet>, FacetManagement, Facet> {
public class ConsistsOfManagement extends RelationManagement<FacetManagement> {
public static final PropagationConstraint DEFAULT_CONSISTS_OF_PC;

View File

@ -6,7 +6,6 @@ import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isrelatedto.IsRelatedToAlreadyPresentException;
@ -20,7 +19,7 @@ import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class IsRelatedToManagement extends RelationManagement<IsRelatedTo<Resource, Resource>, ResourceManagement, Resource> {
public class IsRelatedToManagement extends RelationManagement<ResourceManagement> {
public static final PropagationConstraint DEFAULT_IS_RELATED_TO_PC;

View File

@ -45,17 +45,17 @@ import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public abstract class RelationManagement<R extends Relation<Resource, TE>, T extends EntityManagement<TE>, TE extends Entity>
extends BaseRelationManagement<R, ResourceManagement, T, Resource, TE>{
public abstract class RelationManagement<T extends EntityManagement<? extends Entity>>
extends BaseRelationManagement<ResourceManagement, T>{
public final PropagationConstraint defaultPropagationConstraint;
protected RelationManagement(AccessType accessType, Class<TE> targetEntityClass, PropagationConstraint defaultPropagationConstraint) {
protected RelationManagement(AccessType accessType, Class<? extends Entity> targetEntityClass, PropagationConstraint defaultPropagationConstraint) {
super(accessType, Resource.class, targetEntityClass);
this.defaultPropagationConstraint = defaultPropagationConstraint;
}
protected RelationManagement(AccessType accessType, Class<TE> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph,
protected RelationManagement(AccessType accessType, Class<? extends Entity> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph,
PropagationConstraint defaultPropagationConstraint) {
this(accessType, targetEntityClass, defaultPropagationConstraint);
this.oDatabaseDocument = orientGraph;
@ -119,7 +119,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
}
if(includeTarget) {
EntityManagement<TE> targetEntityManagement = getTargetEntityManagement();
EntityManagement<? extends Entity> targetEntityManagement = getTargetEntityManagement();
((ObjectNode) relation).replace(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson());
}
@ -471,7 +471,7 @@ public abstract class RelationManagement<R extends Relation<Resource, TE>, T ext
continue;
}
RelationManagement<R, T, TE> relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(),
RelationManagement<T> relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(),
oDatabaseDocument, edge);
visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
}

View File

@ -1,122 +0,0 @@
package org.gcube.informationsystem.resourceregistry.instances.type;
import java.util.Iterator;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.entities.BaseEntity;
import org.gcube.informationsystem.base.reference.properties.BaseProperty;
import org.gcube.informationsystem.base.reference.relations.BaseRelation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.instances.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.TypeBinder;
import org.gcube.informationsystem.types.reference.TypeDefinition;
import org.gcube.informationsystem.types.reference.relations.RelationTypeDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
public class SchemaContextManagementOld implements SchemaManagement {
private static Logger logger = LoggerFactory.getLogger(SchemaContextManagementOld.class);
public static final String SCHEMA = "__SCHEMA";
protected OVertex getVertex(ODatabaseDocument oDatabaseDocument, String vertexType) throws Exception {
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(vertexType, false);
Iterator<ODocument> iterator = iterable.iterator();
OVertex vertex = null;
if(iterator.hasNext()) {
vertex = (OVertex) iterator.next();
} else {
String error = String.format("%s is not a registered type", vertexType);
logger.trace(error);
throw new Exception(error);
}
if(iterator.hasNext()) {
String error = String.format(
"More than one instance of %s found in Management Context. This MUST not happen. Please contact system administrator.",
vertexType);
logger.error(error);
throw new Exception(error);
}
return vertex;
}
@Override
public String create(String json, AccessType baseType) throws SchemaException {
ODatabaseDocument orientGraph = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
orientGraph = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
TypeDefinition typeDefinition = TypeBinder.deserializeTypeDefinition(json);
if(BaseEntity.class.isAssignableFrom(baseType.getTypeClass())) {
OVertex oVertex = orientGraph.newVertex(typeDefinition.getName());
oVertex.setProperty(SCHEMA, json);
oVertex.save();
} else if(BaseRelation.class.isAssignableFrom(baseType.getTypeClass())) {
@SuppressWarnings("rawtypes")
String sourceClass = ((RelationTypeDefinition) typeDefinition).getSourceType();
OVertex source = getVertex(orientGraph, sourceClass);
@SuppressWarnings("rawtypes")
String targetClass = ((RelationTypeDefinition) typeDefinition).getTargetType();
OVertex target = getVertex(orientGraph, targetClass);
OEdge oEdge = orientGraph.newEdge(source, target, typeDefinition.getName());
oEdge.setProperty(SCHEMA, json);
oEdge.save();
} else if(BaseProperty.class.isAssignableFrom(baseType.getTypeClass())) {
ODocument doc = new ODocument(typeDefinition.getName());
doc.field(SCHEMA, json);
doc.save();
}
orientGraph.commit();
return json;
} catch(Exception e) {
if(orientGraph != null) {
orientGraph.rollback();
}
throw new SchemaException(e);
} finally {
if(orientGraph != null) {
orientGraph.close();
}
}
}
@Override
public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
// TODO Auto-generated method stub
return null;
}
@Override
public String update(String type, AccessType accessType, String json)
throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
}
@Override
public String delete(String type, AccessType accessType) throws SchemaNotFoundException {
throw new UnsupportedOperationException("Not Yet implemented");
}
}

View File

@ -1,6 +1,7 @@
package org.gcube.informationsystem.resourceregistry.instances.type;
import org.gcube.informationsystem.base.reference.AccessType;
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;
@ -12,7 +13,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
*/
public interface SchemaManagement {
public String create(String json, AccessType accessType) throws SchemaException;
public String create(String json, AccessType accessType) throws SchemaAlreadyPresentException, SchemaException;
public String read(String type, boolean includeSubtypes) throws SchemaNotFoundException, SchemaException;

View File

@ -5,13 +5,10 @@ package org.gcube.informationsystem.resourceregistry.instances.type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.activation.UnsupportedDataTypeException;
@ -19,6 +16,7 @@ import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.ISManageable;
import org.gcube.informationsystem.base.reference.entities.BaseEntity;
import org.gcube.informationsystem.base.reference.properties.BaseProperty;
import org.gcube.informationsystem.base.reference.properties.Header;
import org.gcube.informationsystem.base.reference.relations.BaseRelation;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.entities.Resource;
@ -29,7 +27,11 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.Schema
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaCreationException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.instances.base.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.instances.type.entities.EntityTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.instances.type.properties.PropertyTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.instances.type.relations.RelationTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.types.Type;
@ -54,15 +56,11 @@ import com.orientechnologies.orient.core.metadata.schema.OClassImpl;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.impls.orient.OrientElementType;
/**
* @author Luca Frosini (ISTI - CNR)
*
* TODO Create an instance for each Registered Type in a management SecurityContext so that that management context
* can be used to see Entity and Relations as graph.
*
*/
public class SchemaManagementImpl implements SchemaManagement {
@ -85,7 +83,8 @@ public class SchemaManagementImpl implements SchemaManagement {
return getTypeSchema(oSchema, type, accessType);
}
public static OClass getTypeSchema(OSchema oSchema, String type, AccessType accessType) throws SchemaException, SchemaNotFoundException {
public static OClass getTypeSchema(OSchema oSchema, String type, AccessType accessType)
throws SchemaException, SchemaNotFoundException {
try {
OClass oClass = oSchema.getClass(type);
if(oClass == null) {
@ -104,45 +103,65 @@ public class SchemaManagementImpl implements SchemaManagement {
}
}
public static OClass getTypeSchema(String type, AccessType accessType)
throws SchemaException, ResourceRegistryException {
// TODO Add a Type cache
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
try {
logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
return getTypeSchema(oDatabaseDocument, type, accessType);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
}
}
/*
try {
ExecutorService es = Executors.newSingleThreadExecutor();
Future<OClass> result = es.submit(new Callable<OClass>() {
public OClass call() throws Exception {
ODatabaseDocument oDatabaseDocument = null;
try {
logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type);
Future<OClass> result = es.submit(new Callable<OClass>() {
public OClass call() throws Exception {
ODatabaseDocument oDatabaseDocument = null;
try {
logger.debug("Getting {} Type {} schema", accessType != null ? accessType.getName() : "", type);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.activateOnCurrentThread();
return getTypeSchema(oDatabaseDocument, type, accessType);
} catch(ResourceRegistryException e) {
throw e;
}catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
}
}
});
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.activateOnCurrentThread();
return getTypeSchema(oDatabaseDocument, type, accessType);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
}
}
});
return result.get();
} catch(Exception e) {
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
*/
}
protected static TypeDefinition getTypeDefinition(OClass oClass) throws SchemaException {
ODocument oDocument = ((OClassImpl) oClass).toStream();
String json = oDocument.toJSON();
@SuppressWarnings("unused")
private static TypeDefinition getOClassTypeDefinition(OClass oClass) throws SchemaException {
try {
ODocument oDocument = ((OClassImpl) oClass).toStream();
String json = oDocument.toJSON();
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree(json);
@ -170,6 +189,28 @@ public class SchemaManagementImpl implements SchemaManagement {
}
}
private static TypeDefinition getTypeDefinition(OClass oClass) throws SchemaException {
try {
ERManagement<? extends OElement> erManagement = null;
if(oClass.isSubClassOf(BaseProperty.NAME)) {
erManagement = new PropertyTypeDefinitionManagement();
((PropertyTypeDefinitionManagement) erManagement).setName(oClass.getName());
} else if(oClass.isSubClassOf(BaseEntity.NAME)) {
erManagement = new EntityTypeDefinitionManagement();
((EntityTypeDefinitionManagement) erManagement).setName(oClass.getName());
} else if(oClass.isSubClassOf(BaseRelation.NAME)) {
erManagement = new RelationTypeDefinitionManagement();
((RelationTypeDefinitionManagement) erManagement).setName(oClass.getName());
}
String ret = erManagement.serialize();
return TypeBinder.deserializeTypeDefinition(ret);
} catch(Exception e) {
throw new SchemaException(e);
}
}
protected static String getTypeDefinitionAsString(OClass oClass) throws SchemaException {
try {
TypeDefinition typeDefinition = getTypeDefinition(oClass);
@ -214,41 +255,42 @@ public class SchemaManagementImpl implements SchemaManagement {
return oSuperclasses;
}
private static List<String> baseTypes;
private static List<String> typeDefinitionTypes;
private static Set<String> baseTypes;
private static Set<String> typeDefinitionTypes;
private static Set<String> skipTypeDefinitionCreation;
static {
baseTypes = new ArrayList<String>();
baseTypes = new HashSet<String>();
baseTypes.add(BaseProperty.NAME);
baseTypes.add(BaseEntity.NAME);
baseTypes.add(BaseRelation.NAME);
typeDefinitionTypes = new ArrayList<String>();
typeDefinitionTypes = new HashSet<String>();
typeDefinitionTypes.add(PropertyTypeDefinition.NAME);
typeDefinitionTypes.add(EntityTypeDefinition.NAME);
typeDefinitionTypes.add(RelationTypeDefinition.NAME);
skipTypeDefinitionCreation = new HashSet<String>();
skipTypeDefinitionCreation.addAll(baseTypes);
skipTypeDefinitionCreation.addAll(typeDefinitionTypes);
skipTypeDefinitionCreation.add(Header.NAME);
skipTypeDefinitionCreation.add(PropertyDefinition.NAME);
}
protected String registerTypeSchema(String jsonSchema, AccessType baseType) throws SchemaException {
protected void registerTypeSchema(TypeDefinition typeDefinition, AccessType baseType)
throws SchemaAlreadyPresentException, SchemaException {
ODatabaseDocument oDatabaseDocument = null;
try {
TypeDefinition typeDefinition = null;
try {
typeDefinition = TypeBinder.deserializeTypeDefinition(jsonSchema);
logger.info("Trying to register {} {} : {}", baseType.getName(), typeDefinition.getName(), jsonSchema);
}catch (Exception e) {
logger.error("Error while trying to register {} {}", baseType.getName(), jsonSchema);
throw e;
}
if(typeName.compareTo(typeDefinition.getName())!=0) {
String error = String.format("Provided type name path argument %s does not match with the type name in the definition %S. Please be coherent.", typeName, typeDefinition.getName());
if(typeName.compareTo(typeDefinition.getName()) != 0) {
String error = String.format(
"Provided type name path argument %s does not match with the type name in the definition %S. Please be coherent.",
typeName, typeDefinition.getName());
throw new SchemaCreationException(error);
}
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
@ -261,13 +303,6 @@ public class SchemaManagementImpl implements SchemaManagement {
oClass = oDatabaseDocument.createVertexClass(typeDefinition.getName());
} else if(BaseRelation.class.isAssignableFrom(baseType.getTypeClass())) {
oClass = oDatabaseDocument.createEdgeClass(typeDefinition.getName());
/*
* This information are persisted in Management Context String outBaseType =
* typeDefinition.getOutBaseType(); String inBaseType =
* typeDefinition.getInBaseType();
*/
} else if(BaseProperty.class.isAssignableFrom(baseType.getTypeClass())) {
oClass = oSchema.createClass(typeDefinition.getName());
} else {
@ -279,7 +314,7 @@ public class SchemaManagementImpl implements SchemaManagement {
try {
String description = typeDefinition.getDescription();
if(description!=null && description.compareTo("")!=0) {
if(description != null && description.compareTo("") != 0) {
try {
oClass.setDescription(description);
} catch(Exception e) {
@ -298,7 +333,7 @@ public class SchemaManagementImpl implements SchemaManagement {
typeDefinition.getName());
}
if(! baseTypes.contains(typeDefinition.getName())) {
if(!baseTypes.contains(typeDefinition.getName())) {
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseDocument, typeDefinition,
baseType.getName());
oClass.setSuperClasses(oSuperclasses);
@ -353,7 +388,8 @@ public class SchemaManagementImpl implements SchemaManagement {
OClass linkedClass = getOClass(oSchema, propertyDefinition.getLinkedClass());
if(linkedClass == null) {
logger.trace("class {} not found in schema", propertyDefinition.getLinkedClass());
throw new Exception("class " + propertyDefinition.getLinkedClass() + " not found in schema");
throw new Exception(
"class " + propertyDefinition.getLinkedClass() + " not found in schema");
}
if(linkedClass.isEdgeType() || linkedClass.isVertexType()) {
@ -367,21 +403,10 @@ public class SchemaManagementImpl implements SchemaManagement {
}
}
OClass toBeSerializedOClass = oClass;
if(oClass instanceof OrientElementType) {
toBeSerializedOClass = getOClass(oSchema, typeDefinition.getName());
}
oDatabaseDocument.commit();
/*
* SchemaContextManagement managementUtility = new SchemaContextManagement();
* String ret = managementUtility.create(jsonSchema, baseType);
*/
logger.info("{} {} registered successfully", baseType.getName(), typeDefinition.getName());
// TODO Remove when the previous has been implemented
String ret = getTypeDefinitionAsString(toBeSerializedOClass);
logger.info("{} type registered successfully: {}", baseType.getName(), jsonSchema);
return ret;
} catch(Exception e) {
oSchema.dropClass(typeDefinition.getName());
throw e;
@ -396,9 +421,7 @@ public class SchemaManagementImpl implements SchemaManagement {
} catch(Exception ex) {
throw new SchemaCreationException(ex);
} finally {
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
oDatabaseDocument.close();
}
}
@ -436,8 +459,46 @@ public class SchemaManagementImpl implements SchemaManagement {
}
@Override
public String create(String jsonSchema, AccessType accessType) throws SchemaException {
return registerTypeSchema(jsonSchema, accessType);
public String create(String jsonSchema, AccessType accessType) throws SchemaAlreadyPresentException, SchemaException {
TypeDefinition typeDefinition = null;
try {
try {
typeDefinition = TypeBinder.deserializeTypeDefinition(jsonSchema);
logger.info("Trying to register {} {} : {}", accessType.getName(), typeDefinition.getName(),
jsonSchema);
} catch(Exception e) {
logger.error("Error while trying to register {} {}", accessType.getName(), jsonSchema);
throw new SchemaCreationException(e);
}
registerTypeSchema(typeDefinition, accessType);
ERManagement<? extends OElement> erManagement = null;
if(BaseEntity.class.isAssignableFrom(accessType.getTypeClass())) {
erManagement = new EntityTypeDefinitionManagement();
} else if(BaseRelation.class.isAssignableFrom(accessType.getTypeClass())) {
erManagement = new RelationTypeDefinitionManagement();
} else if(BaseProperty.class.isAssignableFrom(accessType.getTypeClass())) {
erManagement = new PropertyTypeDefinitionManagement();
}
String ret = null;
if(!typeDefinitionTypes.contains(typeDefinition.getName())
&& !skipTypeDefinitionCreation.contains(typeDefinition.getName())) {
erManagement.setJson(jsonSchema);
ret = erManagement.create();
}else {
ret = TypeBinder.serializeTypeDefinition(typeDefinition);
}
return ret;
} catch(SchemaAlreadyPresentException e) {
throw e;
} catch(SchemaException e) {
throw e;
} catch(Exception ex) {
throw new SchemaCreationException(ex);
}
}
@Override
@ -448,12 +509,12 @@ public class SchemaManagementImpl implements SchemaManagement {
@Override
public String update(String entityType, AccessType accessType, String jsonSchema)
throws SchemaNotFoundException, SchemaException {
throw new UnsupportedOperationException("Not Yet implemented");
throw new UnsupportedOperationException();
}
@Override
public String delete(String entityType, AccessType accessType) throws SchemaNotFoundException {
throw new UnsupportedOperationException("Not Yet implemented");
throw new UnsupportedOperationException();
}
}

View File

@ -1,21 +1,24 @@
package org.gcube.informationsystem.resourceregistry.instances.type.entities;
import java.util.HashMap;
import javax.ws.rs.NotAcceptableException;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.entities.BaseEntity;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.base.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.BaseEntityManagement;
import org.gcube.informationsystem.resourceregistry.instances.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.instances.context.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityTypeDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -23,10 +26,12 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? extends BaseEntity>> extends BaseEntityManagement<ETD> {
public class EntityTypeDefinitionManagement extends BaseEntityManagement<EntityTypeDefinition> {
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
private static Logger logger = LoggerFactory.getLogger(EntityTypeDefinitionManagement.class);
protected String name;
@ -39,12 +44,16 @@ public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? e
init();
}
public EntityTypeDefinitionManagement(ODatabaseDocument orientGraph) throws ResourceRegistryException {
public EntityTypeDefinitionManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.oDatabaseDocument = orientGraph;
this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
if(name == null) {
if(element == null) {
@ -58,6 +67,91 @@ public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? e
return name;
}
@Override
public OVertex getElement() throws NotFoundException, ResourceRegistryException {
if(element == null) {
try {
element = retrieveElement();
} catch(NotFoundException e) {
throw e;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
} else {
if(reload) {
element.reload();
}
}
return element;
}
@Override
public OVertex retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if(getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
}
String select = "SELECT FROM " + elementType + " WHERE " + EntityTypeDefinition.NAME_PROPERTY
+ " = \"" + getName() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", elementType, getName());
logger.info(error);
throw new NotFoundException(error);
}
OResult oResult = resultSet.next();
OVertex element = (OVertex) ERManagement.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", elementType, getName(), Utility.toJsonString(element, true));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with name " + getName()
+ ". This is a fatal error please contact Admnistrator");
}
return element;
} catch(NotFoundException e) {
throw getSpecificElementNotFoundException(e);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@Override
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
elementType, jsonNode);
try {
this.element = oDatabaseDocument.newVertex(elementType);
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.info("Created {} is {}", OVertex.class.getSimpleName(),
Utility.toJsonString(element, true));
return element;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), elementType, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + elementType + " with " + jsonNode, e.getCause());
}
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
@ -68,7 +162,7 @@ public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? e
}
@Override
protected SchemaNotFoundException getSpecificElementNotFoundException(NotFoundException e) {
protected NotFoundException getSpecificElementNotFoundException(NotFoundException e) {
return new SchemaNotFoundException(e.getMessage(), e.getCause());
}
@ -79,7 +173,7 @@ public class EntityTypeDefinitionManagement<ETD extends EntityTypeDefinition<? e
@Override
protected AlreadyPresentException getSpecificERAlreadyPresentException(String message) {
throw new NotAcceptableException();
return new SchemaAlreadyPresentException(message);
}
@Override

View File

@ -1,5 +1,215 @@
package org.gcube.informationsystem.resourceregistry.instances.type.properties;
public class PropertyTypeDefinitionManagement {
import java.util.HashMap;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.base.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityTypeDefinition;
import org.gcube.informationsystem.types.reference.properties.PropertyTypeDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
public class PropertyTypeDefinitionManagement extends ERManagement<OElement> {
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
protected String name;
private void init() {
this.elementType = PropertyTypeDefinition.NAME;
}
public PropertyTypeDefinitionManagement() {
super(AccessType.PROPERTY_TYPE_DEFINITION);
init();
}
public PropertyTypeDefinitionManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext();
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getInstance()
.getSecurityContextByUUID(DatabaseEnvironment.SCHEMA_SECURITY_CONTEXT_UUID);
}
return workingContext;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
if(name == null) {
if(element == null) {
if(jsonNode != null) {
name = jsonNode.get(PropertyTypeDefinition.NAME_PROPERTY).asText();
}
} else {
name = element.getProperty(PropertyTypeDefinition.NAME_PROPERTY);
}
}
return name;
}
@Override
public String serialize() throws ResourceRegistryException {
return serializeAsJson().toString();
}
@Override
public JsonNode serializeAsJson() throws ResourceRegistryException {
return serializeSelfOnly();
}
@Override
protected OElement reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", PropertyTypeDefinition.NAME, getName());
try {
this.element = new ODocument(elementType);
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", PropertyTypeDefinition.NAME, Utility.toJsonString(element, true));
return element;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", OElement.class.getSimpleName(),
accessType.getName(), elementType, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + elementType + " with " + jsonNode, e.getCause());
}
}
@Override
protected OElement reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", EntityTypeDefinition.NAME, getName());
OElement propertyTypeDefinition = getElement();
propertyTypeDefinition = (OElement) ERManagement.updateProperties(oClass, propertyTypeDefinition, jsonNode,
ignoreKeys, ignoreStartWithKeys);
return propertyTypeDefinition;
}
@Override
protected boolean reallyDelete() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to remove {} for {}", EntityTypeDefinition.NAME, getName());
getElement().delete();
return true;
}
@Override
public OElement getElement() throws NotFoundException, ResourceRegistryException {
if(element == null) {
try {
element = retrieveElement();
} catch(NotFoundException e) {
throw e;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
} else {
if(reload) {
element.reload();
}
}
return element;
}
@Override
public OElement retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if(getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
}
String select = "SELECT FROM " + elementType + " WHERE " + PropertyTypeDefinition.NAME_PROPERTY + " = \""
+ getName() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", elementType, getName());
logger.info(error);
throw new NotFoundException(error);
}
OResult oResult = resultSet.next();
OElement element = (OElement) ERManagement.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", elementType, getName(), Utility.toJsonString(element, true));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with name " + getName()
+ ". This is a fatal error please contact Admnistrator");
}
return element;
} catch(NotFoundException e) {
throw getSpecificElementNotFoundException(e);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
throw new UnsupportedOperationException();
}
@Override
protected boolean reallyAddToContext(SecurityContext targetSecurityContext)
throws ContextException, ResourceRegistryException {
throw new UnsupportedOperationException();
}
@Override
protected boolean reallyRemoveFromContext(SecurityContext targetSecurityContext)
throws ContextException, ResourceRegistryException {
throw new UnsupportedOperationException();
}
@Override
protected NotFoundException getSpecificElementNotFoundException(NotFoundException e) {
return new SchemaNotFoundException(e.getMessage(), e.getCause());
}
@Override
protected AvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message) {
throw new UnsupportedOperationException();
}
@Override
protected AlreadyPresentException getSpecificERAlreadyPresentException(String message) {
return new SchemaAlreadyPresentException(message);
}
}

View File

@ -1,40 +1,39 @@
package org.gcube.informationsystem.resourceregistry.instances.type.relations;
import java.util.HashMap;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.entities.BaseEntity;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.isparentof.IsParentOfNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.schema.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.base.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.BaseRelationManagement;
import org.gcube.informationsystem.resourceregistry.instances.context.ContextUtility;
import org.gcube.informationsystem.resourceregistry.instances.context.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.instances.type.entities.EntityTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityTypeDefinition;
import org.gcube.informationsystem.types.reference.relations.RelationTypeDefinition;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<SETD, TETD, S, T>,
SEM extends EntityTypeDefinitionManagement<SETD>, TEM extends EntityTypeDefinitionManagement<TETD>,
SETD extends EntityTypeDefinition<S>, TETD extends EntityTypeDefinition<T>,
S extends BaseEntity, T extends BaseEntity>
public class RelationTypeDefinitionManagement extends
BaseRelationManagement<EntityTypeDefinitionManagement,EntityTypeDefinitionManagement> {
extends BaseRelationManagement<R, SEM, TEM, SETD, TETD> {
protected String name;
@SuppressWarnings("unchecked")
public RelationTypeDefinitionManagement() {
super(AccessType.RELATION_TYPE_DEFINITION, (Class<SETD>) EntityTypeDefinition.class, (Class<TETD>) EntityTypeDefinition.class);
super(AccessType.RELATION_TYPE_DEFINITION, EntityTypeDefinition.class, EntityTypeDefinition.class);
}
public RelationTypeDefinitionManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
@ -43,6 +42,23 @@ public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<S
getWorkingContext();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
if(name == null) {
if(element == null) {
if(jsonNode != null) {
name = jsonNode.get(RelationTypeDefinition.NAME_PROPERTY).asText();
}
} else {
name = element.getProperty(RelationTypeDefinition.NAME_PROPERTY);
}
}
return name;
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
@ -53,61 +69,126 @@ public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<S
}
@Override
protected IsParentOfNotFoundException getSpecificElementNotFoundException(NotFoundException e) {
return new IsParentOfNotFoundException(e.getMessage(), e.getCause());
}
protected OEdge reallyCreate() throws ResourceRegistryException {
@Override
protected IsParentOfAlreadyPresentException getSpecificERAlreadyPresentException(String message) {
return new IsParentOfAlreadyPresentException(message);
}
if(sourceEntityManagement == null) {
@Override
public JsonNode serializeAsJson() throws ResourceRegistryException {
return serializeAsJson(false, true);
}
public JsonNode serializeAsJson(boolean includeSource, boolean includeTarget) throws ResourceRegistryException {
JsonNode relation = serializeSelfOnly();
try {
OVertex source = element.getVertex(ODirection.OUT);
ContextManagement sourceContextManagement = new ContextManagement(oDatabaseDocument);
sourceContextManagement.setElement(source);
if(includeSource) {
((ObjectNode)relation).replace(Relation.SOURCE_PROPERTY, sourceContextManagement.serializeSelfOnly());
if(!jsonNode.has(Relation.SOURCE_PROPERTY)) {
throw new ResourceRegistryException("Error while creating relation. No source definition found");
}
OVertex target = element.getVertex(ODirection.IN);
ContextManagement targetContextManagement = new ContextManagement(oDatabaseDocument);
targetContextManagement.setElement(target);
if(includeTarget) {
((ObjectNode)relation).replace(Relation.TARGET_PROPERTY, targetContextManagement.serializeSelfOnly());
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e;
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElementType(EntityTypeDefinition.NAME);
sourceEntityManagement.setJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY));
}
return relation;
if(targetEntityManagement == null) {
targetEntityManagement = newTargetEntityManagement();
if(!jsonNode.has(Relation.TARGET_PROPERTY)) {
throw new ResourceRegistryException(
"Error while creating " + elementType + ". No target definition found");
}
targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElementType(EntityTypeDefinition.NAME);
targetEntityManagement.setJsonNode(jsonNode.get(Relation.TARGET_PROPERTY));
}
logger.trace("Creating {} beetween {} -> {}", elementType, getSourceEntityManagement().serialize(),
getTargetEntityManagement().serialize());
OVertex source = (OVertex) getSourceEntityManagement().getElement();
OVertex target = (OVertex) getTargetEntityManagement().getElement();
element = oDatabaseDocument.newEdge(source, target, elementType);
ERManagement.updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
return element;
}
@Override
protected SEM newSourceEntityManagement() throws ResourceRegistryException {
@SuppressWarnings("unchecked")
SEM sem = (SEM) new EntityTypeDefinitionManagement<SETD>(oDatabaseDocument);
return sem;
public OEdge getElement() throws NotFoundException, ResourceRegistryException {
if(element == null) {
try {
element = retrieveElement();
} catch(NotFoundException e) {
throw e;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
} else {
if(reload) {
element.reload();
}
}
return element;
}
@Override
protected TEM newTargetEntityManagement() throws ResourceRegistryException {
@SuppressWarnings("unchecked")
TEM tem = (TEM) new EntityTypeDefinitionManagement<TETD>(oDatabaseDocument);
return tem;
public OEdge retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if(getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
}
String select = "SELECT FROM " + elementType + " WHERE " + RelationTypeDefinition.NAME_PROPERTY
+ " = \"" + getName() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", elementType, getName());
logger.info(error);
throw new NotFoundException(error);
}
OResult oResult = resultSet.next();
OEdge element = (OEdge) ERManagement.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", elementType, getName(), Utility.toJsonString(element, true));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with name " + getName()
+ ". This is a fatal error please contact Admnistrator");
}
return element;
} catch(NotFoundException e) {
throw getSpecificElementNotFoundException(e);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
@Override
protected EntityTypeDefinitionManagement newSourceEntityManagement()
throws ResourceRegistryException {
return new EntityTypeDefinitionManagement(oDatabaseDocument);
}
@Override
protected EntityTypeDefinitionManagement newTargetEntityManagement()
throws ResourceRegistryException {
return new EntityTypeDefinitionManagement(oDatabaseDocument);
}
@Override
protected NotFoundException getSpecificElementNotFoundException(NotFoundException e) {
return new SchemaNotFoundException(e.getMessage(), e.getCause());
}
@Override
protected AlreadyPresentException getSpecificERAlreadyPresentException(String message) {
return new SchemaAlreadyPresentException(message);
}
@Override
@ -131,4 +212,5 @@ public class RelationTypeDefinitionManagement<R extends RelationTypeDefinition<S
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
throw new UnsupportedOperationException();
}
}

View File

@ -367,6 +367,7 @@ public class SecurityContext {
public void create() throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument adminDatabaseDocument = getAdminDatabaseDocument();
adminDatabaseDocument.activateOnCurrentThread();
@ -433,14 +434,8 @@ public class SecurityContext {
}
public void create(ODatabaseSession oDatabaseSession) {
OSecurity oSecurity = getOSecurity(oDatabaseSession);
createRolesAndUsers(oSecurity);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
public void create(ODatabaseDocument orientGraph) {
OSecurity oSecurity = getOSecurity(orientGraph);
public void create(ODatabaseDocument oDatabaseDocument) {
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
createRolesAndUsers(oSecurity);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}

View File

@ -3,6 +3,7 @@ package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashMap;
import java.util.UUID;
import org.gcube.informationsystem.base.reference.ER;
import org.gcube.informationsystem.base.reference.properties.BaseProperty;
import org.gcube.informationsystem.base.reference.properties.Header;
import org.gcube.informationsystem.model.reference.entities.Entity;
@ -96,7 +97,7 @@ public class Utility {
}
// TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE " + Relation.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
String select = "SELECT FROM " + elementType + " WHERE " + ER.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ " = \"" + uuid.toString() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());

View File

@ -5,12 +5,15 @@ package org.gcube.informationsystem.resourceregistry.schema;
import java.util.List;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.ISManageable;
import org.gcube.informationsystem.base.reference.properties.BaseProperty;
import org.gcube.informationsystem.base.reference.properties.Header;
import org.gcube.informationsystem.base.reference.relations.BaseRelation;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
@ -18,11 +21,23 @@ import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.instances.type.SchemaManagement;
import org.gcube.informationsystem.resourceregistry.instances.type.SchemaManagementImpl;
import org.gcube.informationsystem.types.TypeBinder;
import org.gcube.informationsystem.types.impl.entities.EntityTypeDefinitionImpl;
import org.gcube.informationsystem.types.impl.properties.PropertyTypeDefinitionImpl;
import org.gcube.informationsystem.types.impl.relations.RelationTypeDefinitionImpl;
import org.gcube.informationsystem.types.reference.TypeDefinition;
import org.gcube.informationsystem.types.reference.entities.EntityTypeDefinition;
import org.gcube.informationsystem.types.reference.properties.PropertyTypeDefinition;
import org.gcube.informationsystem.types.reference.relations.RelationTypeDefinition;
import org.gcube.informationsystem.utils.ISMapper;
import org.gcube.resourcemanagement.model.reference.entities.facets.AccessPointFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.ContactFacet;
import org.gcube.resourcemanagement.model.reference.entities.resources.Actor;
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
import org.gcube.resourcemanagement.model.reference.entities.resources.RunningPlugin;
import org.gcube.resourcemanagement.model.reference.properties.ValueSchema;
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory;
import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Hosts;
import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Uses;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -127,4 +142,88 @@ public class SchemaManagementImplTest {
logger.debug("{} list : {}", IsRelatedTo.NAME, list);
}
@Test
public void createPropertyType() throws Exception {
PropertyTypeDefinition<ValueSchema> propertyTypeDefinition = new PropertyTypeDefinitionImpl<>(ValueSchema.class);
SchemaManagement schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(ValueSchema.NAME);
String ret = schemaManagement.create(ISMapper.marshal(propertyTypeDefinition), AccessType.PROPERTY);
logger.debug(ret);
}
@Test
public void createEncryptedType() throws Exception {
PropertyTypeDefinition<Encrypted> propertyTypeDefinition = new PropertyTypeDefinitionImpl<>(Encrypted.class);
SchemaManagement schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(Encrypted.NAME);
String ret = schemaManagement.create(ISMapper.marshal(propertyTypeDefinition), AccessType.PROPERTY);
logger.debug(ret);
}
@Test
public void createFacetType() throws Exception {
EntityTypeDefinition entityTypeDefinition = new EntityTypeDefinitionImpl(AccessPointFacet.class);
SchemaManagement schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(AccessPointFacet.NAME);
String ret = schemaManagement.create(ISMapper.marshal(entityTypeDefinition), AccessType.FACET);
logger.debug(ret);
}
@Test
public void createResourceType() throws Exception {
EntityTypeDefinition entityTypeDefinition = new EntityTypeDefinitionImpl(EService.class);
SchemaManagement schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(EService.NAME);
String ret = schemaManagement.create(ISMapper.marshal(entityTypeDefinition), AccessType.RESOURCE);
logger.debug(ret);
entityTypeDefinition = new EntityTypeDefinitionImpl(RunningPlugin.class);
schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(RunningPlugin.NAME);
ret = schemaManagement.create(ISMapper.marshal(entityTypeDefinition), AccessType.RESOURCE);
logger.debug(ret);
}
@Test
public void createIsRelatedToType() throws Exception {
@SuppressWarnings("unchecked")
RelationTypeDefinition relationTypeDefinition = new RelationTypeDefinitionImpl((Class<? extends BaseRelation<?,?>>) Uses.class);
SchemaManagement schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(Uses.NAME);
String ret = schemaManagement.create(ISMapper.marshal(relationTypeDefinition), AccessType.IS_RELATED_TO);
logger.debug(ret);
}
@Test
public void createConsistsOfType() throws Exception {
@SuppressWarnings("unchecked")
RelationTypeDefinition relationTypeDefinition = new RelationTypeDefinitionImpl((Class<? extends BaseRelation<?,?>>) HasVolatileMemory.class);
SchemaManagement schemaManagement = new SchemaManagementImpl();
((SchemaManagementImpl) schemaManagement).setTypeName(HasVolatileMemory.NAME);
String ret = schemaManagement.create(ISMapper.marshal(relationTypeDefinition), AccessType.CONSISTS_OF);
logger.debug(ret);
}
}