From f8427ea85b41eee2d80c147aefcf5b4879f50560 Mon Sep 17 00:00:00 2001 From: Luca Frosini Date: Fri, 8 Nov 2019 12:29:32 +0100 Subject: [PATCH] Fixing database initializations --- .../dbinitialization/DatabaseEnvironment.java | 127 +++++----- .../instances/base/ERManagement.java | 19 +- .../properties/BasePropertyManagement.java | 2 +- .../relations/BaseRelationManagement.java | 15 +- .../relations/IsParentOfManagement.java | 3 +- .../model/relations/ConsistsOfManagement.java | 4 +- .../relations/IsRelatedToManagement.java | 3 +- .../model/relations/RelationManagement.java | 12 +- .../type/SchemaContextManagementOld.java | 122 --------- .../instances/type/SchemaManagement.java | 3 +- .../instances/type/SchemaManagementImpl.java | 239 +++++++++++------- .../EntityTypeDefinitionManagement.java | 110 +++++++- .../PropertyTypeDefinitionManagement.java | 212 +++++++++++++++- .../RelationTypeDefinitionManagement.java | 208 ++++++++++----- .../security/SecurityContext.java | 11 +- .../resourceregistry/utils/Utility.java | 3 +- .../schema/SchemaManagementImplTest.java | 99 ++++++++ 17 files changed, 802 insertions(+), 390 deletions(-) delete mode 100644 src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaContextManagementOld.java diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java index 70dc979..ad2699c 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/dbinitialization/DatabaseEnvironment.java @@ -93,7 +93,7 @@ public class DatabaseEnvironment { private static final String SERVER_URI; public static final String DB_URI; - + public static final String O_RESTRICTED_CLASS = "ORestricted"; public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT; @@ -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 packages = new ArrayList(); Class 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,66 +272,66 @@ public class DatabaseEnvironment { logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI); OrientDB orientDB = new OrientDB(SERVER_URI, ROOT_USERNAME, ROOT_PASSWORD, OrientDBConfig.defaultConfig()); - - 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); - - ODatabasePool pool = new ODatabasePool(orientDB,DB, DEFAULT_ADMIN_USERNAME,DEFAULT_ADMIN_PASSWORD); - ODatabaseSession oDatabaseSession = pool.acquire(); - - DatabaseEnvironment.setDateTimeFormat(oDatabaseSession); - - - OMetadata oMetadata = oDatabaseSession.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()); + try { + 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); + + ODatabasePool pool = new ODatabasePool(orientDB, DB, DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD); + ODatabaseSession oDatabaseSession = pool.acquire(); + + DatabaseEnvironment.setDateTimeFormat(oDatabaseSession); + + OMetadata oMetadata = oDatabaseSession.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); + + OClass v = oSchema.getClass("V"); + v.addSuperClass(oRestricted); + + 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() { return KEY; } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ERManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ERManagement.java index 639f577..416ac36 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ERManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/ERManagement.java @@ -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 { } } + 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 { Set oldKeys = element.getPropertyNames(); Map 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()); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/properties/BasePropertyManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/properties/BasePropertyManagement.java index 588970d..e58de31 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/properties/BasePropertyManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/properties/BasePropertyManagement.java @@ -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 diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/BaseRelationManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/BaseRelationManagement.java index 5cb0c77..f6367b3 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/BaseRelationManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/base/relations/BaseRelationManagement.java @@ -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, SEM extends BaseEntityManagement, TEM extends BaseEntityManagement, S extends BaseEntity, T extends BaseEntity> +public abstract class BaseRelationManagement, TEM extends BaseEntityManagement> extends ERManagement { - protected final Class sourceEntityClass; - protected final Class targetEntityClass; + protected final Class sourceEntityClass; + protected final Class targetEntityClass; protected SEM sourceEntityManagement; protected TEM targetEntityManagement; - protected BaseRelationManagement(AccessType accessType, Class sourceEntityClass, Class targetEntityClass) { + protected BaseRelationManagement(AccessType accessType, Class sourceEntityClass, Class targetEntityClass) { super(accessType); this.ignoreKeys.add(Relation.HEADER_PROPERTY); @@ -52,7 +51,7 @@ public abstract class BaseRelationManagement, SEM e this.targetEntityManagement = null; } - protected BaseRelationManagement(AccessType accessType, Class sourceEntityClass, Class targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) { + protected BaseRelationManagement(AccessType accessType, Class sourceEntityClass, Class targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) { this(accessType, sourceEntityClass, targetEntityClass); this.oDatabaseDocument = orientGraph; setWorkingContext(workingContext); @@ -101,12 +100,12 @@ public abstract class BaseRelationManagement, SEM e try { if(includeSource) { - BaseEntityManagement sourceEntityManagement = getSourceEntityManagement(); + BaseEntityManagement sourceEntityManagement = getSourceEntityManagement(); ((ObjectNode) relation).replace(Relation.SOURCE_PROPERTY, sourceEntityManagement.serializeSelfOnly()); } if(includeTarget) { - BaseEntityManagement targetEntityManagement = getTargetEntityManagement(); + BaseEntityManagement targetEntityManagement = getTargetEntityManagement(); ((ObjectNode) relation).replace(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson()); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/context/relations/IsParentOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/context/relations/IsParentOfManagement.java index 37d809e..6227de0 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/context/relations/IsParentOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/context/relations/IsParentOfManagement.java @@ -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 { +public class IsParentOfManagement extends BaseRelationManagement { public IsParentOfManagement() { super(AccessType.IS_PARENT_OF, Context.class, Context.class); diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java index 8030b1c..77fad43 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/ConsistsOfManagement.java @@ -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, FacetManagement, Facet> { +public class ConsistsOfManagement extends RelationManagement { public static final PropagationConstraint DEFAULT_CONSISTS_OF_PC; diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/IsRelatedToManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/IsRelatedToManagement.java index d106b6f..baaa5fb 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/IsRelatedToManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/IsRelatedToManagement.java @@ -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, ResourceManagement, Resource> { +public class IsRelatedToManagement extends RelationManagement { public static final PropagationConstraint DEFAULT_IS_RELATED_TO_PC; diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/RelationManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/RelationManagement.java index 106862d..6886c6c 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/RelationManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/model/relations/RelationManagement.java @@ -45,17 +45,17 @@ import com.orientechnologies.orient.core.record.impl.ODocument; /** * @author Luca Frosini (ISTI - CNR) */ -public abstract class RelationManagement, T extends EntityManagement, TE extends Entity> - extends BaseRelationManagement{ +public abstract class RelationManagement> + extends BaseRelationManagement{ public final PropagationConstraint defaultPropagationConstraint; - protected RelationManagement(AccessType accessType, Class targetEntityClass, PropagationConstraint defaultPropagationConstraint) { + protected RelationManagement(AccessType accessType, Class targetEntityClass, PropagationConstraint defaultPropagationConstraint) { super(accessType, Resource.class, targetEntityClass); this.defaultPropagationConstraint = defaultPropagationConstraint; } - protected RelationManagement(AccessType accessType, Class targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph, + protected RelationManagement(AccessType accessType, Class targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph, PropagationConstraint defaultPropagationConstraint) { this(accessType, targetEntityClass, defaultPropagationConstraint); this.oDatabaseDocument = orientGraph; @@ -119,7 +119,7 @@ public abstract class RelationManagement, T ext } if(includeTarget) { - EntityManagement targetEntityManagement = getTargetEntityManagement(); + EntityManagement targetEntityManagement = getTargetEntityManagement(); ((ObjectNode) relation).replace(Relation.TARGET_PROPERTY, targetEntityManagement.serializeAsJson()); } @@ -471,7 +471,7 @@ public abstract class RelationManagement, T ext continue; } - RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), + RelationManagement relationManagement = ERManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge); visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaContextManagementOld.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaContextManagementOld.java deleted file mode 100644 index 8a933b5..0000000 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaContextManagementOld.java +++ /dev/null @@ -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 iterable = oDatabaseDocument.browseClass(vertexType, false); - Iterator 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"); - } - -} diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagement.java index bccefb9..14b73f2 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagement.java @@ -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; diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagementImpl.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagementImpl.java index 4feb7cb..6b1c5a2 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagementImpl.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/SchemaManagementImpl.java @@ -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 result = es.submit(new Callable() { - 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(); - } - } - } - }); + Future result = es.submit(new Callable() { + 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(); + } + } + } + }); 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); @@ -152,7 +171,7 @@ public class SchemaManagementImpl implements SchemaManagement { node.put(ISManageable.CLASS_PROPERTY, EntityTypeDefinition.NAME); } else if(oClass.isSubClassOf(BaseRelation.NAME)) { node.put(ISManageable.CLASS_PROPERTY, RelationTypeDefinition.NAME); - } + } ArrayNode arrayNode = (ArrayNode) node.get(TypeDefinition.PROPERTIES_PROPERTY); Iterator iterator = arrayNode.iterator(); @@ -161,7 +180,7 @@ public class SchemaManagementImpl implements SchemaManagement { propertyNode.put(ISManageable.CLASS_PROPERTY, PropertyDefinition.NAME); } - String managedJson = mapper.writeValueAsString(node); + String managedJson = mapper.writeValueAsString(node); logger.trace("{} -> {}", json, managedJson); return TypeBinder.deserializeTypeDefinition(managedJson); @@ -170,6 +189,28 @@ public class SchemaManagementImpl implements SchemaManagement { } } + private static TypeDefinition getTypeDefinition(OClass oClass) throws SchemaException { + try { + ERManagement 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 baseTypes; - private static List typeDefinitionTypes; + private static Set baseTypes; + private static Set typeDefinitionTypes; + private static Set skipTypeDefinitionCreation; static { - baseTypes = new ArrayList(); + baseTypes = new HashSet(); baseTypes.add(BaseProperty.NAME); baseTypes.add(BaseEntity.NAME); baseTypes.add(BaseRelation.NAME); - typeDefinitionTypes = new ArrayList(); + typeDefinitionTypes = new HashSet(); typeDefinitionTypes.add(PropertyTypeDefinition.NAME); typeDefinitionTypes.add(EntityTypeDefinition.NAME); typeDefinitionTypes.add(RelationTypeDefinition.NAME); + + skipTypeDefinitionCreation = new HashSet(); + 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 { @@ -278,8 +313,8 @@ public class SchemaManagementImpl implements SchemaManagement { try { - String description = typeDefinition.getDescription(); - if(description!=null && description.compareTo("")!=0) { + String description = typeDefinition.getDescription(); + 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 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 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(); } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/entities/EntityTypeDefinitionManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/entities/EntityTypeDefinitionManagement.java index 52b3853..cc34cb3 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/entities/EntityTypeDefinitionManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/entities/EntityTypeDefinitionManagement.java @@ -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> extends BaseEntityManagement { +public class EntityTypeDefinitionManagement extends BaseEntityManagement { - 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()); + + + 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 { + + 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); + } } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/relations/RelationTypeDefinitionManagement.java b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/relations/RelationTypeDefinitionManagement.java index dba771b..ffc27f3 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/relations/RelationTypeDefinitionManagement.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/instances/type/relations/RelationTypeDefinitionManagement.java @@ -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, - SEM extends EntityTypeDefinitionManagement, TEM extends EntityTypeDefinitionManagement, - SETD extends EntityTypeDefinition, TETD extends EntityTypeDefinition, - S extends BaseEntity, T extends BaseEntity> - - extends BaseRelationManagement { +public class RelationTypeDefinitionManagement extends + BaseRelationManagement { + + protected String name; - @SuppressWarnings("unchecked") public RelationTypeDefinitionManagement() { - super(AccessType.RELATION_TYPE_DEFINITION, (Class) EntityTypeDefinition.class, (Class) EntityTypeDefinition.class); + super(AccessType.RELATION_TYPE_DEFINITION, EntityTypeDefinition.class, EntityTypeDefinition.class); } public RelationTypeDefinitionManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException { @@ -43,6 +42,23 @@ public class RelationTypeDefinitionManagement {}", 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(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(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 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 AvailableInAnotherContextException getSpecificERAvailableInAnotherContextException(String message) { throw new UnsupportedOperationException(); } - + @Override public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException { throw new UnsupportedOperationException(); } + } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/security/SecurityContext.java b/src/main/java/org/gcube/informationsystem/resourceregistry/security/SecurityContext.java index 082796f..da361ac 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/security/SecurityContext.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/security/SecurityContext.java @@ -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()); } diff --git a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java index abafe0a..2c04906 100644 --- a/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java +++ b/src/main/java/org/gcube/informationsystem/resourceregistry/utils/Utility.java @@ -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<>()); diff --git a/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java b/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java index 2344697..d160d36 100644 --- a/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java +++ b/src/test/java/org/gcube/informationsystem/resourceregistry/schema/SchemaManagementImplTest.java @@ -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 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 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>) 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>) HasVolatileMemory.class); + + SchemaManagement schemaManagement = new SchemaManagementImpl(); + ((SchemaManagementImpl) schemaManagement).setTypeName(HasVolatileMemory.NAME); + String ret = schemaManagement.create(ISMapper.marshal(relationTypeDefinition), AccessType.CONSISTS_OF); + + logger.debug(ret); + + } + + }