Compare commits

..

9 Commits

137 changed files with 2327 additions and 5937 deletions

2
.gitignore vendored
View File

@ -1,5 +1,3 @@
target
.classpath
.project
/.DS_Store
/bin/

View File

@ -2,31 +2,13 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Resource Registry Service
## [v4.4.0-SNAPSHOT]
- Added query parameters to paginate result of queries [#24648]
- Completely refactored JSON Query management [#24163]
## [v4.3.0]
- Migrated code to reorganized E/R format [#24992]
- Metadata are added only if requested by the client [#25040]
- Restored Encrypted Property Type and removed Vault [#25041]
- Cleaned RequestInfo in RequestFilter class [#25211]
- Solved bug which allow to create two query template with the same name if a null id was provided [#25650]
## [v4.2.0]
## [v5.0.0-SNAPSHOT]
- Switched to gcube-smartgears-bom 3.0.0
- Fixed bug on JSONQuery for Facets which does not have any properties to match [#24237]
- Fixed bug on JSONQuery for IsRelatedTo relations indicating both source and target resources [#24264]
- Fixed bug on returned boolean values as string [#24240]
- Enabled array properties [#24225]
- Using delete in propagation contraint as action indication for delete operation [#24301]
- Fixed default value of propagation constraint of remove action for ConsistsOf to 'cascade' [#24223]
- Removed Encrypted Property Type and added Vault instead [#24655]
- Enhanced gcube-smartgears-bom version
## [v4.1.0]

39
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry</artifactId>
<version>4.4.0-SNAPSHOT</version>
<version>5.0.0-SNAPSHOT</version>
<name>Resource Registry Service</name>
<description>The Resource Registry is a web-service which represent the core component of the gCube Information System</description>
<packaging>war</packaging>
@ -31,7 +31,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-smartgears-bom</artifactId>
<version>2.5.0</version>
<version>3.0.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -40,25 +40,16 @@
<dependencies>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-api</artifactId>
<scope>provided</scope>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>information-system-model</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-utils</artifactId>
<version>[2.2.0, 3.0.0-SNAPSHOT)</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-api</artifactId>
</dependency>
<dependency>
<groupId>com.orientechnologies</groupId>
@ -81,10 +72,6 @@
<groupId>org.gcube.common</groupId>
<artifactId>gxHTTP</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
</dependency>
<!-- Jersey -->
<dependency>
<groupId>javax.ws.rs</groupId>
@ -101,20 +88,6 @@
<scope>provided</scope>
</dependency>
<!-- END Jersey -->
<!-- Added to support Java 11 JDK -->
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- END Added to support Java 11 JDK -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>

View File

@ -5,10 +5,13 @@ import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.ContextBean;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
@ -16,8 +19,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecur
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -25,6 +27,7 @@ import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
@ -50,6 +53,33 @@ public class ContextUtility {
contexts = new HashMap<>();
}
private static final InheritableThreadLocal<Boolean> hierarchicalMode = new InheritableThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
public static InheritableThreadLocal<Boolean> getHierarchicalMode() {
return hierarchicalMode;
}
private static final InheritableThreadLocal<Boolean> includeInstanceContexts = new InheritableThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
public static InheritableThreadLocal<Boolean> getIncludeInstanceContexts() {
return includeInstanceContexts;
}
public static String getCurrentContextFullName() {
return SecretManagerProvider.instance.get().getContext();
}
@ -82,7 +112,7 @@ public class ContextUtility {
SecurityContext securityContext = null;
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
UUID uuid = ServerContextCache.getInstance().getUUIDByFullName(fullName);
UUID uuid = ContextCache.getInstance().getUUIDByFullName(fullName);
if(uuid != null) {
securityContext = contexts.get(uuid);
@ -95,7 +125,9 @@ public class ContextUtility {
OVertex contextVertex = getContextVertexByFullName(oDatabaseDocument, fullName);
uuid = UUIDUtility.getUUID(contextVertex);
ODocument oDocument = contextVertex.getProperty(IdentifiableElement.HEADER_PROPERTY);
uuid = UUID.fromString(oDocument.getProperty(Header.UUID_PROPERTY));
securityContext = getSecurityContextByUUID(uuid, contextVertex);
@ -139,7 +171,7 @@ public class ContextUtility {
ODatabaseDocument oDatabaseDocument = null;
try {
oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER);
OVertex oVertex = OrientDBUtility.getElementByUUID(oDatabaseDocument, Context.NAME, uuid,
OVertex oVertex = Utility.getElementByUUID(oDatabaseDocument, Context.NAME, uuid,
OVertex.class);
return oVertex;
} finally {
@ -166,7 +198,7 @@ public class ContextUtility {
OVertex parentVertex = contextVertex.getVertices(ODirection.IN, IsParentOf.NAME).iterator().next();
if(parentVertex != null) {
UUID parentUUID = UUIDUtility.getUUID(parentVertex);
UUID parentUUID = Utility.getUUID(parentVertex);
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
}
@ -190,7 +222,7 @@ public class ContextUtility {
private OVertex getContextVertexByFullName(ODatabaseDocument oDatabaseDocument, String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} with full name '{}'", Context.NAME, OVertex.class.getSimpleName(), fullName);
ScopeBean scopeBean = new ScopeBean(fullName);
ContextBean scopeBean = new ContextBean(fullName);
String name = scopeBean.name();
// TODO Rewrite better query. This query works because all the scope parts has a different name
@ -207,7 +239,7 @@ public class ContextUtility {
OResult oResult = resultSet.next();
OVertex context = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
logger.trace("Context Representing Vertex : {}", OrientDBUtility.getAsStringForLogging(context));
logger.trace("Context Representing Vertex : {}", Utility.toJsonString(context, true));
if(resultSet.hasNext()) {
throw new ContextNotFoundException("Found more than one context with name " + name

View File

@ -1,242 +0,0 @@
package org.gcube.informationsystem.resourceregistry.contexts;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.com.fasterxml.jackson.databind.node.TextNode;
import org.gcube.informationsystem.contexts.impl.entities.ContextImpl;
import org.gcube.informationsystem.contexts.impl.relations.IsParentOfImpl;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ServerContextCache extends ContextCache {
private static Logger logger = LoggerFactory.getLogger(ServerContextCache.class);
protected List<Context> contextsMetaPrivacy;
protected Map<UUID, Context> uuidToContextMetaPrivacy;
protected List<Context> contextsNoMeta;
protected Map<UUID, Context> uuidToContextNoMeta;
protected boolean includeMeta;
protected static ServerContextCache singleton;
public synchronized static ServerContextCache getInstance() {
if(singleton==null) {
singleton = new ServerContextCache();
}
return singleton;
}
@Override
public void cleanCache() {
cleanCache(Calendar.getInstance());
}
@Override
protected void cleanCache(Calendar now) {
super.cleanCache(now);
contextsMetaPrivacy = null;
uuidToContextMetaPrivacy = null;
contextsNoMeta = null;
uuidToContextNoMeta = null;
}
public ServerContextCache() {
Calendar now = Calendar.getInstance();
cleanCache(now);
initContextCacheRenewal();
}
public boolean isIncludeMeta() {
return includeMeta;
}
public void setIncludeMeta(boolean includeMeta) {
this.includeMeta = includeMeta;
}
public void initContextCacheRenewal() {
ContextCacheRenewal contextCacheRenewal = new ContextCacheRenewal() {
@Override
public List<Context> renew() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceOffset(0);
contextManagement.setForceLimit(-1);
String contextsJsonString = contextManagement.allFromDatabase(false);
List<Context> contexts = null;
try {
contexts = ElementMapper.unmarshalList(contextsJsonString);
} catch (IOException e) {
logger.error("Unable to read contexts from DB", e);
}
return contexts;
}
};
setContextCacheRenewal(contextCacheRenewal);
}
protected boolean isUserAllowedToGetPrivacyMeta() {
return ElementManagement.isUserAllowedToGetPrivacyMeta();
}
@Override
public synchronized List<Context> getContexts() throws ResourceRegistryException {
refreshContextsIfNeeded();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
if(requestInfo.getUriInfo()!=null && !requestInfo.includeMeta()){
return contextsNoMeta;
}
if(isUserAllowedToGetPrivacyMeta()) {
return contexts;
}else {
return contextsMetaPrivacy;
}
}
@Override
public synchronized Context getContextByUUID(UUID uuid) throws ResourceRegistryException {
refreshContextsIfNeeded();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
if(requestInfo.getUriInfo()!=null && !requestInfo.includeMeta()){
return uuidToContextNoMeta.get(uuid);
}
if(isUserAllowedToGetPrivacyMeta()) {
return uuidToContext.get(uuid);
}else {
return uuidToContextMetaPrivacy.get(uuid);
}
}
protected Metadata getMetadataForPrivacy(ObjectMapper objectMapper, Metadata metadata) {
ObjectNode objectNode = objectMapper.valueToTree(metadata);
objectNode.replace(Metadata.CREATED_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER));
objectNode.replace(Metadata.LAST_UPDATE_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER));
try {
Metadata metadataWithPrivacy = objectMapper.treeToValue(objectNode, Metadata.class);
return metadataWithPrivacy;
} catch (JsonProcessingException e) {
return metadata;
}
}
@Override
protected void setContexts(Calendar calendar, List<Context> contexts) {
this.contexts = new ArrayList<>();
this.uuidToContext = new LinkedHashMap<>();
this.contextsMetaPrivacy = new ArrayList<>();
this.uuidToContextMetaPrivacy = new LinkedHashMap<>();
this.contextsNoMeta = new ArrayList<>();
this.uuidToContextNoMeta = new LinkedHashMap<>();
ObjectMapper objectMapper = ElementMapper.getObjectMapper();
for(Context c : contexts) {
UUID uuid = c.getID();
Context contextWithMeta = new ContextImpl(c.getName());
contextWithMeta.setMetadata(c.getMetadata());
contextWithMeta.setID(uuid);
this.contexts.add(contextWithMeta);
this.uuidToContext.put(uuid, contextWithMeta);
Context contextMetaPrivacy = new ContextImpl(c.getName());
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, c.getMetadata());
contextMetaPrivacy.setMetadata(metadataWithPrivacy);
contextMetaPrivacy.setID(uuid);
this.contextsMetaPrivacy.add(contextMetaPrivacy);
this.uuidToContextMetaPrivacy.put(uuid, contextMetaPrivacy);
Context contextNoMeta = new ContextImpl(c.getName());
contextNoMeta.setMetadata(null);
contextNoMeta.setID(uuid);
this.contextsNoMeta.add(contextNoMeta);
this.uuidToContextNoMeta.put(uuid, contextNoMeta);
}
for(Context c : contexts) {
UUID uuid = c.getID();
Context contextMeta = this.uuidToContext.get(uuid);
Context contextMetaPrivacy = this.uuidToContextMetaPrivacy.get(uuid);
Context contextNoMeta = this.uuidToContextNoMeta.get(uuid);
if(c.getParent()!=null) {
IsParentOf ipo = c.getParent();
UUID isParentOfParentUUID = ipo.getID();
UUID contextParentUUID = ipo.getSource().getID();
Context parentWithMeta = this.uuidToContext.get(contextParentUUID);
IsParentOf isParentOfWithMeta = new IsParentOfImpl(parentWithMeta, contextMeta);
isParentOfWithMeta.setID(isParentOfParentUUID);
isParentOfWithMeta.setMetadata(ipo.getMetadata());
parentWithMeta.addChild(isParentOfWithMeta);
contextMeta.setParent(isParentOfWithMeta);
Context parentWithMetaPrivacy = this.uuidToContextMetaPrivacy.get(contextParentUUID);
IsParentOf isParentOfMetaPrivacy = new IsParentOfImpl(parentWithMetaPrivacy, contextMetaPrivacy);
isParentOfMetaPrivacy.setID(isParentOfParentUUID);
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, ipo.getMetadata());
isParentOfMetaPrivacy.setMetadata(metadataWithPrivacy);
parentWithMetaPrivacy.addChild(isParentOfMetaPrivacy);
contextMetaPrivacy.setParent(isParentOfMetaPrivacy);
Context parentNoMeta = this.uuidToContextNoMeta.get(contextParentUUID);
IsParentOf isParentOfNoMeta = new IsParentOfImpl(parentNoMeta, contextNoMeta);
isParentOfNoMeta.setMetadata(null);
isParentOfNoMeta.setID(isParentOfParentUUID);
parentNoMeta.addChild(isParentOfNoMeta);
contextNoMeta.setParent(isParentOfNoMeta);
}
}
for(Context context : contexts) {
UUID uuid = context.getID();
String fullName = getContextFullName(context);
this.uuidToContextFullName.put(uuid, fullName);
this.contextFullNameToUUID.put(fullName, uuid);
}
SortedSet<String> contextFullNames = new TreeSet<String>(contextFullNameToUUID.keySet());
for(String contextFullName : contextFullNames) {
UUID uuid = contextFullNameToUUID.get(contextFullName);
Context context = uuidToContext.get(uuid);
contextsTree.addNode(context);
}
}
}

View File

@ -1,9 +1,7 @@
package org.gcube.informationsystem.resourceregistry.contexts.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ -14,10 +12,11 @@ import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.NullNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -27,20 +26,15 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.relations.IsParentOfManagement;
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.queries.operators.ComparisonOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.LogicalOperator;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.utils.UUIDManager;
import org.gcube.informationsystem.utils.UUIDUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -59,25 +53,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
protected String name;
protected Integer forceOffset;
protected Integer forceLimit;
public void setForceOffset(Integer forceOffset) {
this.forceOffset = forceOffset;
}
public void setForceLimit(Integer forceLimit) {
this.forceLimit = forceLimit;
}
private void init() {
this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY);
this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY);
this.typeName = Context.NAME;
this.forceIncludeMeta = true;
this.forceIncludeAllMeta = true;
this.forceOffset = null;
this.forceLimit = null;
}
public ContextManagement() {
@ -142,13 +122,15 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
select.append(parentId);
select.append(" MAXDEPTH 1) WHERE ");
select.append(Context.NAME_PROPERTY);
select.append(ComparisonOperator.EQ.getDbOperator());
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
select.append("\"");
select.append(getName());
select.append("\"");
select.append(LogicalOperator.AND.getDbOperator());
select.append(IdentifiableElement.ID_PROPERTY);
select.append(ComparisonOperator.NE.getDbOperator());
select.append(QueryLogicalOperator.AND.getLogicalOperator());
select.append(Context.HEADER_PROPERTY);
select.append(".");
select.append(Header.UUID_PROPERTY);
select.append(QueryConditionalOperator.NE.getConditionalOperator());
select.append("\"");
select.append(parentContext.uuid);
select.append("\"");
@ -164,11 +146,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
select.append(Context.NAME);
select.append(" WHERE ");
select.append(Context.NAME_PROPERTY);
select.append(ComparisonOperator.EQ.getDbOperator());
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
select.append("\"");
select.append(getName());
select.append("\"");
select.append(LogicalOperator.AND.getDbOperator());
select.append(QueryLogicalOperator.AND.getLogicalOperator());
select.append("in(\"");
select.append(IsParentOf.NAME);
select.append("\").size() = 0");
@ -210,7 +192,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
((ObjectNode) context).replace(Context.PARENT_PROPERTY, isParentOf);
}
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ContextException("");
}
}
@ -224,10 +206,10 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
JsonNode isParentOf = isParentOfManagement.serializeAsJsonNode();
context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY);
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e;
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e);
}
}
@ -253,7 +235,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
checkContext(parentContextManagement);
if (uuid == null) {
uuid = UUIDManager.getInstance().generateValidUUID();
uuid = UUID.randomUUID();
}
createVertex();
@ -284,7 +266,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
if (parentSecurityContext != null && securityContext != null) {
parentSecurityContext.getChildren().remove(securityContext);
}
ServerContextCache.getInstance().cleanCache();
ContextCache.getInstance().cleanCache();
}
throw e;
}
@ -303,7 +285,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
for (OVertex p : iterable) {
if (found) {
String message = String.format("{} has more than one parent. {}", Context.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(message.toString());
}
parent = p;
@ -325,7 +307,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
if (parentContextJsonNode != null && !(parentContextJsonNode instanceof NullNode)) {
UUID parentUUID = UUIDUtility.getUUID(parentContextJsonNode);
UUID parentUUID = org.gcube.informationsystem.utils.Utility.getUUIDFromJsonNode(parentContextJsonNode);
if (actualParentContextManagement != null) {
if (parentUUID.compareTo(actualParentContextManagement.uuid) != 0) {
parentChanged = true;
@ -363,7 +345,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ServerContextCache.getInstance().cleanCache();
ContextCache.getInstance().cleanCache();
return element;
}
@ -387,7 +369,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
if (edgeIterator.hasNext()) {
throw new ContextException(
"Seems that the Context has more than one Parent. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
"Seems that the Context has more than one Parent. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -420,55 +402,23 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(oDatabaseDocument);
ServerContextCache.getInstance().cleanCache();
ContextCache.getInstance().cleanCache();
}
@Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(forceLimit!=null) {
limit = forceLimit;
}
if(limit == null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(forceOffset!=null) {
offset = forceOffset;
}
if(offset == null) {
offset = 0;
}
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceIncludeMeta(forceIncludeMeta);
contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta);
contextManagement.setElement((OVertex) vertex);
try {
JsonNode jsonObject = contextManagement.serializeAsJsonNode();
arrayNode.add(jsonObject);
if(limit > 0 && ++count >= limit) {
break;
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {
@ -478,54 +428,17 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
}
public String allFromDatabase(boolean polymorphic) throws ResourceRegistryException {
public String allFromServer(boolean polymorphic) throws ResourceRegistryException {
return super.all(polymorphic);
}
@Override
public String all(boolean polymorphic) throws ResourceRegistryException {
try {
ServerContextCache contextCache = ServerContextCache.getInstance();
List<Context> contexts = contextCache.getContexts();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(forceLimit!=null) {
limit = forceLimit;
}else if(limit == null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(forceOffset!=null) {
offset = forceOffset;
}else if(offset == null) {
offset = 0;
}
int position = -1;
int count = 0;
if(offset==0 && limit<=0) {
return ElementMapper.marshal(contexts);
}
List<Context> requestedContexts = new ArrayList<>();
for (Context c : contexts) {
if(++position < offset) {
continue;
}
requestedContexts.add(c);
if(limit > 0 && ++count >= limit) {
break;
}
}
return ElementMapper.marshal(requestedContexts);
ContextCache contextCache = ContextCache.getInstance();
return ElementMapper.marshal(contextCache.getContexts());
} catch (JsonProcessingException | ResourceRegistryException e) {
return allFromDatabase(polymorphic);
return allFromServer(polymorphic);
}
}
@ -537,7 +450,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
public String readAsString()
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try {
ServerContextCache contextCache = ServerContextCache.getInstance();
ContextCache contextCache = ContextCache.getInstance();
return ElementMapper.marshal(contextCache.getContextByUUID(uuid));
} catch (JsonProcessingException | ResourceRegistryException e) {
return readFromServer();

View File

@ -18,7 +18,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextMan
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
@ -38,10 +38,8 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
this();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext();
this.includeSource = false;
this.includeTarget = true;
this.forceIncludeMeta = true;
this.forceIncludeAllMeta = true;
includeSource = false;
includeTarget = true;
}
@Override
@ -90,10 +88,10 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, 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, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}

View File

@ -42,11 +42,6 @@ public class AdminSecurityContext extends SecurityContext {
super(ADMIN_SECURITY_CONTEXT_UUID, false);
}
@Override
protected boolean isHierarchicalMode() {
return false;
}
@Override
public void create() {
throw new RuntimeException("Cannot use this method for Admin Context");

View File

@ -40,11 +40,6 @@ public class ContextSecurityContext extends SecurityContext {
super(CONTEXT_SECURITY_CONTEXT_UUID, false);
}
@Override
protected boolean isHierarchicalMode() {
return false;
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());

View File

@ -40,11 +40,6 @@ public class QueryTemplatesSecurityContext extends SecurityContext {
super(QUERY_TEMPLATES_SECURITY_CONTEXT_UUID, false);
}
@Override
protected boolean isHierarchicalMode() {
return false;
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());

View File

@ -10,14 +10,16 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.utils.UUIDManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -91,7 +93,7 @@ public class SecurityContext {
protected Set<SecurityContext> children;
protected boolean isHierarchicalMode() {
return hierarchical || RequestUtility.getRequestInfo().get().isHierarchicalMode();
return hierarchical && ContextUtility.getHierarchicalMode().get();
}
public void setParentSecurityContext(SecurityContext parentSecurityContext) {
@ -163,7 +165,7 @@ public class SecurityContext {
errorMessage.append(" to non hierarchic ");
errorMessage.append(SecurityContext.class.getSimpleName());
errorMessage.append(". ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
final String error = errorMessage.toString();
logger.error(error);
throw new RuntimeException(error);
@ -295,7 +297,7 @@ public class SecurityContext {
String[] list = name.split("_");
if (list.length == 2) {
String contextUUID = list[1];
if (!UUIDManager.getInstance().isReservedUUID(contextUUID)) {
if (!UUIDManager.isReservedUUID(contextUUID)) {
contexts.add(contextUUID);
}
}
@ -410,9 +412,14 @@ public class SecurityContext {
}
protected boolean allowed(final ORole role, final ODocument oDocument) {
ServerRequestInfo sri = RequestUtility.getRequestInfo().get();
Boolean hm = sri.isHierarchicalMode();
sri.setHierarchicalMode(false);
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
ContextUtility.getHierarchicalMode().set(false);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
@ -427,8 +434,6 @@ public class SecurityContext {
} catch(Exception e) {
return false;
} finally {
sri.setHierarchicalMode(hm);
if(oDatabaseDocument!=null) {
oDatabaseDocument.close();
}
@ -437,7 +442,16 @@ public class SecurityContext {
current.activateOnCurrentThread();
}
}
}
};
Future<Boolean> result = executor.submit(callable);
try {
return result.get();
} catch(Exception e) {
return false;
}
}
public void create() throws ResourceRegistryException {

View File

@ -1,72 +0,0 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ShadowContextSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
private static final String SHADOW_CONTEXT_SECURITY_CONTEXT;
private static final UUID SHADOW_CONTEXT_SECURITY_CONTEXT_UUID;
static {
SHADOW_CONTEXT_SECURITY_CONTEXT = "cccccccc-cccc-cccc-cccc-cccccccccccc";
SHADOW_CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(SHADOW_CONTEXT_SECURITY_CONTEXT);
}
private static ShadowContextSecurityContext instance;
public static ShadowContextSecurityContext getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new ShadowContextSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(SHADOW_CONTEXT_SECURITY_CONTEXT, instance);
}
return instance;
}
private ShadowContextSecurityContext() throws ResourceRegistryException {
super(SHADOW_CONTEXT_SECURITY_CONTEXT_UUID, false);
}
@Override
protected boolean isHierarchicalMode() {
return false;
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_ALL);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_ALL);
break;
case READER:
role.addRule(ORule.ResourceGeneric.CLUSTER, null, ORole.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.SYSTEM_CLUSTERS, null, ORole.PERMISSION_READ);
role.addRule(ORule.ResourceGeneric.CLASS, null, ORole.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -40,11 +40,6 @@ public class TypeSecurityContext extends SecurityContext {
super(SCHEMA_SECURITY_CONTEXT_UUID, false);
}
@Override
protected boolean isHierarchicalMode() {
return false;
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());

View File

@ -1,31 +0,0 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.discovery.DiscoveredElementAction;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class CreateTypeAction implements DiscoveredElementAction<Element> {
private static Logger logger = LoggerFactory.getLogger(CreateTypeAction.class);
@Override
public void analizeElement(Class<Element> e) throws Exception {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(e);
try {
typeManagement.create();
} catch(SchemaAlreadyPresentException sape) {
logger.warn("{} already exists. It will be ignored", typeManagement.getTypeName());
} catch(Exception ex) {
logger.error("Error creating schema for {} {}: {}", typeManagement.getType().getAccessType(), typeManagement.getTypeName(), ex.getMessage());
throw ex;
}
}
}

View File

@ -1,6 +1,7 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Key;
@ -17,19 +18,19 @@ import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.entities.EntityElement;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.base.reference.relations.RelationElement;
import org.gcube.informationsystem.discovery.Discovery;
import org.gcube.informationsystem.discovery.RegistrationProvider;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type;
@ -42,6 +43,10 @@ import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.types.reference.relations.ConsistsOfType;
import org.gcube.informationsystem.types.reference.relations.IsRelatedToType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.informationsystem.utils.discovery.ElementSpecilizationDiscovery;
import org.gcube.informationsystem.utils.discovery.RegistrationProvider;
import org.gcube.informationsystem.utils.discovery.SchemaAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -65,6 +70,7 @@ import com.orientechnologies.orient.core.record.OElement;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("unchecked")
public class DatabaseEnvironment {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class);
@ -187,11 +193,10 @@ public class DatabaseEnvironment {
TypeSecurityContext.getInstance().create();
ContextSecurityContext.getInstance().create();
/* We must create only OrientDB types */
List<Class<? extends Element>> definitionToBeCreated = new ArrayList<>();
definitionToBeCreated.add(PropertyElement.class);
definitionToBeCreated.add(Property.class);
definitionToBeCreated.add(Metadata.class);
definitionToBeCreated.add(Header.class);
definitionToBeCreated.add(PropertyDefinition.class);
definitionToBeCreated.add(PropertyType.class);
definitionToBeCreated.add(LinkedEntity.class);
@ -204,40 +209,24 @@ public class DatabaseEnvironment {
definitionToBeCreated.add(IsRelatedToType.class);
definitionToBeCreated.add(ConsistsOfType.class);
SchemaAction schemaAction = new SchemaActionImpl();
for(Class<? extends Element> clz : definitionToBeCreated) {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(clz);
if(clz.equals(Property.class) || clz.equals(Metadata.class) ) {
((TypeManagement) typeManagement).setSkipTypeDefinitionCreation(true);
if(PropertyElement.class.isAssignableFrom(clz)) {
schemaAction.managePropertyClass((Class<? extends PropertyElement>) clz);
} else if(EntityElement.class.isAssignableFrom(clz)) {
schemaAction.manageEntityClass((Class<? extends EntityElement>) clz);
} else if(RelationElement.class.isAssignableFrom(clz)) {
schemaAction.manageRelationClass((Class<? extends RelationElement<? extends EntityElement, ? extends EntityElement>>) clz);
}
}
try {
typeManagement.create();
} catch(SchemaAlreadyPresentException sape) {
logger.warn("{} already exists. It will be ignored", typeManagement.getTypeName());
} catch(Exception ex) {
logger.error("Error creating schema for {} {}: {}", typeManagement.getType().getAccessType(), typeManagement.getTypeName(), ex.getMessage());
throw ex;
}
}
/*
* We have already created Property and Metadata
* because Metadata is needed to create
* types for internal use (i.e. Context, EntityType).
*
* For Property and Metadata we also need
* to create the instance in TypeSecurityContext
* as we will do for any other Property specialization.
*/
List<Class<? extends Element>> schemaToBeCreated = new ArrayList<>();
schemaToBeCreated.add(Property.class);
schemaToBeCreated.add(Metadata.class);
for(Class<? extends Element> clazz : schemaToBeCreated) {
schemaToBeCreated.add(Header.class);
for(Class<? extends Element> clz : schemaToBeCreated) {
ElementManagement<? extends OElement,?> erManagement = new PropertyTypeDefinitionManagement();
erManagement.setJson(TypeMapper.serializeType(clazz));
erManagement.setJson(TypeMapper.serializeType(clz));
erManagement.create();
}
@ -247,12 +236,10 @@ public class DatabaseEnvironment {
Class<Type> typeClz = Type.class;
packages.add(typeClz.getPackage());
// Adding all packages of AccessType
AccessType[] accessTypes = AccessType.values();
for(AccessType accessType : accessTypes) {
Class<Element> clazz = accessType.getTypeClass();
packages.add(clazz.getPackage());
Class<Element> clz = accessType.getTypeClass();
packages.add(clz.getPackage());
}
ServiceLoader<? extends RegistrationProvider> regsitrationProviders = ServiceLoader
@ -261,20 +248,7 @@ public class DatabaseEnvironment {
packages.addAll(registrationProvider.getPackagesToRegister());
}
AccessType[] veryBaseTypes = new AccessType[] {
AccessType.PROPERTY_ELEMENT,
AccessType.ENTITY_ELEMENT,
AccessType.RELATION_ELEMENT
};
for(AccessType accessType : veryBaseTypes) {
Discovery<Element> discovery = new Discovery<>(accessType.getTypeClass());
discovery.addPackages(packages);
CreateTypeAction createTypeAction = new CreateTypeAction();
discovery.addDiscoveredElementActions(createTypeAction);
discovery.discover();
}
ElementSpecilizationDiscovery.manageISM(schemaAction, packages);
}
logger.info("Database Connection has been properly initialized");
@ -286,8 +260,8 @@ public class DatabaseEnvironment {
KEY = initDbKey(properties);
// Initializing ServerContextCache instance
ServerContextCache.getInstance();
initContextCacheRenewal();
}
protected static Key initDbKey(Properties properties) {
@ -375,6 +349,26 @@ public class DatabaseEnvironment {
}
}
public static void initContextCacheRenewal() {
ContextCacheRenewal contextCacheRenewal = new ContextCacheRenewal() {
@Override
public List<Context> renew() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement();
String contextsJsonString = contextManagement.allFromServer(false);
List<Context> contexts = null;
try {
contexts = ElementMapper.unmarshalList(contextsJsonString);
} catch (IOException e) {
logger.error("Unable to read contexts from DB", e);
}
return contexts;
}
};
ContextCache.getInstance().setContextCacheRenewal(contextCacheRenewal);
}
public static Key getDatabaseKey() {
return KEY;
}

View File

@ -0,0 +1,68 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.gcube.informationsystem.base.reference.entities.EntityElement;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.base.reference.relations.RelationElement;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.utils.discovery.SchemaAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class SchemaActionImpl implements SchemaAction {
private static Logger logger = LoggerFactory.getLogger(SchemaActionImpl.class);
@Override
public <R extends RelationElement<? extends EntityElement,? extends EntityElement>> void manageRelationClass(Class<R> r)
throws Exception {
try {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(r);
typeManagement.create();
} catch(SchemaAlreadyPresentException sape) {
logger.warn("{} already exists. It will be ignored", TypeMapper.getType(r));
} catch(Exception ex) {
logger.error("Error creating schema for {} {}: {}", RelationElement.NAME, r.getSimpleName(), ex.getMessage());
throw ex;
}
}
@Override
public <E extends EntityElement> void manageEntityClass(Class<E> e) throws Exception {
try {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(e);
typeManagement.create();
} catch(SchemaAlreadyPresentException sape) {
logger.warn("{} already exists. It will be ignored", TypeMapper.getType(e));
} catch(Exception ex) {
logger.error("Error creating schema for {} {}: {}", EntityElement.NAME, e.getSimpleName(), ex.getMessage());
throw ex;
}
}
@Override
public <P extends PropertyElement> void managePropertyClass(Class<P> p) throws Exception {
try {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(p);
if(p.equals(Property.class) || p.equals(Header.class) ) {
((TypeManagement) typeManagement).setSkipTypeDefinitionCreation(true);
}
typeManagement.create();
} catch(SchemaAlreadyPresentException sape) {
logger.warn("{} already exists. It will be ignored", TypeMapper.getType(p));
} catch(Exception ex) {
logger.error("Error creating schema for {} {}: {}", PropertyElement.NAME, p.getSimpleName(), ex.getMessage());
throw ex;
}
}
}

View File

@ -24,15 +24,11 @@ import org.gcube.com.fasterxml.jackson.databind.node.BooleanNode;
import org.gcube.com.fasterxml.jackson.databind.node.JsonNodeType;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.com.fasterxml.jackson.databind.node.TextNode;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -41,26 +37,20 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.properties.PropertyElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataOrient;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.resourceregistry.utils.HeaderOrient;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.Type;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.properties.PropertyDefinition;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.informationsystem.utils.UUIDManager;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -83,7 +73,6 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
public final static String AT = "@";
public final static String UNDERSCORE = "_";
public final static String DOLLAR = "$";
protected final Set<String> ignoreKeys;
protected final Set<String> ignoreStartWithKeys;
@ -106,19 +95,6 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
protected El element;
protected boolean reload;
/**
* Used to force Meta inclusion.
* It is use for example to request to include meta
* by the context cache manager.
*/
protected boolean forceIncludeMeta;
/**
* Used to force Meta inclusion in all instances.
* It is use for example to request to include meta
* by the context cache manager.
*/
protected boolean forceIncludeAllMeta;
/**
* Some operation, e.g. delete has a cascade impact which is not know a priori by the client.
* Setting this variable to false the system just simulate the operation so an interested client
@ -158,16 +134,11 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
this.accessType = accessType;
this.ignoreKeys = new HashSet<String>();
this.ignoreKeys.add(Element.TYPE_PROPERTY);
this.ignoreKeys.add(ModelElement.SUPERTYPES_PROPERTY);
this.ignoreKeys.add(ModelElement.EXPECTED_TYPE_PROPERTY);
this.ignoreKeys.add(IdentifiableElement.ID_PROPERTY);
this.ignoreKeys.add(IdentifiableElement.METADATA_PROPERTY);
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(ElementManagement.AT);
this.ignoreStartWithKeys.add(ElementManagement.UNDERSCORE);
this.ignoreStartWithKeys.add(ElementManagement.DOLLAR);
this.reload = false;
@ -181,29 +152,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
this.dryRun = false;
this.affectedInstances = new HashMap<>();
this.forceIncludeMeta = false;
this.forceIncludeAllMeta = false;
}
public boolean isForceIncludeMeta() {
return forceIncludeMeta;
}
public void setForceIncludeMeta(boolean forceIncludeMeta) {
this.forceIncludeMeta = forceIncludeMeta;
}
public boolean isForceIncludeAllMeta() {
return forceIncludeAllMeta;
}
public void setForceIncludeAllMeta(boolean forceIncludeAllMeta) {
this.forceIncludeAllMeta = forceIncludeAllMeta;
}
public Map<UUID,JsonNode> getAffectedInstances() {
return affectedInstances;
@ -217,7 +167,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
this.dryRun = dryRun;
}
public void setAsEntryPoint() {
protected void setAsEntryPoint() {
this.entryPoint = true;
}
@ -352,13 +302,16 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
public String getTypeName() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
if(typeName==null) {
if(element!=null) {
typeName = getOClass().getName();
typeName = element.getProperty(Element.CLASS_PROPERTY);
}
if(typeName==null && jsonNode!=null) {
this.typeName = TypeUtility.getTypeName(jsonNode);
this.typeName = getClassProperty(jsonNode);
}
if(typeName==null) {
typeName = getOClass().getName();
}
}
return typeName;
}
@ -366,23 +319,15 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
protected void checkJsonNode() throws ResourceRegistryException {
if(uuid == null) {
try {
uuid = UUIDUtility.getUUID(jsonNode);
uuid = org.gcube.informationsystem.utils.Utility.getUUIDFromJsonNode(jsonNode);
} catch(Exception e) {
}
} else {
checkUUIDMatch();
}
if(uuid!=null) {
try {
UUIDManager.getInstance().validateUUID(uuid);
} catch (Exception e) {
throw new ResourceRegistryException(e.getMessage());
}
}
if(this.typeName == null) {
this.typeName = TypeUtility.getTypeName(jsonNode);
this.typeName = getClassProperty(jsonNode);
getOClass();
} else {
checkERMatch();
@ -391,7 +336,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
protected void checkERMatch() throws ResourceRegistryException {
if(jsonNode != null) {
String type = TypeUtility.getTypeName(jsonNode);
String type = getClassProperty(jsonNode);
if(type != null && type.compareTo(typeName) != 0) {
String error = String.format("Requested type does not match with json representation %s!=%s",
typeName, type);
@ -402,14 +347,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
getOClass();
}
protected void checkUUIDMatch() throws ResourceRegistryException {
UUID resourceUUID = UUIDUtility.getUUID(jsonNode);
if(resourceUUID!=null) {
Header header = null;
try {
header = HeaderUtility.getHeader(jsonNode, false);
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
if(header != null) {
UUID resourceUUID = header.getUUID();
if(resourceUUID.compareTo(uuid) != 0) {
String error = String.format(
"UUID provided in the instance (%s) differs from UUID (%s) used to identify the %s instance",
"UUID provided in header (%s) differs from the one (%s) used to identify the %s instance",
resourceUUID.toString(), uuid.toString(), typeName);
throw new ResourceRegistryException(error);
@ -417,11 +367,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
}
private void analizeProperty(OElement element, String key, ObjectNode objectNode) throws ResourceRegistryException {
private JsonNode createSelfJsonNode() throws ResourceRegistryException {
try {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
OElement element = getElement();
Set<String> keys = element.getPropertyNames();
for(String key : keys) {
Object object = element.getProperty(key);
if(object == null) {
objectNode.replace(key, null);
return;
continue;
}
JsonNode jsonNode = getPropertyForJson(key, object);
if(jsonNode != null) {
@ -429,72 +387,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
}
private JsonNode createSelfJsonNode() throws ResourceRegistryException {
try {
objectNode.put(Element.CLASS_PROPERTY, getTypeName());
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
Collection<String> superClasses = getCachedType().getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
OElement element = getElement();
Set<String> keys = element.getPropertyNames();
/* Add first these key to provide an order in Json */
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
List<String> keysToAddFirst = new ArrayList<>();
keysToAddFirst.add(Element.TYPE_PROPERTY);
keysToAddFirst.add(ModelElement.SUPERTYPES_PROPERTY);
keysToAddFirst.add(IdentifiableElement.ID_PROPERTY);
keysToAddFirst.add(IdentifiableElement.METADATA_PROPERTY);
keysToAddFirst.add(ERElement.CONTEXTS_PROPERTY);
keysToAddFirst.add(Relation.PROPAGATION_CONSTRAINT_PROPERTY);
for(String key : keysToAddFirst) {
switch (key) {
case Element.TYPE_PROPERTY:
objectNode.put(Element.TYPE_PROPERTY, getTypeName());
break;
case ModelElement.SUPERTYPES_PROPERTY:
Collection<String> supertypes = getCachedType().getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(supertypes);
if(arrayNode==null || arrayNode.size()==0) {
objectNode.remove(ModelElement.SUPERTYPES_PROPERTY);
}else {
objectNode.replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
}
break;
case IdentifiableElement.METADATA_PROPERTY:
if(requestInfo.includeMeta() || forceIncludeMeta) {
if(requestInfo.allMeta() || entryPoint || forceIncludeAllMeta) {
analizeProperty(element, key, objectNode);
}
}
break;
case ERElement.CONTEXTS_PROPERTY:
if(requestInfo.includeContexts()) {
objectNode.replace(ERElement.CONTEXTS_PROPERTY, getContextsAsObjectNode());
}
break;
default:
if(keys.contains(key)) {
analizeProperty(element, key, objectNode);
}
break;
}
}
for(String key : keys) {
if(keysToAddFirst.contains(key)) {
// the property has been already added
continue;
}
analizeProperty(element, key, objectNode);
}
objectNode.replace(Element.SUPERCLASSES_PROPERTY, arrayNode);
return objectNode;
} catch(ResourceRegistryException e) {
@ -538,18 +436,16 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
try {
setOperation(Operation.CREATE);
UUIDManager uuidManager = UUIDManager.getInstance();
reallyCreate();
if(uuid == null) {
uuid = uuidManager.generateValidUUID();
Header entityHeader = HeaderUtility.getHeader(jsonNode, true);
if(entityHeader != null) {
element.setProperty(IdentifiableElement.HEADER_PROPERTY, entityHeader);
} else {
entityHeader = HeaderUtility.addHeader(element, null);
uuid = entityHeader.getUUID();
}
element = reallyCreate();
element.setProperty(IdentifiableElement.ID_PROPERTY, uuid.toString());
MetadataUtility.addMetadata(element);
getWorkingContext().addElement(element, oDatabaseDocument);
element.save();
@ -572,7 +468,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
reallyUpdate();
MetadataUtility.updateModifiedByAndLastUpdate(element);
HeaderUtility.updateModifiedByAndLastUpdate(element);
element.save();
@ -607,7 +503,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
throw new ResourceRegistryException("Trying to set null " + elementClass.getSimpleName() + " in " + this);
}
this.element = element;
this.uuid = UUIDUtility.getUUID(element);
this.uuid = HeaderUtility.getHeader(element).getUUID();
OClass oClass = getOClass();
this.typeName = oClass.getName();
}
@ -641,7 +537,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
if(uuid == null) {
throw new NotFoundException("null UUID does not allow to retrieve the Element");
}
return OrientDBUtility.getElementByUUID(oDatabaseDocument, typeName == null ? accessType.getName() : typeName, uuid,
return Utility.getElementByUUID(oDatabaseDocument, typeName == null ? accessType.getName() : typeName, uuid,
elementClass);
} catch(NotFoundException e) {
throw getSpecificNotFoundException(e);
@ -654,7 +550,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
public El retrieveElementFromAnyContext() throws NotFoundException, ResourceRegistryException {
try {
return OrientDBUtility.getElementByUUIDAsAdmin(typeName == null ? accessType.getName() : typeName, uuid,
return Utility.getElementByUUIDAsAdmin(typeName == null ? accessType.getName() : typeName, uuid,
elementClass);
} catch(NotFoundException e) {
throw getSpecificNotFoundException(e);
@ -723,17 +619,16 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
boolean update = false;
setAsEntryPoint();
try {
setAsEntryPoint();
getElement();
setOperation(Operation.UPDATE);
update = true;
internalUpdate();
} catch(NotFoundException e) {
setOperation(Operation.CREATE);
String calledMethod = CalledMethodProvider.instance.get();
setAsEntryPoint();
String calledMethod = InnerMethodName.instance.get();
calledMethod = calledMethod.replace("update", "create");
CalledMethodProvider.instance.set(calledMethod);
InnerMethodName.instance.set(calledMethod);
internalCreate();
}
@ -919,10 +814,10 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
}
public Set<String> getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException {
logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument instanceDB = this.oDatabaseDocument;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
@ -946,10 +841,6 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
if(current!=null) {
current.activateOnCurrentThread();
}
if(instanceDB!=null) {
this.oDatabaseDocument = instanceDB;
}
}
}
@ -968,7 +859,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
private ObjectNode getContextsAsObjectNode(ObjectMapper objectMapper) throws NotFoundException, ContextException, ResourceRegistryException {
try {
Set<String> contexts = getContextsSet();
ServerContextCache contextCache = ServerContextCache.getInstance();
ContextCache contextCache = ContextCache.getInstance();
ObjectNode objectNode = objectMapper.createObjectNode();
for(String contextUUID : contexts) {
String contextFullName = contextCache.getContextFullNameByUUID(contextUUID);
@ -987,6 +878,13 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
return getContextsAsObjectNode(objectMapper);
}
public static String getClassProperty(JsonNode jsonNode) {
if(jsonNode.has(Element.CLASS_PROPERTY)) {
return jsonNode.get(Element.CLASS_PROPERTY).asText();
}
return null;
}
public static Object getObjectFromJsonNode(JsonNode value)
throws UnsupportedDataTypeException, ResourceRegistryException {
JsonNodeType jsonNodeType = value.getNodeType();
@ -1177,6 +1075,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
for(String key : properties.keySet()) {
try {
JsonNode value = properties.get(key);
OProperty oProperty = oClass.getProperty(key);
@ -1224,12 +1123,9 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
element.removeProperty(key);
}
return element;
}
element.save();
public static boolean isUserAllowedToGetPrivacyMeta() {
// TODO
return true;
return element;
}
protected JsonNode getPropertyForJson(String key, Object object) throws ResourceRegistryException {
@ -1242,30 +1138,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
return (JsonNode) object;
}
if(key.compareTo(IdentifiableElement.METADATA_PROPERTY) == 0) {
// Keeping the metadata
MetadataOrient metadataOrient = MetadataUtility.getMetadataOrient((ODocument) object);
ObjectNode metadataJson = (ObjectNode) OrientDBUtility.toJsonNode(metadataOrient);
if(!isUserAllowedToGetPrivacyMeta()) {
metadataJson.replace(Metadata.CREATED_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER));
metadataJson.replace(Metadata.LAST_UPDATE_BY_PROPERTY, new TextNode(Metadata.HIDDEN_FOR_PRIVACY_USER));
if(key.compareTo(IdentifiableElement.HEADER_PROPERTY) == 0) {
// Keeping the header
HeaderOrient headerOrient = HeaderUtility.getHeaderOrient((ODocument) object);
JsonNode headerJson = Utility.toJsonNode(headerOrient, false);
if(ContextUtility.getIncludeInstanceContexts().get()) {
((ObjectNode) headerJson).set(Header.__CONTEXTS, getContextsAsObjectNode());
}
// TODO check a solution for supertypes
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<Property>> metadataType = (CachedType<PropertyType<Property>>) typesCache.getCachedType(Metadata.NAME);
ObjectMapper objectMapper = new ObjectMapper();
Collection<String> superClasses = metadataType.getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
metadataJson.replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
return metadataJson;
}
if(key.compareTo(IdentifiableElement.ID_PROPERTY) == 0 ) {
return new TextNode(object.toString());
return headerJson;
}
if(ignoreKeys.contains(key)) {
@ -1342,6 +1222,30 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
}
/*
protected List<String> getSuperclasses() throws SchemaException, ResourceRegistryException {
List<String> superClasses = new ArrayList<>();
List<OClass> allSuperClasses = getOClass().getSuperClasses();
while(allSuperClasses.size()>0) {
List<OClass> toBeAnalysed = new ArrayList<>(allSuperClasses);
allSuperClasses = new ArrayList<>();
for(OClass oSuperClass : toBeAnalysed) {
String name = oSuperClass.getName();
if(name.compareTo(StringFactory.V.toUpperCase()) == 0 || name.compareTo(StringFactory.E.toUpperCase()) == 0
|| name.compareTo(DatabaseEnvironment.O_RESTRICTED_CLASS) == 0) {
continue;
}
if(superClassesToBeExcluded.contains(name)) {
continue;
}
superClasses.add(superClasses.size(), name);
allSuperClasses.addAll(oSuperClass.getSuperClasses());
}
}
return superClasses;
}
*/
protected String getNotNullErrorMessage(String fieldName) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("The type ");

View File

@ -20,7 +20,7 @@ import org.gcube.informationsystem.resourceregistry.instances.model.relations.Co
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -81,9 +81,9 @@ public class ElementManagementUtility {
public static OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
try {
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OVertex.class);
return Utility.getElementByUUIDAsAdmin(null, uuid, OVertex.class);
} catch(NotFoundException e) {
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OEdge.class);
return Utility.getElementByUUIDAsAdmin(null, uuid, OEdge.class);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
@ -94,9 +94,9 @@ public class ElementManagementUtility {
public static OElement getAnyElementByUUID(ODatabaseDocument oDatabaseDocument, UUID uuid)
throws NotFoundException, ResourceRegistryException {
try {
return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OVertex.class);
return Utility.getElementByUUID(oDatabaseDocument, null, uuid, OVertex.class);
} catch(NotFoundException e) {
return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OEdge.class);
return Utility.getElementByUUID(oDatabaseDocument, null, uuid, OEdge.class);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
@ -121,12 +121,12 @@ public class ElementManagementUtility {
if(oDatabaseDocument == null) {
throw new ResourceRegistryException(
ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
ODatabaseDocument.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(vertex == null) {
throw new ResourceRegistryException(
OVertex.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OVertex.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
OClass oClass = null;
@ -134,7 +134,7 @@ public class ElementManagementUtility {
oClass = ElementManagementUtility.getOClass(vertex);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", vertex.toString(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
@ -146,7 +146,7 @@ public class ElementManagementUtility {
entityManagement = new FacetManagement();
} else {
String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
entityManagement.setODatabaseDocument(oDatabaseDocument);
@ -160,12 +160,12 @@ public class ElementManagementUtility {
if(oDatabaseDocument == null) {
throw new ResourceRegistryException(
ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
ODatabaseDocument.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(edge == null) {
throw new ResourceRegistryException(
OEdge.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OEdge.class.getSimpleName() + "instance is null. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
OClass oClass = ElementManagementUtility.getOClass(edge);
@ -177,7 +177,7 @@ public class ElementManagementUtility {
relationManagement = new IsRelatedToManagement();
} else {
String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}

View File

@ -18,7 +18,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
@ -43,6 +43,8 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
protected EntityElementManagement(AccessType accessType) {
super(accessType);
this.ignoreKeys.add(EntityElement.HEADER_PROPERTY);
this.ignoreStartWithKeys.add(IN_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OUT_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(IN_PREFIX.toUpperCase());
@ -85,7 +87,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
relationManagements.put(id, baseRelationManagement);
@ -122,6 +124,8 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
throw new ResourceRegistryException(error);
}
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName);
try {
if(uuid != null) {
OVertex v = getElement();
@ -146,7 +150,6 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
throw e;
}
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName);
this.element = vertexEntity;
if(accessType == AccessType.RESOURCE) {
@ -156,7 +159,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
}
logger.info("Created {} is {}", OVertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging(element));
Utility.toJsonString(element, true));
return element;
} catch(ResourceRegistryException e) {

View File

@ -1,21 +1,18 @@
package org.gcube.informationsystem.resourceregistry.instances.base.properties;
import java.security.Key;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
@ -25,11 +22,8 @@ import org.gcube.informationsystem.resourceregistry.instances.base.ElementManage
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -52,29 +46,18 @@ public class PropertyElementManagement {
PROPERTY_IGNORE_START_WITH_KEYS = new HashSet<String>();
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.AT);
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.UNDERSCORE);
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.DOLLAR);
}
public static ODocument getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException {
public static ODocument getPropertyDocument(JsonNode jsonNode) throws ResourceRegistryException {
ODocument oDocument = null;
if(jsonNodeOrig.isNull()) {
if(jsonNode.isNull()) {
return null;
}
JsonNode jsonNode = jsonNodeOrig.deepCopy();
if(jsonNode.has(ModelElement.SUPERTYPES_PROPERTY)) {
((ObjectNode) jsonNode).remove(ModelElement.SUPERTYPES_PROPERTY);
}
if(jsonNode.has(ModelElement.EXPECTED_TYPE_PROPERTY)) {
((ObjectNode) jsonNode).remove(ModelElement.EXPECTED_TYPE_PROPERTY);
}
String type = TypeUtility.getTypeName(jsonNode);
if(type!=null) {
if(jsonNode.has(Element.CLASS_PROPERTY)) {
// Complex type
String type = ElementManagement.getClassProperty(jsonNode);
OClass oClass = null;
try {
@ -86,29 +69,18 @@ public class PropertyElementManagement {
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName());
}
} catch(SchemaNotFoundException e) {
throw e;
}
try {
UUID uuid = UUIDUtility.getUUID(jsonNode);
if(uuid != null) {
throw new ResourceRegistryException("A property object cannot have an UUID");
Header header = HeaderUtility.getHeader(jsonNode, false);
if(header != null) {
throw new ResourceRegistryException("A property object cannot have an Header");
}
} catch(Exception e) {
logger.warn("An invalid UUID has been provided. Anyway property object cannot have an UUID.");
throw new ResourceRegistryException("An property object cannot have an UUID");
}
try {
Metadata metadata = MetadataUtility.getMetadata(jsonNode);
if(metadata != null) {
throw new ResourceRegistryException("A property object cannot have a Metadata");
}
} catch(Exception e) {
logger.warn("An invalid Metadata has been provided. Anyway property object cannot have a Metadata.");
throw new ResourceRegistryException("An property object cannot have a Metadata");
logger.warn("An invalid Header has been provided. Anyway property object cannot have an Header.");
throw new ResourceRegistryException("An property object cannot have an Header");
}
@ -125,7 +97,7 @@ public class PropertyElementManagement {
String contextEncryptedValue = encrypted.getEncryptedValue();
// Decrypting with Context Key (default key)
String decryptedValue = StringEncrypter.getEncrypter().decrypt(contextEncryptedValue);
String decryptedValue = EncryptedImpl.decrypt(contextEncryptedValue);
encrypted.setDecryptedValue(decryptedValue, false);
} catch(Exception e) {
@ -145,7 +117,7 @@ public class PropertyElementManagement {
public static JsonNode getJsonNode(ODocument oDocument) throws ResourceRegistryException {
try {
String type = oDocument.getClassName();
String json = OrientDBUtility.toJsonString(oDocument);
String json = oDocument.toJSON("class");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
@ -163,11 +135,6 @@ public class PropertyElementManagement {
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName());
}
Collection<String> superClasses = cachedType.getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
((ObjectNode) jsonNode).replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
/*
* In case it is an Encrypted type the value is encrypted with the DB Key
* Resource Registry must decrypt the value with the DB Key and Encrypt it with Context key.
@ -183,6 +150,7 @@ public class PropertyElementManagement {
if(oDocument instanceof EncryptedOrient) {
encrypted = (EncryptedOrient) oDocument;
if(encrypted.getDbEncryptedValue().compareTo(encryptedValue)==0) {
// encrypted.setEncryptedValue(encrypted.getContextEncryptedValue());
((ObjectNode) jsonNode).put(Encrypted.VALUE, encrypted.getContextEncryptedValue());
}
}else {
@ -191,17 +159,20 @@ public class PropertyElementManagement {
// Decrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey();
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encryptedValue, databaseKey);
String decryptedValue = EncryptedImpl.decrypt(encryptedValue, databaseKey);
// encrypted.setDecryptedValue(decryptedValue, true);
// Encrypting with Context Key (default key)
String contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue);
String contextEncryptedValue = EncryptedImpl.encrypt(decryptedValue);
// Setting the value encrypted with DB key
//encrypted.setEncryptedValue(contextEncryptedValue);
((ObjectNode) jsonNode).put(Encrypted.VALUE, contextEncryptedValue);
}
}catch (Exception e) {
throw new ResourceRegistryException("Errror while managing " + EncryptedOrient.NAME+ " "+ Property.NAME, e);
throw new ResourceRegistryException("Errror while managing " + Encrypted.NAME+ " "+ Property.NAME, e);
}
}

View File

@ -16,10 +16,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaV
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.gcube.informationsystem.utils.UUIDUtility;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
@ -47,6 +46,7 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass) {
super(accessType);
this.ignoreKeys.add(Relation.HEADER_PROPERTY);
this.ignoreKeys.add(Relation.SOURCE_PROPERTY);
this.ignoreKeys.add(Relation.TARGET_PROPERTY);
this.ignoreKeys.add(IN.toLowerCase());
@ -123,10 +123,10 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, 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, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}
@ -144,7 +144,8 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
throw new ResourceRegistryException("Error while creating relation. No source definition found");
}
UUID sourceUUID = UUIDUtility.getUUID(jsonNode.get(Relation.SOURCE_PROPERTY));
UUID sourceUUID = org.gcube.informationsystem.utils.Utility
.getUUIDFromJsonNode(jsonNode.get(Relation.SOURCE_PROPERTY));
sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setUUID(sourceUUID);

View File

@ -6,6 +6,7 @@ import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
@ -15,7 +16,6 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -43,7 +43,7 @@ public class ERManagementUtility {
Map<UUID, ElementManagement<?,?>> instancesManagement = new HashMap<>();
Set<UUID> uuids = expectedInstances.keySet();
for(UUID uuid : uuids) {
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
String type = expectedInstances.get(uuid).get(Element.CLASS_PROPERTY).asText();
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setWorkingContext(adminSecurityContext);
elementManagement.setODatabaseDocument(oDatabaseDocument);
@ -123,7 +123,7 @@ public class ERManagementUtility {
Map<UUID, ElementManagement<?,?>> instancesManagement = new HashMap<>();
for(UUID uuid : expectedInstances.keySet()) {
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
String type = expectedInstances.get(uuid).get(Element.CLASS_PROPERTY).asText();
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setWorkingContext(adminSecurityContext);
elementManagement.setODatabaseDocument(oDatabaseDocument);

View File

@ -6,9 +6,9 @@ import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath.SharingOperation;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -59,8 +59,8 @@ public class SharingOperationValidator implements OperationValidator {
throw new ResourceRegistryException(errorMessage);
}
String expectedType = TypeUtility.getTypeName(expectedJsonNode);
String affectedType = TypeUtility.getTypeName(affectedJsonNode);
String expectedType = expectedJsonNode.get(Element.CLASS_PROPERTY).asText();
String affectedType = affectedJsonNode.get(Element.CLASS_PROPERTY).asText();
if(expectedType.compareTo(affectedType)!=0) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("The expected type of the instance with UUID ");

View File

@ -1,7 +1,11 @@
package org.gcube.informationsystem.resourceregistry.instances.model.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
@ -14,17 +18,19 @@ import org.gcube.informationsystem.contexts.reference.entities.Context;
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.Header;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
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.contexts.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
@ -33,14 +39,14 @@ import org.gcube.informationsystem.resourceregistry.instances.base.entities.Enti
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
@ -141,6 +147,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
protected EntityManagement(AccessType accessType) {
super(accessType);
this.ignoreKeys.add(Entity.HEADER_PROPERTY);
this.ignoreStartWithKeys.add(IN_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OUT_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(IN_PREFIX.toUpperCase());
@ -149,8 +157,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
this.relationManagements = new HashMap<>();
/*
* By the default the system honor the propagation constraints
* so this variable is initialized as true.
* By the default the system honour the propagation constraints
* so this variable is initialised as true.
*/
this.honourPropagationConstraintsInContextSharing = true;
@ -165,7 +173,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
try {
retrieveElementFromAnyContext();
throw getSpecificAvailableInAnotherContextException(typeName == null ? accessType.getName()
: typeName + " with ID " + uuid + " is available in another "
: typeName + " with UUID " + uuid + " is available in another "
+ Context.class.getSimpleName());
} catch(AvailableInAnotherContextException e1) {
throw e1;
@ -207,7 +215,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
relationManagements.put(id, relationManagement);
@ -279,7 +287,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
logger.debug("Created {} is {}", OVertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging((OVertex) element));
Utility.toJsonString((OVertex) element, true));
return element;
} catch(ResourceRegistryException e) {
@ -306,7 +314,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the instance is added in internalAddToContext() function after
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
*/
if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
@ -330,7 +338,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
setOperation(Operation.ADD_TO_CONTEXT);
reallyAddToContext();
if(!skipped) {
MetadataUtility.updateModifiedByAndLastUpdate(element);
HeaderUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
@ -345,7 +353,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
@Override
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
@ -394,7 +402,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
try {
setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext();
MetadataUtility.updateModifiedByAndLastUpdate(element);
HeaderUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
@ -434,7 +442,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
/*
* DO NOT UNCOMMENT
* the instance is added internalAddToContext() function after
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
* affectedInstances.put(uuid, serializeSelfOnly());
*/
}
@ -491,31 +499,207 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for(ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) vertex);
try {
entityManagement.setAsEntryPoint();
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
arrayNode.add(jsonNode);
if(limit > 0 && ++count >= limit) {
break;
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {
return objectMapper.writeValueAsString(arrayNode);
} catch(JsonProcessingException e) {
throw new ResourceRegistryException(e);
}
}
public boolean propertyMatchRequestedValue(OVertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
return requestedValue.compareTo(instanceValue.toString())==0;
/*
OClass oClass = ElementManagement.getOClass(v);
OProperty oProperty = oClass.getProperty(key);
if(oProperty==null){
// It is an additional property
return requestedValue.compareTo(instanceValue.toString())==0;
}
OType oType = oProperty.getType();
switch (oType) {
case BOOLEAN:
Boolean requested = Boolean.valueOf(requestedValue.toLowerCase());
return requested == (Boolean) instanceValue;
case STRING:
return requestedValue.compareTo((String) instanceValue)==0;
default:
return false;
}
*/
}
/*
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<?> references = null;
if(referenceUUID != null) {
OElement element = null;
try {
element = ElementManagementUtility.getAnyElementByUUID(oDatabaseDocument, referenceUUID);
}catch (ResourceRegistryException e) {
String error = String.format("No instace with UUID %s exists", referenceUUID.toString());
throw new InvalidQueryException(error);
}
if(element instanceof OVertex) {
EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) element);
String elementType = entityManagement.getTypeName();
if(elementType.compareTo(referenceType) != 0) {
if(polymorphic && getOClass().isSubClassOf(referenceType)) {
// OK
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
}
List<OVertex> vertexes = new ArrayList<>();
vertexes.add((OVertex) element);
references = vertexes;
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
} else {
references = oDatabaseDocument.browseClass(referenceType, polymorphic);
}
Set<ORID> analysed = new HashSet<>();
for(Object r : references) {
OVertex v = (OVertex) r;
boolean skip = false;
// checking if the constraints are satisfied
for(String key : constraint.keySet()) {
String value = constraint.get(key);
Object o = v.getProperty(key);
if(value==null) {
if(o==null) {
//ok
}else {
skip = true;
break;
}
}else {
if(o==null) {
// The vertex has not a required property to be tested
// or the property is null
skip = true;
break;
}else {
skip = !propertyMatchRequestedValue(v, key, value, o);
if(skip) {
break;
}
}
}
}
if(skip) {
continue;
}
List<ODirection> directions = new ArrayList<>();
if(direction==ODirection.BOTH) {
directions.add(ODirection.IN);
directions.add(ODirection.OUT);
}else {
directions.add(direction);
}
for(ODirection d : directions) {
Iterable<OEdge> edges = v.getEdges(d.opposite(), relationType);
for(OEdge edge : edges) {
OVertex vertex = edge.getVertex(d);
ORID vertexORID = vertex.getIdentity();
if(analysed.contains(vertexORID)) {
continue;
}
analysed.add(vertexORID);
if(v.getIdentity().compareTo(vertexORID) == 0) {
continue;
}
OClass oClass = ElementManagementUtility.getOClass(vertex);
/*
* If the requested type (i.e. elementType)
* differs form the resulting type (i.e. oClass.getName())
* we need to evaluate if polymorphism is requested and
* if the resulting type is a subclass of the requested type
*
*/
if(oClass.getName().compareTo(typeName)!=0) {
if(polymorphic && oClass.isSubClassOf(typeName)) {
// OK
} else {
// excluding from results
continue;
}
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex);
try {
if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
continue;
}
/*
JsonNode jsonNode;
if(includeRelationInResult) {
RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
oDatabaseDocument, edge);
jsonNode = relationManagement.serializeAsJsonNode();
}else {
jsonNode = entityManagement.serializeAsJsonNode();
}
*/
JsonNode node = entityManagement.serializeAsJsonNode();
arrayNode.add(node);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
}
}
@ -526,115 +710,102 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
}
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID,
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
ODirection direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
if(referenceUUID != null) {
constraint.put(Entity.ID_PROPERTY, referenceUUID.toString());
constraint.put(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY, referenceUUID.toString());
}
// TODO check types
/*
* SELECT FROM (
* TRAVERSE outV('EService'), inE('isIdentifiedBy') FROM (
* SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'
* )
* )
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
* FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
*
* WHERE @class INSTANCEOF 'EService' // if polymorphic is true
*
* WHERE @class='EService' // if polymorphic is false
* WHERE @class='EService' // Only is not polymorphic
*/
StringBuffer selectStringBuffer = new StringBuffer();
selectStringBuffer.append("SELECT FROM (TRAVERSE ");
selectStringBuffer.append(direction.name().toLowerCase());
selectStringBuffer.append("V('");
selectStringBuffer.append(typeName);
selectStringBuffer.append("')");
selectStringBuffer.append(", ");
selectStringBuffer.append(direction.opposite().name().toLowerCase());
selectStringBuffer.append("E('");
selectStringBuffer.append(relationType);
selectStringBuffer.append("')");
selectStringBuffer.append(" FROM (SELECT FROM ");
selectStringBuffer.append(referenceType);
StringBuilder selectStringBuilder = new StringBuilder("SELECT FROM (TRAVERSE ");
selectStringBuilder.append(direction.name().toLowerCase());
selectStringBuilder.append("E('");
selectStringBuilder.append(relationType);
selectStringBuilder.append("'), ");
selectStringBuilder.append(direction.opposite().name().toLowerCase());
selectStringBuilder.append("V('");
selectStringBuilder.append(typeName);
selectStringBuilder.append("') FROM (SELECT FROM ");
selectStringBuilder.append(referenceType);
boolean first = true;
for(String key : constraint.keySet()) {
if(first) {
selectStringBuffer.append(" WHERE ");
selectStringBuilder.append(" WHERE ");
first = false;
} else {
selectStringBuffer.append(" AND ");
selectStringBuilder.append(" AND ");
}
selectStringBuffer.append(key);
selectStringBuffer.append("=");
selectStringBuilder.append(key);
selectStringBuilder.append("=");
String value = constraint.get(key).trim();
selectStringBuffer.append("'");
selectStringBuffer.append(value);
selectStringBuffer.append("'");
selectStringBuilder.append("'");
selectStringBuilder.append(value);
selectStringBuilder.append("'");
}
selectStringBuffer.append(" ))");
selectStringBuilder.append(" ))");
selectStringBuffer.append(" WHERE @class");
if(polymorphic) {
selectStringBuffer.append(" INSTANCEOF '");
} else {
selectStringBuffer.append("='");
}
selectStringBuffer.append(typeName);
selectStringBuffer.append("'");
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(limit==null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(offset == null) {
offset = 0;
if(!polymorphic) {
selectStringBuilder.append(" WHERE @class='");
selectStringBuilder.append(typeName);
selectStringBuilder.append("'");
}
selectStringBuffer.append(" SKIP :offset");
selectStringBuffer.append(" LIMIT :limit");
Map<String, Object> map = new HashMap<>();
map.put("offset", offset);
map.put("limit", limit);
String select = selectStringBuffer.toString();
String select = selectStringBuilder.toString();
logger.trace(select);
OResultSet resultSet = oDatabaseDocument.command(select, map);
OResultSet resultSet = oDatabaseDocument.command(select,new HashMap<>());
while(resultSet.hasNext()) {
OResult oResult = resultSet.next();
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
if(polymorphic) {
OClass oClass = null;
try {
if(element instanceof OEdge) {
continue;
}
oClass = ElementManagementUtility.getOClass(element);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", element.toString(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
if(oClass.isSubClassOf(typeName)) {
continue;
}
}
OVertex vertex = (OVertex) element;
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex);
try {
if(constraint.containsKey(Entity.ID_PROPERTY)) {
String uuid = constraint.get(Entity.ID_PROPERTY);
if(constraint.containsKey(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY)) {
String uuid = constraint.get(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY);
if(entityManagement.getUUID().compareTo(UUID.fromString(uuid)) == 0) {
continue;
}
}
entityManagement.setAsEntryPoint();
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -645,6 +816,10 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
}
/*
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {

View File

@ -187,7 +187,7 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}
public OVertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
if(entryPoint) {
if(entryPoint && operation == Operation.CREATE) {
throw new SchemaViolationException("You cannot create a stand alone Facet");
}
return super.internalCreate();

View File

@ -32,7 +32,7 @@ import org.gcube.informationsystem.resourceregistry.instances.model.relations.Is
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
@ -104,7 +104,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
errorMessage.append("SourceEntityManagement for ");
errorMessage.append(relationManagement.getClass().getSimpleName());
errorMessage.append(" is not the one expected. ");
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
@ -114,10 +114,10 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode consistsOf = relationManagement.serializeAsJsonNode();
sourceResource = addConsistsOf(sourceResource, consistsOf);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e;
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e);
}
@ -234,8 +234,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement();
} else {
logger.warn("{} is not a {} nor a {}. {}", OrientDBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME,
ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn("{} is not a {} nor a {}. {}", Utility.toJsonString(edge, true), IsRelatedTo.NAME,
ConsistsOf.NAME, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(relationManagement != null) {
relationManagement.setWorkingContext(getWorkingContext());
@ -274,7 +274,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the instance is added in internalAddToContext() function after
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
*/
if(honourPropagationConstraintsInContextSharing) {
@ -413,7 +413,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
/**
* The default sanity check is not valid for resources which do not have properties
* and instead must be validated in terms of facets.
* The Resource Metadata is managed with dedicated code for all instaces.
* The Resource Header is managed with dedicated code for all instaces.
*/
@Override
public void sanityCheck() throws SchemaViolationException, ResourceRegistryException {

View File

@ -7,7 +7,6 @@ import org.gcube.informationsystem.model.impl.properties.PropagationConstraintIm
import org.gcube.informationsystem.model.reference.entities.Facet;
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.DeleteConstraint;
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;
@ -36,7 +35,6 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
static {
DEFAULT_CONSISTS_OF_PC = new PropagationConstraintImpl();
DEFAULT_CONSISTS_OF_PC.setDeleteConstraint(DeleteConstraint.cascade);
DEFAULT_CONSISTS_OF_PC.setRemoveConstraint(RemoveConstraint.cascade);
DEFAULT_CONSISTS_OF_PC.setAddConstraint(AddConstraint.propagate);
}

View File

@ -8,7 +8,6 @@ import org.gcube.informationsystem.model.impl.properties.PropagationConstraintIm
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.DeleteConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -19,7 +18,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isr
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
@ -32,7 +31,6 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
static {
DEFAULT_IS_RELATED_TO_PC = new PropagationConstraintImpl();
DEFAULT_IS_RELATED_TO_PC.setDeleteConstraint(DeleteConstraint.keep);
DEFAULT_IS_RELATED_TO_PC.setRemoveConstraint(RemoveConstraint.keep);
DEFAULT_IS_RELATED_TO_PC.setAddConstraint(AddConstraint.unpropagate);
}
@ -88,10 +86,10 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, 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, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}

View File

@ -17,10 +17,10 @@ import org.gcube.informationsystem.model.reference.entities.Entity;
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.DeleteConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
@ -28,7 +28,6 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
@ -39,16 +38,14 @@ import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.EntityManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.PropagationConstraintOrient;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.gcube.informationsystem.utils.ElementMapper;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OType;
@ -221,7 +218,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else {
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
}
@ -233,7 +230,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else {
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
@ -255,10 +252,10 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
propagationConstraint = (PropagationConstraint) oDocument;
} else {
try {
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, OrientDBUtility.toJsonString(oDocument));
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, oDocument.toJSON());
} catch(Exception e) {
logger.warn("Unable to recreate {}. {}", PropagationConstraint.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -285,22 +282,6 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
}
propagationConstraintOrient.setRemoveConstraint(removeConstraint);
DeleteConstraint deleteConstraint = propagationConstraint.getDeleteConstraint();
if(deleteConstraint == null) {
deleteConstraint = defaultPropagationConstraint.getDeleteConstraint();
logger.debug("Unable to get {}. Default value ({}) will be used", DeleteConstraint.class.getSimpleName(),
deleteConstraint);
}else {
if (this instanceof ConsistsOfManagement && deleteConstraint == DeleteConstraint.keep) {
deleteConstraint = defaultPropagationConstraint.getDeleteConstraint();
logger.warn("A {} cannot use {}.{}. Default value ({}) will be used", ConsistsOf.NAME,
DeleteConstraint.class.getSimpleName(), DeleteConstraint.keep, deleteConstraint);
}
}
propagationConstraintOrient.setDeleteConstraint(deleteConstraint);
return propagationConstraintOrient;
}
@ -408,21 +389,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
AddConstraint addConstraint = AddConstraint.unpropagate;
try {
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element,
propagationConstraint = Utility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.ADD_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.ADD_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error);
throw new ResourceRegistryException(error, e);
}
@ -446,7 +427,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the relation instance is added in internalAddToContext() function after
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
*/
break;
@ -463,7 +444,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the relation instance is added in internalAddToContext() function after
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
*/
}
}
@ -475,7 +456,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
operation = Operation.ADD_TO_CONTEXT;
reallyAddToContext();
if(!skipped && propagationConstraint.getAddConstraint()==PropagationConstraint.AddConstraint.propagate) {
MetadataUtility.updateModifiedByAndLastUpdate(element);
HeaderUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
}
@ -512,7 +493,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
@Override
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
@ -563,21 +544,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
RemoveConstraint removeConstraint = RemoveConstraint.keep;
try {
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element,
propagationConstraint = Utility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.REMOVE_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error, e);
@ -652,7 +633,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
try {
setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext();
MetadataUtility.updateModifiedByAndLastUpdate(element);
HeaderUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
} catch(ResourceRegistryException e) {
@ -721,25 +702,23 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
getSourceEntityManagement().getElement();
DeleteConstraint deleteConstraint = DeleteConstraint.keep;
RemoveConstraint removeConstraint = RemoveConstraint.keep;
try {
PropagationConstraint propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class,
PropagationConstraint propagationConstraint = Utility.getPropertyDocument(PropagationConstraint.class,
element, Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getDeleteConstraint() != null) {
deleteConstraint = propagationConstraint.getDeleteConstraint();
if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.DELETE_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
deleteConstraint = DeleteConstraint.values()[propagationConstraint.getRemoveConstraint().ordinal()];
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
OrientDBUtility.getAsStringForException(element), deleteConstraint, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Utility.toJsonString(element, true), removeConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
// pre-loading target entity because after deleting the relation we will not be able to get it
@ -751,7 +730,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
affectedInstances.put(uuid, serializeAsAffectedInstance());
element.delete();
switch(deleteConstraint) {
switch(removeConstraint) {
case cascade:
t.internalDelete();
break;
@ -762,7 +741,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
Iterator<OEdge> iterator = iterable.iterator();
if(iterator.hasNext()) {
logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
target, deleteConstraint);
target, removeConstraint);
} else {
getTargetEntityManagement().internalDelete();
}
@ -779,23 +758,11 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
}
private Collection<JsonNode> serializeEdges(Iterable<ODocument> edges, boolean postFilterPolymorphic)
protected Collection<JsonNode> serializeEdges(Iterable<ODocument> edges, boolean postFilterPolymorphic)
throws ResourceRegistryException {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
// Map<String,JsonNode> visitedSourceResources = new HashMap<>();
List<JsonNode> serilizedEdges = new ArrayList<>();
for(ODocument d : edges) {
if(++position < offset) {
continue;
}
OEdge edge = (OEdge) d;
if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) {
@ -806,9 +773,6 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
oDatabaseDocument, edge);
// visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
serilizedEdges.add(relationManagement.serializeAsJsonNode());
if(limit > 0 && ++count >= limit) {
break;
}
}
return serilizedEdges;
}

View File

@ -10,7 +10,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityCo
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,7 +37,7 @@ public class QueryImpl implements Query {
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.begin();
logger.debug("Going to execute query '{}'", query);
logger.debug("Going to execute query '{} limit {}'", query);
OResultSet resultSet = oDatabaseDocument.query(query);
@ -52,23 +52,22 @@ public class QueryImpl implements Query {
if(raw) {
if(oResult.isElement()) {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
jsonNode = OrientDBUtility.toJsonNode(element);
jsonNode = Utility.toJsonNode(element, false);
}else {
ObjectMapper mapper = new ObjectMapper();
jsonNode = mapper.readTree(OrientDBUtility.toJsonString(oResult));
jsonNode = mapper.readTree(oResult.toJSON());
}
} else {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
element);
erManagement.setAsEntryPoint();
jsonNode = erManagement.serializeAsJsonNode();
}
arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
OrientDBUtility.toJsonString(oResult), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
oResult.toJSON(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}

View File

@ -2,16 +2,14 @@ package org.gcube.informationsystem.resourceregistry.queries.json;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Direction;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
@ -26,11 +24,9 @@ import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.J
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryResource;
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryConsistsOf;
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -46,6 +42,8 @@ public class JsonQuery {
private static Logger logger = LoggerFactory.getLogger(JsonQuery.class);
private static final Integer UNBOUNDED_LIMIT = -1;
protected ObjectMapper objectMapper;
protected JsonNode jsonQuery;
protected JsonQueryERElement entryPoint;
@ -69,7 +67,7 @@ public class JsonQuery {
}
public static JsonQueryERElement getJsonQueryERElement(JsonNode jsonQuery) throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
String type = TypeUtility.getTypeName(jsonQuery);
String type = jsonQuery.get(Element.CLASS_PROPERTY).asText();
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
@ -100,17 +98,11 @@ public class JsonQuery {
return jsonQueryERElement;
}
public StringBuffer createQuery() throws SchemaException, InvalidQueryException, ResourceRegistryException {
entryPoint = getJsonQueryERElement(jsonQuery);
entryPoint.setEntryPoint(true);
return entryPoint.createQuery(new StringBuffer());
}
public StringBuffer createMatchQuery() throws SchemaException, InvalidQueryException, ResourceRegistryException {
entryPoint = getJsonQueryERElement(jsonQuery);
entryPoint.setEntryPoint(true);
return entryPoint.createMatchQuery(new StringBuffer());
return entryPoint.analize(new StringBuffer());
}
public String query() throws InvalidQueryException, ResourceRegistryException {
@ -122,24 +114,11 @@ public class JsonQuery {
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.begin();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(limit==null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(offset == null) {
offset = 0;
}
StringBuffer stringBuffer = createQuery();
stringBuffer.append(" SKIP :offset");
stringBuffer.append(" LIMIT :limit");
stringBuffer.append(" limit :limit");
Map<String, Object> map = new HashMap<>();
map.put("offset", offset);
map.put("limit", limit);
map.put("limit", JsonQuery.UNBOUNDED_LIMIT);
String query = stringBuffer.toString();
logger.trace("Going to execute the following query:\n{} \n from the JSONQuery\n{}", query, objectMapper.writeValueAsString(jsonQuery));
@ -148,52 +127,37 @@ public class JsonQuery {
ArrayNode arrayNode = objectMapper.createArrayNode();
boolean projection = entryPoint.isProjection();
boolean first = true;
Set<String> keys = new HashSet<>();
while(resultSet.hasNext()) {
OResult oResult = resultSet.next();
if(projection) {
if(first) {
keys = oResult.getPropertyNames();
first = false;
}
ObjectNode objectNode = objectMapper.createObjectNode();
for(String key : keys) {
Object value = oResult.getProperty(key);
if(value == null) {
objectNode.put(key, "");
}else if(value instanceof String) {
objectNode.put(key, (String) value);
}else if(value instanceof Integer) {
objectNode.put(key, (Integer) value);
}else if(value instanceof Long) {
objectNode.put(key, (Long) value);
}else {
objectNode.put(key, value.toString());
}
}
arrayNode.add(objectNode);
}else {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
try {
JsonNode jsonNodeResult = null;
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
element);
erManagement.setAsEntryPoint();
// To support polymorphism we do not include @class="TypeName" in query. So we need post processing filtering of results
String requestedType = entryPoint.getType();
String gotType = erManagement.getTypeName();
if(requestedType.compareTo(gotType)==0) {
jsonNodeResult = erManagement.serializeAsJsonNode();
arrayNode.add(jsonNodeResult);
continue;
}
CachedType<?> cachedType = TypesCache.getInstance().getCachedType(gotType);
if(cachedType.getSuperTypes().contains(requestedType)) {
jsonNodeResult = erManagement.serializeAsJsonNode();
arrayNode.add(jsonNodeResult);
continue;
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
element.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
element.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}

View File

@ -1,13 +1,9 @@
package org.gcube.informationsystem.resourceregistry.queries.json.base;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
@ -15,23 +11,17 @@ import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Direction;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.queries.operators.ComparisonOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.LogicalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.MatemathicsOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.ProjectionOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class JsonQueryERElement {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
// private Logger logger = LoggerFactory.getLogger(this.getClass());
public static void validateType(String type, AccessType requiredAccessType) throws SchemaException, ResourceRegistryException {
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
@ -50,74 +40,16 @@ public abstract class JsonQueryERElement {
protected Direction direction;
protected boolean entryPoint;
/* Start of variables used to create in MATCH queries */
/**
* Instruct the JSON query analyzer if it is a projection
*/
protected boolean projection;
/**
* The chain of callers of this instance analyzer.
* breadcrumb.get(breadcrumb.size-1) == caller
* breadcrumb is empty if this instance is an entry point
*/
protected List<JsonQueryERElement> breadcrumb;
/**
* The breadcrumb.size() provide the level of nesting.
* The position which element number at the same level.
* E.g. the index of a ConsistsOf when the caller is a Resource.
*
* It is used in conjunction with breadcrumb.size() to attach a number to the alias.
* This allows to generate a predictive not clashing alias instead of using random string/number.
* This is useful for testing purposes.
*/
protected int position;
/**
* Contains the alias if needed by the class
*/
protected String alias;
/**
* This field is used by entry point only.
* Any class at any level can retrieve the entry point using
* breadcrumb.get(0);
*/
protected List<String> fieldsToEmit;
/* Start of variables used to create in MATCH queries */
/**
* it indicates the number of properties in this.jsonNode
* This number is manipulated while analyzing the jsonNode
* to properly create the query.
*/
protected int size;
protected boolean traverseBack;
public JsonQueryERElement(JsonNode jsonQuery, AccessType accessType) throws SchemaException, ResourceRegistryException {
this.objectMapper = new ObjectMapper();
this.type = TypeUtility.getTypeName(jsonQuery);
this.type = jsonQuery.get(Element.CLASS_PROPERTY).asText();
this.jsonNode = jsonQuery;
this.size = jsonNode.size();
this.accessType = accessType;
this.entryPoint = false;
this.traverseBack = true;
this.projection = false;
this.breadcrumb = new ArrayList<>();
this.position = 0;
this.alias = null;
this.fieldsToEmit = new ArrayList<>();
this.fieldNamesToRemove = new HashSet<>();
this.fieldNamesToRemove.add(Element.TYPE_PROPERTY);
this.fieldNamesToRemove.add(ModelElement.SUPERTYPES_PROPERTY);
this.fieldNamesToRemove.add(ModelElement.EXPECTED_TYPE_PROPERTY);
fieldNamesToRemove.add(Element.CLASS_PROPERTY);
fieldNamesToRemove.add(Element.SUPERCLASSES_PROPERTY);
validateType(this.type, this.accessType);
}
@ -140,93 +72,16 @@ public abstract class JsonQueryERElement {
public void setEntryPoint(boolean entryPoint) {
this.entryPoint = entryPoint;
this.traverseBack = !entryPoint;
}
public boolean isProjection() {
return projection;
}
public abstract StringBuffer analize(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException;
public void setProjection(boolean projection) {
if(!projection) {
throw new InternalServerErrorException("Projection can only be set to true from code. This is a server side bug. Please contact the administrator.");
}
this.projection = projection;
if(!entryPoint) {
// Set the projection in the parent
breadcrumb.get(breadcrumb.size()-2).setProjection(projection);
}
}
public List<JsonQueryERElement> getBreadcrumb() {
return breadcrumb;
}
public void setBreadcrumb(List<JsonQueryERElement> breadcrumb) {
this.breadcrumb = breadcrumb;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getAlias() {
return alias;
}
public String getAlias(boolean generateifNull) {
if(alias==null && generateifNull) {
alias = generateAlias().toString();
}
return alias;
}
protected StringBuffer generateAlias() {
StringBuffer sb = new StringBuffer();
sb.append(type.toLowerCase());
for(JsonQueryERElement elem : breadcrumb) {
sb.append(elem.getPosition());
}
sb.append(this.position);
return sb;
}
/**
* Add a field to emit only if this instance is the entry point
* @param fieldToEmit
*/
protected void addFieldToEmit(String fieldToEmit) {
fieldsToEmit.add(fieldToEmit);
logger.trace("The field to emit ({}) has been added to {} with alias {}", fieldToEmit, this.type, this.alias);
if(!entryPoint) {
logger.trace("The field to emit ({}) will be added to the parent too", fieldToEmit);
breadcrumb.get(breadcrumb.size()-2).addFieldToEmit(fieldToEmit);
}
}
public boolean isTraverseBack() {
return traverseBack;
}
public void setTraverseBack(boolean traverseBack) {
this.traverseBack = traverseBack;
}
public StringBuffer createQuery(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException {
return createMatchQuery(stringBuffer);
}
public abstract StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException;
protected StringBuffer addConstraints(JsonNode jsonNode, LogicalOperator queryLogicalOperator, String fieldNamePrefix) throws InvalidQueryException {
protected StringBuffer addConstraints(JsonNode jsonNode, QueryLogicalOperator queryLogicalOperator, String fieldNamePrefix) throws InvalidQueryException {
StringBuffer stringBuffer = new StringBuffer();
if(queryLogicalOperator==null) {
queryLogicalOperator = LogicalOperator.AND;
queryLogicalOperator = QueryLogicalOperator.AND;
}
JsonNode copiedJsonNode = jsonNode.deepCopy();
@ -241,17 +96,13 @@ public abstract class JsonQueryERElement {
while(iterator.hasNext()) {
String fieldName = iterator.next();
JsonNode node = objectNode.get(fieldName);
StringBuffer evBuffer = evaluateNode(node, fieldName, fieldNamePrefix);
if(evBuffer!=null && evBuffer.length()>0) {
if(first) {
first = false;
}else {
stringBuffer.append(queryLogicalOperator.getDbOperator());
}
stringBuffer.append(evBuffer);
stringBuffer.append(queryLogicalOperator.getLogicalOperator());
}
JsonNode node = objectNode.get(fieldName);
stringBuffer.append(evaluateNode(node, fieldName, fieldNamePrefix));
}
}
@ -260,19 +111,13 @@ public abstract class JsonQueryERElement {
Iterator<JsonNode> iterator = arrayNode.iterator();
boolean first = true;
while(iterator.hasNext()) {
JsonNode node = iterator.next();
StringBuffer evBuffer = evaluateNode(node, null, fieldNamePrefix);
if(!first) {
stringBuffer.append(queryLogicalOperator.getDbOperator());
}
if(evBuffer!=null && evBuffer.length()>0) {
if(first) {
first = false;
}else {
stringBuffer.append(queryLogicalOperator.getLogicalOperator());
}
stringBuffer.append(evBuffer);
}
JsonNode node = iterator.next();
stringBuffer.append(evaluateNode(node, null, fieldNamePrefix));
}
}
@ -280,56 +125,26 @@ public abstract class JsonQueryERElement {
}
protected StringBuffer evaluateNode(JsonNode jsonNode, String fieldName, String fieldNamePrefix) throws InvalidQueryException {
if(ProjectionOperator.getOperators().contains(fieldName)) {
--size;
setProjection(true);
Iterator<String> iterator = jsonNode.fieldNames();
while(iterator.hasNext()) {
String fieldNameToEmit = iterator.next();
String nameOfFieldToEmit = jsonNode.get(fieldNameToEmit).asText();
StringBuffer b = new StringBuffer();
b.append(getAlias(true));
b.append(".");
if(fieldNamePrefix !=null) {
b.append(fieldNamePrefix);
b.append(".");
}
b.append(fieldNameToEmit);
b.append(" AS `");
b.append(nameOfFieldToEmit);
b.append("`");
addFieldToEmit(b.toString());
}
return null;
}
if(MatemathicsOperator.getOperators().contains(fieldName)) {
--size;
setProjection(true);
MatemathicsOperator mo = MatemathicsOperator.getOperator(fieldName);
String fieldToEmit = mo.generateFieldToEmit(jsonNode, getAlias(true));
addFieldToEmit(fieldToEmit);
return null;
}
StringBuffer stringBuffer = new StringBuffer();
if(LogicalOperator.getOperators().contains(fieldName)) {
LogicalOperator queryLogicalOperator = LogicalOperator.getOperator(fieldName);
if(QueryLogicalOperator.getOperators().contains(fieldName)) {
QueryLogicalOperator queryLogicalOperator = QueryLogicalOperator.getQueryLogicalOperator(fieldName);
stringBuffer.append("(");
stringBuffer.append(addConstraints(jsonNode, queryLogicalOperator, fieldNamePrefix));
stringBuffer.append(")");
return stringBuffer;
}
if(ComparisonOperator.getOperators().contains(fieldName)) {
ComparisonOperator comparisonOperator = ComparisonOperator.getOperator(fieldName);
if(QueryConditionalOperator.getOperators().contains(fieldName)) {
QueryConditionalOperator queryConditionalOperator = QueryConditionalOperator.getQueryComparisonOperator(fieldName);
String key = getKey(null, fieldNamePrefix);
String value = getValue(jsonNode);
stringBuffer.append(comparisonOperator.addCondition(key, value));
if(queryConditionalOperator == QueryConditionalOperator.IN) {
throw new UnsupportedOperationException();
}
StringBuffer key = getKey(null, fieldNamePrefix);
StringBuffer value = getValue(jsonNode);
stringBuffer.append(addCondition(queryConditionalOperator, key, value));
return stringBuffer;
}
@ -346,39 +161,43 @@ public abstract class JsonQueryERElement {
newPrefix.append(fieldName);
}
stringBuffer.append(addConstraints(jsonNode, null, newPrefix.length()>0 ? newPrefix.toString() : null));
stringBuffer.append(addConstraints(jsonNode, null, newPrefix.toString()));
return stringBuffer;
}
if(jsonNode.isTextual() || jsonNode.isNumber()) {
String key = getKey(fieldName, fieldNamePrefix);
String value = getValue(jsonNode);
stringBuffer.append(ComparisonOperator.EQ.addCondition(key, value));
}
if(jsonNode.isNull()) {
String key = getKey(fieldName, null);
stringBuffer.append(ComparisonOperator.IS.addCondition(key, null));
StringBuffer key = getKey(fieldName, fieldNamePrefix);
StringBuffer value = getValue(jsonNode);
stringBuffer.append(addCondition(QueryConditionalOperator.EQ, key, value));
}
return stringBuffer;
}
protected String getKey(String fieldName, String fieldNamePrefix) {
protected StringBuffer addCondition(QueryConditionalOperator queryConditionalOperator, StringBuffer key, StringBuffer value) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(key);
stringBuffer.append(queryConditionalOperator.getConditionalOperator());
stringBuffer.append(value);
return stringBuffer;
}
protected StringBuffer getKey(String fieldName, String fieldNamePrefix) {
StringBuffer stringBuffer = new StringBuffer();
if(fieldNamePrefix!=null) {
stringBuffer.append(fieldNamePrefix.trim());
if(fieldName!=null && fieldName.trim().length()!=0) {
stringBuffer.append(fieldNamePrefix);
if(fieldName!=null && fieldName.compareTo("")!=0) {
stringBuffer.append(".");
}
}
if(fieldName!=null) {
stringBuffer.append(fieldName.trim());
stringBuffer.append(fieldName);
}
return stringBuffer.toString();
return stringBuffer;
}
protected String getValue(JsonNode jsonNode) {
protected StringBuffer getValue(JsonNode jsonNode) {
StringBuffer stringBuffer = new StringBuffer();
String value = jsonNode.asText();
@ -389,92 +208,6 @@ public abstract class JsonQueryERElement {
stringBuffer.append(value);
stringBuffer.append("\"");
}
return stringBuffer.toString();
}
protected List<JsonQueryERElement> getChildrenBreadcrumb() {
List<JsonQueryERElement> childrenBreadcrumb = new ArrayList<>(this.breadcrumb);
childrenBreadcrumb.add(this);
return childrenBreadcrumb;
}
protected StringBuffer wrapMatchQuery(StringBuffer buffer) throws InvalidQueryException {
if(entryPoint) {
alias = getAlias(true);
StringBuffer sb = null;
if(size > 1) {
sb = addConstraints(jsonNode, null, null);
}
StringBuffer entryBuffer = new StringBuffer();
entryBuffer.append("MATCH\n");
entryBuffer.append("\t{class: "); // The { has to be closed
entryBuffer.append(type);
entryBuffer.append(", as: ");
entryBuffer.append(alias);
entryBuffer.append(", where: ");
if(sb!=null && sb.length()>0) {
entryBuffer.append("(");
}
entryBuffer.append("($currentMatch['@class'] INSTANCEOF '");
entryBuffer.append(type);
entryBuffer.append("')"); // close the second (
if(sb!=null && sb.length()>0) {
entryBuffer.append(" AND (");
entryBuffer.append(sb);
entryBuffer.append(")");
entryBuffer.append(")");
}
entryBuffer.append("}\n");
entryBuffer.append(buffer);
entryBuffer.append("\nRETURN\n");
if(!projection) {
entryBuffer.append("\tDISTINCT(");
entryBuffer.append(alias);
entryBuffer.append(") as ret");
StringBuffer wrap = new StringBuffer();
wrap.append("SELECT EXPAND(ret) FROM (\n");
wrap.append(entryBuffer);
wrap.append("\n)");
entryBuffer = wrap;
}else {
int size = fieldsToEmit.size();
for(int i=0; i<size; i++) {
entryBuffer.append("\t");
entryBuffer.append(fieldsToEmit.get(i));
if(i<(size-1)) {
entryBuffer.append(",\n");
}
}
}
return entryBuffer;
}else {
return buffer;
}
}
protected abstract StringBuffer getSpecificMatchQuery(List<JsonQueryERElement> childrenBreadcrumb) throws SchemaException, ResourceRegistryException;
public StringBuffer createMatchQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
List<JsonQueryERElement> childrenBreadcrumb = getChildrenBreadcrumb();
if(entryPoint) {
getAlias(true);
}
StringBuffer buffer = getSpecificMatchQuery(childrenBreadcrumb);
buffer = wrapMatchQuery(buffer);
stringBuffer.append(buffer);
return stringBuffer;
}
}

View File

@ -1,46 +1,42 @@
package org.gcube.informationsystem.resourceregistry.queries.json.base.entities;
import java.util.List;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Direction;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.queries.json.base.JsonQueryERElement;
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryConsistsOf;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class JsonQueryFacet extends JsonQueryEntity {
public final static String _SOURCE = "_source";
public final static String _IN = "_in";
public JsonQueryFacet(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
super(jsonQuery, AccessType.FACET);
fieldNamesToRemove.add(JsonQueryFacet._SOURCE);
fieldNamesToRemove.add(JsonQueryFacet._IN);
}
@Override
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
StringBuffer newBuffer = new StringBuffer();
int size = jsonNode.size();
boolean traverseBackLocal = traverseBack;
if(jsonNode.has(_SOURCE)) {
boolean entry = entryPoint;
if(jsonNode.has(_IN)) {
if(!entryPoint) {
throw new InvalidQueryException(_SOURCE + " property cannot be used in a facet if it is not the entry object");
throw new InvalidQueryException(_IN + " property cannot be used in a facet if it is not the entry object");
}
JsonNode consistsOfNode = jsonNode.get(_SOURCE);
JsonNode consistsOfNode = jsonNode.get(_IN);
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfNode);
jsonQueryConsistsOf.setTraverseBack(traverseBackLocal);
jsonQueryConsistsOf.setEntryPoint(entryPoint);
jsonQueryConsistsOf.setDirection(Direction.OUT);
stringBuffer = jsonQueryConsistsOf.createTraversalQuery(stringBuffer);
traverseBackLocal = true;
stringBuffer = jsonQueryConsistsOf.analize(stringBuffer);
entry = false;
/* Need to substract 1 from size otherwise
* it add WHERE at the end because _in
@ -51,134 +47,28 @@ public class JsonQueryFacet extends JsonQueryEntity {
newBuffer.append("SELECT FROM ");
if(traverseBackLocal) {
if(!entry) {
newBuffer.append("( ");
newBuffer.append("TRAVERSE inV(\"");
}
newBuffer.append(type);
if(traverseBackLocal) {
if(!entry) {
newBuffer.append("\") FROM ( ");
newBuffer.append(stringBuffer);
newBuffer.append(")");
newBuffer.append(")");
}
/*
* If size >1 I have to add constraints.
* If is an entry point I have to add the INSTANCEOF to properly support polymorphism
*/
if(size > 1 || entryPoint) {
newBuffer.append(" WHERE ");
}
// Size 1 means that only 'type' property is present
// Size 1 means that only '@class' property is present
if(size > 1) {
newBuffer.append(" WHERE ");
newBuffer.append(addConstraints(jsonNode, null, null));
if(entryPoint) {
newBuffer.append(" AND ");
}
}
if(entryPoint) {
newBuffer.append(OrientDBUtility.ORIENTDB_CLASS_PROPERTY);
newBuffer.append(" INSTANCEOF \"");
newBuffer.append(type);
newBuffer.append("\"");
}
return newBuffer;
}
@Override
protected StringBuffer getSpecificMatchQuery(List<JsonQueryERElement> childrenBreadcrumb)
throws SchemaException, ResourceRegistryException {
StringBuffer newBuffer = new StringBuffer();
boolean traverseBack = this.traverseBack;
if(jsonNode.has(_SOURCE)) {
if(!entryPoint) {
throw new InvalidQueryException(_SOURCE + " property cannot be used in a facet if it is not the entry object");
}
traverseBack = true;
JsonNode consistsOfNode = jsonNode.get(_SOURCE);
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfNode);
jsonQueryConsistsOf.setTraverseBack(traverseBack);
jsonQueryConsistsOf.setDirection(Direction.IN);
jsonQueryConsistsOf.setBreadcrumb(childrenBreadcrumb);
newBuffer = jsonQueryConsistsOf.createMatchQuery(newBuffer);
newBuffer.append("\n\t");
newBuffer.append(".inV('");
newBuffer.append(type);
newBuffer.append("')");
newBuffer.append(" { where: ($matched.");
newBuffer.append(alias);
newBuffer.append(" == $currentMatch)}");
traverseBack = false;
/* Need to substract 1 from size otherwise
* it add WHERE at the end because _in
* is not a property to be used for a WHERE compare
*/
--size;
}
StringBuffer buffer = new StringBuffer();
if(!entryPoint) {
buffer.append("\n\t");
buffer.append(".inV('");
buffer.append(type);
buffer.append("')");
alias = getAlias(true);
StringBuffer sb = null;
if(size > 0) {
sb = addConstraints(jsonNode, null, null);
}
buffer.append(" {");
buffer.append(" as: ");
buffer.append(alias);
buffer.append(",");
buffer.append(" where: ");
if(sb!=null && sb.length()>0) {
buffer.append("(");
}
buffer.append("($currentMatch['@class'] INSTANCEOF '");
buffer.append(type);
buffer.append("')");
if(sb!=null && sb.length()>0) {
buffer.append(" AND (");
buffer.append(sb);
buffer.append(")");
buffer.append(")");
}
buffer.append("}");
}
buffer.append(newBuffer);
// if(traverseBack) {
// buffer.append("\n\t");
// buffer.append(".inV('");
// buffer.append(type);
// buffer.append("')");
// buffer.append(" { where: ($matched.");
// buffer.append(alias);
// buffer.append(" == $currentMatch)}");
// }
return buffer;
}
}

View File

@ -1,18 +1,15 @@
package org.gcube.informationsystem.resourceregistry.queries.json.base.entities;
import java.util.List;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Direction;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.queries.json.base.JsonQueryERElement;
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryConsistsOf;
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
/**
* @author Luca Frosini (ISTI - CNR)
@ -21,232 +18,71 @@ public class JsonQueryResource extends JsonQueryEntity {
public JsonQueryResource(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
super(jsonQuery, AccessType.RESOURCE);
this.fieldNamesToRemove.add(Resource.CONSISTS_OF_PROPERTY);
this.fieldNamesToRemove.add(Resource.IS_RELATED_TO_PROPERTY);
}
public StringBuffer createSelect(StringBuffer stringBuffer, boolean wrapInnerQuery) throws SchemaException, ResourceRegistryException {
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT FROM ");
if(wrapInnerQuery) {
buffer.append("( ");
buffer.append(stringBuffer);
buffer.append(")");
}else {
buffer.append(type);
}
if(entryPoint || size>1) {
buffer.append(" WHERE ");
}
if(size > 1) {
buffer.append(addConstraints(jsonNode, null, null));
if(entryPoint) {
buffer.append(" AND ");
}
}
if(entryPoint) {
buffer.append(OrientDBUtility.ORIENTDB_CLASS_PROPERTY);
buffer.append(" INSTANCEOF \"");
buffer.append(type);
buffer.append("\"");
}
return buffer;
fieldNamesToRemove.add(Resource.CONSISTS_OF_PROPERTY);
fieldNamesToRemove.add(Resource.IS_RELATED_TO_PROPERTY);
}
@Override
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
boolean wrapInnerQuery = false;
if(traverseBack) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.name().toLowerCase());
buffer.append("V(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
wrapInnerQuery = true;
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
if(!entryPoint) {
StringBuffer newBuffer = new StringBuffer();
newBuffer.append("TRAVERSE ");
newBuffer.append(direction.name().toLowerCase());
newBuffer.append("V(\"");
newBuffer.append(type);
newBuffer.append("\") FROM ( ");
newBuffer.append(stringBuffer);
newBuffer.append(")");
stringBuffer = newBuffer;
}
boolean initFound = false;
ArrayNode isRelatedToArray = (ArrayNode) jsonNode.get(Resource.IS_RELATED_TO_PROPERTY);
if(isRelatedToArray!=null && isRelatedToArray.size()>0) {
--size;
initFound = true;
for(int i=0; i<isRelatedToArray.size(); i++) {
JsonNode isRelatedToJsonNode = isRelatedToArray.get(i);
JsonQueryIsRelatedTo jsonQueryIsRelatedTo = new JsonQueryIsRelatedTo(isRelatedToJsonNode);
jsonQueryIsRelatedTo.setRequestedResourceType(type);
jsonQueryIsRelatedTo.setDirectionByJson();
jsonQueryIsRelatedTo.setTraverseBack( (!(!traverseBack) && i==0) );
stringBuffer = jsonQueryIsRelatedTo.createTraversalQuery(stringBuffer);
jsonQueryIsRelatedTo.setEntryPoint(entryPoint && i==0);
stringBuffer = jsonQueryIsRelatedTo.analize(stringBuffer);
}
wrapInnerQuery = true;
}
ArrayNode consistsOfArray = (ArrayNode) jsonNode.get(Resource.CONSISTS_OF_PROPERTY);
if(consistsOfArray!=null && consistsOfArray.size()>0) {
--size;
for(int i=0; i<consistsOfArray.size(); i++) {
JsonNode consistsOfJsonNode = consistsOfArray.get(i);
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfJsonNode);
jsonQueryConsistsOf.setRequestedResourceType(type);
jsonQueryConsistsOf.setDirection(Direction.IN);
jsonQueryConsistsOf.setTraverseBack(!((!traverseBack) && !wrapInnerQuery && i==0));
stringBuffer = jsonQueryConsistsOf.createTraversalQuery(stringBuffer);
jsonQueryConsistsOf.setEntryPoint(entryPoint && !initFound && i==0);
stringBuffer = jsonQueryConsistsOf.analize(stringBuffer);
}
wrapInnerQuery = true; // Must be set after the cycle and not before
initFound = true; // Must be set after the cycle and not before
}
// The Resource has no other referenced ER inside
if(!wrapInnerQuery) {
return createSelect(stringBuffer, wrapInnerQuery);
if(!initFound) {
if(entryPoint) {
stringBuffer = new StringBuffer();
stringBuffer.append("SELECT FROM ");
stringBuffer.append(type);
}
}
if(entryPoint || size>1) {
return createSelect(stringBuffer, wrapInnerQuery);
if(jsonNode.has(IdentifiableElement.HEADER_PROPERTY)) {
StringBuffer newBuffer = new StringBuffer();
newBuffer.append("SELECT FROM ( ");
newBuffer.append(stringBuffer);
newBuffer.append(") WHERE ");
newBuffer.append(addConstraints(jsonNode, null, null));
stringBuffer = newBuffer;
}
return stringBuffer;
}
@Override
protected StringBuffer getSpecificMatchQuery(List<JsonQueryERElement> childrenBreadcrumb) throws SchemaException, ResourceRegistryException {
StringBuffer newBuffer = new StringBuffer();
int isRelatedToSize = 0;
ArrayNode consistsOfArray = (ArrayNode) jsonNode.get(Resource.CONSISTS_OF_PROPERTY);
int consistsOfSize = 0;
if(consistsOfArray!=null) {
consistsOfSize = consistsOfArray.size();
}
int total = consistsOfSize;
ArrayNode isRelatedToArray = (ArrayNode) jsonNode.get(Resource.IS_RELATED_TO_PROPERTY);
if(isRelatedToArray!=null && isRelatedToArray.size()>0) {
--size;
isRelatedToSize = isRelatedToArray.size();
total += isRelatedToSize;
for(int i=0; i<isRelatedToSize; i++) {
JsonNode isRelatedToJsonNode = isRelatedToArray.get(i);
JsonQueryIsRelatedTo jsonQueryIsRelatedTo = new JsonQueryIsRelatedTo(isRelatedToJsonNode);
jsonQueryIsRelatedTo.setRequestedResourceType(type);
jsonQueryIsRelatedTo.setDirectionByJson(true);
jsonQueryIsRelatedTo.setBreadcrumb(childrenBreadcrumb);
jsonQueryIsRelatedTo.setPosition(i);
boolean traverseBack = true;
// boolean traverseBack = false;
// if(i<(isRelatedToSize-1) || consistsOfSize>0) {
// traverseBack = true;
// }
jsonQueryIsRelatedTo.setTraverseBack(traverseBack);
newBuffer = jsonQueryIsRelatedTo.createMatchQuery(newBuffer);
if(traverseBack) {
newBuffer.append("\n\t.");
newBuffer.append(jsonQueryIsRelatedTo.getDirection().name().toLowerCase());
newBuffer.append("V('");
newBuffer.append(type);
newBuffer.append("') ");
newBuffer.append("{ where: ($matched.");
newBuffer.append(getAlias(true));
newBuffer.append(" == $currentMatch)}");
if(entryPoint && i<(total-1)) {
newBuffer.append("\n");
}
}
}
}
if(consistsOfSize>0) {
--size;
for(int i=0; i<consistsOfArray.size(); i++) {
JsonNode consistsOfJsonNode = consistsOfArray.get(i);
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfJsonNode);
jsonQueryConsistsOf.setRequestedResourceType(type);
jsonQueryConsistsOf.setDirection(Direction.OUT);
jsonQueryConsistsOf.setBreadcrumb(childrenBreadcrumb);
jsonQueryConsistsOf.setPosition(isRelatedToSize+i);
boolean traverseBack = true;
jsonQueryConsistsOf.setTraverseBack(traverseBack);
newBuffer = jsonQueryConsistsOf.createMatchQuery(newBuffer);
if(traverseBack) {
newBuffer.append("\n\t.");
newBuffer.append(jsonQueryConsistsOf.getDirection().name().toLowerCase());
newBuffer.append("V('");
newBuffer.append(type);
newBuffer.append("')");
newBuffer.append(" { where: ($matched.");
newBuffer.append(getAlias(true));
newBuffer.append(" == $currentMatch)}");
if(entryPoint && i<(consistsOfSize-1)) {
newBuffer.append("\n");
}
}
}
}
StringBuffer buffer = new StringBuffer();
if(!entryPoint) {
buffer.append("\n\t");
buffer.append(".");
buffer.append(direction.name().toLowerCase());
buffer.append("V('");
buffer.append(type);
buffer.append("')");
alias = getAlias(true);
StringBuffer sb = null;
if(size > 0) {
sb = addConstraints(jsonNode, null, null);
}
buffer.append(" {");
buffer.append(" as: ");
buffer.append(alias);
buffer.append(",");
buffer.append(" where: ");
if(sb!=null && sb.length()>0) {
buffer.append("(");
}
buffer.append("($currentMatch['@class'] INSTANCEOF '");
buffer.append(type);
buffer.append("')");
if(sb!=null && sb.length()>0) {
buffer.append(" AND (");
buffer.append(sb);
buffer.append(")");
buffer.append(")");
}
buffer.append("}");
}
buffer.append(newBuffer);
if(entryPoint) {
buffer.append("\n");
}
return buffer;
}
}

View File

@ -1,17 +1,13 @@
package org.gcube.informationsystem.resourceregistry.queries.json.base.relations;
import java.util.List;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Direction;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.queries.json.base.JsonQueryERElement;
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryFacet;
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryResource;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
/**
* @author Luca Frosini (ISTI - CNR)
@ -33,223 +29,67 @@ public class JsonQueryConsistsOf extends JsonQueryRelation {
this.requestedResourceType = requestedResourceType;
}
protected StringBuffer traverseBackToCallerResource(StringBuffer stringBuffer) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("V(\"");
buffer.append(requestedResourceType);
buffer.append("\") FROM ( "); // Open (
buffer.append(stringBuffer);
buffer.append(")"); // Close )
return buffer;
}
public StringBuffer createSelect(StringBuffer stringBuffer, boolean wrapInnerQuery) throws SchemaException, ResourceRegistryException {
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT FROM ");
if(wrapInnerQuery) {
buffer.append("( ");
buffer.append(stringBuffer);
buffer.append(")");
}else {
buffer.append(type);
}
if(entryPoint || size>1) {
buffer.append(" WHERE ");
}
if(size > 1) {
buffer.append(addConstraints(jsonNode, null, null));
if(entryPoint) {
buffer.append(" AND ");
}
}
if(entryPoint) {
buffer.append(OrientDBUtility.ORIENTDB_CLASS_PROPERTY);
buffer.append(" INSTANCEOF \"");
buffer.append(type);
buffer.append("\"");
}
return buffer;
}
@Override
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
StringBuffer consistsOfBuffer = new StringBuffer();
boolean wrapInnerQuery = false;
if(traverseBack) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
wrapInnerQuery = true;
if(!jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
consistsOfBuffer.append("TRAVERSE ");
consistsOfBuffer.append(direction.opposite().name().toLowerCase());
consistsOfBuffer.append("V(\"");
consistsOfBuffer.append(requestedResourceType);
consistsOfBuffer.append("\") FROM ( "); // Open ( 1
}
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
--size;
JsonNode facetJsonNode = jsonNode.get(ConsistsOf.TARGET_PROPERTY);
JsonQueryFacet jsonQueryFacet = new JsonQueryFacet(facetJsonNode);
jsonQueryFacet.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
stringBuffer = jsonQueryFacet.createTraversalQuery(stringBuffer);
wrapInnerQuery = true;
int size = jsonNode.size();
if(size > 2) {
consistsOfBuffer.append("SELECT FROM ( "); // Open ( SELECT
}
if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
--size;
JsonNode resourceJsonNode = jsonNode.get(ConsistsOf.SOURCE_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
jsonQueryResource.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
stringBuffer = jsonQueryResource.createTraversalQuery(stringBuffer);
wrapInnerQuery = true;
}
if(wrapInnerQuery) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
}
if(entryPoint || size>1) {
stringBuffer = createSelect(stringBuffer, wrapInnerQuery);
}
if(!entryPoint && requestedResourceType!=null) {
stringBuffer = traverseBackToCallerResource(stringBuffer);
}
return stringBuffer;
}
@Override
protected StringBuffer getSpecificMatchQuery(List<JsonQueryERElement> childrenBreadcrumb)
throws SchemaException, ResourceRegistryException {
int childrenPosition = 0;
boolean traverseBack = this.traverseBack;
StringBuffer newBuffer = new StringBuffer();
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
--size;
JsonNode facetJsonNode = jsonNode.get(ConsistsOf.TARGET_PROPERTY);
JsonQueryFacet jsonQueryFacet = new JsonQueryFacet(facetJsonNode);
jsonQueryFacet.setBreadcrumb(childrenBreadcrumb);
jsonQueryFacet.setPosition(childrenPosition++);
jsonQueryFacet.setTraverseBack(true);
Direction direction = Direction.IN;
jsonQueryFacet.setDirection(direction);
newBuffer = jsonQueryFacet.createMatchQuery(newBuffer);
newBuffer.append("\n\t");
newBuffer.append(".");
newBuffer.append(direction.name().toLowerCase());
newBuffer.append("E('");
newBuffer.append(type);
newBuffer.append("') ");
newBuffer.append(" { where: ($matched.");
newBuffer.append(getAlias(true));
newBuffer.append(" == $currentMatch)}");
traverseBack = false;
}
if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
--size;
JsonNode resourceJsonNode = jsonNode.get(ConsistsOf.SOURCE_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
jsonQueryResource.setBreadcrumb(childrenBreadcrumb);
jsonQueryResource.setPosition(childrenPosition++);
jsonQueryResource.setTraverseBack(true);
Direction direction = Direction.OUT;
jsonQueryResource.setDirection(direction);
newBuffer = jsonQueryResource.createMatchQuery(newBuffer);
newBuffer.append("\n\t");
newBuffer.append(".");
newBuffer.append(direction.name().toLowerCase());
newBuffer.append("E('");
newBuffer.append(type);
newBuffer.append("') ");
newBuffer.append(" { where: ($matched.");
newBuffer.append(getAlias(true));
newBuffer.append(" == $currentMatch)}");
traverseBack = false;
}
StringBuffer buffer = new StringBuffer();
consistsOfBuffer.append("TRAVERSE ");
consistsOfBuffer.append(direction.name().toLowerCase());
consistsOfBuffer.append("E(\"");
consistsOfBuffer.append(type);
consistsOfBuffer.append("\") FROM ( "); // Open ( 2
if(!entryPoint) {
buffer.append("\n\t");
buffer.append(".");
buffer.append(direction.name().toLowerCase());
buffer.append("E('");
buffer.append(type);
buffer.append("')");
alias = getAlias(true);
StringBuffer sb = null;
if(size > 0) {
sb = addConstraints(jsonNode, null, null);
}
buffer.append(" {");
buffer.append(" as: ");
buffer.append(alias);
buffer.append(",");
buffer.append(" where: ");
if(sb!=null && sb.length()>0) {
buffer.append("(");
}
buffer.append("($currentMatch['@class'] INSTANCEOF '");
buffer.append(type);
buffer.append("')");
if(sb!=null && sb.length()>0) {
buffer.append(" AND (");
buffer.append(sb);
buffer.append(")");
buffer.append(")");
}
buffer.append("}");
}
buffer.append(newBuffer);
if(traverseBack) {
buffer.append("\n\t");
buffer.append(".");
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("E('");
buffer.append("E(\"");
buffer.append(type);
buffer.append("') ");
buffer.append(" { where: ($matched.");
buffer.append(alias);
buffer.append(" == $currentMatch)}");
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
}
return buffer;
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
JsonNode facetJsonNode = jsonNode.get(ConsistsOf.TARGET_PROPERTY);
JsonQueryFacet jsonQueryFacet = new JsonQueryFacet(facetJsonNode);
jsonQueryFacet.setEntryPoint(entryPoint);
stringBuffer = jsonQueryFacet.analize(stringBuffer);
} else if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
JsonNode resourceJsonNode = jsonNode.get(ConsistsOf.SOURCE_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
jsonQueryResource.setEntryPoint(entryPoint);
stringBuffer = jsonQueryResource.analize(stringBuffer);
}
consistsOfBuffer.append(stringBuffer);
consistsOfBuffer.append(")"); // Close ) 2
// Size 2 means that only '@class' and 'target' properties are present
if(size > 2) {
consistsOfBuffer.append(") WHERE "); // Close ) SELECT
consistsOfBuffer.append(addConstraints(jsonNode, null, null));
}
if(!jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
consistsOfBuffer.append(")"); // Close ) 1
}
return consistsOfBuffer;
}
}

View File

@ -1,20 +1,13 @@
package org.gcube.informationsystem.resourceregistry.queries.json.base.relations;
import java.util.List;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Direction;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.queries.json.base.JsonQueryERElement;
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryResource;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
/**
* @author Luca Frosini (ISTI - CNR)
@ -25,7 +18,6 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
public JsonQueryIsRelatedTo(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
super(jsonQuery, AccessType.IS_RELATED_TO);
direction = null;
}
public String getRequestedResourceType() {
@ -36,294 +28,123 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
this.requestedResourceType = requestedResourceType;
}
protected StringBuffer traverseBackToCallerResource(StringBuffer stringBuffer) {
private StringBuffer traverseThisEdge(StringBuffer stringBuffer) throws InvalidQueryException {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("V(\"");
buffer.append(requestedResourceType);
buffer.append("\") FROM ( "); // Open (
buffer.append(stringBuffer);
buffer.append(")"); // Close )
return buffer;
int size = jsonNode.size();
// Remove @class from size
--size;
if(jsonNode.has(IsRelatedTo.SOURCE_PROPERTY)) {
--size;
}
public StringBuffer createSelect(StringBuffer stringBuffer, boolean wrapInnerQuery) throws SchemaException, ResourceRegistryException {
StringBuffer buffer = new StringBuffer();
if(jsonNode.has(IsRelatedTo.TARGET_PROPERTY)) {
--size;
}
if(size > 0) {
buffer.append("SELECT FROM ");
if(wrapInnerQuery) {
buffer.append("( ");
buffer.append(stringBuffer);
buffer.append(")");
if(entryPoint) {
buffer.append(type);
}else {
buffer.append(type);
buffer.append(" ( "); // Open ( SELECT
}
if(entryPoint || size>1) {
buffer.append(" WHERE ");
}
if(size > 1) {
buffer.append(addConstraints(jsonNode, null, null));
}else {
if(entryPoint) {
buffer.append(" AND ");
}
}
if(entryPoint) {
buffer.append(OrientDBUtility.ORIENTDB_CLASS_PROPERTY);
buffer.append(" INSTANCEOF \"");
buffer.append("SELECT FROM ");
buffer.append(type);
buffer.append("\"");
}
return buffer;
}
public void setDirectionByJson() throws InvalidQueryException {
setDirectionByJson(false);
}
public void setDirectionByJson(boolean matchQuery) throws InvalidQueryException {
if(entryPoint) {
String error = "The function JsonQueryIsRelatedTo#setDirectionByJson() cannot be called for an entry point";
logger.error(error);
throw new InternalServerErrorException(error);
}
boolean found = false;
if(jsonNode.has(IsRelatedTo.SOURCE_PROPERTY)) {
logger.trace("{} for type {} has {} property", IsRelatedTo.NAME, type, IsRelatedTo.SOURCE_PROPERTY);
direction = Direction.OUT;
found = true;
}
if(jsonNode.has(IsRelatedTo.TARGET_PROPERTY)) {
if(found) {
StringBuffer buffer = new StringBuffer();
buffer.append(IsRelatedTo.NAME);
buffer.append(" for type ");
buffer.append(type);
buffer.append(" has both ");
buffer.append(IsRelatedTo.SOURCE_PROPERTY);
buffer.append(" and ");
buffer.append(IsRelatedTo.TARGET_PROPERTY);
buffer.append(" property. Only entry points can have both because one is implicit from the resource containg the ");
buffer.append(IsRelatedTo.NAME);
buffer.append(" relation.");
logger.error("This part of the json query is not valid {}\n{}", jsonNode.toString(), buffer.toString());
throw new InvalidQueryException(buffer.toString());
}
direction = Direction.IN;
}
if(matchQuery) {
direction = direction.opposite();
}
}
@Override
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
if(!entryPoint && direction==null) {
throw new InternalServerErrorException("Caller Resource must invoke setDirectionByJson() first. This is a server bug. Please contact the administator. ");
}
boolean wrapInnerQuery = false;
if(traverseBack) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
wrapInnerQuery = true;
}
Direction wrapDirection = direction;
if(jsonNode.has(IsRelatedTo.SOURCE_PROPERTY)) {
--size;
JsonNode sourceJsonNode = jsonNode.get(IsRelatedTo.SOURCE_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(sourceJsonNode);
wrapDirection = Direction.OUT;
jsonQueryResource.setDirection(Direction.OUT);
jsonQueryResource.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
stringBuffer = jsonQueryResource.createTraversalQuery(stringBuffer);
wrapInnerQuery = true;
}
if(jsonNode.has(IsRelatedTo.TARGET_PROPERTY)) {
if(jsonNode.has(IsRelatedTo.SOURCE_PROPERTY)) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(wrapDirection.name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
}
--size;
JsonNode targetJsonNode = jsonNode.get(IsRelatedTo.TARGET_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(targetJsonNode);
wrapDirection = Direction.IN;
jsonQueryResource.setDirection(Direction.IN);
jsonQueryResource.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
stringBuffer = jsonQueryResource.createTraversalQuery(stringBuffer);
wrapInnerQuery = true;
}
if(wrapInnerQuery) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(wrapDirection.name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
}
if(entryPoint || size>1) {
stringBuffer = createSelect(stringBuffer, wrapInnerQuery);
}
if(!entryPoint) {
stringBuffer = traverseBackToCallerResource(stringBuffer);
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
}
stringBuffer = buffer;
// Size 0 means that only '@class' and 'target'/'source' properties are present
if(size > 0) {
if(!entryPoint) {
stringBuffer.append(" )"); // Close ) SELECT
}
stringBuffer.append(" WHERE ");
stringBuffer.append(addConstraints(jsonNode, null, null));
}
return stringBuffer;
}
@Override
protected StringBuffer getSpecificMatchQuery(List<JsonQueryERElement> childrenBreadcrumb) throws SchemaException, ResourceRegistryException {
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
if(!entryPoint && direction==null) {
throw new InternalServerErrorException("Caller Resource must invoke setDirectionByJson() first. This is a server bug. Please contact the administator. ");
}
int childrenPosition = 0;
boolean traverseBack = this.traverseBack;
StringBuffer newBuffer = new StringBuffer();
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
--size;
JsonNode targetJsonNode = jsonNode.get(IsRelatedTo.TARGET_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(targetJsonNode);
Direction direction = Direction.IN;
jsonQueryResource.setDirection(direction);
jsonQueryResource.setBreadcrumb(childrenBreadcrumb);
jsonQueryResource.setPosition(childrenPosition++);
jsonQueryResource.setTraverseBack(true);
newBuffer = jsonQueryResource.createMatchQuery(newBuffer);
newBuffer.append("\n\t");
newBuffer.append(".");
newBuffer.append(direction.name().toLowerCase());
newBuffer.append("E('");
newBuffer.append(type);
newBuffer.append("') ");
newBuffer.append(" { where: ($matched.");
newBuffer.append(getAlias(true));
newBuffer.append(" == $currentMatch)}");
traverseBack = false;
}
if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
--size;
JsonNode sourceJsonNode = jsonNode.get(IsRelatedTo.SOURCE_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(sourceJsonNode);
Direction direction = Direction.OUT;
jsonQueryResource.setDirection(direction);
jsonQueryResource.setBreadcrumb(childrenBreadcrumb);
jsonQueryResource.setPosition(childrenPosition++);
jsonQueryResource.setTraverseBack(true);
newBuffer = jsonQueryResource.createMatchQuery(newBuffer);
JsonNode targetJsonNode = jsonNode.get(IsRelatedTo.TARGET_PROPERTY);
newBuffer.append("\n\t");
newBuffer.append(".");
newBuffer.append(direction.name().toLowerCase());
newBuffer.append("E('");
newBuffer.append(type);
newBuffer.append("') ");
newBuffer.append(" { where: ($matched.");
newBuffer.append(getAlias(true));
newBuffer.append(" == $currentMatch)}");
JsonNode resourceJsonNode = null;
traverseBack = false;
if(sourceJsonNode!=null) {
resourceJsonNode = sourceJsonNode;
direction = Direction.OUT;
} else if(targetJsonNode!=null) {
resourceJsonNode = targetJsonNode;
direction = Direction.IN;
}
stringBuffer = traverseThisEdge(stringBuffer);
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
jsonQueryResource.setDirection(direction);
jsonQueryResource.setEntryPoint(false);
stringBuffer = jsonQueryResource.analize(stringBuffer);
StringBuffer buffer = new StringBuffer();
if(!entryPoint) {
buffer.append("\n\t");
buffer.append(".");
buffer.append(direction.name().toLowerCase());
buffer.append("E('");
buffer.append(type);
buffer.append("')");
alias = getAlias(true);
StringBuffer sb = null;
if(size > 0) {
sb = addConstraints(jsonNode, null, null);
}
buffer.append(" {");
buffer.append(" as: ");
buffer.append(alias);
buffer.append(",");
buffer.append(" where: ");
if(sb!=null && sb.length()>0) {
buffer.append("(");
}
buffer.append("($currentMatch['@class'] INSTANCEOF '");
buffer.append(type);
buffer.append("')");
if(sb!=null && sb.length()>0) {
buffer.append(" AND (");
buffer.append(sb);
buffer.append(")");
buffer.append(")");
}
buffer.append("}");
}
buffer.append(newBuffer);
if(traverseBack) {
buffer.append("\n\t");
buffer.append(".");
if(requestedResourceType!=null) {
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("E('");
buffer.append("V(\"");
buffer.append(requestedResourceType);
buffer.append("\") FROM ( ");
}
buffer.append("TRAVERSE ");
buffer.append(direction.name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("') ");
buffer.append(" { where: ($matched.");
buffer.append(getAlias(true));
buffer.append(" == $currentMatch)}");
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
if(requestedResourceType!=null) {
buffer.append(")");
}
stringBuffer = buffer;
if(sourceJsonNode!=null && targetJsonNode!=null) {
// Target has still to be analised
jsonQueryResource = new JsonQueryResource(targetJsonNode);
jsonQueryResource.setDirection(Direction.IN);
jsonQueryResource.setEntryPoint(false);
stringBuffer = jsonQueryResource.analize(stringBuffer);
boolean entryPointOldValue = entryPoint;
// It is no more and entry point for the function traverseThisEdge
entryPoint = false;
stringBuffer = traverseThisEdge(stringBuffer);
// Restoring entryPoint indication
entryPoint = entryPointOldValue;
}
return buffer;
return stringBuffer;
}
}

View File

@ -1,118 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.NotImplementedException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.types.PropertyTypeName.BaseTypeGroup;
/**
* @author Luca Frosini (ISTI - CNR)
* See https://www.orientdb.com/docs/3.0.x/sql/SQL-Where.html
* https://www.orientdb.com/docs/3.0.x/sql/SQL-Syntax.html#conditions
* https://www.orientdb.com/docs/3.0.x/sql/SQL-Syntax.html#comparison-operators
* https://www.orientdb.com/docs/3.0.x/sql/SQL-Syntax.html#boolean-operators
*/
public enum ComparisonOperator {
EQ("_eq", " = ", 2, BaseTypeGroup.ANY, "Matches values that are equal to a specified value. E.g. `name = 'Luke'`"),
GT("_gt", " > ", 2, BaseTypeGroup.ANY, "Matches values that are greater than a specified value. "),
GTE("_gte", " >= ", 2, BaseTypeGroup.ANY, "Matches values that are greater than or equal to a specified value."),
LT("_lt", " < ", 2, BaseTypeGroup.ANY, "Matches values that are less than a specified value."),
LTE("_lte", " <= ", 2, BaseTypeGroup.ANY, "Matches values that are less than or equal to a specified value."),
NE("_ne", " <> ", 2, BaseTypeGroup.ANY, "Matches all values that are not equal to a specified value."),
BETWEEN("_between", " BETWEEN %s AND %s", 3, BaseTypeGroup.ANY, "Returns TRUE is a value is between two values, eg. 5 BETWEEN 1 AND 10. The value is between a range. E.g. `price BETWEEN 10 AND 30`. It's equivalent to `price >= 10 AND price <= 30`."),
IS("_is", " IS ", 2, BaseTypeGroup.ANY, "Used to test if a value is NULL"),
LIKE("_like", " LIKE ", 2, BaseTypeGroup.STRING, "For strings, checks if a string contains another string. % is used as a wildcard, eg. 'foobar CONTAINS '%ooba%''. Similar to equals, but allow the wildcard '%' that means 'any'. E.g. `name LIKE 'Luk%'`"),
CONTAINS_TEXT("_containsText", " CONTAINSTEXT ", 2, BaseTypeGroup.STRING, "The string contains such text. E.g. `text CONTAINSTEXT 'jay'`"),
MATCHES("_matches", " MATCHES ", 2, BaseTypeGroup.STRING, "Checks if a string matches a regular expression. Matches the string using a Regular Expression. E.g. `text MATCHES '\b[A-Z0-9.%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b'`"),
IN("_in", " IN ", 2, BaseTypeGroup.COLLECTION, "The same as CONTAINS, but with inverted operands. Matches any of the values specified in an array. E.g. `name in ['European','Asiatic']`"),
CONTAINS("_contains", " CONTAINS ", 2, BaseTypeGroup.COLLECTION, "Checks if the left collection contains the right element. The left argument has to be a colleciton, otherwise it returns FALSE. It's NOT the check of colleciton intersections, so ['a', 'b', 'c'] CONTAINS ['a', 'b'] will return FALSE, while ['a', 'b', 'c'] CONTAINS 'a' will return TRUE. True if the collection contains at least one element that satisfy the next condition. Condition can be a single item: in this case the behaviour is like the IN operator. E.g. `children contains (name = 'Luke')` - `map.values() contains (name = 'Luke')`"),
CONTAINS_ALL("_containsAll", " CONTAINSALL ", 2, BaseTypeGroup.COLLECTION, "True if all the elements of the collection satisfy the next condition. E.g. `children CONTAINSALL (name = 'Luke')`"),
CONTAINS_ANY("_containsAny", " CONTAINSANY ", 2, BaseTypeGroup.COLLECTION, "True if all the elements of the collection satisfy the next condition. E.g. `children CONTAINSANY (name = 'Luke')`"),
CONTAINS_KEY("_containsKey", " CONTAINSKEY ", 2, BaseTypeGroup.MAP, "For maps, the same as for CONTAINS, but checks on the map keys. True if the map contains at least one key equals to the requested. You can also use map.keys() CONTAINS in place of it. E.g. `connections CONTAINSKEY 'Luke'`"),
CONTAINS_VALUE("_containsValue", " CONTAINSVALUE ", 2, BaseTypeGroup.MAP , "For maps, the same as for CONTAINS, but checks on the map values. True if the map contains at least one value equals to the requested. You can also use map.values() CONTAINS in place of it. E.g. `connections containsValue 10:3`"),
IS_DEFINED("_isDefined", " IS DEFINED ", 1, BaseTypeGroup.ANY, "Returns TRUE is a field is defined in a document"),
IS_NOT_DEFINED("_isNotDefined", " IS NOT DEFINED ", 1, BaseTypeGroup.ANY, "Returns TRUE is a field is not defined in a document");
protected final String operatorKey;
protected final int numberOfOperand;
protected final String dbOperator;
protected final BaseTypeGroup allowed;
protected final String description;
private ComparisonOperator(String operatorKey, String dbOperator, int numberOfOperand, BaseTypeGroup allowed, String description) {
this.operatorKey = operatorKey;
this.dbOperator = dbOperator;
this.numberOfOperand = numberOfOperand;
this.allowed = allowed;
this.description = description;
}
protected String getOperatorKey() {
return operatorKey;
}
public String getDbOperator() {
return dbOperator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,ComparisonOperator> operatorByKey;
static {
ComparisonOperator.operators = new HashSet<>();
ComparisonOperator.operatorByKey = new HashMap<>();
for(ComparisonOperator queryComparisonOperator : ComparisonOperator.values()) {
ComparisonOperator.operators.add(queryComparisonOperator.getOperatorKey());
ComparisonOperator.operatorByKey.put(queryComparisonOperator.getOperatorKey(), queryComparisonOperator);
}
}
public static Set<String> getOperators() {
return ComparisonOperator.operators;
}
public static ComparisonOperator getOperator(String key) {
return operatorByKey.get(key);
}
public StringBuffer addCondition(String... operands) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(operands[0]);
stringBuffer.append(getDbOperator());
stringBuffer.append(operands[1]);
return stringBuffer;
}
public static String getValue(JsonNode jsonNode) {
StringBuffer stringBuffer = new StringBuffer();
String value = jsonNode.asText();
if(jsonNode.isNumber()) {
stringBuffer.append(value);
} else {
stringBuffer.append("\"");
stringBuffer.append(value);
stringBuffer.append("\"");
}
return stringBuffer.toString();
}
public StringBuffer addCondition(JsonNode jn, String fieldNamePrefix) {
throw new NotImplementedException();
}
}

View File

@ -1,29 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
/**
* @author Luca Frosini (ISTI - CNR)
*
* Methods: also called "Field Operators"
*
* SQL Methods are similar to SQL functions but they apply to values.
* In Object Oriented paradigm they are called "methods", as functions related to a class.
* So what's the difference between a function and a method?
*
* This is a SQL function:
*
* SELECT sum( salary ) FROM employee
*
* This is a SQL method:
*
* SELECT salary.toJSON() FROM employee
*
* As you can see the method is executed against a field/value.
* Methods can receive parameters, like functions.
* You can concatenate N operators in sequence.
*
* See https://orientdb.com/docs/3.0.x/sql/SQL-Where.html#methods
* http://orientdb.com/docs/3.0.x/sql/SQL-Methods.html
*/
public enum FieldOperator {
}

View File

@ -1,9 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
/**
* @author Luca Frosini (ISTI - CNR)
* See https://www.orientdb.com/docs/3.0.x/sql/SQL-Functions.html
*/
public class Function {
}

View File

@ -1,60 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Luca Frosini (ISTI - CNR)
* See https://www.orientdb.com/docs/3.0.x/sql/SQL-Where.html
*/
public enum LogicalOperator {
AND("_and", " AND ", "true if both the conditions are true"),
OR("_or", " OR ", "true if at least one of the condition is true"),
NOT("_not", " NOT ", "true if the condition is false.");
protected final String operatorKey;
protected final String dbOperator;
protected final String description;
private LogicalOperator(String operatorKey, String dbOperator, String description) {
this.operatorKey = operatorKey;
this.dbOperator = dbOperator;
this.description = description;
}
public String getOperatorKey() {
return operatorKey;
}
public String getDbOperator() {
return dbOperator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,LogicalOperator> operatorByKey;
static {
LogicalOperator.operators = new HashSet<>();
LogicalOperator.operatorByKey = new HashMap<>();
for(LogicalOperator logicalOperator : LogicalOperator.values()) {
LogicalOperator.operators.add(logicalOperator.getOperatorKey());
LogicalOperator.operatorByKey.put(logicalOperator.getOperatorKey(), logicalOperator);
}
}
public static Set<String> getOperators() {
return LogicalOperator.operators;
}
public static LogicalOperator getOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -1,180 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.BadRequestException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.com.fasterxml.jackson.databind.node.TextNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*
* OrientDB supports the eval() function to execute complex operations. Example:
*
* SELECT eval( "amount * 120 / 100 - discount" ) as finalPrice from Order
*
* See https://www.orientdb.com/docs/3.0.x/sql/SQL-Where.html#mathematics-operators
* https://www.orientdb.com/docs/3.0.x/sql/SQL-Syntax.html#math-operators
* https://www.orientdb.com/docs/3.0.x/sql/SQL-Syntax.html#math-operators-precedence
* https://www.orientdb.com/docs/3.0.x/sql/SQL-Syntax.html#array-concatenation
*/
public enum MatemathicsOperator {
SUM("_sum", "+", ""),
MINUS("_minus", "-", ""),
MULTIPLY("_multiply", "*", ""),
DIVIDE("_divide", "/", ""),
MODULE("_mod", "%", ""),
BITWISE_RIGHT_SHIFT("_bitrshift", ">>", ""),
BITWISE_LEFT_SHIFT("_bitlshift", "<<", ""),
BITWISE_AND("_bitand", "&", ""),
BITWISE_OR("_bitor", "|", ""),
BITWISE_XOR("_bitxor", "^", ""),
ARRAY_CONCATENATION("_arrayconcat", "||", "");
protected static Logger logger = LoggerFactory.getLogger(MatemathicsOperator.class);
public static final String VALUES_KEY = "values";
public static final String SEPARATOR_KEY = "separator";
public static final String AS_KEY = "as";
protected final String operatorKey;
protected final String dbOperator;
protected final String description;
private MatemathicsOperator(String operatorKey, String dbOperator, String description) {
this.operatorKey = operatorKey;
this.dbOperator = dbOperator;
this.description = description;
}
protected String getOperatorKey() {
return operatorKey;
}
protected String getDbOperator() {
return dbOperator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,MatemathicsOperator> operatorByKey;
static {
MatemathicsOperator.operators = new HashSet<>();
MatemathicsOperator.operatorByKey = new HashMap<>();
for(MatemathicsOperator matemathicsOperator : MatemathicsOperator.values()) {
MatemathicsOperator.operators.add(matemathicsOperator.getOperatorKey());
MatemathicsOperator.operatorByKey.put(matemathicsOperator.getOperatorKey(), matemathicsOperator);
}
}
public static Set<String> getOperators() {
return operators;
}
public static MatemathicsOperator getOperator(String key) {
return operatorByKey.get(key);
}
protected String getError(String key, Class<?> clazz, boolean mandatory) {
StringBuffer error = new StringBuffer();
error.append("Root emitting MatemathicsOperator (i.e. ");
error.append(this.operatorKey);
error.append(")");
error.append(" contains ");
if(mandatory) {
error.append("mandatory ");
}
error.append(key);
error.append(" which must be a");
error.append(clazz.getSimpleName());
error.append(". This is a client error. Please fix your query");
logger.error(error.toString());
throw new BadRequestException(error.toString());
}
public String generateFieldToEmit(JsonNode jsonNode, String fieldPrefix) {
JsonNode jn = jsonNode.get(VALUES_KEY);
if(jn.isNull() || !jn.isArray()) {
getError(VALUES_KEY, ArrayNode.class, true);
}
String fieldSeparator = null;
if(this == MatemathicsOperator.SUM && jsonNode.has(SEPARATOR_KEY)) {
JsonNode sep = jsonNode.get(SEPARATOR_KEY);
if(!sep.isTextual()) {
getError(SEPARATOR_KEY, TextNode.class, false);
}
fieldSeparator = sep.asText();
}
StringBuffer sb = new StringBuffer();
sb.append("(");
sb.append(generateFieldToEmit((ArrayNode) jn, fieldSeparator, fieldPrefix));
JsonNode jnAs = jsonNode.get(AS_KEY);
if(jnAs.isNull() || !jnAs.isTextual()) {
getError(AS_KEY, TextNode.class, true);
}
sb.append(") AS `");
sb.append(jnAs.asText());
sb.append("`");
return sb.toString();
}
protected StringBuffer addFieldPrefix(StringBuffer sb, String fieldPrefix) {
if(fieldPrefix !=null && fieldPrefix.trim().length()>0) {
sb.append(fieldPrefix.trim());
sb.append(".");
}
return sb;
}
protected StringBuffer generateFieldToEmit(ArrayNode arrayNode, String fieldsSeparator, String fieldPrefix) {
StringBuffer buffer = new StringBuffer();
int size = arrayNode.size();
for(int i=0; i<size; i++) {
JsonNode jn = arrayNode.get(i);
if(jn.isObject()) {
ObjectNode on = (ObjectNode) jn;
String key = on.fieldNames().next();
MatemathicsOperator mo = MatemathicsOperator.getOperator(key);
ArrayNode an = (ArrayNode) on.get(key);
buffer.append("(");
buffer.append(mo.generateFieldToEmit(an, null, fieldPrefix));
buffer.append(")");
}
if(jn.isTextual()) {
buffer = addFieldPrefix(buffer, fieldPrefix);
buffer.append(jn.asText());
}
if(i<(size-1)) {
buffer.append(" ");
buffer.append(dbOperator);
buffer.append(" ");
if(fieldsSeparator!=null) {
buffer.append("'");
buffer.append(fieldsSeparator);
buffer.append("' ");
buffer.append(dbOperator);
buffer.append(" ");
}
}
}
return buffer;
}
}

View File

@ -1,53 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Luca Frosini (ISTI - CNR)
* See https://www.orientdb.com/docs/3.0.x/sql/SQL-Where.html
*/
public enum ProjectionOperator {
EMIT("_emit", "");
protected final String operator;
protected final String description;
private ProjectionOperator(String operator, String description) {
this.operator = operator;
this.description = description;
}
public String getOperator() {
return operator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,ProjectionOperator> operatorByKey;
static {
ProjectionOperator.operators = new HashSet<>();
ProjectionOperator.operatorByKey = new HashMap<>();
for(ProjectionOperator po : ProjectionOperator.values()) {
ProjectionOperator.operators.add(po.getOperator());
ProjectionOperator.operatorByKey.put(po.getOperator(), po);
}
}
public static Set<String> getOperators() {
return ProjectionOperator.operators;
}
public static ProjectionOperator getQueryLogicalOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -0,0 +1,64 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public enum QueryConditionalOperator {
EQ("$eq", " = ", "Matches values that are equal to a specified value."),
GT("$gt", " > ", "Matches values that are greater than a specified value."),
GTE("$gte", " >= ", "Matches values that are greater than or equal to a specified value."),
LT("$lt", " < ", "Matches values that are less than a specified value."),
LTE("$lte", " <= ", "Matches values that are less than or equal to a specified value."),
NE("$ne", " <> ", "Matches all values that are not equal to a specified value."),
IN("$in", " IN ", "Matches any of the values specified in an array.");
protected final String operator;
protected final String conditionalOperator;
protected final String description;
private QueryConditionalOperator(String operator, String conditionalOperator, String description) {
this.operator = operator;
this.conditionalOperator = conditionalOperator;
this.description = description;
}
public String getOperator() {
return operator;
}
public String getConditionalOperator() {
return conditionalOperator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,QueryConditionalOperator> operatorByKey;
static {
QueryConditionalOperator.operators = new HashSet<>();
QueryConditionalOperator.operatorByKey = new HashMap<>();
for(QueryConditionalOperator queryComparisonOperator : QueryConditionalOperator.values()) {
QueryConditionalOperator.operators.add(queryComparisonOperator.getOperator());
QueryConditionalOperator.operatorByKey.put(queryComparisonOperator.getOperator(), queryComparisonOperator);
}
}
public static Set<String> getOperators() {
return QueryConditionalOperator.operators;
}
public static QueryConditionalOperator getQueryComparisonOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -0,0 +1,59 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public enum QueryLogicalOperator {
AND("$and", " AND ", "true if both the conditions are true"),
OR("$or", " OR ", "true if at least one of the condition is true"),
NOT("$not", " NOT ", "true if the condition is false.");
protected final String operator;
protected final String logicalOperator;
protected final String description;
private QueryLogicalOperator(String operator, String logicalOperator, String description) {
this.operator = operator;
this.logicalOperator = logicalOperator;
this.description = description;
}
public String getOperator() {
return operator;
}
public String getLogicalOperator() {
return logicalOperator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,QueryLogicalOperator> operatorByKey;
static {
QueryLogicalOperator.operators = new HashSet<>();
QueryLogicalOperator.operatorByKey = new HashMap<>();
for(QueryLogicalOperator queryLogicalOperator : QueryLogicalOperator.values()) {
QueryLogicalOperator.operators.add(queryLogicalOperator.getOperator());
QueryLogicalOperator.operatorByKey.put(queryLogicalOperator.getOperator(), queryLogicalOperator);
}
}
public static Set<String> getOperators() {
return QueryLogicalOperator.operators;
}
public static QueryLogicalOperator getQueryLogicalOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -1,38 +1,27 @@
package org.gcube.informationsystem.resourceregistry.queries.templates;
import java.util.HashMap;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
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.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.utils.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -140,7 +129,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
return select;
}
protected void checkIfNameAlreadyExists() throws QueryTemplateAlreadyPresentException {
protected void checkIfNameAlreadyExists() throws AlreadyPresentException {
StringBuffer select = getSelectQuery();
StringBuffer errorMessage = new StringBuffer();
@ -157,13 +146,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
if (resultSet != null) {
try {
if(resultSet.hasNext()) {
OResult oResult = resultSet.next();
try {
element = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
} catch (ResourceRegistryException e) {
}
throw new QueryTemplateAlreadyPresentException(errorMessage.toString());
throw new AlreadyPresentException(errorMessage.toString());
}
}finally {
resultSet.close();
@ -196,13 +179,13 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
if(resultSet!=null) {
resultSet.close();
}
throw new QueryTemplateNotFoundException("Error retrieving " + QueryTemplate.NAME + " with name " + getName());
throw new NotFoundException("Error retrieving " + QueryTemplate.NAME + " with name " + getName());
}
OResult oResult = resultSet.next();
OVertex queryTemplate = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, OrientDBUtility.getAsStringForLogging(queryTemplate));
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, Utility.toJsonString(queryTemplate, true));
if(resultSet.hasNext()) {
resultSet.close();
@ -220,80 +203,6 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
}
}
@Override
public String createOrUpdate()
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
boolean update = false;
setAsEntryPoint();
try {
checkIfNameAlreadyExists();
setOperation(Operation.CREATE);
String calledMethod = CalledMethodProvider.instance.get();
calledMethod = calledMethod.replace("update", "create");
CalledMethodProvider.instance.set(calledMethod);
internalCreate();
} catch(QueryTemplateAlreadyPresentException e) {
String uuidVertexString = element.getProperty(QueryTemplate.ID_PROPERTY).toString();
this.uuid = UUID.fromString(uuidVertexString);
/*
* The service accepts the update if:
* - the JSON does NOT contains the field 'id': because the name is an id too;
* - the JSON contains the field 'id' and the value is null: because some serializators could set to null a missing value;
* - the JSON contains the field 'id' and the value is the same value contained in the vertex in the DB.
*
* In other words, the service refuse the update with Bad Request if
* the JSON contains the field 'id' and the value differs from the value contained in the vertex in the DB.
*/
JsonNode idNode = jsonNode.get(QueryTemplate.ID_PROPERTY);
if(idNode != null && !idNode.isNull() && idNode.isTextual()) {
String jsonID = idNode.asText();
if(uuidVertexString.compareTo(jsonID)!=0) {
throw new ResourceRegistryException("If you provide the id of the " + QueryTemplate.NAME + " it must has the same value of the id contained in the IS (i.e. " + uuidVertexString + ")");
}
}
setOperation(Operation.UPDATE);
update = true;
internalUpdate();
}
oDatabaseDocument.commit();
if(update) {
setReload(true);
}
// TODO Notify to subscriptionNotification
return serializeAsJsonNode().toString();
} catch(ResourceRegistryException e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw e;
} catch(Exception e) {
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid, e);
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ResourceRegistryException(e);
} finally {
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
@Override
protected OVertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException {
try {
@ -329,9 +238,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
@Override
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to delete {} with name {}", accessType.getName(), name);
OVertex oVertex = getElement();
uuid = UUID.fromString((String) oVertex.getProperty(IdentifiableElement.ID_PROPERTY));
oVertex.delete();
getElement().delete();
}
@Override
@ -348,31 +255,16 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setElement((OVertex) vertex);
try {
JsonNode jsonObject = queryTemplateManagement.serializeAsJsonNode();
arrayNode.add(jsonObject);
if(limit > 0 && ++count >= limit) {
break;
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {

View File

@ -1,21 +0,0 @@
package org.gcube.informationsystem.resourceregistry.requests;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class RequestUtility {
private static final InheritableThreadLocal<ServerRequestInfo> requestInfo = new InheritableThreadLocal<ServerRequestInfo>() {
@Override
protected ServerRequestInfo initialValue() {
return new ServerRequestInfo();
}
};
public static InheritableThreadLocal<ServerRequestInfo> getRequestInfo() {
return requestInfo;
}
}

View File

@ -1,228 +0,0 @@
package org.gcube.informationsystem.resourceregistry.requests;
import java.util.List;
import javax.ws.rs.core.UriInfo;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.request.RequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ServerRequestInfo extends BaseRequestInfo implements RequestInfo {
protected static Logger logger = LoggerFactory.getLogger(ServerRequestInfo.class);
protected UriInfo uriInfo;
public ServerRequestInfo() {
super();
this.uriInfo = null;
}
public ServerRequestInfo(int offset, int limit) {
super(offset, limit);
this.uriInfo = null;
}
public UriInfo getUriInfo() {
return uriInfo;
}
/**
* -check if the user is allowed to set such a request
* @param queryParameterKey requested query parameter
* @return true is the user is allowed to set such a request
*/
public boolean isAllowed(String queryParameterKey) {
switch (queryParameterKey) {
case InstancePath.INCLUDE_META_QUERY_PARAMETER:
// TODO check is the user has the role to request such parameter
return true;
case InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER:
// TODO check is the user has the role to request such parameter
return true;
case InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER:
// TODO check is the user has the role to request such parameter
return true;
case InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER:
// TODO check is the user has the role to request such parameter
return true;
case InstancePath.LIMIT_QUERY_PARAMETER:
// TODO check is the user has the role to request such parameter
return true;
case InstancePath.OFFSET_QUERY_PARAMETER:
// TODO check is the user has the role to request such parameter
return true;
default:
break;
}
return true;
}
/**
* Set the parameter if the user is allowed otherwise the default is maintained
* @param queryParameterKey requested query parameter
* @param bool the value to set
* @param forceAllowed force the value and skip the isAllowed check
* @return the value of variable corresponding the request parameter
* independently if the value has been set.
*/
public boolean setIfAllowed(String queryParameterKey, boolean bool, boolean forceAllowed) {
switch (queryParameterKey) {
case InstancePath.INCLUDE_META_QUERY_PARAMETER:
if(forceAllowed || isAllowed(queryParameterKey)) {
includeMeta = bool;
}
return includeMeta;
case InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER:
if(forceAllowed || isAllowed(queryParameterKey)) {
allMeta = bool;
}
return allMeta;
case InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER:
if(forceAllowed || isAllowed(queryParameterKey)) {
includeContexts = bool;
}
return includeContexts;
case InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER:
if(forceAllowed || isAllowed(queryParameterKey)) {
hierarchicalMode = bool;
}
return hierarchicalMode;
default:
break;
}
return false;
}
/**
* Set the parameter if the user is allowed otherwise the default is maintained
* @param queryParameterKey requested query parameter
* @param bool the value to set
* @return the value of variable corresponding the request parameter
* independently if the value has been set.
*/
public boolean setIfAllowed(String queryParameterKey, boolean bool) {
return setIfAllowed(queryParameterKey, bool, false);
}
/**
* Set the parameter if the user is allowed otherwise the default is maintained
* @param queryParameterKey requested query parameter
* @param integer the int value to set
* @param forceAllowed force the value and skip the isAllowed check
* @return the value of variable corresponding the request parameter independently if
* the value has been set.
*/
public int setIfAllowed(String queryParameterKey, int integer, boolean forceAllowed) {
switch (queryParameterKey) {
case InstancePath.LIMIT_QUERY_PARAMETER:
if(forceAllowed || isAllowed(queryParameterKey)) {
limit = integer;
}
return limit;
case InstancePath.OFFSET_QUERY_PARAMETER:
if(forceAllowed || isAllowed(queryParameterKey)) {
offset = integer;
}
return offset;
default:
break;
}
return -1;
}
/**
* Set the parameter if the user is allowed otherwise the default is maintained
* @param queryParameterKey requested query parameter
* @param integer the int value to set
* @return the value of variable corresponding the request parameter independently if
* the value has been set.
*/
public int setIfAllowed(String queryParameterKey, int integer) {
return setIfAllowed(queryParameterKey, integer, false);
}
public void checkBooleanQueryParameter(String queryParameterKey) {
try {
List<String> queryParameterList = uriInfo.getQueryParameters().get(queryParameterKey);
if(queryParameterList!=null && queryParameterList.size()>0) {
String booleanString = queryParameterList.get(0);
boolean bool = Boolean.valueOf(booleanString);
setIfAllowed(queryParameterKey, bool);
}
}catch (Throwable t) {
logger.warn("Unable to properly set " + queryParameterKey, t.getMessage());
}
}
public void checkIntegerQueryParameter(String queryParameterKey) {
checkIntegerQueryParameter(queryParameterKey, null);
}
public void checkIntegerQueryParameter(String queryParameterKey, Integer defaultValue) {
try {
List<String> queryParameterList = uriInfo.getQueryParameters().get(queryParameterKey);
if(queryParameterList!=null && queryParameterList.size()>0) {
String intString = queryParameterList.get(0);
int integer = Integer.valueOf(intString);
setIfAllowed(queryParameterKey, integer);
}else if(defaultValue!=null) {
setIfAllowed(queryParameterKey, defaultValue, true);
}
}catch (Throwable t) {
logger.warn("Unable to properly set " + queryParameterKey, t.getMessage());
}
}
public void setUriInfo(UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
public void checkAllBooleanQueryParameters() {
checkAllIncludeQueryParameters();
checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
}
public void checkAllIncludeQueryParameters() {
checkIncludeAllMetaQueryParameters();
checkBooleanQueryParameter(InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER);
}
public void checkIncludeAllMetaQueryParameters() {
checkBooleanQueryParameter(InstancePath.INCLUDE_META_QUERY_PARAMETER);
checkBooleanQueryParameter(InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER);
}
public void checkLimitOffset(int offset, int limit) {
checkIntegerQueryParameter(InstancePath.OFFSET_QUERY_PARAMETER, offset);
checkIntegerQueryParameter(InstancePath.LIMIT_QUERY_PARAMETER, limit);
}
public void checkLimitOffset() {
checkLimitOffset(DEFAULT_OFFSET, DEFAULT_LIMIT);
}
}

View File

@ -5,7 +5,6 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
@ -15,14 +14,12 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -30,7 +27,6 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
@ -43,11 +39,10 @@ import org.gcube.informationsystem.resourceregistry.instances.model.entities.Res
import org.gcube.informationsystem.resourceregistry.queries.Query;
import org.gcube.informationsystem.resourceregistry.queries.QueryImpl;
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type;
import org.gcube.smartgears.utils.InnerMethodName;
import com.orientechnologies.orient.core.record.ODirection;
@ -61,11 +56,6 @@ public class Access extends BaseRest {
public static final String RELATION_TYPE_PATH_PARAMETER = "RELATION_TYPE_NAME";
public static final String REFERENCE_TYPE_PATH_PARAMETER = "REFERENCE_TYPE_NAME";
public static final String RAW_QUERY_METHOD = "raw";
public static final String GRAPH_QUERY_METHOD = "graph";
public static final String JSON_QUERY_METHOD = "json";
public static final String PREPARED_QUERY_METHOD = "prepared";
public Access() {
super();
}
@ -78,12 +68,7 @@ public class Access extends BaseRest {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String getAllContexts() throws ResourceRegistryException {
logger.info("Requested to read all {}s", org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
setAccountingMethod(Method.LIST, org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
InnerMethodName.instance.set("listContexts");
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
@ -102,18 +87,13 @@ public class Access extends BaseRest {
uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString();
}
logger.info("Requested to read {} with id {} ", org.gcube.informationsystem.contexts.reference.entities.Context.NAME, uuid);
setAccountingMethod(Method.READ, org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("readContext");
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
return contextManagement.readAsString();
}
/*
* GET /access/types/{TYPE_NAME}[?polymorphic=false]
* e.g. GET /access/types/ContactFacet?polymorphic=true
@ -125,11 +105,7 @@ public class Access extends BaseRest {
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
throws SchemaNotFoundException, ResourceRegistryException {
logger.info("Requested Schema for type {}", type);
setAccountingMethod(Method.READ, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("readType");
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeName(type);
@ -141,72 +117,6 @@ public class Access extends BaseRest {
}
}
/*
* GET /access/query-templates
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART)
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String allQueryTemplates() throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", QueryTemplate.NAME);
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
}
/*
* GET /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. GET /access/query-templates/GetAllEServiceWithState
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String readQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.READ, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
return queryTemplateManagement.read();
}
/*
* POST /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. POST /access/query-templates/GetAllEServiceWithState
*
* params = { "$state" : "ready" }
*
*/
@POST
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String runQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
queryTemplateManagement.setParams(params);
return queryTemplateManagement.run();
}
/*
* GET /access/instances/{TYPE_NAME}[?polymorphic=true]
* e.g. GET /access/instances/ContactFacet?polymorphic=true
@ -219,11 +129,10 @@ public class Access extends BaseRest {
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
InnerMethodName.instance.set("listInstances");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
checkHierarchicalMode();
checkIncludeInstancesContexts();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
@ -240,10 +149,10 @@ public class Access extends BaseRest {
public Response instanceExists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to check if {} with id {} exists", type, uuid);
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
InnerMethodName.instance.set("existInstance");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
checkHierarchicalMode();
checkIncludeInstancesContexts();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
@ -277,10 +186,10 @@ public class Access extends BaseRest {
public String getInstance(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read {} with id {}", type, uuid);
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
InnerMethodName.instance.set("readInstance");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
checkHierarchicalMode();
checkIncludeInstancesContexts();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
@ -290,6 +199,8 @@ public class Access extends BaseRest {
return erManagement.read().toString();
}
/*
* GET /access/instances/{TYPE_NAME}/{UUID}/contexts
* e.g. GET /access/instances/ContactFacet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86/contexts
@ -301,14 +212,13 @@ public class Access extends BaseRest {
public String getInstanceContexts(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String instanceId) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
setAccountingMethod(InstancesManager.GET_INSTANCE_CONTEXTS_METHOD);
InnerMethodName.instance.set("getInstanceContexts");
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(instanceId));
return erManagement.getContexts();
}
/**
* It includeSubtypes to query Entities and Relations in the current Context.<br />
* It accepts idempotent query only.. <br />
@ -321,9 +231,6 @@ public class Access extends BaseRest {
*
* e.g. GET /access/query?q=SELECT FROM V
*
* It is responsibility of the client impose manage paginated results
* according the SQL syntax (see SKIP and LIMIT parameters in the documentation indicated above)
*
* @param query Defines the query to send to the backend.
* @param raw request a raw response (not a Element based response)
* @return The JSON representation of the result
@ -336,19 +243,10 @@ public class Access extends BaseRest {
@QueryParam(AccessPath.RAW_QUERY_PARAMETER) @DefaultValue(AccessPath.RAW_QUERY_PARAMETER_DEFAULT_VALUE) Boolean raw)
throws InvalidQueryException {
logger.info("Requested query (Raw {}):\n{}", raw, query);
if(raw) {
setAccountingMethod(Method.QUERY, RAW_QUERY_METHOD);
}else {
setAccountingMethod(Method.QUERY, GRAPH_QUERY_METHOD);
}
InnerMethodName.instance.set("graphQuery");
ServerRequestInfo serverRequestInfo = initRequestInfo();
if(raw) {
// TODO Check if the role allow to request raw data
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
}else {
serverRequestInfo.checkAllBooleanQueryParameters();
}
checkHierarchicalMode();
checkIncludeInstancesContexts();
Query queryManager = new QueryImpl();
return queryManager.query(query, raw);
@ -360,30 +258,30 @@ public class Access extends BaseRest {
* Content Body example:
*
* {
* "": "EService",
* "@class": "EService",
* "consistsOf": [
* {
* "": "ConsistsOf",
* "@class": "ConsistsOf",
* "propagationConstraint" : {
* "add": "propagate"
* },
* "target": {
* "": "StateFacet",
* "@class": "StateFacet",
* "value": "down"
* }
* },
* {
* "": "IsIdentifiedBy",
* "@class": "IsIdentifiedBy",
* "target": {
* "": "SoftwareFacet",
* "@class": "SoftwareFacet",
* "name": "data-transfer-service",
* "group": "DataTransfer"
* }
* },
* {
* "": "ConsistsOf",
* "@class": "ConsistsOf",
* "target": {
* "": "AccessPointFacet",
* "@class": "AccessPointFacet",
* "endpoint": "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
* }
* }
@ -399,11 +297,10 @@ public class Access extends BaseRest {
@Path(AccessPath.QUERY_PATH_PART)
public String jsonQuery(String jsonQuery) throws InvalidQueryException, ResourceRegistryException {
logger.info("Requested json query \n{}", jsonQuery);
setAccountingMethod(Method.QUERY, JSON_QUERY_METHOD);
InnerMethodName.instance.set("jsonQuery");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
checkHierarchicalMode();
checkIncludeInstancesContexts();
JsonQuery jsonQueryManager = new JsonQuery();
jsonQueryManager.setJsonQuery(jsonQuery);
@ -426,12 +323,12 @@ public class Access extends BaseRest {
* All the Resources with a ContactFacet :
* /access/query/Resource/ConsistsOf/ContactFacet?_polymorphic=true&_direction=out
*
* All the EService having an incoming (IN) Hosts relation with an HostingNode (i.e. all smartgears services)
* All the Eservice having an incoming (IN) Hosts relation with an HostingNode (i.e. all smartgears services)
* GET /access/query/EService/Hosts/HostingNode?_polymorphic=true&_direction=in
*
* All the EService having an incoming (IN) Hosts relation (i.e. hosted by) the HostingNode with UUID
* All the Eservice having an incoming (IN) Hosts relation (i.e. hosted by) the HostingNode with UUID
* 16032d09-3823-444e-a1ff-a67de4f350a
* * GET /access/query/EService/Hosts/HostingNode?_reference=16032d09-3823-444e-a1ff-a67de4f350a8&_polymorphic=true&_direction=in
* * GET /access/query/EService/hosts/HostingNode?_reference=16032d09-3823-444e-a1ff-a67de4f350a8&_polymorphic=true&_direction=in
*
*/
@SuppressWarnings({"rawtypes"})
@ -451,11 +348,10 @@ public class Access extends BaseRest {
logger.info("Requested {} instances having a(n) {} ({}={}} with {} ({}={}). Request URI is {})", resourcetype, relationType,
AccessPath._DIRECTION_QUERY_PARAMETER, direction, referenceType, AccessPath._POLYMORPHIC_QUERY_PARAMETER, polymorphic, uriInfo.getRequestUri());
setAccountingMethod(Method.QUERY, PREPARED_QUERY_METHOD);
InnerMethodName.instance.set("query");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
checkHierarchicalMode();
checkIncludeInstancesContexts();
ElementManagement erManagement = ElementManagementUtility.getERManagement(resourcetype);

View File

@ -1,11 +1,12 @@
package org.gcube.informationsystem.resourceregistry.rest;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -16,39 +17,56 @@ public class BaseRest {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public BaseRest() {
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
}
@Context
protected UriInfo uriInfo;
public BaseRest() {
protected boolean isRequesterAllowedToPerformHierarchicalRequests() {
// TODO check is the user has the role to query in hierarchic mode
return true;
}
protected void setAccountingMethod(String method) {
CalledMethodProvider.instance.set(method);
protected void checkHierarchicalMode() {
try {
List<String> hierarchicalQueryParameterList = uriInfo.getQueryParameters().get(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
if(hierarchicalQueryParameterList!=null && hierarchicalQueryParameterList.size()>0) {
String hierarchicalBooleanString = hierarchicalQueryParameterList.get(0);
boolean hierarchical = Boolean.valueOf(hierarchicalBooleanString);
boolean h = hierarchical && isRequesterAllowedToPerformHierarchicalRequests();
if(h) {
logger.info("The request was performed in hierarchical mode and the requester is allowed. Going to set hierarchical mode.");
ContextUtility.getHierarchicalMode().set(h);
}
}
}catch (Throwable t) {
logger.warn("Unable to properly set the Hierarchical Mode is set", t.getMessage());
}
}
protected void setAccountingMethod(Method method, String type) {
StringBuffer accountingMethod = new StringBuffer();
accountingMethod.append(method.getPrefix());
accountingMethod.append(type);
accountingMethod.append(method.getSuffix());
setAccountingMethod(accountingMethod.toString());
protected boolean isRequesterAllowedToRequestInstancesContexts() {
// TODO check is the user has the role to query in get instance Contexts
return true;
}
private ServerRequestInfo initRequestInfo(ServerRequestInfo requestInfo) {
requestInfo.setUriInfo(uriInfo);
RequestUtility.getRequestInfo().set(requestInfo);
return requestInfo;
protected void checkIncludeInstancesContexts() {
try {
List<String> includeContextsQueryParameterList = uriInfo.getQueryParameters().get(InstancePath.INCLUDE_CONTEXTS_IN_HEADER_QUERY_PARAMETER);
if(includeContextsQueryParameterList!=null && includeContextsQueryParameterList.size()>0) {
String includeContextsBooleanString = includeContextsQueryParameterList.get(0);
boolean includeContexts = Boolean.valueOf(includeContextsBooleanString);
boolean i = includeContexts && isRequesterAllowedToRequestInstancesContexts();
if(i) {
logger.info("The requet to include the contexts in header is allowed.");
ContextUtility.getIncludeInstanceContexts().set(true);
}
protected ServerRequestInfo initRequestInfo(int offset, int limit) {
ServerRequestInfo requestInfo = new ServerRequestInfo(offset, limit);
return initRequestInfo(requestInfo);
}
protected ServerRequestInfo initRequestInfo() {
ServerRequestInfo requestInfo = new ServerRequestInfo();
return initRequestInfo(requestInfo);
}catch (Throwable t) {
logger.warn("Unable to properly set the Hierarchical Mode is set", t.getMessage());
}
}
}

View File

@ -13,27 +13,33 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Path(ContextPath.CONTEXTS_PATH_PART)
public class ContextManager extends BaseRest {
public class ContextManager {
public static final String CONTEXT_UUID_PATH_PARAMETER = "CONTEXT_UUID";
/**
* Logger
*/
private static Logger logger = LoggerFactory.getLogger(ContextManager.class);
public ContextManager() {
super();
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
}
/*
@ -45,12 +51,7 @@ public class ContextManager extends BaseRest {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String all() throws ContextNotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", Context.NAME);
setAccountingMethod(Method.LIST, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
InnerMethodName.instance.set("listContexts");
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
@ -71,11 +72,7 @@ public class ContextManager extends BaseRest {
uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString();
}
logger.info("Requested to read {} with id {} ", Context.NAME, uuid);
setAccountingMethod(Method.READ, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("readContext");
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
@ -96,11 +93,7 @@ public class ContextManager extends BaseRest {
public String updateCreate(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid, String json)
throws ResourceRegistryException {
logger.info("Requested to update/create {} with json {} ", Context.NAME, json);
setAccountingMethod(Method.UPDATE, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("updateContext");
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
@ -118,7 +111,7 @@ public class ContextManager extends BaseRest {
public Response delete(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid)
throws ContextNotFoundException, ResourceRegistryException {
logger.info("Requested to delete {} with id {} ", Context.NAME, uuid);
CalledMethodProvider.instance.set("deleteContext");
InnerMethodName.instance.set("deleteContext");
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));

View File

@ -26,7 +26,7 @@ import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.smartgears.utils.InnerMethodName;
/**
* @author Luca Frosini (ISTI - CNR)
@ -36,9 +36,6 @@ public class InstancesManager extends BaseRest {
public static final String UUID_PATH_PARAMETER = "UUID";
public static final String INSTANCE = "Instance";
public static final String GET_INSTANCE_CONTEXTS_METHOD = "getInstanceContexts";
public InstancesManager() {
super();
}
@ -56,11 +53,10 @@ public class InstancesManager extends BaseRest {
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
InnerMethodName.instance.set("listInstances");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
checkHierarchicalMode();
checkIncludeInstancesContexts();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
@ -78,10 +74,10 @@ public class InstancesManager extends BaseRest {
public Response exists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to check if {} with id {} exists", type, uuid);
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
InnerMethodName.instance.set("existInstance");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
checkHierarchicalMode();
checkIncludeInstancesContexts();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
@ -116,10 +112,10 @@ public class InstancesManager extends BaseRest {
public String read(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read {} with id {}", type, uuid);
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
InnerMethodName.instance.set("readInstance");
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
checkHierarchicalMode();
checkIncludeInstancesContexts();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
erManagement.setElementType(type);
@ -142,10 +138,7 @@ public class InstancesManager extends BaseRest {
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid, String json) throws ResourceRegistryException {
logger.info("Requested to update/create {} with id {}", type, uuid);
logger.trace("Requested to update/create {} with id {} with json {}", type, uuid, json);
setAccountingMethod(Method.UPDATE, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllIncludeQueryParameters();
InnerMethodName.instance.set("updateInstance");
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
@ -165,7 +158,7 @@ public class InstancesManager extends BaseRest {
public Response delete(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws ResourceRegistryException {
logger.info("Requested to delete {} with id {}", type, uuid);
setAccountingMethod(Method.DELETE, InstancesManager.INSTANCE);
InnerMethodName.instance.set("deleteInstance");
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(uuid));
@ -192,7 +185,7 @@ public class InstancesManager extends BaseRest {
@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String contextId)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
setAccountingMethod(InstancesManager.GET_INSTANCE_CONTEXTS_METHOD);
InnerMethodName.instance.set("getInstanceContexts");
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);

View File

@ -1,33 +0,0 @@
package org.gcube.informationsystem.resourceregistry.rest;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public enum Method {
LIST("list","s"),
CREATE("create",""),
EXIST("exist",""),
READ("read",""),
UPDATE("update",""),
RUN("run",""),
DELETE("delete",""),
QUERY("","Query");
protected final String prefix;
protected final String suffix;
Method(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
}

View File

@ -17,23 +17,22 @@ import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath;
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART)
public class QueryTemplateManager extends BaseRest {
public class QueryTemplateManager {
private static Logger logger = LoggerFactory.getLogger(QueryTemplateManager.class);
public static final String QUERY_TEMPLATE_NAME_PATH_PARAMETER = "QUERY_TEMPLATE_NAME";
public QueryTemplateManager() {
super();
}
/**
** GET /query-templates
*/
@ -42,12 +41,7 @@ public class QueryTemplateManager extends BaseRest {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String all() throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", QueryTemplate.NAME);
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
InnerMethodName.instance.set("listQueryTemplates");
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
@ -64,11 +58,11 @@ public class QueryTemplateManager extends BaseRest {
* "description" : "The following query return all the EService having the state provided as parameters, e.g. down, ready.
* The content of the request to run this query template will be something like {\"$state\": "ready"}",
* "template": {
* "type": "EService",
* "@class": "EService",
* "consistsOf": [{
* "type": "ConsistsOf",
* "@class": "ConsistsOf",
* "target": {
* "type": "StateFacet",
* "@class": "StateFacet",
* "value": "$state"
* }
* }]
@ -87,19 +81,17 @@ public class QueryTemplateManager extends BaseRest {
@Path("{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String updateCreate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String json)
public Response updateCreate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String json)
throws InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} creation with name {} and content {}", QueryTemplate.NAME, queryTemplateName, json);
setAccountingMethod(Method.UPDATE, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("createQueryTemplate");
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
queryTemplateManagement.setJson(json);
return queryTemplateManagement.createOrUpdate();
String ret = queryTemplateManagement.createOrUpdate();
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build();
}
/*
@ -112,11 +104,7 @@ public class QueryTemplateManager extends BaseRest {
public String read(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.READ, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("readQueryTemplate");
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -126,7 +114,7 @@ public class QueryTemplateManager extends BaseRest {
/*
* POST /query-templates/{QUERY_TEMPLATE_NAME}
* e.g. POST /query-templates/GetAllEServiceWithState
* e.g. GET /query-templates/GetAllEServiceWithState
*
* params = { "$state" : "ready" }
*
@ -137,10 +125,7 @@ public class QueryTemplateManager extends BaseRest {
public String run(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
InnerMethodName.instance.set("readQueryTemplate");
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -159,7 +144,7 @@ public class QueryTemplateManager extends BaseRest {
public Response delete(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested to delete {} with name {} ", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.DELETE, QueryTemplate.NAME);
InnerMethodName.instance.set("deleteQueryTemplate");
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);

View File

@ -9,14 +9,6 @@ import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.GCubeSecret;
import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -32,33 +24,12 @@ public class RequestFilter implements ContainerRequestFilter, ContainerResponseF
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
logger.trace("PreMatching RequestFilter");
SecretManagerProvider.instance.remove();
SecretManager secretManager = new SecretManager();
String token = AccessTokenProvider.instance.get();
if(token!=null) {
Secret secret = new JWTSecret(token);
secretManager.addSecret(secret);
}
token = SecurityTokenProvider.instance.get();
if(token!=null) {
Secret secret = new GCubeSecret(token);
secretManager.addSecret(secret);
}
SecretManagerProvider.instance.set(secretManager);
RequestUtility.getRequestInfo().remove();
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
logger.trace("ResponseFilter");
SecretManagerProvider.instance.remove();
RequestUtility.getRequestInfo().remove();
}
}

View File

@ -15,7 +15,10 @@ import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
@ -23,21 +26,25 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.reso
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath;
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath.SharingOperation;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Path(SharingPath.SHARING_PATH_PART)
public class SharingManager extends BaseRest {
public class SharingManager {
private static Logger logger = LoggerFactory.getLogger(SharingManager.class);
public SharingManager() {
super();
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
}
protected String serializeAffectedInstaces(ObjectMapper objectMapper, Map<UUID,JsonNode> affectedInstances) throws ResourceRegistryException {
@ -58,9 +65,9 @@ public class SharingManager extends BaseRest {
* The the body is the following
*
* [
* {"type" : "HostingNode", "id" : "16032d09-3823-444e-a1ff-a67de4f350a8" },
* {"type" : "Hosts", "id" : "97ab8a6b-6b1b-4868-b8fc-ba48d0439ba9"},
* {"type" : "EService", "id" : "d3b1a29b-aa70-4a5a-be83-361a4209dd3e"}
* {"@class" : "HostingNode", header : { "uuid" : "16032d09-3823-444e-a1ff-a67de4f350a8"}},
* {"@class" : "Hosts", header : { "uuid" : "97ab8a6b-6b1b-4868-b8fc-ba48d0439ba9"}},
* {"@class" : "EService", header : { "uuid" : "d3b1a29b-aa70-4a5a-be83-361a4209dd3e"}}
* ]
*
*
@ -88,9 +95,6 @@ public class SharingManager extends BaseRest {
String body)
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllIncludeQueryParameters();
try {
StringBuffer calledMethod = new StringBuffer();
if(dryRun==null) {
@ -109,7 +113,7 @@ public class SharingManager extends BaseRest {
calledMethod.append("RemoveFromContext");
}
calledMethod.append("NoPropagationConstraint");
setAccountingMethod(calledMethod.toString());
InnerMethodName.instance.set(calledMethod.toString());
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(body);
@ -118,8 +122,9 @@ public class SharingManager extends BaseRest {
for(JsonNode node : arrayNode) {
@SuppressWarnings("unused")
String type = TypeUtility.getTypeName(node);
UUID uuid = UUIDUtility.getUUID(node);
String type = node.get(Element.CLASS_PROPERTY).asText();
String instanceId = node.get(IdentifiableElement.HEADER_PROPERTY).get(Header.UUID_PROPERTY).asText();
UUID uuid = UUID.fromString(instanceId);
expectedInstances.put(uuid, node);
}
@ -170,9 +175,6 @@ public class SharingManager extends BaseRest {
@QueryParam(SharingPath.FORCE_ADD_TO_CONTEXT_QUERY_PARAMETER) @DefaultValue("false") Boolean forceAddToContext)
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllIncludeQueryParameters();
StringBuffer calledMethod = new StringBuffer();
if(dryRun==null) {
dryRun = false;
@ -189,7 +191,7 @@ public class SharingManager extends BaseRest {
logger.info("Requested {} {} with UUID {} from {} with UUID {}", dryRun? "a dry run for removing": "to remove", type, instanceId, Context.NAME, contextId);
calledMethod.append("RemoveFromContext");
}
setAccountingMethod(calledMethod.toString());
InnerMethodName.instance.set(calledMethod.toString());
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);

View File

@ -19,21 +19,27 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.TypePath;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Path(TypePath.TYPES_PATH_PART)
public class TypeManager extends BaseRest {
public class TypeManager {
private static Logger logger = LoggerFactory.getLogger(TypeManager.class);
public static final String TYPE_PATH_PARAMETER = "TYPE_NAME";
public TypeManager() {
super();
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
}
/*
@ -50,11 +56,7 @@ public class TypeManager extends BaseRest {
public Response create(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String typeName, String json)
throws SchemaException, ResourceRegistryException {
logger.info("Requested {} creation with schema {}", typeName, json);
setAccountingMethod(Method.CREATE, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("createType");
TypeManagement schemaManagement = new TypeManagement();
schemaManagement.setTypeName(typeName);
@ -76,11 +78,7 @@ public class TypeManager extends BaseRest {
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
throws SchemaNotFoundException, ResourceRegistryException {
logger.info("Requested Schema for type {}", type);
setAccountingMethod(Method.READ, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
InnerMethodName.instance.set("readType");
TypeManagement schemaManagement = new TypeManagement();
schemaManagement.setTypeName(type);

View File

@ -38,10 +38,10 @@ public class CachedType<T extends Type> {
static {
superClassesToBeExcluded = AccessType.names();
AccessType[] modelTypes = AccessType.getModelTypes();
for(AccessType accessType : modelTypes) {
superClassesToBeExcluded.remove(accessType.getName());
}
superClassesToBeExcluded.remove(AccessType.RESOURCE.getName());
superClassesToBeExcluded.remove(AccessType.FACET.getName());
superClassesToBeExcluded.remove(AccessType.CONSISTS_OF.getName());
superClassesToBeExcluded.remove(AccessType.IS_RELATED_TO.getName());
}
protected final String typeName;

View File

@ -115,10 +115,6 @@ public class TypeManagement {
return oSchema.getClass(typeName);
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
@ -129,10 +125,45 @@ public class TypeManagement {
this.json = TypeMapper.serializeTypeDefinition(type);
}
public Type getType() {
return type;
/*
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);
if(oClass.isSubClassOf(Property.NAME)) {
node.put(ISManageable.CLASS_PROPERTY, PropertyTypeDefinition.NAME);
} else if(oClass.isSubClassOf(Resource.NAME)) {
node.put(ISManageable.CLASS_PROPERTY, ResourceTypeDefinition.NAME);
} else if(oClass.isSubClassOf(Facet.NAME)) {
node.put(ISManageable.CLASS_PROPERTY, FacetTypeDefinition.NAME);
} else if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
node.put(ISManageable.CLASS_PROPERTY, IsRelatedToTypeDefinition.NAME);
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
node.put(ISManageable.CLASS_PROPERTY, ConsistsOfTypeDefinition.NAME);
}
if(!oClass.isSubClassOf(Resource.NAME)) {
ArrayNode arrayNode = (ArrayNode) node.get(EntityTypeDefinition.PROPERTIES_PROPERTY);
Iterator<JsonNode> iterator = arrayNode.iterator();
while(iterator.hasNext()) {
ObjectNode propertyNode = (ObjectNode) iterator.next();
propertyNode.put(ISManageable.CLASS_PROPERTY, PropertyDefinition.NAME);
}
}
String managedJson = mapper.writeValueAsString(node);
logger.trace("{} -> {}", json, managedJson);
return TypeBinder.deserializeTypeDefinition(managedJson);
} catch(Exception e) {
throw new SchemaException(e);
}
}
*/
private static ElementManagement<?,?> getTypeManagement(AccessType accessType, String name) {
ElementManagement<? extends OElement,?> erManagement = null;
@ -215,6 +246,27 @@ public class TypeManagement {
}
}
/*
private String getTypeAsString(AccessType accessType, String name) throws SchemaException {
try {
ElementManagement<? extends OElement> erManagement = getTypeManagement(accessType, name);
return getTypeAsString(erManagement);
} catch(Exception e) {
throw new SchemaException(e);
}
}
/*
private Type getType(AccessType accessType, String name) throws SchemaException {
try {
String typeString = getTypeAsString(accessType, name);
return TypeMapper.deserializeTypeDefinition(typeString);
} catch(Exception e) {
throw new SchemaException(e);
}
}
*/
private Type getType(OClass oClass) throws SchemaException {
try {
String typeString = getTypeAsString(oClass);
@ -227,7 +279,7 @@ public class TypeManagement {
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
Type type, String baseType) throws SchemaException, SchemaNotFoundException {
Set<String> superClasses = type.getExtendedTypes();
Set<String> superClasses = type.getSuperClasses();
if(baseType != null) {
if(superClasses == null || superClasses.size() == 0) {
throw new RuntimeException(
@ -442,8 +494,8 @@ public class TypeManagement {
private boolean superClassesMatch(Type actualTypeDefinition, Type newTypeDefinition) {
// Checking superclasses. Must be the same. If differs the operation will be aborted.
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getExtendedTypes());
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getSuperClasses());
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getSuperClasses());
if(actualSuperClasses.size()!=newSuperClasses.size()) {
return false;
@ -454,7 +506,7 @@ public class TypeManagement {
return false;
}
actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
actualSuperClasses = new HashSet<>(actualTypeDefinition.getSuperClasses());
newSuperClasses.removeAll(actualSuperClasses);
if(newSuperClasses.size()>0) {
return false;
@ -463,6 +515,7 @@ public class TypeManagement {
return true;
}
// TODO
protected void updateTypeSchema(Type actualTypeDefinition, Type newTypeDefinition, AccessType baseElementAccessType)
throws SchemaNotFoundException, SchemaException {
@ -482,10 +535,10 @@ public class TypeManagement {
if(!superClassesMatch(actualTypeDefinition, newTypeDefinition)){
StringBuffer error = new StringBuffer();
error.append("The new type definition has a different set of supertypes. Actual version supertypes are: ");
error.append(actualTypeDefinition.getExtendedTypes());
error.append(". New version supertypes are: ");
error.append(newTypeDefinition.getExtendedTypes());
error.append("The new type definition has a different set of superclasses. Actual version superclasses are: ");
error.append(actualTypeDefinition.getSuperClasses());
error.append(". New version superclasses are: ");
error.append(newTypeDefinition.getSuperClasses());
error.append(". This kind update is not supported for a type.");
throw new SchemaException(error.toString());
}
@ -512,6 +565,9 @@ public class TypeManagement {
newTypeDefinition.getName());
}
if(!(newTypeDefinition instanceof ResourceType)) {
// A Resource cannot contains any properties.
@ -533,9 +589,7 @@ public class TypeManagement {
String propertyName = newPropertyDefinition.getName();
if(propertyName.compareTo(IdentifiableElement.ID_PROPERTY)==0 ||
propertyName.compareTo(IdentifiableElement.METADATA_PROPERTY)==0 ||
propertyName.compareTo(Relation.PROPAGATION_CONSTRAINT_PROPERTY)==0) {
if(propertyName.compareTo(IdentifiableElement.HEADER_PROPERTY)==0 || propertyName.compareTo(Relation.PROPAGATION_CONSTRAINT_PROPERTY)==0) {
continue;
}

View File

@ -17,7 +17,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecuri
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.slf4j.Logger;
@ -39,7 +39,6 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
protected EntityTypeDefinitionManagement(Class<E> clz) {
super(AccessType.ENTITY_TYPE);
this.typeName = TypeMapper.getType(clz);
this.forceIncludeAllMeta = true;
}
@Override
@ -140,7 +139,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
OResult oResult = resultSet.next();
OVertex element = (OVertex) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), Utility.toJsonString(element, true));
if (resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -169,7 +168,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", OVertex.class.getSimpleName(), OrientDBUtility.getAsStringForLogging(element));
logger.debug("Created {} is {}", OVertex.class.getSimpleName(), Utility.toJsonString(element, true));
return element;
} catch (ResourceRegistryException e) {

View File

@ -16,7 +16,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecuri
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.slf4j.Logger;
@ -146,7 +146,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
OResult oResult = resultSet.next();
OElement element = (OElement) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), Utility.toJsonString(element, true));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -169,7 +169,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", PropertyType.NAME, OrientDBUtility.getAsStringForLogging(element));
logger.debug("Created {} is {}", PropertyType.NAME, Utility.toJsonString(element, true));
return element;
} catch(ResourceRegistryException e) {

View File

@ -21,7 +21,7 @@ import org.gcube.informationsystem.resourceregistry.instances.base.ElementManage
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.types.entities.EntityTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
@ -43,7 +43,6 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
public RelationTypeDefinitionManagement(Class<TT> clz) {
super(AccessType.RELATION_TYPE, ResourceType.class, clz);
this.typeName = RelationType.NAME;
this.forceIncludeAllMeta = true;
}
public RelationTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument,
@ -177,7 +176,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
OResult oResult = resultSet.next();
OEdge element = (OEdge) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), Utility.toJsonString(element, true));
if (resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()

View File

@ -1,36 +1,25 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class EncryptedOrient extends ODocument implements Encrypted {
public static final String NAME = "Encrypted";
public static final String VALUE = "value";
public class EncryptedOrient extends ODocument implements org.gcube.informationsystem.model.reference.properties.Encrypted {
protected String decryptedValue;
protected String dbEncryptedValue;
protected String contextEncryptedValue;
public EncryptedOrient() {
super(EncryptedOrient.NAME);
super(Encrypted.NAME);
}
protected EncryptedOrient(String iClassName) {
@ -38,37 +27,21 @@ public class EncryptedOrient extends ODocument implements Encrypted {
}
@Override
public String getTypeName() {
return TypeUtility.getTypeName(this.getClass());
}
@Override
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {
List<String> list = new ArrayList<>();
list.add(TypeUtility.getTypeName(Property.class));
return list;
}
}
@Override
public String getExpectedtype() {
return null;
}
public String getEncryptedValue() {
return this.field(EncryptedOrient.VALUE);
return this.field(Encrypted.VALUE);
}
@Override
public void setEncryptedValue(String encryptedValue) {
this.field(EncryptedOrient.VALUE, encryptedValue);
this.field(Encrypted.VALUE, encryptedValue);
}
@Override
public String toJSON(String iFormat) {
return super.toJSON(iFormat);
}
public String getDecryptedValue() {
return decryptedValue;
}
@ -86,10 +59,10 @@ public class EncryptedOrient extends ODocument implements Encrypted {
// Encrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey();
this.dbEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue, databaseKey);
this.dbEncryptedValue = EncryptedImpl.encrypt(decryptedValue, databaseKey);
// Encrypting with Context Key (default key)
this.contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue);
this.contextEncryptedValue = EncryptedImpl.encrypt(decryptedValue);
if(setEncryptedForContext) {
@ -102,39 +75,25 @@ public class EncryptedOrient extends ODocument implements Encrypted {
@Override
public Map<String, Object> getAdditionalProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
// TODO Auto-generated method stub
}
@Override
public Object getAdditionalProperty(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAdditionalProperty(String key, Object value) {
// TODO Auto-generated method stub
}
@Override
public String getValue() {
return getEncryptedValue();
}
@Override
public void setValue(String value) {
setEncryptedValue(value);
}
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret);
return ret;
}
}

View File

@ -0,0 +1,92 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.gcube.informationsystem.model.reference.properties.Header;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class HeaderOrient extends ODocument implements Header {
public HeaderOrient() {
super(Header.NAME);
}
protected HeaderOrient(String iClassName) {
super(iClassName);
}
@Override
public UUID getUUID() {
return UUID.fromString((String) this.field(Header.UUID_PROPERTY));
}
@Override
public void setUUID(UUID uuid) {
this.field(Header.UUID_PROPERTY, uuid.toString());
}
@Override
public String getCreatedBy() {
return this.field(Header.CREATED_BY_PROPERTY);
}
public void setCreatedBy(String createdBy) {
this.field(Header.CREATED_BY_PROPERTY, createdBy);
}
@Override
public Date getCreationTime() {
return this.field(Header.CREATION_TIME_PROPERTY);
}
public void setCreationTime(Date creationTime) {
this.field(Header.CREATION_TIME_PROPERTY, creationTime);
}
@Override
public String getLastUpdateBy() {
return this.field(Header.LAST_UPDATE_BY_PROPERTY);
}
public void setLastUpdateBy(String lastUpdateBy) {
this.field(Header.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
}
@Override
public Date getLastUpdateTime() {
return this.field(Header.LAST_UPDATE_TIME_PROPERTY);
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
}
@Override
public Map<String, Object> getAdditionalProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
// TODO Auto-generated method stub
}
@Override
public Object getAdditionalProperty(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAdditionalProperty(String key, Object value) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,137 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonParseException;
import org.gcube.com.fasterxml.jackson.databind.JsonMappingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.informationsystem.utils.UUIDManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class HeaderUtility {
private static final Logger logger = LoggerFactory.getLogger(HeaderUtility.class);
public static String getUser() {
String user = Header.UNKNOWN_USER;
try {
user = SecretManagerProvider.instance.get().getOwner().getId();
} catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user);
}
return user;
}
public static Header createHeader(UUID uuid) {
HeaderOrient header = new HeaderOrient();
if(uuid == null) {
uuid = UUIDManager.generateValidRandomUUID();
}
header.setUUID(uuid);
String creator = getUser();
header.setCreatedBy(creator);
header.setLastUpdateBy(creator);
Date date = Calendar.getInstance().getTime();
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
logger.trace("Setting Last Update and Creation Time to " + ft.format(date));
header.setCreationTime(date);
header.setLastUpdateTime(date);
return header;
}
public static Header getHeader(JsonNode jsonNode, boolean creation)
throws JsonParseException, JsonMappingException, IOException, ResourceRegistryException {
if(jsonNode.has(IdentifiableElement.HEADER_PROPERTY)) {
JsonNode headerNode = jsonNode.get(IdentifiableElement.HEADER_PROPERTY);
if(headerNode.isNull()) {
return null;
}
HeaderOrient header = null;
if(creation) {
// If an header is provided, it MUST contains an UUID otherwise is
// an invalid request so that let that an exception is raised
UUID uuid = UUID.fromString(headerNode.get(Header.UUID_PROPERTY).asText());
if(UUIDManager.isReservedUUID(uuid)) {
throw new ResourceRegistryException("The provided UUID " + uuid.toString() + "is reserved. The reserved UUID are : " + UUIDManager.getAllReservedUUIDAsStrings());
}
header = (HeaderOrient) createHeader(uuid);
} else {
header = new HeaderOrient();
header.fromJSON(headerNode.toString());
}
return header;
}
return null;
}
public static HeaderOrient getHeaderOrient(ODocument oDocument) throws ResourceRegistryException {
if(oDocument instanceof HeaderOrient) {
return (HeaderOrient) oDocument;
} else {
try {
HeaderOrient headerOrient = new HeaderOrient();
String json = oDocument.toJSON();
Header header = ElementMapper.unmarshal(Header.class, json);
headerOrient.setUUID(header.getUUID());
headerOrient.setCreatedBy(header.getCreatedBy());
headerOrient.setCreationTime(header.getCreationTime());
headerOrient.setLastUpdateBy(header.getLastUpdateBy());
headerOrient.setLastUpdateTime(header.getLastUpdateTime());
return headerOrient;
} catch(Exception e) {
throw new ResourceRegistryException(
"Unable to recreate Header. " + Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
}
public static Header addHeader(OElement element, UUID uuid) {
Header header = createHeader(uuid);
element.setProperty(IdentifiableElement.HEADER_PROPERTY, header);
return header;
}
/*
public static Header addHeader(Edge edge, UUID uuid) {
Header header = createHeader(uuid);
edge.setProperty(IdentifiableElement.HEADER_PROPERTY, header);
return header;
}
*/
public static Header getHeader(OElement element) throws ResourceRegistryException {
return Utility.getPropertyDocument(Header.class, element, IdentifiableElement.HEADER_PROPERTY);
}
public static void updateModifiedByAndLastUpdate(OElement element) throws ResourceRegistryException {
ODocument oDocument = element.getProperty(IdentifiableElement.HEADER_PROPERTY);
String lastUpdateBy = getUser();
oDocument.field(Header.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
Date lastUpdateTime = Calendar.getInstance().getTime();
oDocument.field(Header.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
element.setProperty(IdentifiableElement.HEADER_PROPERTY, oDocument);
}
}

View File

@ -1,118 +0,0 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class MetadataOrient extends ODocument implements Metadata {
public MetadataOrient() {
super(Metadata.NAME);
}
protected MetadataOrient(String iClassName) {
super(iClassName);
}
@Override
public String getTypeName() {
return TypeUtility.getTypeName(this.getClass());
}
@Override
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {
List<String> list = new ArrayList<>();
list.add(TypeUtility.getTypeName(Property.class));
return list;
}
}
@Override
public String getExpectedtype() {
return null;
}
@Override
public String getCreatedBy() {
return this.field(Metadata.CREATED_BY_PROPERTY);
}
public void setCreatedBy(String createdBy) {
this.field(Metadata.CREATED_BY_PROPERTY, createdBy);
}
@Override
public Date getCreationTime() {
return this.field(Metadata.CREATION_TIME_PROPERTY);
}
public void setCreationTime(Date creationTime) {
this.field(Metadata.CREATION_TIME_PROPERTY, creationTime);
}
@Override
public String getLastUpdateBy() {
return this.field(Metadata.LAST_UPDATE_BY_PROPERTY);
}
public void setLastUpdateBy(String lastUpdateBy) {
this.field(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
}
@Override
public Date getLastUpdateTime() {
return this.field(Metadata.LAST_UPDATE_TIME_PROPERTY);
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.field(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
}
@Override
public Map<String, Object> getAdditionalProperties() {
return null;
}
@Override
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
}
@Override
public Object getAdditionalProperty(String key) {
return null;
}
@Override
public void setAdditionalProperty(String key, Object value) {
}
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret);
return ret;
}
}

View File

@ -1,113 +0,0 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.gcube.com.fasterxml.jackson.core.JsonParseException;
import org.gcube.com.fasterxml.jackson.databind.JsonMappingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class MetadataUtility {
private static final Logger logger = LoggerFactory.getLogger(MetadataUtility.class);
public static String getUser() {
String user = Metadata.UNKNOWN_USER;
try {
user = SecretManagerProvider.instance.get().getUser().getUsername();
} catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user);
}
return user;
}
public static Metadata createMetadata() {
MetadataOrient metadata = new MetadataOrient();
String creator = getUser();
metadata.setCreatedBy(creator);
metadata.setLastUpdateBy(creator);
Date date = Calendar.getInstance().getTime();
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
logger.trace("Setting Last Update and Creation Time to " + ft.format(date));
metadata.setCreationTime(date);
metadata.setLastUpdateTime(date);
return metadata;
}
public static Metadata getMetadata(JsonNode jsonNode)
throws JsonParseException, JsonMappingException, IOException, ResourceRegistryException {
if(jsonNode.has(IdentifiableElement.METADATA_PROPERTY)) {
ObjectNode metadataNode = jsonNode.get(IdentifiableElement.METADATA_PROPERTY).deepCopy();
if(metadataNode.isNull()) {
return null;
}
MetadataOrient metadata = new MetadataOrient();
metadataNode.set(OrientDBUtility.ORIENTDB_CLASS_PROPERTY, metadataNode.get(Element.TYPE_PROPERTY));
metadataNode.remove(Element.TYPE_PROPERTY);
metadata.fromJSON(metadataNode.toString());
return metadata;
}
return null;
}
public static MetadataOrient getMetadataOrient(ODocument oDocument) throws ResourceRegistryException {
if(oDocument instanceof MetadataOrient) {
return (MetadataOrient) oDocument;
} else {
try {
MetadataOrient metadataOrient = new MetadataOrient();
String json = OrientDBUtility.toJsonString(oDocument);
Metadata metadata = ElementMapper.unmarshal(Metadata.class, json);
metadataOrient.setCreatedBy(metadata.getCreatedBy());
metadataOrient.setCreationTime(metadata.getCreationTime());
metadataOrient.setLastUpdateBy(metadata.getLastUpdateBy());
metadataOrient.setLastUpdateTime(metadata.getLastUpdateTime());
return metadataOrient;
} catch(Exception e) {
throw new ResourceRegistryException(
"Unable to recreate Metadata. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
}
public static Metadata addMetadata(OElement element) {
Metadata metadata = createMetadata();
element.setProperty(IdentifiableElement.METADATA_PROPERTY, metadata);
return metadata;
}
public static Metadata getMetadata(OElement element) throws ResourceRegistryException {
return OrientDBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY);
}
public static void updateModifiedByAndLastUpdate(OElement element) throws ResourceRegistryException {
ODocument oDocument = element.getProperty(IdentifiableElement.METADATA_PROPERTY);
String lastUpdateBy = getUser();
oDocument.field(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
Date lastUpdateTime = Calendar.getInstance().getTime();
oDocument.field(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
element.setProperty(IdentifiableElement.METADATA_PROPERTY, oDocument);
}
}

View File

@ -1,23 +1,15 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class PropagationConstraintOrient extends ODocument implements PropagationConstraint {
public class PropagationConstraintOrient extends ODocument implements org.gcube.informationsystem.model.reference.properties.PropagationConstraint {
public PropagationConstraintOrient() {
super(PropagationConstraint.NAME);
@ -28,27 +20,13 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio
}
@Override
public String getTypeName() {
return TypeUtility.getTypeName(this.getClass());
public RemoveConstraint getRemoveConstraint() {
return RemoveConstraint.valueOf((String) this.field(PropagationConstraint.REMOVE_PROPERTY));
}
@Override
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {
List<String> list = new ArrayList<>();
list.add(TypeUtility.getTypeName(Property.class));
return list;
}
}
@Override
public String getExpectedtype() {
return null;
public void setRemoveConstraint(RemoveConstraint removeConstraint) {
this.field(PropagationConstraint.REMOVE_PROPERTY, removeConstraint.name());
}
@Override
@ -61,26 +39,6 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio
this.field(PropagationConstraint.ADD_PROPERTY, addConstraint.name());
}
@Override
public DeleteConstraint getDeleteConstraint() {
return DeleteConstraint.valueOf((String) this.field(PropagationConstraint.DELETE_PROPERTY));
}
@Override
public void setDeleteConstraint(DeleteConstraint deleteConstraint) {
this.field(PropagationConstraint.DELETE_PROPERTY, deleteConstraint.name());
}
@Override
public RemoveConstraint getRemoveConstraint() {
return RemoveConstraint.valueOf((String) this.field(PropagationConstraint.REMOVE_PROPERTY));
}
@Override
public void setRemoveConstraint(RemoveConstraint removeConstraint) {
this.field(PropagationConstraint.REMOVE_PROPERTY, removeConstraint.name());
}
@Override
public Map<String, Object> getAdditionalProperties() {
return null;
@ -101,11 +59,4 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio
}
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret);
return ret;
}
}

View File

@ -1,21 +0,0 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.UUID;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import com.orientechnologies.orient.core.record.OElement;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class UUIDUtility extends org.gcube.informationsystem.utils.UUIDUtility {
public static UUID getUUID(OElement element) throws ResourceRegistryException {
String uuidString = element.getProperty(IdentifiableElement.ID_PROPERTY);
UUID uuid = UUID.fromString(uuidString);
return uuid;
}
}

View File

@ -5,11 +5,10 @@ import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
@ -17,7 +16,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -27,64 +26,43 @@ import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class OrientDBUtility {
public class Utility {
private static final Logger logger = LoggerFactory.getLogger(OrientDBUtility.class);
public static final String ORIENTDB_CLASS_PROPERTY = ODocumentHelper.ATTRIBUTE_CLASS;
private static final Logger logger = LoggerFactory.getLogger(Utility.class);
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JsonNode toJsonNode(OElement element) throws ResourceRegistryException {
public static JsonNode toJsonNode(OElement element, boolean raw) throws ResourceRegistryException {
ORecord oRecord = element.getRecord();
return OrientDBUtility.toJsonNode(oRecord);
return Utility.toJsonNode(oRecord, raw);
}
public static JsonNode toJsonNode(ORecord oRecord) throws ResourceRegistryException {
public static JsonNode toJsonNode(ORecord oRecord, boolean raw) throws ResourceRegistryException {
try {
ObjectMapper objectMapper = new ObjectMapper();
String string = toJsonString(oRecord);
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(string);
return objectNode;
return objectMapper.readTree(toJsonString(oRecord, raw));
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static String replaceType(String s) {
s = s.replace("\"" + ORIENTDB_CLASS_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\"");
return s;
public static String toJsonString(OElement element, boolean raw) {
ORecord oRecord = element.getRecord();
return Utility.toJsonString(oRecord, raw);
}
public static String toJsonString(OResult oResult) {
String ret = oResult.toJSON();
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
}
public static String toJsonString(ORecord oRecord) {
String ret = oRecord.toJSON("class");
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
}
public static String getAsStringForLogging(ORecord oRecord) {
public static String toJsonString(ORecord oRecord, boolean raw) {
if(raw) {
return oRecord.toJSON();
}
public static String getAsStringForException(ORecord oRecord) {
return toJsonString(oRecord);
return oRecord.toJSON("class");
}
public static <El extends OElement> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
@ -95,7 +73,7 @@ public class OrientDBUtility {
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
adminDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
return Utility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
} finally {
if(adminDatabaseDocument != null) {
adminDatabaseDocument.close();
@ -119,7 +97,8 @@ public class OrientDBUtility {
}
// TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE " + IdentifiableElement.ID_PROPERTY + " = \"" + uuid.toString() + "\"";
String select = "SELECT FROM " + elementType + " WHERE " + IdentifiableElement.HEADER_PROPERTY + "." + Header.UUID_PROPERTY
+ " = \"" + uuid.toString() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
@ -134,7 +113,7 @@ public class OrientDBUtility {
@SuppressWarnings("unchecked")
El element = (El) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", elementType, uuid.toString(), OrientDBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", elementType, uuid.toString(), Utility.toJsonString(element, true));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
@ -148,12 +127,22 @@ public class OrientDBUtility {
throws ResourceRegistryException {
try {
ODocument oDocument = element.getProperty(property);
P e = ElementMapper.unmarshal(clz, OrientDBUtility.toJsonString(oDocument));
P e = ElementMapper.unmarshal(clz, oDocument.toJSON());
return e;
} catch(Exception ex) {
String error = String.format("Error while getting %s from %s", property, getAsStringForException(element));
String error = String.format("Error while getting %s from %s", property, toJsonString(element, true));
throw new ResourceRegistryException(error, ex);
}
}
public static UUID getUUID(OElement element) throws ResourceRegistryException {
/*
* ODocument header = element.getProperty(Entity.HEADER_PROPERTY); String
* contextID = header.field(Header.UUID_PROPERTY); return
* UUID.fromString(contextID);
*/
Header header = HeaderUtility.getHeader(element);
return header.getUUID();
}
}

View File

@ -7,27 +7,17 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.authorization.utils.secret.SecretUtility;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.KeycloakClientHelper;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.CredentialSecret;
import org.gcube.common.security.secrets.Secret;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ContextTest {
private static final Logger logger = LoggerFactory.getLogger(ContextTest.class);
protected static final String CONFIG_INI_FILENAME = "config.ini";
public static final String PARENT_DEFAULT_TEST_SCOPE;
@ -42,10 +32,11 @@ public class ContextTest {
protected static final Properties properties;
public static final String TYPE_PROPERTY_KEY = "type";
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String PASSWORD_PROPERTY_KEY = "password";
public static final String CLIENT_ID_PROPERTY_KEY = "clientId";
protected static final String CLIENT_ID_PROPERTY_KEY = "client_id";
protected static final String CLIENT_SECRET_PROPERTY_KEY = "client_secret";
protected static final String clientID;
protected static final String clientSecret;
static {
GCUBE = "/gcube";
@ -63,101 +54,30 @@ public class ContextTest {
try {
// load the properties file
properties.load(input);
clientID = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
clientSecret = properties.getProperty(CLIENT_SECRET_PROPERTY_KEY);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private enum Type{
USER, CLIENT_ID
};
public static void set(Secret secret) throws Exception {
SecretManagerProvider.instance.reset();
SecretManager secretManager = new SecretManager();
secretManager.addSecret(secret);
SecretManagerProvider.instance.set(secretManager);
SecretManagerProvider.instance.get().set();
SecretManagerProvider.instance.set(secret);
}
public static void setContextByName(String fullContextName) throws Exception {
logger.debug("Going to set credentials for context {}", fullContextName);
Secret secret = getSecretByContextName(fullContextName);
set(secret);
}
private static TokenResponse getJWTAccessToken(String context) throws Exception {
Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString());
TokenResponse tr = null;
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
switch (type) {
case CLIENT_ID:
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
String clientSecret = properties.getProperty(root);
tr = KeycloakClientFactory.newInstance().queryUMAToken(context, clientId, clientSecret, context, null);
break;
case USER:
default:
String username = properties.getProperty(USERNAME_PROPERTY_KEY);
String password = properties.getProperty(PASSWORD_PROPERTY_KEY);
switch (root) {
case "/gcube":
default:
clientId = "next.d4science.org";
break;
case "/pred4s":
clientId = "pre.d4science.org";
break;
case "/d4science.research-infrastructures.eu":
clientId = "services.d4science.org";
break;
}
clientSecret = null;
tr = KeycloakClientHelper.getTokenForUser(context, username, password);
break;
}
return tr;
}
public static Secret getSecretByContextName(String context) throws Exception {
TokenResponse tr = getJWTAccessToken(context);
Secret secret = new JWTSecret(tr.getAccessToken());
return secret;
}
public static void setContext(String token) throws Exception {
Secret secret = getSecret(token);
set(secret);
}
private static Secret getSecret(String token) throws Exception {
Secret secret = SecretUtility.getSecretByTokenString(token);
return secret;
}
public static String getUser() {
String user = Metadata.UNKNOWN_USER;
try {
user = SecretManagerProvider.instance.get().getUser().getUsername();
} catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user);
}
return user;
private static Secret getSecretByContextName(String fullContextName) throws Exception {
CredentialSecret credentialSecret = new CredentialSecret(clientID, clientSecret, fullContextName);
return credentialSecret;
}
@BeforeClass

View File

@ -1,10 +1,8 @@
package org.gcube.informationsystem.resourceregistry.contexts;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
@ -12,7 +10,9 @@ import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.contexts.impl.entities.ContextImpl;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
@ -22,8 +22,9 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSec
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -45,32 +46,32 @@ public class ContextManagementTest extends ContextTest {
public static final String CTX_NAME_B = "B";
public static final String CTX_NAME_C = "C";
public static void checkUUUIDAndMetadata(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getMetadata() != null);
Assert.assertTrue(er.getID() != null);
public static void checkHeader(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader() != null);
Assert.assertTrue(er.getHeader().getUUID() != null);
if(uuid != null) {
Assert.assertTrue(er.getID().compareTo(uuid) == 0);
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0);
}
String user = MetadataUtility.getUser();
Assert.assertTrue(er.getMetadata().getLastUpdateBy().compareTo(user) == 0);
String user = HeaderUtility.getUser();
Assert.assertTrue(er.getHeader().getLastUpdateBy().compareTo(user) == 0);
if(create) {
Assert.assertTrue(er.getMetadata().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getMetadata().getCreationTime().compareTo(er.getMetadata().getLastUpdateTime()) == 0);
Assert.assertTrue(er.getHeader().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
} else {
Assert.assertTrue(er.getMetadata().getCreationTime().before(er.getMetadata().getLastUpdateTime()));
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
}
}
protected void assertions(Context pre, Context post, boolean checkParent, boolean create)
throws ResourceRegistryException {
if(checkParent) {
if(pre.getMetadata() != null) {
checkUUUIDAndMetadata(post, pre.getID(), create);
if(pre.getHeader() != null) {
checkHeader(post, pre.getHeader().getUUID(), create);
} else {
checkUUUIDAndMetadata(post, null, create);
checkHeader(post, null, create);
}
}
@ -148,7 +149,7 @@ public class ContextManagementTest extends ContextTest {
logger.debug("Created {}", contextString);
Context c = ElementMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, true);
roleUserAssertions(c.getID(), null, false);
roleUserAssertions(c.getHeader().getUUID(), null, false);
return c;
}
@ -159,7 +160,7 @@ public class ContextManagementTest extends ContextTest {
logger.debug("Updated {}", contextString);
Context c = ElementMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, false);
roleUserAssertions(c.getID(), null, false);
roleUserAssertions(c.getHeader().getUUID(), null, false);
return c;
}
@ -180,7 +181,7 @@ public class ContextManagementTest extends ContextTest {
}
protected void delete(Context context) throws ResourceRegistryException {
delete(context.getID());
delete(context.getHeader().getUUID());
}
protected void invalidCreate(Context context) throws ResourceRegistryException, IOException {
@ -420,7 +421,7 @@ public class ContextManagementTest extends ContextTest {
delete(contextA5);
} catch(ContextNotFoundException e) {
logger.debug("The context with uuid {} was not found. (Was already deleted)",
contextA5.getID());
contextA5.getHeader().getUUID());
}
delete(contextB3);
@ -435,7 +436,7 @@ public class ContextManagementTest extends ContextTest {
// ________A1________
Context contextC = new ContextImpl(CTX_NAME_C);
contextC.setID(contextA1.getID());
contextC.setHeader(new HeaderImpl(contextA1.getHeader().getUUID()));
invalidCreate(contextC);
delete(contextA1);
@ -443,13 +444,7 @@ public class ContextManagementTest extends ContextTest {
}
private List<Context> getAll() throws Exception {
return getAll(0, -1);
}
private List<Context> getAll(Integer forceOffset, Integer forcelimit) throws Exception {
ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceOffset(forceOffset);
contextManagement.setForceLimit(forcelimit);
String allString = contextManagement.all(false);
logger.trace(allString);
List<Context> all = ElementMapper.unmarshalList(Context.class, allString);
@ -477,16 +472,16 @@ public class ContextManagementTest extends ContextTest {
@Test
public void testGetAll() throws Exception {
List<Context> contexts = getAll();
contexts = ServerContextCache.getInstance().getContexts();
contexts = ContextCache.getInstance().getContexts();
for(Context context : contexts) {
logger.info(ElementMapper.marshal(context));
logger.trace(ElementMapper.marshal(context));
List<IsParentOf> children = context.getChildren();
for(IsParentOf child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
Assert.assertTrue(childContext.getParent().getSource() == context);
}
roleUserAssertions(context.getID(), null, false);
roleUserAssertions(context.getHeader().getUUID(), null, false);
}
}
@ -502,22 +497,24 @@ public class ContextManagementTest extends ContextTest {
delete(context);
}
@Test
public void testContextCache() throws Exception {
DatabaseEnvironment.initContextCacheRenewal();
List<Context> contexts = getAll();
logger.info("{}", contexts);
logger.debug("{}", contexts);
ServerContextCache contextCache = ServerContextCache.getInstance();
ContextCache contextCache = ContextCache.getInstance();
Map<UUID, String> uuidToContextFullName = contextCache.getUUIDToContextFullNameAssociation();
logger.debug("{}", uuidToContextFullName);
List<Context> contextsFromCache = contextCache.getContexts();
for(Context c : contextsFromCache) {
UUID uuid = c.getID();
UUID uuid = c.getHeader().getUUID();
if(c.getParent()!=null) {
IsParentOf isParentOf = c.getParent();
Context parentContext = isParentOf.getSource();
UUID parentUUID = parentContext.getID();
UUID parentUUID = parentContext.getHeader().getUUID();
Assert.assertTrue(parentContext.getName().compareTo(contextCache.getContextByUUID(parentUUID).getName())==0);
List<IsParentOf> children = parentContext.getChildren();
boolean found = false;
@ -528,9 +525,9 @@ public class ContextManagementTest extends ContextTest {
}
}
Assert.assertTrue(found);
logger.debug("{} : {} (parent {} : {})", c.getID(), contextCache.getContextFullNameByUUID(uuid), parentUUID, contextCache.getContextFullNameByUUID(parentUUID));
logger.debug("{} : {} (parent {} : {})", c.getHeader().getUUID(), contextCache.getContextFullNameByUUID(uuid), parentUUID, contextCache.getContextFullNameByUUID(parentUUID));
}else {
logger.debug("{} : {}", c.getID(), contextCache.getContextFullNameByUUID(uuid));
logger.debug("{} : {}", c.getHeader().getUUID(), contextCache.getContextFullNameByUUID(uuid));
}
}
@ -538,100 +535,10 @@ public class ContextManagementTest extends ContextTest {
logger.debug("Current context : {}", currentContext);
for(Context c : contexts) {
UUID uuid = c.getID();
UUID uuid = c.getHeader().getUUID();
Context context = read(uuid);
String fullName = ServerContextCache.getInstance().getContextFullNameByUUID(uuid);
String fullName = ContextCache.getInstance().getContextFullNameByUUID(uuid);
logger.debug("{} - {} : {}", uuid, fullName, context);
}
}
@Test
public void testLimitOffset() throws Exception {
int limit = 2;
int offset = limit * 0;
List<Context> contexts = getAll(offset, limit);
logger.info("Going to check {}s pagination validity", Context.NAME);
if(contexts.size()==0) {
return;
}
Assert.assertTrue(contexts.size() <= limit);
if(contexts.size()< limit) {
return;
}
Set<UUID> uuids = new HashSet<>();
for(Context context : contexts) {
UUID uuid = context.getID();
uuids.add(uuid);
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
}
offset = limit * 1;
contexts = getAll(offset, limit);
if(contexts.size()>0) {
Assert.assertTrue(contexts.size() <= limit);
for(Context context : contexts) {
UUID uuid = context.getID();
Assert.assertFalse(uuids.contains(uuid));
uuids.add(uuid);
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
}
if(contexts.size()<limit) {
return;
}
int doubleLimit = limit*2;
offset = 0;
contexts = getAll(0, doubleLimit);
Assert.assertTrue(contexts.size() <= doubleLimit);
for(Context context : contexts) {
UUID uuid = context.getID();
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, doubleLimit, Context.NAME, uuid, context.getName());
Assert.assertTrue(uuids.contains(uuid));
}
}
logger.info("Going to check all {}s", Context.NAME);
List<Context> all = getAll();
uuids = new HashSet<>();
int i = -1;
while(true) {
offset = ++i * limit;
contexts = getAll(offset, limit);
for(Context context : contexts) {
UUID uuid = context.getID();
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
uuids.add(uuid);
}
if(contexts.size()<limit) {
break;
}
}
Assert.assertTrue(all.size()==uuids.size());
for(Context context : all) {
UUID uuid = context.getID();
Assert.assertTrue(uuids.contains(uuid));
logger.info("Using getAll() found {} with UUID {} and name {}", Context.NAME, uuid, context.getName());
}
logger.info("{} pagination seems properly working", Context.NAME);
}
}

View File

@ -8,42 +8,36 @@ import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.ModelElement;
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.Metadata;
import org.gcube.informationsystem.model.reference.properties.Header;
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.DeleteConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.utils.Utility;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.entities.facets.AccessPointFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
@ -80,12 +74,15 @@ import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPers
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory;
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Activates;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.exception.ODatabaseException;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@ -116,14 +113,6 @@ public class ERManagementTest extends ContextTest {
// }
// }
@Before
public void before() throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
requestInfo.setLimit(1000);
requestInfo.setOffset(0);
}
public static SoftwareFacet getSoftwareFacet() {
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
@ -143,7 +132,7 @@ public class ERManagementTest extends ContextTest {
Configuration configuration = new ConfigurationImpl();
IdentifierFacet identifierFacet = new IdentifierFacetImpl();
identifierFacet.setIdentificationType(IdentificationType.STRING);
identifierFacet.setType(IdentificationType.STRING);
identifierFacet.setValue("MyID");
identifierFacet.setPersistent(false);
@ -179,8 +168,8 @@ public class ERManagementTest extends ContextTest {
LicenseFacet licenseFacet = new LicenseFacetImpl();
licenseFacet.setName("EUPL");
licenseFacet.setTextURL(new URL(
"https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
licenseFacet.setTextURL(
new URL("https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
eService.addFacet(licenseFacet);
return eService;
@ -234,64 +223,58 @@ public class ERManagementTest extends ContextTest {
return hostingNode;
}
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement,
IdentifiableElement createdIdentifiableElement) {
UUID createdUUID = createdIdentifiableElement.getID();
public static void checkHeader(IdentifiableElement identifiableElement, IdentifiableElement createdIdentifiableElement) {
Header createdHeader = createdIdentifiableElement.getHeader();
Assert.assertTrue(createdHeader!=null);
UUID createdUUID = createdHeader.getUUID();
Assert.assertTrue(createdUUID!=null);
if (identifiableElement.getID() != null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID()) == 0);
}
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
Assert.assertTrue(createdMetadata != null);
String createdBy = createdMetadata.getCreatedBy();
String createdBy = createdHeader.getCreatedBy();
Assert.assertTrue(createdBy!=null);
String lastUpdateBy = createdMetadata.getLastUpdateBy();
String lastUpdateBy = createdHeader.getLastUpdateBy();
Assert.assertTrue(lastUpdateBy!=null);
Date creationTime = createdMetadata.getCreationTime();
Date creationTime = createdHeader.getCreationTime();
Assert.assertTrue(creationTime!=null);
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
Date lastUpdateTime = createdHeader.getLastUpdateTime();
Assert.assertTrue(lastUpdateTime!=null);
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
Metadata metadata = identifiableElement.getMetadata();
if (metadata != null) {
Header header = identifiableElement.getHeader();
if(header!=null) {
if(header.getUUID()!=null) {
Assert.assertTrue(createdUUID.compareTo(header.getUUID())==0);
}
if (metadata.getCreatedBy() != null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy()) == 0);
if(header.getCreatedBy()!=null) {
Assert.assertTrue(createdBy.compareTo(header.getCreatedBy())==0);
}else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser()) == 0);
Assert.assertTrue(createdBy.compareTo(HeaderUtility.getUser())==0);
}
if (metadata.getLastUpdateBy() != null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy()) == 0);
if(header.getLastUpdateBy()!=null) {
Assert.assertTrue(lastUpdateBy.compareTo(header.getLastUpdateBy())==0);
}else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser()) == 0);
Assert.assertTrue(lastUpdateBy.compareTo(HeaderUtility.getUser())==0);
}
if (metadata.getLastUpdateTime() != null) {
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime())
|| lastUpdateTime.compareTo(metadata.getLastUpdateTime()) == 0);
if(header.getLastUpdateTime()!=null) {
Assert.assertTrue(lastUpdateTime.after(header.getLastUpdateTime()));
}
}
}
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint,
PropagationConstraint gotPropagationConstraint) {
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint, PropagationConstraint gotPropagationConstraint) {
Assert.assertTrue(propagationConstraint.getAddConstraint()==gotPropagationConstraint.getAddConstraint());
Assert.assertTrue(
propagationConstraint.getRemoveConstraint() == gotPropagationConstraint.getRemoveConstraint());
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==gotPropagationConstraint.getRemoveConstraint());
}
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf,
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf, ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
checkHeader(consistsOf, gotConsistsOf);
if(consistsOf.getPropagationConstraint()==null) {
PropagationConstraint propagationConstraint = gotConsistsOf.getPropagationConstraint();
@ -303,9 +286,9 @@ public class ERManagementTest extends ContextTest {
}
Map<String, Object> additionalProperties = new HashMap<>(consistsOf.getAdditionalProperties());
additionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
additionalProperties.remove(Element.SUPERCLASSES_PROPERTY);
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
gotAdditionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
gotAdditionalProperties.remove(Element.SUPERCLASSES_PROPERTY);
Assert.assertTrue(additionalProperties.size()==gotAdditionalProperties.size());
for(String key : additionalProperties.keySet()) {
Assert.assertTrue(gotAdditionalProperties.containsKey(key));
@ -317,7 +300,7 @@ public class ERManagementTest extends ContextTest {
}
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
checkUUIDAndMetadata(facet, gotFacet);
checkHeader(facet, gotFacet);
Class<? extends Facet> clz = facet.getClass();
Class<? extends Facet> gotClz = gotFacet.getClass();
Assert.assertTrue(clz==gotClz);
@ -329,7 +312,7 @@ public class ERManagementTest extends ContextTest {
protected static <R extends Resource> void checkResource(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
checkHeader(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
@ -337,8 +320,7 @@ public class ERManagementTest extends ContextTest {
for(ConsistsOf<? extends Resource, ? extends Facet> consistsOf : resourceConsistsOf) {
@SuppressWarnings("unchecked")
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf = (ConsistsOf<? extends Resource, ? extends Facet>) gotResource
.getConsistsOf(consistsOf.getClass(), consistsOf.getTarget().getClass()).get(0);
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf = (ConsistsOf<? extends Resource, ? extends Facet>) gotResource.getConsistsOf(consistsOf.getClass(), consistsOf.getTarget().getClass()).get(0);
checkConsistOf(consistsOf, gotConsistsOf);
Facet facet = consistsOf.getTarget();
@ -348,93 +330,58 @@ public class ERManagementTest extends ContextTest {
}
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
protected static <R extends Resource> void checkResourceNoMeta(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
Assert.assertNull(gotResource.getMetadata());
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
public static <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(r.getTypeName());
resourceManagement.setElementType(Utility.getTypeName(r));
resourceManagement.setJson(ElementMapper.marshal(r));
if (r.getID() != null) {
resourceManagement.setUUID(r.getID());
if(r.getHeader()!=null && r.getHeader().getUUID()!=null) {
resourceManagement.setUUID(r.getHeader().getUUID());
}
return resourceManagement;
}
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(
IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
public static <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
isRelatedToManagement.setElementType(Utility.getTypeName(isRelatedTo));
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
if (isRelatedTo.getID() != null) {
isRelatedToManagement.setUUID(isRelatedTo.getID());
if(isRelatedTo.getHeader()!=null && isRelatedTo.getHeader().getUUID()!=null) {
isRelatedToManagement.setUUID(isRelatedTo.getHeader().getUUID());
}
return isRelatedToManagement;
}
public <R extends Resource> R createResource(R r) throws Exception {
public static <R extends Resource> R createResource(R r) throws Exception {
ResourceManagement resourceManagement = getResourceManagement(r);
String json = resourceManagement.create();
logger.debug("Created resource {}", json);
@SuppressWarnings("unchecked")
R createdR = (R) ElementMapper.unmarshal(r.getClass(), json);
logger.debug("Unmarshalled created resource {}", ElementMapper.marshal(createdR));
checkResource(r, createdR);
return createdR;
}
public EService createEService() throws Exception {
public static EService createEService() throws Exception {
EService eService = ERManagementTest.instantiateValidEService();
return createResource(eService);
}
public HostingNode createHostingNode() throws Exception {
public static HostingNode createHostingNode() throws Exception {
return createHostingNode(null);
}
public HostingNode createHostingNode(EService eService) throws Exception {
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
public static HostingNode createHostingNode(EService eService) throws Exception {
return createHostingNode(eService, RemoveConstraint.cascade);
}
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint,
DeleteConstraint deleteConstraint) throws Exception {
public static HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint) throws Exception {
HostingNode hostingNode = ERManagementTest.instantiateValidHostingNode();
if(eService!=null) {
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
propagationConstraint.setRemoveConstraint(removeConstraint);
propagationConstraint.setDeleteConstraint(deleteConstraint);
Activates<HostingNode, EService> activates = new ActivatesImpl<HostingNode, EService>(hostingNode, eService,
propagationConstraint);
hostingNode.attachResource(activates);
@ -442,12 +389,12 @@ public class ERManagementTest extends ContextTest {
return createResource(hostingNode);
}
public Configuration createConfiguration() throws Exception {
public static Configuration createConfiguration() throws Exception {
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
return createResource(configuration);
}
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
public static Map<String, Resource> createHostingNodeAndEService() throws Exception {
Map<String, Resource> map = new HashMap<>();
EService eService = createEService();
@ -459,13 +406,14 @@ public class ERManagementTest extends ContextTest {
return map;
}
public <R extends Resource> void deleteResource(R r) throws Exception {
public static <R extends Resource> void deleteResource(R r) throws Exception {
if(r!=null) {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.delete();
}
}
@Test
public void testCreateEService() throws Exception {
EService eService = null;
@ -477,52 +425,24 @@ public class ERManagementTest extends ContextTest {
}
@Test
public void testCreateAndReadEService() throws Exception {
EService eService = null;
try {
eService = createEService();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
EService readEService = (EService) readResource(eService.getID());
checkResource(eService, readEService);
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceRootMetaOnly(eService, readEService);
requestInfo.setIncludeMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceNoMeta(eService, readEService);
} finally {
deleteResource(eService);
}
}
protected Resource readResource(UUID uuid) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
String json = resourceManagement.read().toString();
logger.debug(json);
return ElementMapper.unmarshal(Resource.class, json);
}
/*
* @Test public void testReadResource() throws Exception {
* readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e")); }
@Test
public void testReadResource() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e"));
String read = resourceManagement.read().toString();
logger.debug(read);
}
*/
/*
* @Test public void testDeleteResource() throws Exception { ResourceManagement
* resourceManagement = new ResourceManagement();
* resourceManagement.setUUID(UUID.fromString(
* "64635295-7ced-4931-a55f-40fc8199b280")); boolean deleted =
* resourceManagement.delete(); Assert.assertTrue(deleted); }
@Test
public void testDeleteResource() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString("64635295-7ced-4931-a55f-40fc8199b280"));
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
}
*/
@Test
@ -538,7 +458,7 @@ public class ERManagementTest extends ContextTest {
@Test
public void testCreateHostingNodeAndEService() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
Map<String, Resource> map = ERManagementTest.createHostingNodeAndEService();
deleteResource(map.get(HostingNode.NAME));
}
@ -555,13 +475,12 @@ public class ERManagementTest extends ContextTest {
ConsistsOf<EService, CPUFacet> consistsOf = new ConsistsOfImpl<EService, CPUFacet>(eService, cpuFacet);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(consistsOf.getTypeName());
consistsOfManagement.setElementType(Utility.getTypeName(consistsOf));
consistsOfManagement.setJson(ElementMapper.marshal(consistsOf));
String createdConsistsOfString = consistsOfManagement.create();
@SuppressWarnings("unchecked")
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class,
createdConsistsOfString);
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class, createdConsistsOfString);
CPUFacet createdCpuFacet = createdConsistsOf.getTarget();
@ -569,10 +488,10 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor()) == 0);
UUID uuid = createdCpuFacet.getID();
UUID uuid = createdCpuFacet.getHeader().getUUID();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(createdCpuFacet.getTypeName());
facetManagement.setElementType(Utility.getTypeName(createdCpuFacet));
facetManagement.setUUID(uuid);
String readJson = facetManagement.read().toString();
@ -581,7 +500,7 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(readCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getID()) == 0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getHeader().getUUID()) == 0);
String newVendor = "Intel";
String newClockSpeed = "2 GHz";
@ -593,7 +512,7 @@ public class ERManagementTest extends ContextTest {
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setElementType(Utility.getTypeName(readCpuFacet));
facetManagement.setUUID(uuid);
facetManagement.setJson(ElementMapper.marshal(readCpuFacet));
@ -605,12 +524,12 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(newVendor) == 0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
String user = ContextTest.getUser();
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID()) == 0);
String user = SecretManagerProvider.instance.get().getOwner().getId();
Assert.assertTrue(updatedCpuFacet.getHeader().getLastUpdateBy().compareTo(user) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(updatedCpuFacet.getTypeName());
facetManagement.setElementType(Utility.getTypeName(updatedCpuFacet));
facetManagement.setUUID(uuid);
String readUpdatedJson = facetManagement.read().toString();
@ -621,10 +540,10 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(readUpdatedCpuFacet.getVendor()) == 0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID()) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setElementType(Utility.getTypeName(readCpuFacet));
facetManagement.setUUID(uuid);
facetManagement.delete();
@ -651,14 +570,14 @@ public class ERManagementTest extends ContextTest {
authorization.setSchema(uri);
accessPointFacet.setAuthorization(authorization);
String additionalPropertyKey = "Test";
String additionlaPropertyKey = "Test";
String additionlaPropertyValue = "MyTest";
accessPointFacet.setAdditionalProperty(additionalPropertyKey, additionlaPropertyValue);
accessPointFacet.setAdditionalProperty(additionlaPropertyKey, additionlaPropertyValue);
Encrypted encrypted = new EncryptedImpl();
String plainValue = "Encrypted";
String encryptedValue = StringEncrypter.getEncrypter().encrypt(plainValue);
encrypted.setValue(encryptedValue);
String encryptedValue = EncryptedImpl.encrypt(plainValue);
encrypted.setEncryptedValue(encryptedValue);
String encryptedKey = "Enc";
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
@ -674,16 +593,16 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema);
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
String encValue = enc.getValue();
String encValue = enc.getEncryptedValue();
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
String decryptedValue = EncryptedImpl.decrypt(encValue);
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
Assert.assertTrue(
((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
Assert.assertTrue(((String) apf.getAdditionalProperty(additionlaPropertyKey)).compareTo(additionlaPropertyValue) == 0);
deleteResource(createdConfiguration);
}
@Test
public void testUpdateFacetValue() throws Exception {
EService eService =null;
@ -702,8 +621,7 @@ public class ERManagementTest extends ContextTest {
SoftwareFacet softwareFacet = updatedEService.getFacets(SoftwareFacet.class).get(0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
} catch (Throwable e) {
throw e;
}finally {
deleteResource(eService);
}
@ -722,7 +640,7 @@ public class ERManagementTest extends ContextTest {
// EService eService = ElementMapper.unmarshal(EService.class, fileInputStream);
//
// ResourceManagement resourceManagement = new ResourceManagement();
// resourceManagement.setUUID(eService.getUUID());
// resourceManagement.setUUID(eService.getHeader().getUUID());
// resourceManagement.setJson(ElementMapper.marshal(eService));
//
// resourceManagement.update();
@ -737,125 +655,4 @@ public class ERManagementTest extends ContextTest {
logger.debug("{}", ret);
}
protected List<ERElement> getPaginatedInstances(Class<? extends ERElement> clz, int offset, int limit) throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setOffset(offset);
requestInfo.setLimit(limit);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(TypeUtility.getTypeName(clz));
String ret = erManagement.all(true);
List<ERElement> list = ElementMapper.unmarshalList(ERElement.class, ret);
return list;
}
@Test
public void testLimitOffset() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
logger.debug("---------------------------------------------------------------------");
try {
for(int i=1; i<6; i++) {
testLimitOffset(Resource.class, i);
testLimitOffset(Facet.class, i);
testLimitOffset(IsRelatedTo.class, i);
testLimitOffset(ConsistsOf.class, i);
}
logger.debug("---------------------------------------------------------------------\n\n\n");
} finally {
deleteResource(map.get(HostingNode.NAME));
}
}
public void testLimitOffset(Class<? extends ERElement> clz, int limit) throws Exception {
if(limit <1) {
throw new Exception("This test has been designed for limit>0 to test pagination");
}
String typeName = TypeUtility.getTypeName(clz);
logger.debug("Going to test pagination of {} using limit {}", typeName, limit);
int offset = limit * 0;
List<ERElement> list = getPaginatedInstances(clz, offset, limit);
if (list.size() == 0) {
logger.debug("Found 0 instances");
logger.debug("Successfully tested pagination of {} using limit {}\n\n", typeName, limit);
return;
}
Assert.assertTrue(list.size() <= limit);
Set<UUID> uuids = new HashSet<>();
for (ERElement erElement : list) {
UUID uuid = erElement.getID();
uuids.add(uuid);
logger.debug("[offset={},limit={}] Found {} with UUID {}", offset, limit, erElement.getTypeName(), uuid);
}
if (list.size() < limit) {
logger.debug("Successfully tested pagination of {} using limit {}\n\n", typeName, limit);
return;
}
offset = limit * 1;
list = getPaginatedInstances(clz, offset, limit);
if (list.size() > 0) {
Assert.assertTrue(list.size() <= limit);
for (ERElement erElement : list) {
UUID uuid = erElement.getID();
Assert.assertFalse(uuids.contains(uuid));
uuids.add(uuid);
logger.debug("[offset={},limit={}] Found {} with UUID {}", offset, limit, erElement.getTypeName(), uuid);
}
if (list.size() < limit) {
logger.debug("Successfully tested pagination of {} using limit {}\n\n", typeName, limit);
return;
}
offset = 0;
int doubleLimit = limit * 2;
list = getPaginatedInstances(clz, offset, doubleLimit);
Assert.assertTrue(list.size() <= doubleLimit);
for (ERElement erElement : list) {
UUID uuid = erElement.getID();
logger.debug("[offset={},limit={}] Found {} with UUID {}", offset, doubleLimit, erElement.getTypeName(), uuid);
Assert.assertTrue(uuids.contains(uuid));
}
}
logger.info("Going to check all {} instances", typeName);
List<ERElement> all = getPaginatedInstances(clz, 0, -1);
uuids = new HashSet<>();
int i = -1;
while(true) {
offset = ++i * limit;
list = getPaginatedInstances(clz, offset, limit);
for(ERElement erElement : list) {
UUID uuid = erElement.getID();
logger.info("[offset={},limit={}] Found {} with UUID {}", offset, limit, erElement.getTypeName(), uuid);
uuids.add(uuid);
}
if(list.size()<limit) {
break;
}
}
Assert.assertTrue(all.size()==uuids.size());
for(ERElement erElement : all) {
UUID uuid = erElement.getID();
Assert.assertTrue(uuids.contains(uuid));
logger.info("[UNLIMITED] Found {} with UUID {}", erElement.getTypeName(), uuid);
}
logger.debug("Successfully tested pagination of {} using limit {}\n\n", TypeUtility.getTypeName(clz), limit);
}
}

View File

@ -2,12 +2,11 @@ package org.gcube.informationsystem.resourceregistry.instances;
import java.security.Key;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.reference.entities.facets.CPUFacet;
import org.gcube.resourcemanagement.model.reference.entities.resources.Configuration;
@ -21,38 +20,32 @@ public class EncryptionTest extends ERManagementTest {
public static final String PLAIN_VALUE = "plain-value";
// @Test
// public void decryptPwd() throws Exception {
// String pwd = StringEncrypter.getEncrypter().decrypt("");
// Assert.assertTrue(true);
// }
@Test
public void test() throws Exception {
Encrypted encrypted = new EncryptedImpl();
String contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(PLAIN_VALUE);
encrypted.setValue(contextEncryptedValue);
String contextEncryptedValue = EncryptedImpl.encrypt(PLAIN_VALUE);
encrypted.setEncryptedValue(contextEncryptedValue);
String getContextEncryptedValue = encrypted.getValue();
String getContextEncryptedValue = encrypted.getEncryptedValue();
Assert.assertTrue(getContextEncryptedValue.compareTo(getContextEncryptedValue)==0);
// Decrypting with Context Key (default key)
String decryptedValue = StringEncrypter.getEncrypter().decrypt(contextEncryptedValue);
String decryptedValue = EncryptedImpl.decrypt(contextEncryptedValue);
Assert.assertTrue(decryptedValue.compareTo(PLAIN_VALUE)==0);
// Encrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey();
String dbEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue, databaseKey);
String dbEncryptedValue = EncryptedImpl.encrypt(decryptedValue, databaseKey);
// Setting the value encrypted with DB key
encrypted.setValue(dbEncryptedValue);
encrypted.setEncryptedValue(dbEncryptedValue);
String getDBEncryptedValue = encrypted.getValue();
String getDBEncryptedValue = encrypted.getEncryptedValue();
Assert.assertTrue(getDBEncryptedValue.compareTo(dbEncryptedValue)==0);
decryptedValue = StringEncrypter.getEncrypter().decrypt(getDBEncryptedValue, databaseKey);
decryptedValue = EncryptedImpl.decrypt(getDBEncryptedValue, databaseKey);
Assert.assertTrue(decryptedValue.compareTo(PLAIN_VALUE)==0);
}
@ -70,8 +63,8 @@ public class EncryptionTest extends ERManagementTest {
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
Encrypted encrypted = new EncryptedImpl();
String encryptedValue = StringEncrypter.getEncrypter().encrypt(PLAIN_VALUE);
encrypted.setValue(encryptedValue);
String encryptedValue = EncryptedImpl.encrypt(PLAIN_VALUE);
encrypted.setEncryptedValue(encryptedValue);
String additionalKey = "test";
cpuFacet.setAdditionalProperty(additionalKey, encrypted);
configuration.addFacet(cpuFacet);
@ -86,9 +79,9 @@ public class EncryptionTest extends ERManagementTest {
Configuration createdConfiguration = ElementMapper.unmarshal(Configuration.class, configurationJsonString);
CPUFacet readCpuFacet = createdConfiguration.getFacets(CPUFacet.class).get(0);
String gotEncryptedValue = ((Encrypted) readCpuFacet.getAdditionalProperty(additionalKey)).getValue();
String gotEncryptedValue = ((Encrypted) readCpuFacet.getAdditionalProperty(additionalKey)).getEncryptedValue();
Assert.assertTrue(gotEncryptedValue.compareTo(encryptedValue) == 0);
String gotPlainValue = StringEncrypter.getEncrypter().decrypt(gotEncryptedValue);
String gotPlainValue = EncryptedImpl.decrypt(gotEncryptedValue);
Assert.assertTrue(gotPlainValue.compareTo(PLAIN_VALUE) == 0);
resourceManagement.delete();

View File

@ -3,7 +3,7 @@ package org.gcube.informationsystem.resourceregistry.instances;
import java.util.Map;
import java.util.UUID;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
@ -11,11 +11,12 @@ import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.resource.ResourceAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.api.utils.Utility;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.SimpleFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl;
@ -41,13 +42,13 @@ public class InvalidOperationTest extends ERManagementTest {
private static Logger logger = LoggerFactory.getLogger(InvalidOperationTest.class);
public static final String ACTIVATES = "{\"propagationConstraint\":{\"" + Element.TYPE_PROPERTY + "\":\"PropagationConstraint\",\"add\":\"propagate\",\"remove\":\"cascade\",\"delete\":\"cascade\"},\"" + Element.TYPE_PROPERTY + "\":\"Activates\",\"source\":{\"" + Element.TYPE_PROPERTY + "\":\"Configuration\",\"uuid\":\"CONFIGURATION_UUID\"},\"target\":{\"uuid\":\"ESERVICE_UUID\",\"" + Element.TYPE_PROPERTY + "\":\"EService\"}}";
public static final String ACTOR = "{\"" + Element.TYPE_PROPERTY + "\":\"Actor\",\"metadata\":null,\"consistsOf\":[{\"" + Element.TYPE_PROPERTY + "\":\"IsIdentifiedBy\",\"metadata\":null,\"propagationConstraint\":{\"" + Element.TYPE_PROPERTY + "\":\"PropagationConstraint\",\"remove\":\"cascade\",\"delete\":\"cascade\",\"add\":\"propagate\"},\"source\":{\"" + Element.TYPE_PROPERTY + "\":\"Actor\",\"metadata\":null},\"target\":{\"" + Element.TYPE_PROPERTY + "\":\"ContactFacet\",\"metadata\":null,\"title\":\"Dr.\",\"name\":\"Frosini\",\"middleName\":null,\"surname\":null,\"eMail\":\"luca.frosini@isti.cnr.it\"}}],\"isRelatedTo\":[]}";
public static final String ACTIVATES = "{\"propagationConstraint\":{\"@class\":\"PropagationConstraint\",\"add\":\"propagate\",\"remove\":\"cascade\"},\"@class\":\"Activates\",\"source\":{\"header\":{\"@class\":\"Header\",\"uuid\":\"CONFIGURATION_UUID\"},\"@class\":\"Configuration\"},\"target\":{\"header\":{\"@class\":\"Header\",\"uuid\":\"ESERVICE_UUID\"},\"@class\":\"EService\"}}";
public static final String ACTOR = "{\"@class\":\"Actor\",\"header\":null,\"consistsOf\":[{\"@class\":\"IsIdentifiedBy\",\"header\":null,\"propagationConstraint\":{\"@class\":\"PropagationConstraint\",\"remove\":\"cascadeWhenOrphan\",\"add\":\"propagate\"},\"source\":{\"@class\":\"Actor\",\"header\":null},\"target\":{\"@class\":\"ContactFacet\",\"header\":null,\"title\":\"Dr.\",\"name\":\"Frosini\",\"middleName\":null,\"surname\":null,\"eMail\":\"luca.frosini@isti.cnr.it\"}}],\"isRelatedTo\":[]}";
@Test(expected = SchemaViolationException.class)
public void createInvalidIsRealtedTo() throws Exception {
Configuration configuration = createConfiguration();
EService eService = createEService();
Configuration configuration = ERManagementTest.createConfiguration();
EService eService = ERManagementTest.createEService();
try {
/*
* Trying to create a relation activates between a Configuration and EService
@ -61,23 +62,23 @@ public class InvalidOperationTest extends ERManagementTest {
*/
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(Activates.NAME);
String json = ACTIVATES.replace("CONFIGURATION_UUID", configuration.getID().toString());
json = json.replace("ESERVICE_UUID", eService.getID().toString());
String json = ACTIVATES.replace("CONFIGURATION_UUID", configuration.getHeader().getUUID().toString());
json = json.replace("ESERVICE_UUID", eService.getHeader().getUUID().toString());
isRelatedToManagement.setJson(json);
isRelatedToManagement.create();
}finally {
deleteResource(configuration);
deleteResource(eService);
ERManagementTest.deleteResource(configuration);
ERManagementTest.deleteResource(eService);
}
}
@Test(expected = ResourceAlreadyPresentException.class)
public void testRecreate() throws Exception {
EService eService = createEService();
EService eService = ERManagementTest.createEService();
try {
createResource(eService);
ERManagementTest.createResource(eService);
}finally {
deleteResource(eService);
ERManagementTest.deleteResource(eService);
}
}
@ -111,12 +112,12 @@ public class InvalidOperationTest extends ERManagementTest {
IsIdentifiedBy<RunningPlugin, SoftwareFacet> isIdentifiedBy = new IsIdentifiedByImpl<>(runningPlugin, softwareFacet);
runningPlugin.addFacet(isIdentifiedBy);
createResource(runningPlugin);
ERManagementTest.createResource(runningPlugin);
}
@Test(expected = ResourceRegistryException.class)
public void testCreateAnEntityDifferentFromDeclared() throws Exception {
EService eService = instantiateValidEService();
EService eService = ERManagementTest.instantiateValidEService();
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(Service.NAME);
resourceManagement.setJson(ElementMapper.marshal(eService));
@ -133,7 +134,7 @@ public class InvalidOperationTest extends ERManagementTest {
@Test(expected = SchemaViolationException.class)
public void testCreateHostingNodeAndEServiceWithSharedFacet() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
Map<String, Resource> map = ERManagementTest.createHostingNodeAndEService();
EService eService = (EService) map.get(EService.NAME);
HostingNode hostingNode = (HostingNode) map.get(HostingNode.NAME);
try {
@ -150,8 +151,8 @@ public class InvalidOperationTest extends ERManagementTest {
logger.debug("Created : {}", json);
} finally {
deleteResource(eService);
deleteResource(hostingNode);
ERManagementTest.deleteResource(eService);
ERManagementTest.deleteResource(hostingNode);
}
}
@ -160,55 +161,55 @@ public class InvalidOperationTest extends ERManagementTest {
public void testCreateEServiceAndDeleteRequiredConsistsOf() throws Exception {
EService eService = null;
try {
eService = createEService();
eService = ERManagementTest.createEService();
@SuppressWarnings("unchecked")
IsIdentifiedBy<EService, SoftwareFacet> isIdentifiedBy = (IsIdentifiedBy<EService, SoftwareFacet>) eService.getConsistsOf(IsIdentifiedBy.class).get(0);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(isIdentifiedBy.getTypeName());
consistsOfManagement.setUUID(isIdentifiedBy.getID());
consistsOfManagement.setElementType(Utility.getTypeName(isIdentifiedBy));
consistsOfManagement.setUUID(isIdentifiedBy.getHeader().getUUID());
consistsOfManagement.delete();
}finally {
deleteResource(eService);
ERManagementTest.deleteResource(eService);
}
}
@Test(expected = SchemaViolationException.class)
public void testCreateEServiceAndDeleteRequiredFacet() throws Exception {
EService eService = createEService();
EService eService = ERManagementTest.createEService();
@SuppressWarnings("unchecked")
IsIdentifiedBy<EService, SoftwareFacet> isIdentifiedBy = (IsIdentifiedBy<EService, SoftwareFacet>) eService.getConsistsOf(IsIdentifiedBy.class).get(0);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(IsIdentifiedBy.NAME);
consistsOfManagement.setUUID(isIdentifiedBy.getID());
consistsOfManagement.setUUID(isIdentifiedBy.getHeader().getUUID());
SoftwareFacet softwareFacet = isIdentifiedBy.getTarget();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setUUID(softwareFacet.getID());
facetManagement.setUUID(softwareFacet.getHeader().getUUID());
try {
facetManagement.delete();
}finally {
deleteResource(eService);
ERManagementTest.deleteResource(eService);
}
}
@Test(expected = SchemaViolationException.class)
public void testCreateConsistsOfBeetweenResources() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
Map<String, Resource> map = ERManagementTest.createHostingNodeAndEService();
UUID hostingNodeUUID = map.get(HostingNode.NAME).getID();
UUID eServiceUUID = map.get(EService.NAME).getID();
UUID hostingNodeUUID = map.get(HostingNode.NAME).getHeader().getUUID();
UUID eServiceUUID = map.get(EService.NAME).getHeader().getUUID();
HostingNode hostingNode = new HostingNodeImpl();
hostingNode.setID(hostingNodeUUID);
hostingNode.setHeader(new HeaderImpl(hostingNodeUUID));
SimpleFacet fakeEServiceAsSimpleFacet = new SimpleFacetImpl();
fakeEServiceAsSimpleFacet.setID(eServiceUUID);
fakeEServiceAsSimpleFacet.setHeader(new HeaderImpl(eServiceUUID));
ConsistsOf<HostingNode, SimpleFacet> consistsOf = new ConsistsOfImpl<HostingNode, SimpleFacet>(hostingNode, fakeEServiceAsSimpleFacet);
@ -223,8 +224,8 @@ public class InvalidOperationTest extends ERManagementTest {
consistsOfManagement.create();
throw new Exception("A ConsistsOf has been created between two resoures. This should not happen");
} finally {
deleteResource(map.get(EService.NAME));
deleteResource(map.get(HostingNode.NAME));
ERManagementTest.deleteResource(map.get(EService.NAME));
ERManagementTest.deleteResource(map.get(HostingNode.NAME));
}
}

View File

@ -33,17 +33,18 @@ import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.UUIDManager;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.MemoryFacetImpl;
@ -90,10 +91,11 @@ public class SmartgearResourcesTest extends ERManagementTest {
@Test
public void testHostingNodeOperations() throws ResourceRegistryException,
IOException, URISyntaxException {
UUID uuid = UUIDManager.getInstance().generateValidUUID();
UUID uuid = UUID.randomUUID();
HostingNode hostingNode = new HostingNodeImpl();
hostingNode.setID(uuid);
Header header = new HeaderImpl(uuid);
hostingNode.setHeader(header);
NetworkingFacet networkingFacet = new NetworkingFacetImpl();
try {
@ -445,37 +447,6 @@ public class SmartgearResourcesTest extends ERManagementTest {
public static final String CPU_MODEL_B = "model\b";
public static final String CPU_MODEL_NUMBER = "modelNumber";
public static List<CPUFacet> getFakeCPUFacets() {
List<CPUFacet> cpuFacets = new ArrayList<>();
if(cpuFacets.size()==0) {
for(int i=0; i<8; i++) {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setVendor("Apple");
cpuFacet.setModel("Apple M2 Pro");
cpuFacet.setClockSpeed("3,504 GHz");
cpuFacet.setAdditionalProperty("coreType", "Performance Cores (Avalanche)");
cpuFacets.add(cpuFacet);
}
for(int i=0; i<4; i++) {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setVendor("Apple");
cpuFacet.setModel("Apple M2 Pro");
cpuFacet.setClockSpeed("2.424 GHz");
cpuFacet.setAdditionalProperty("coreType", "Efficiency Cores (Blizzard)");
cpuFacets.add(cpuFacet);
}
}
return cpuFacets;
}
/**
* This function properly works on Linux but fails on
* other system such as Mac OS. In such case, the function
* getFakeCPUFacet() is used instead;
*/
public static List<CPUFacet> getCPUFacets() {
List<CPUFacet> cpuFacets = new ArrayList<>();
@ -484,7 +455,7 @@ public class SmartgearResourcesTest extends ERManagementTest {
if (!file.exists()) {
logger.warn("cannot acquire CPU info (no /proc/cpuinfo)");
return getFakeCPUFacets();
return cpuFacets;
}
BufferedReader input = null;
@ -562,11 +533,6 @@ public class SmartgearResourcesTest extends ERManagementTest {
}
}
}
if(cpuFacets.size()==0) {
return getFakeCPUFacets();
}
return cpuFacets;
}
}

View File

@ -6,7 +6,9 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.reference.properties.Header;
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;
@ -15,11 +17,11 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundExcep
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.entities.facets.ContactFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.CoverageFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.IdentifierFacetImpl;
@ -52,13 +54,13 @@ public class AddToContextTest extends MultiContextTest {
@Test
public void testCreateEServiceAndRemoveFromContextRequiredFacet() throws Exception {
EService eService = createEService();
EService eService = ERManagementTest.createEService();
@SuppressWarnings("unchecked")
IsIdentifiedBy<EService, SoftwareFacet> isIdentifiedBy = (IsIdentifiedBy<EService, SoftwareFacet>) eService.getConsistsOf(IsIdentifiedBy.class).get(0);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(IsIdentifiedBy.NAME);
consistsOfManagement.setUUID(isIdentifiedBy.getID());
consistsOfManagement.setUUID(isIdentifiedBy.getHeader().getUUID());
try {
consistsOfManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
@ -66,14 +68,14 @@ public class AddToContextTest extends MultiContextTest {
}catch (SchemaViolationException e) {
// As expected
}catch (Exception e) {
deleteResource(eService);
ERManagementTest.deleteResource(eService);
throw e;
}
SoftwareFacet softwareFacet = isIdentifiedBy.getTarget();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(SoftwareFacet.NAME);
facetManagement.setUUID(softwareFacet.getID());
facetManagement.setUUID(softwareFacet.getHeader().getUUID());
try {
facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
@ -81,21 +83,21 @@ public class AddToContextTest extends MultiContextTest {
}catch (SchemaViolationException e) {
// As expected
}catch (Exception e) {
deleteResource(eService);
ERManagementTest.deleteResource(eService);
throw e;
}
deleteResource(eService);
ERManagementTest.deleteResource(eService);
}
protected Dataset createDataset(String id, String uuidString) throws Exception {
Dataset dataset = new DatasetImpl();
dataset.setID(UUID.fromString(uuidString));
dataset.setHeader(new HeaderImpl(UUID.fromString(uuidString)));
IdentifierFacet identifierFacet = new IdentifierFacetImpl();
identifierFacet.setValue(id);
identifierFacet.setIdentificationType(IdentificationType.STRING);
identifierFacet.setType(IdentificationType.STRING);
identifierFacet.setPersistent(false);
IsIdentifiedBy<Dataset, IdentifierFacet> isIdentifiedBy = new IsIdentifiedByImpl<>(dataset, identifierFacet);
dataset.addFacet(isIdentifiedBy);
@ -137,7 +139,7 @@ public class AddToContextTest extends MultiContextTest {
protected IsCorrelatedTo<Dataset, Dataset> createIsCorrelatedTo(Dataset source, Dataset target, String uuid) throws Exception {
PropagationConstraint propagationConstraint = getPropagationConstraint();
IsCorrelatedTo<Dataset, Dataset> isCorrelatedTo = new IsCorrelatedToImpl<Dataset, Dataset>(source, target, propagationConstraint);
isCorrelatedTo.setID(UUID.fromString(uuid));
isCorrelatedTo.setHeader(new HeaderImpl(UUID.fromString(uuid)));
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(isCorrelatedTo);
String json = isRelatedToManagement.create();
@ -151,22 +153,20 @@ public class AddToContextTest extends MultiContextTest {
protected void checkNumerOfContext(Dataset dataset, int expectedContextSize) throws Exception {
setContextByName(GCUBE);
RequestUtility.getRequestInfo().get().setHierarchicalMode(true);
RequestUtility.getRequestInfo().get().setIncludeContexts(true);
ContextUtility.getHierarchicalMode().set(true);
ContextUtility.getIncludeInstanceContexts().set(true);
String json = getResourceManagement(dataset).read();
logger.trace("Resource with contexts in HierarchicalMode from server is {}", json);
Dataset r1 = ElementMapper.unmarshal(Dataset.class, json);
logger.trace("Resource with contexts in HierarchicalMode with Jackson is {}", r1.toString());
Map<UUID,String> contextsR1 = r1.getContexts();
@SuppressWarnings("unchecked")
Map<String,String> contextsR1 = (Map<String, String>) r1.getHeader().getAdditionalProperty(Header.__CONTEXTS);
Set<String> contextsR1Fullname = new HashSet<>(contextsR1.values());
logger.info("Contexts of {} with UUID {} and Id {} are {}", Dataset.NAME, r1.getID(), ((IdentifierFacet)r1.getIdentificationFacets().get(0)).getValue(), contextsR1Fullname);
logger.info("Contexts of {} with UUID {} and Id {} are {}", Dataset.NAME, r1.getHeader().getUUID(), ((IdentifierFacet)r1.getIdentificationFacets().get(0)).getValue(), contextsR1Fullname);
Assert.assertTrue(contextsR1.size()==expectedContextSize);
RequestUtility.getRequestInfo().get().setHierarchicalMode(false);
RequestUtility.getRequestInfo().get().setIncludeContexts(false);
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
}
@Test
@ -285,9 +285,8 @@ public class AddToContextTest extends MultiContextTest {
logger.error("", e);
throw e;
}finally {
RequestUtility.getRequestInfo().get().setHierarchicalMode(false);
RequestUtility.getRequestInfo().get().setIncludeContexts(false);
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
setContextByName(GCUBE);
deleteResource(datasetR1);
@ -309,8 +308,9 @@ public class AddToContextTest extends MultiContextTest {
// public void testAddToContext() throws Exception {
// ContextCache contextCache = ContextCache.getInstance();
// HostingNode hostingNode = new HostingNodeImpl();
// hostingNode.setUUID(UUID.fromString("a87bb07e-5320-4fd8-a48d-bf3cc55756c4"));
// ResourceManagement resourceManagement = getResourceManagement(hostingNode);
// Header header = new HeaderImpl(UUID.fromString("a87bb07e-5320-4fd8-a48d-bf3cc55756c4"));
// hostingNode.setHeader(header);
// ResourceManagement resourceManagement = ERManagementTest.getResourceManagement(hostingNode);
// resourceManagement.setDryRun(false);
// UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName("/gcube/devsec").getUUID();
// resourceManagement.addToContext(contextUUID);

View File

@ -10,7 +10,6 @@ import java.util.UUID;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.DeleteConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.ContextTest;
@ -18,10 +17,11 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.reso
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToNotFoundException;
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Activates;
@ -56,7 +56,7 @@ public class BasicTest extends MultiContextTest {
logger.debug("Created : {}", json);
CPUFacet createdCPUFacet = ElementMapper.unmarshal(CPUFacet.class, json);
UUID uuid = createdCPUFacet.getUUID();
UUID uuid = createdCPUFacet.getHeader().getUUID();
facetManagement = new FacetManagement();
facetManagement.setUUID(uuid);
@ -133,13 +133,13 @@ public class BasicTest extends MultiContextTest {
@Test
public void testAddResourceToContext() throws Exception {
EService eService = createEService();
EService eService = ERManagementTest.createEService();
try {
addToContextThenTestIfBehaveProperly(eService, ALTERNATIVE_TEST_SCOPE);
} catch (Exception e) {
throw e;
} finally {
deleteResource(eService);
ERManagementTest.deleteResource(eService);
}
}
@ -147,24 +147,24 @@ public class BasicTest extends MultiContextTest {
@Test
public void testCreateEServiceHostingNode() throws Exception {
EService eService = createEService();
EService eService = ERManagementTest.createEService();
Map<UUID, IdentifiableElement> eServiceInstances = new HashMap<>();
eServiceInstances.put(eService.getID(), eService);
eServiceInstances.put(eService.getHeader().getUUID(), eService);
for(ConsistsOf<?,?> consistsOf : eService.getConsistsOf()) {
eServiceInstances.put(consistsOf.getID(), consistsOf);
eServiceInstances.put(consistsOf.getTarget().getID(), consistsOf.getTarget());
eServiceInstances.put(consistsOf.getHeader().getUUID(), consistsOf);
eServiceInstances.put(consistsOf.getTarget().getHeader().getUUID(), consistsOf.getTarget());
}
HostingNode hostingNode = createHostingNode(eService);
UUID hostingNodeUUID = hostingNode.getID();
HostingNode hostingNode = ERManagementTest.createHostingNode(eService);
UUID hostingNodeUUID = hostingNode.getHeader().getUUID();
Map<UUID, IdentifiableElement> hostingNodeInstances = new HashMap<>();
hostingNodeInstances.put(hostingNodeUUID, hostingNode);
for(ConsistsOf<?,?> consistsOf : hostingNode.getConsistsOf()) {
hostingNodeInstances.put(consistsOf.getID(), consistsOf);
hostingNodeInstances.put(consistsOf.getTarget().getID(), consistsOf.getTarget());
hostingNodeInstances.put(consistsOf.getHeader().getUUID(), consistsOf);
hostingNodeInstances.put(consistsOf.getTarget().getHeader().getUUID(), consistsOf.getTarget());
}
/* ------------------------------------------------------------------ */
@ -178,7 +178,7 @@ public class BasicTest extends MultiContextTest {
addToContextThenTestIfBehaveProperly(hostingNode, targetContextFullName);
deleteResource(hostingNode);
ERManagementTest.deleteResource(hostingNode);
rm = (ResourceManagement) ElementManagementUtility.getERManagement(Resource.NAME);
all = rm.all(true);
@ -202,10 +202,10 @@ public class BasicTest extends MultiContextTest {
}
/* Creating EService */
EService eService = createEService();
EService eService = ERManagementTest.createEService();
/* Creating HostingNode */
HostingNode hostingNode = createHostingNode(eService, removeConstraint, DeleteConstraint.cascade);
HostingNode hostingNode = ERManagementTest.createHostingNode(eService, removeConstraint);
@SuppressWarnings("unchecked")
Activates<HostingNode, EService> activates = (Activates<HostingNode, EService>) getOutcomingIsRelatedTo(hostingNode).get(0);
@ -216,7 +216,7 @@ public class BasicTest extends MultiContextTest {
// Adding Activated to ALTERNATIVE_TEST_SCOPE
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(activates);
IsRelatedToManagement isRelatedToManagement = ERManagementTest.getIsRelatedToManagement(activates);
addToContextThenTestIfBehaveProperly(activates, ALTERNATIVE_TEST_SCOPE);
/* ------------------------------------------------------------------ */
@ -232,30 +232,30 @@ public class BasicTest extends MultiContextTest {
* I MUST not be able to read Activates relation and EService
*/
ResourceManagement resourceManagement = getResourceManagement(hostingNode);
ResourceManagement resourceManagement = ERManagementTest.getResourceManagement(hostingNode);
try {
resourceManagement.read();
String error = String.format("{} with UUID {} should not be visible.", HostingNode.NAME, hostingNode.getID());
String error = String.format("{} with UUID {} should not be visible.", HostingNode.NAME, hostingNode.getHeader().getUUID());
logger.trace(error);
throw new Exception(error);
}catch (ResourceAvailableInAnotherContextException e) {
// OK
}
isRelatedToManagement = getIsRelatedToManagement(activates);
isRelatedToManagement = ERManagementTest.getIsRelatedToManagement(activates);
try {
isRelatedToManagement.read();
String error = String.format("{} with UUID {} should not be visible.", Activates.NAME, activates.getID());
String error = String.format("{} with UUID {} should not be visible.", Activates.NAME, activates.getHeader().getUUID());
logger.trace(error);
throw new Exception(error);
}catch (RelationAvailableInAnotherContextException e) {
// OK
}
resourceManagement = getResourceManagement(eService);
resourceManagement = ERManagementTest.getResourceManagement(eService);
try {
resourceManagement.read();
String error = String.format("{} with UUID {} should not be visible.", EService.NAME, eService.getID());
String error = String.format("{} with UUID {} should not be visible.", EService.NAME, eService.getHeader().getUUID());
logger.trace(error);
throw new Exception(error);
}catch (ResourceAvailableInAnotherContextException e) {
@ -267,46 +267,46 @@ public class BasicTest extends MultiContextTest {
// The Instances MUST be still available in ALTERNATIVE_TEST_SCOPE
ContextTest.setContextByName(ALTERNATIVE_TEST_SCOPE);
resourceManagement = getResourceManagement(hostingNode);
resourceManagement = ERManagementTest.getResourceManagement(hostingNode);
resourceManagement.read();
isRelatedToManagement = getIsRelatedToManagement(activates);
isRelatedToManagement = ERManagementTest.getIsRelatedToManagement(activates);
isRelatedToManagement.read();
resourceManagement = getResourceManagement(eService);
resourceManagement = ERManagementTest.getResourceManagement(eService);
resourceManagement.read();
} finally {
// Removing HostingNode MUST delete Activates and EService due to propagationConstraint
ResourceManagement resourceManagement = getResourceManagement(hostingNode);
ResourceManagement resourceManagement = ERManagementTest.getResourceManagement(hostingNode);
resourceManagement.delete();
resourceManagement = getResourceManagement(hostingNode);
resourceManagement = ERManagementTest.getResourceManagement(hostingNode);
try {
resourceManagement.read();
String error = String.format("{} with UUID {} should not be found.", HostingNode.NAME, hostingNode.getID());
String error = String.format("{} with UUID {} should not be found.", HostingNode.NAME, hostingNode.getHeader().getUUID());
logger.trace(error);
throw new Exception(error);
}catch (ResourceNotFoundException e) {
// OK
}
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(activates);
IsRelatedToManagement isRelatedToManagement = ERManagementTest.getIsRelatedToManagement(activates);
try {
isRelatedToManagement.read();
String error = String.format("{} with UUID {} should not be found.", Activates.NAME, activates.getID());
String error = String.format("{} with UUID {} should not be found.", Activates.NAME, activates.getHeader().getUUID());
logger.trace(error);
throw new Exception(error);
}catch (IsRelatedToNotFoundException e) {
// OK
}
resourceManagement = getResourceManagement(eService);
resourceManagement = ERManagementTest.getResourceManagement(eService);
try {
resourceManagement.read();
String error = String.format("{} with UUID {} should not be found.", EService.NAME, eService.getID());
String error = String.format("{} with UUID {} should not be found.", EService.NAME, eService.getHeader().getUUID());
logger.trace(error);
throw new Exception(error);
}catch (ResourceNotFoundException e) {

View File

@ -10,13 +10,14 @@ import org.gcube.informationsystem.model.reference.properties.PropagationConstra
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.api.utils.Utility;
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.relations.isrelatedto.ActivatesImpl;
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
@ -34,11 +35,14 @@ public class ComplexTest extends MultiContextTest {
public void testGetInstancesContexts() throws ResourceRegistryException, Exception {
ContextTest.setContextByName(DEVNEXT);
ContextCache contextCache = ContextCache.getInstance();
contextCache.setContextCacheRenewal(contextCacheRenewal);
/* Creating HostingNode */
HostingNode hostingNode = createHostingNode();
HostingNode hostingNode = ERManagementTest.createHostingNode();
/* Creating EService */
EService eService = createEService();
EService eService = ERManagementTest.createEService();
/* Creating Activates Relation */
@ -68,7 +72,7 @@ public class ComplexTest extends MultiContextTest {
logger.debug("Switching to alternative scope");
ContextTest.setContextByName(NEXTNEXT);
ResourceManagement hostingNodeManagement = getResourceManagement(hostingNode);
ResourceManagement hostingNodeManagement = ERManagementTest.getResourceManagement(hostingNode);
String hostingNodeContexts = hostingNodeManagement.getContexts();
logger.debug("Contexts of {} with UUID {} have the following UUID {}", HostingNode.NAME, hostingNodeManagement.getUUID(), hostingNodeContexts);
@ -79,8 +83,8 @@ public class ComplexTest extends MultiContextTest {
for(Facet facet : hostingNode.getFacets()) {
FacetManagement facetManagement = new FacetManagement();
facetManagement.setUUID(facet.getID());
String typeName = TypeUtility.getTypeName(facet.getClass());
facetManagement.setUUID(facet.getHeader().getUUID());
String typeName = Utility.getTypeName(facet.getClass());
facetManagement.setElementType(typeName);
String facetContexts = facetManagement.getContexts();
logger.debug("Contexts of {} with UUID {} have the following UUID {}", typeName, facetManagement.getUUID(), facetContexts);
@ -93,8 +97,8 @@ public class ComplexTest extends MultiContextTest {
}
activatesManagement = new IsRelatedToManagement();
activatesManagement.setUUID(createdActivates.getID());
activatesManagement.setElementType(TypeUtility.getTypeName(createdActivates.getClass()));
activatesManagement.setUUID(createdActivates.getHeader().getUUID());
activatesManagement.setElementType(Utility.getTypeName(createdActivates.getClass()));
String isRelatedToContexts = activatesManagement.getContexts();
logger.debug("Contexts of {} with UUID {} have the following UUID {}", Activates.NAME, activatesManagement.getUUID(), isRelatedToContexts);
Map<UUID, String> activatesContextMap = org.gcube.informationsystem.resourceregistry.api.contexts.ContextUtility.getContextMap(isRelatedToContexts);
@ -105,7 +109,7 @@ public class ComplexTest extends MultiContextTest {
logger.debug("Contexts of {} with UUID {} are {}", Activates.NAME, activatesManagement.getUUID(), activatesContextMap.values());
ResourceManagement eServiceManagement = getResourceManagement(eService);
ResourceManagement eServiceManagement = ERManagementTest.getResourceManagement(eService);
String eServiceContexts = eServiceManagement.getContexts();
logger.debug("Contexts of {} with UUID {} have the following UUID {}", EService.NAME, eServiceManagement.getUUID(), eServiceContexts);
Map<UUID,String> eServiceContextMap = org.gcube.informationsystem.resourceregistry.api.contexts.ContextUtility.getContextMap(eServiceContexts);
@ -113,15 +117,15 @@ public class ComplexTest extends MultiContextTest {
Assert.assertTrue(eServiceContextsUUID.size()==1);
Assert.assertFalse(eServiceContextsUUID.containsAll(hostingNodeContextUUID));
Assert.assertTrue(hostingNodeContextUUID.containsAll(eServiceContextsUUID));
Set<String> eServiceContextFullNames = org.gcube.informationsystem.resourceregistry.api.contexts.ContextUtility.getContextFullNameSet(ServerContextCache.getInstance(), eServiceContextsUUID);
Set<String> eServiceContextFullNames = org.gcube.informationsystem.resourceregistry.api.contexts.ContextUtility.getContextFullNameSet(eServiceContextsUUID);
Assert.assertTrue(eServiceContextFullNames.size()==1);
logger.debug("Contexts of {} with UUID {} are {}", EService.NAME, eServiceManagement.getUUID(), eServiceContextFullNames);
deleteResource(hostingNode);
ERManagementTest.deleteResource(hostingNode);
try {
ContextTest.setContextByName(DEVNEXT);
deleteResource(eService);
ERManagementTest.deleteResource(eService);
} catch (Exception e) {
logger.error("",e);
}

View File

@ -1,5 +1,6 @@
package org.gcube.informationsystem.resourceregistry.instances.multicontext;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -8,8 +9,9 @@ import java.util.TreeSet;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
@ -18,14 +20,15 @@ import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -39,7 +42,7 @@ public class MultiContextTest extends ERManagementTest {
@SuppressWarnings({ "unchecked", "unused" })
private Map<UUID, Element> getRemovedExpectedInstances(Resource r) throws Exception {
Map<UUID, Element> expected = new HashMap<>();
expected.put(r.getID(), r);
expected.put(r.getHeader().getUUID(), r);
@SuppressWarnings("rawtypes")
List<IsRelatedTo> list = getOutcomingIsRelatedTo(r);
@ -47,16 +50,16 @@ public class MultiContextTest extends ERManagementTest {
for (IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo : list) {
if (isRelatedTo.getPropagationConstraint().getRemoveConstraint() == RemoveConstraint.cascade) {
expected.put(isRelatedTo.getID(), isRelatedTo);
expected.put(isRelatedTo.getHeader().getUUID(), isRelatedTo);
expected.putAll(getRemovedExpectedInstances(isRelatedTo.getTarget()));
}
if (isRelatedTo.getPropagationConstraint().getRemoveConstraint() == RemoveConstraint.cascadeWhenOrphan) {
expected.put(isRelatedTo.getID(), isRelatedTo);
expected.put(isRelatedTo.getHeader().getUUID(), isRelatedTo);
@SuppressWarnings("rawtypes")
List<IsRelatedTo> incoming = getIncomingIsRelatedTo(r);
if(incoming.size()==1) {
Assert.assertTrue(incoming.get(0).getID().compareTo(isRelatedTo.getID())==0);
Assert.assertTrue(incoming.get(0).getHeader().getUUID().compareTo(isRelatedTo.getHeader().getUUID())==0);
expected.putAll(getRemovedExpectedInstances(isRelatedTo.getTarget()));
}
@ -66,9 +69,9 @@ public class MultiContextTest extends ERManagementTest {
for (ConsistsOf<? extends Resource, ? extends Facet> consistsOf : r.getConsistsOf()) {
if (consistsOf.getPropagationConstraint().getRemoveConstraint() == RemoveConstraint.cascade || consistsOf
.getPropagationConstraint().getRemoveConstraint() == RemoveConstraint.cascadeWhenOrphan) {
expected.put(consistsOf.getID(), consistsOf);
expected.put(consistsOf.getHeader().getUUID(), consistsOf);
Facet facet = consistsOf.getTarget();
expected.put(facet.getID(), facet);
expected.put(facet.getHeader().getUUID(), facet);
}
}
@ -79,7 +82,7 @@ public class MultiContextTest extends ERManagementTest {
// Must be investigated cause infinite recursion to Jackson
// Map<UUID, Element> expectedInstances = getRemovedExpectedInstances(r);
ResourceManagement resourceManagement = getResourceManagement(r);
ResourceManagement resourceManagement = ERManagementTest.getResourceManagement(r);
resourceManagement.setDryRun(dryRun);
UUID contextUUID = ContextUtility.getCurrentSecurityContext().getUUID();
resourceManagement.removeFromContext(contextUUID);
@ -102,7 +105,7 @@ public class MultiContextTest extends ERManagementTest {
// String expectedType = TypeMapper.getType(element.getClass());
//
// JsonNode affectedJsonNode = affectedInstances.get(uuid);
// String affectedType = affectedJsonNode.get(Element.TYPE_PROPERTY).asText();
// String affectedType = affectedJsonNode.get(Element.CLASS_PROPERTY).asText();
//
// Assert.assertTrue(affectedType.compareTo(expectedType) == 0);
// }
@ -111,7 +114,7 @@ public class MultiContextTest extends ERManagementTest {
// resourceManagement = ERManagementTest.getResourceManagement(r);
// try {
// resourceManagement.read();
// String error = String.format("{} with UUID {} should not be visible.", Utility.getTypeName(r), r.getUUID());
// String error = String.format("{} with UUID {} should not be visible.", Utility.getTypeName(r), r.getHeader().getUUID());
// logger.trace(error);
// throw new Exception(error);
// }catch (ResourceAvailableInAnotherContextException e) {
@ -150,7 +153,7 @@ public class MultiContextTest extends ERManagementTest {
resourceManagement.setElementType(Resource.NAME);
String resourceType = TypeMapper.getType(r);
UUID resourceUUID = r.getID();
UUID resourceUUID = r.getHeader().getUUID();
// resourceManagement.setUUID(resourceUUID);
String ret = resourceManagement.query(IsRelatedTo.NAME, resourceType, resourceUUID, oDirection, true,
@ -175,11 +178,11 @@ public class MultiContextTest extends ERManagementTest {
protected Map<UUID, Element> getExpectedInstancesAddToContext(Resource resource) throws ResourceRegistryException, Exception {
String json = getResourceManagement(resource).read();
String json = ERManagementTest.getResourceManagement(resource).read();
Resource r = ElementMapper.unmarshal(resource.getClass(), json);
Map<UUID, Element> expected = new HashMap<>();
expected.put(r.getID(), r);
expected.put(r.getHeader().getUUID(), r);
RelationConstraintEvaluator relationConstraintEvaluator = new RelationConstraintEvaluator() {
@ -199,15 +202,15 @@ public class MultiContextTest extends ERManagementTest {
for (IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo : r.getIsRelatedTo()) {
if (isRelatedTo.getPropagationConstraint().getAddConstraint() == AddConstraint.propagate) {
expected.put(isRelatedTo.getID(), isRelatedTo);
expected.put(isRelatedTo.getHeader().getUUID(), isRelatedTo);
expected.putAll(getExpectedInstancesAddToContext(isRelatedTo.getTarget()));
}
}
for (ConsistsOf<? extends Resource, ? extends Facet> consistsOf : r.getConsistsOf()) {
if (consistsOf.getPropagationConstraint().getAddConstraint() == AddConstraint.propagate) {
expected.put(consistsOf.getID(), consistsOf);
expected.put(consistsOf.getHeader().getUUID(), consistsOf);
Facet facet = consistsOf.getTarget();
expected.put(facet.getID(), facet);
expected.put(facet.getHeader().getUUID(), facet);
}
}
return expected;
@ -218,7 +221,7 @@ public class MultiContextTest extends ERManagementTest {
// Map<UUID, Element> expectedInstances = getExpectedInstancesAddToContext(r);
ResourceManagement resourceManagement = getResourceManagement(r);
ResourceManagement resourceManagement = ERManagementTest.getResourceManagement(r);
resourceManagement.setDryRun(dryRun);
UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(targetContextFullName).getUUID();
resourceManagement.addToContext(contextUUID);
@ -229,11 +232,11 @@ public class MultiContextTest extends ERManagementTest {
if(!dryRun) {
String currentContext = SecretManagerProvider.instance.get().getContext();
ContextTest.setContextByName(targetContextFullName);
resourceManagement = getResourceManagement(r);
resourceManagement = ERManagementTest.getResourceManagement(r);
String json = resourceManagement.read();
Resource resource = ElementMapper.unmarshal(r.getClass(), json);
Assert.assertTrue(resource.getClass() == r.getClass());
Assert.assertTrue(resource.getID().compareTo(r.getID())==0);
Assert.assertTrue(resource.getHeader().getUUID().compareTo(r.getHeader().getUUID())==0);
ContextTest.setContextByName(currentContext);
}
}
@ -257,7 +260,7 @@ public class MultiContextTest extends ERManagementTest {
String expectedType = TypeMapper.getType(element.getClass());
JsonNode affectedJsonNode = affectedInstances.get(uuid);
String affectedType = TypeUtility.getTypeName(affectedJsonNode);
String affectedType = affectedJsonNode.get(Element.CLASS_PROPERTY).asText();
Assert.assertTrue(affectedType.compareTo(expectedType) == 0);
@ -275,9 +278,9 @@ public class MultiContextTest extends ERManagementTest {
// Must be investigated cause infinite recursion to Jackson
// Map<UUID, Element> expectedInstances = getExpectedInstancesAddToContext(isRelatedTo.getSource());
// expectedInstances.putAll(getExpectedInstancesAddToContext(isRelatedTo.getTarget()));
// expectedInstances.put(isRelatedTo.getUUID(), isRelatedTo);
// expectedInstances.put(isRelatedTo.getHeader().getUUID(), isRelatedTo);
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(isRelatedTo);
IsRelatedToManagement isRelatedToManagement = ERManagementTest.getIsRelatedToManagement(isRelatedTo);
isRelatedToManagement.setDryRun(dryRun);
UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(targetContextFullName).getUUID();
isRelatedToManagement.addToContext(contextUUID);
@ -294,21 +297,21 @@ public class MultiContextTest extends ERManagementTest {
// @SuppressWarnings("unchecked")
// IsRelatedTo<Resource, Resource> irt = ElementMapper.unmarshal(isRelatedTo.getClass(), json);
// Assert.assertTrue(isRelatedTo.getClass() == irt.getClass());
// Assert.assertTrue(isRelatedTo.getUUID().compareTo(irt.getUUID())==0);
// Assert.assertTrue(isRelatedTo.getHeader().getUUID().compareTo(irt.getHeader().getUUID())==0);
//
// Resource source = irt.getSource();
// ResourceManagement resourceManagement = ERManagementTest.getResourceManagement(source);
// json = resourceManagement.read();
// Resource resource = ElementMapper.unmarshal(source.getClass(), json);
// Assert.assertTrue(resource.getClass() == source.getClass());
// Assert.assertTrue(resource.getUUID().compareTo(source.getUUID())==0);
// Assert.assertTrue(resource.getHeader().getUUID().compareTo(source.getHeader().getUUID())==0);
//
// Resource target = irt.getTarget();
// resourceManagement = ERManagementTest.getResourceManagement(target);
// json = resourceManagement.read();
// resource = ElementMapper.unmarshal(target.getClass(), json);
// Assert.assertTrue(resource.getClass() == target.getClass());
// Assert.assertTrue(resource.getUUID().compareTo(target.getUUID())==0);
// Assert.assertTrue(resource.getHeader().getUUID().compareTo(target.getHeader().getUUID())==0);
//
// ContextTest.setContextByName(currentContext);
// }
@ -319,4 +322,20 @@ public class MultiContextTest extends ERManagementTest {
addToContextThenTestIfBehaveProperly(isRelatedTo, false, targetContextFullName);
}
protected ContextCacheRenewal contextCacheRenewal = new ContextCacheRenewal() {
@Override
public List<Context> renew() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement();
String contextsJsonString = contextManagement.allFromServer(false);
List<Context> contexts = null;
try {
contexts = ElementMapper.unmarshalList(contextsJsonString);
} catch (IOException e) {
logger.error("Unable to read context from server", e);
}
return contexts;
}
};
}

View File

@ -5,17 +5,11 @@ import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -35,45 +29,8 @@ public class JsonQueryTest extends ContextTest {
return new File(resourcesDirectory, "queries");
}
public File getProjectionQueriesDirectory() throws Exception {
URL logbackFileURL = JsonQueryTest.class.getClassLoader().getResource("logback-test.xml");
File logbackFile = new File(logbackFileURL.toURI());
File resourcesDirectory = logbackFile.getParentFile();
return new File(resourcesDirectory, "projection-queries");
}
protected boolean compareQueries(StringBuffer createdSb, StringBuffer expectedSb) {
return compareQueries(createdSb.toString(), expectedSb.toString());
}
protected String normalizeString(String s) {
return s.replaceAll("\n{1,}", "")
.replaceAll("\r{1,}", "")
.replaceAll("\t{1,}", "")
.replaceAll("\\s{2,}", " ")
.replaceAll("\\(\\s{1,}", "(")
.replaceAll("\\s{1,}\\(", "(")
.replaceAll("\\)\\s{1,}", ")")
.replaceAll("\\s{1,}\\)", ")");
}
protected boolean compareQueries(String createdString, String expectedString) {
String created = normalizeString(createdString);
String expected = normalizeString(expectedString);
logger.debug(created);
logger.debug(expected);
return created.compareTo(expected)==0 ? true : false;
}
@Test
public void testCompares() throws Exception {
String a = "))\n\t\r ) ) ) )";
String b = "))))))";
Assert.assertTrue(compareQueries(a, b));
}
@Test
public void testQueries() throws Exception {
public void testJsonQueries() throws Exception {
ContextTest.setContextByName(DEVVRE);
File queriesDirectory = getQueriesDirectory();
@ -86,7 +43,7 @@ public class JsonQueryTest extends ContextTest {
};
for(File jsonQueryFile : queriesDirectory.listFiles(filenameFilter)) {
logger.info("Going to read JSON query from file {}", jsonQueryFile.getAbsolutePath());
logger.info("Going to read JSON query frtm file {}", jsonQueryFile.getAbsolutePath());
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
@ -99,7 +56,7 @@ public class JsonQueryTest extends ContextTest {
logger.info("Created Query from JSON: {}", createdStringBuffer.toString());
StringBuffer expectedStringBuffer = new StringBuffer();
File expectedQueryFile = new File(queriesDirectory, jsonQueryFile.getName().replace("json", "match.oquery"));
File expectedQueryFile = new File(queriesDirectory, jsonQueryFile.getName().replace("json", "query"));
try(BufferedReader br = new BufferedReader(new FileReader(expectedQueryFile))) {
for(String line; (line = br.readLine()) != null; ) {
expectedStringBuffer.append(line);
@ -107,7 +64,8 @@ public class JsonQueryTest extends ContextTest {
}
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
Assert.assertTrue(compareQueries(createdStringBuffer, expectedStringBuffer));
Assert.assertTrue(createdStringBuffer.toString().compareTo(expectedStringBuffer.toString())==0);
String result = jsonQuery.query();
logger.info("Result : {}", result);
@ -115,9 +73,9 @@ public class JsonQueryTest extends ContextTest {
}
@Test
public void testSingleQuery() throws Exception {
public void testSingleCreateQuery() throws Exception {
File queriesDirectory = getQueriesDirectory();
File jsonQueryFile = new File(queriesDirectory, "query10.json");
File jsonQueryFile = new File(queriesDirectory, "query9.json");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
logger.info("Going to test the following JSON query {}", jsonNode.toString());
@ -127,26 +85,13 @@ public class JsonQueryTest extends ContextTest {
StringBuffer createdStringBuffer = jsonQuery.createQuery();
logger.info("Created Query from JSON: {}", createdStringBuffer.toString());
StringBuffer expectedStringBuffer = new StringBuffer();
File expectedQueryFile = new File(queriesDirectory, jsonQueryFile.getName().replace("json", "match.oquery"));
try(BufferedReader br = new BufferedReader(new FileReader(expectedQueryFile))) {
for(String line; (line = br.readLine()) != null; ) {
expectedStringBuffer.append(line);
}
}
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
Assert.assertTrue(compareQueries(createdStringBuffer, expectedStringBuffer));
String result = jsonQuery.query();
logger.info("Result : {}", result);
}
protected List<Entity> testSingleQuery(int offset, int limit) throws Exception {
// @Test
public void testSingleQuery() throws Exception {
ContextTest.setContextByName(DEVVRE);
File queriesDirectory = getQueriesDirectory();
File jsonQueryFile = new File(queriesDirectory, "query1.json");
File jsonQueryFile = new File(queriesDirectory, "query3.json");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
logger.info("Going to test the following JSON query {}", jsonNode.toString());
@ -155,140 +100,6 @@ public class JsonQueryTest extends ContextTest {
jsonQuery.setJsonQuery(jsonNode);
String res = jsonQuery.query();
logger.info(res);
List<Entity> ret = ElementMapper.unmarshalList(Entity.class, res);
return ret;
}
@Test
public void testLimitOffset() throws Exception {
int limit = 2;
List<Entity> entities = testSingleQuery(0, limit);
if(entities.size()==0) {
return;
}
Assert.assertTrue(entities.size() <= limit);
if(entities.size()< limit) {
return;
}
Set<UUID> uuids = new HashSet<>();
for(Entity entity : entities) {
UUID uuid = entity.getID();
uuids.add(uuid);
logger.info("Found {} with UUID {}", Entity.NAME, uuid);
}
entities = testSingleQuery(limit, limit);
if(entities.size()>0) {
Assert.assertTrue(entities.size() <= limit);
for(Entity entity : entities) {
UUID uuid = entity.getID();
Assert.assertFalse(uuids.contains(uuid));
uuids.add(uuid);
logger.info("Found {} with UUID {}", Entity.NAME, uuid);
}
if(entities.size()<limit) {
return;
}
int doubleLimit = limit*2;
entities = testSingleQuery(0, doubleLimit);
Assert.assertTrue(entities.size() <= doubleLimit);
for(Entity entity : entities) {
UUID uuid = entity.getID();
logger.info("Checking if {} with UUID {} was contained in the previous queries", Entity.NAME, uuid);
Assert.assertTrue(uuids.contains(uuid));
logger.info("As expected got {} with UUID {} and name {}", Entity.NAME, uuid);
}
}
entities = testSingleQuery(0, -1);
Assert.assertTrue(entities.size()>=uuids.size());
for(Entity entity : entities) {
UUID uuid = entity.getID();
logger.info("No limit listing: Got {} with UUID {}", Entity.NAME, uuid);
}
}
@Test
public void testSingleProjectionQuery() throws Exception {
File queriesDirectory = getProjectionQueriesDirectory();
File jsonQueryFile = new File(queriesDirectory, "HostingNode-query.json");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
logger.info("Going to test the following JSON query {}", jsonNode.toString());
JsonQuery jsonQuery = new JsonQuery();
jsonQuery.setJsonQuery(jsonNode);
StringBuffer createdStringBuffer = jsonQuery.createMatchQuery();
logger.info("Created Query from JSON:\n{}", createdStringBuffer.toString());
StringBuffer expectedStringBuffer = new StringBuffer();
File expectedQueryFile = new File(queriesDirectory, jsonQueryFile.getName().replace("-query.json", ".match.oquery"));
try(BufferedReader br = new BufferedReader(new FileReader(expectedQueryFile))) {
for(String line; (line = br.readLine()) != null; ) {
expectedStringBuffer.append(line);
}
}
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
Assert.assertTrue(compareQueries(createdStringBuffer, expectedStringBuffer));
String result = jsonQuery.query();
logger.info("Result : {}", result);
}
@Test
public void testProjectionQueries() throws Exception {
File queriesDirectory = getProjectionQueriesDirectory();
FilenameFilter filenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith("-query.json");
}
};
for(File jsonQueryFile : queriesDirectory.listFiles(filenameFilter)) {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
logger.info("Going to test the following JSON query {}", jsonNode.toString());
JsonQuery jsonQuery = new JsonQuery();
jsonQuery.setJsonQuery(jsonNode);
StringBuffer createdStringBuffer = jsonQuery.createMatchQuery();
logger.info("Created Query from JSON:\n{}", createdStringBuffer.toString());
StringBuffer expectedStringBuffer = new StringBuffer();
File expectedQueryFile = new File(queriesDirectory, jsonQueryFile.getName().replace("-query.json", ".match.oquery"));
try(BufferedReader br = new BufferedReader(new FileReader(expectedQueryFile))) {
for(String line; (line = br.readLine()) != null; ) {
expectedStringBuffer.append(line);
}
}
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
Assert.assertTrue(compareQueries(createdStringBuffer, expectedStringBuffer));
String result = jsonQuery.query();
logger.info("Result : {}", result);
}
}
}

View File

@ -14,14 +14,14 @@ import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.utils.Utility;
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.resourcemanagement.model.impl.entities.facets.IdentifierFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.SimplePropertyFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.resources.ConfigurationImpl;
@ -57,7 +57,7 @@ public class QueryTest extends ERManagementTest {
public void testRawQuery() throws InvalidQueryException {
QueryImpl queryImpl = new QueryImpl();
String query = "SELECT FROM SoftwareFacet";
String query = "select from SoftwareFacet";
String ret = queryImpl.query(query, false);
logger.debug(ret);
@ -76,7 +76,7 @@ public class QueryTest extends ERManagementTest {
int typeNumber = 0;
for (int i = 0; i < MAX; i++) {
Map<String, Resource> map = createHostingNodeAndEService();
Map<String, Resource> map = ERManagementTest.createHostingNodeAndEService();
if (typeNumber == 0) {
typeNumber = map.size();
}
@ -150,20 +150,20 @@ public class QueryTest extends ERManagementTest {
List<Resource> resourceList = resources.get(HostingNode.NAME);
for (Resource r : resourceList) {
deleteResource(r);
ERManagementTest.deleteResource(r);
}
}
}
@Test
public void testGetAllFrom() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
Map<String, Resource> map = ERManagementTest.createHostingNodeAndEService();
EService eService = (EService) map.get(EService.NAME);
HostingNode hostingNode = (HostingNode) map.get(HostingNode.NAME);
try {
UUID eServiceUUID = eService.getID();
UUID hostingNodeUUID = hostingNode.getID();
UUID eServiceUUID = eService.getHeader().getUUID();
UUID hostingNodeUUID = hostingNode.getHeader().getUUID();
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(Service.NAME);
@ -174,13 +174,13 @@ public class QueryTest extends ERManagementTest {
List<Resource> resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1);
Resource resource = resourceList.get(0);
Assert.assertTrue(resource.getID().compareTo(hostingNodeUUID) == 0);
Assert.assertTrue(resource.getHeader().getUUID().compareTo(hostingNodeUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.OUT, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1);
resource = resourceList.get(0);
Assert.assertTrue(resource.getID().compareTo(hostingNodeUUID) == 0);
Assert.assertTrue(resource.getHeader().getUUID().compareTo(hostingNodeUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, EService.NAME, eServiceUUID, ODirection.IN, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json);
@ -202,7 +202,7 @@ public class QueryTest extends ERManagementTest {
null);
resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1);
Assert.assertTrue(resourceList.get(0).getID().compareTo(eServiceUUID) == 0);
Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.OUT, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json);
@ -211,7 +211,7 @@ public class QueryTest extends ERManagementTest {
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.IN, true, null);
resourceList = ElementMapper.unmarshalList(Resource.class, json);
Assert.assertTrue(resourceList.size() == 1);
Assert.assertTrue(resourceList.get(0).getID().compareTo(eServiceUUID) == 0);
Assert.assertTrue(resourceList.get(0).getHeader().getUUID().compareTo(eServiceUUID) == 0);
json = resourceManagement.query(IsRelatedTo.NAME, HostingNode.NAME, hostingNodeUUID, ODirection.BOTH, false,
null);
@ -229,7 +229,7 @@ public class QueryTest extends ERManagementTest {
/* END Getting HostingNode */
Facet identificationFacet = eService.getIdentificationFacets().get(0);
UUID identificationFacetUUID = identificationFacet.getID();
UUID identificationFacetUUID = identificationFacet.getHeader().getUUID();
/* EService --ConsistsOf--> SoftwareFacet */
try {
@ -245,8 +245,8 @@ public class QueryTest extends ERManagementTest {
Assert.assertTrue(resourceList.size() == 1);
resource = resourceList.get(0);
Facet targetIdentificationFacet = ((GCubeResource) resource).getIdentificationFacets().get(0);
Assert.assertTrue(resource.getID().compareTo(eServiceUUID) == 0);
Assert.assertTrue(targetIdentificationFacet.getID().compareTo(identificationFacetUUID) == 0);
Assert.assertTrue(resource.getHeader().getUUID().compareTo(eServiceUUID) == 0);
Assert.assertTrue(targetIdentificationFacet.getHeader().getUUID().compareTo(identificationFacetUUID) == 0);
try {
json = resourceManagement.query(ConsistsOf.NAME, SoftwareFacet.NAME, identificationFacetUUID, ODirection.IN,
@ -280,8 +280,8 @@ public class QueryTest extends ERManagementTest {
/* END EService --ConsistsOf--> SoftwareFacet */
} finally {
deleteResource(eService);
deleteResource(hostingNode);
ERManagementTest.deleteResource(eService);
ERManagementTest.deleteResource(hostingNode);
}
}
@ -317,7 +317,7 @@ public class QueryTest extends ERManagementTest {
IdentifierFacet identifierFacet = new IdentifierFacetImpl();
identifierFacet.setValue(name);
identifierFacet.setIdentificationType(IdentificationType.STRING);
identifierFacet.setType(IdentificationType.STRING);
if(value!=null) {
identifierFacet.setAdditionalProperty(EXTRA, value);
}
@ -330,14 +330,14 @@ public class QueryTest extends ERManagementTest {
simplePropertyFacet.setValue("test");
configuration.addFacet(simplePropertyFacet);
return createResource(configuration);
return ERManagementTest.createResource(configuration);
}
@Test
public void getAllResourcesHavingFacet() throws ObjectNotFound, Exception {
String[] names = new String[]{"MyTest", "MyTest", "Aux", "MyID", "MyID"};
Object[] additionalProperties = new Object[] {5, 6.0, false, "test", null};
Object[] additionalProperties = new Object[] {5, 5.0, false, "test", null};
List<Configuration> createdConfigurations = new ArrayList<>();
@ -346,10 +346,10 @@ public class QueryTest extends ERManagementTest {
}
try {
String parentResourceType = TypeUtility.getTypeName(ConfigurationTemplate.class);
String resourceType = TypeUtility.getTypeName(Configuration.class);
String relationType = TypeUtility.getTypeName(IsIdentifiedBy.class);
String referenceType = TypeUtility.getTypeName(IdentifierFacet.class);
String parentResourceType = Utility.getTypeName(ConfigurationTemplate.class);
String resourceType = Utility.getTypeName(Configuration.class);
String relationType = Utility.getTypeName(IsIdentifiedBy.class);
String referenceType = Utility.getTypeName(IdentifierFacet.class);
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(resourceType);
@ -366,8 +366,8 @@ public class QueryTest extends ERManagementTest {
int expectedSize = 1;
Set<UUID> expectedUUIDFor2Results = new HashSet<>();
expectedUUIDFor2Results.add(createdConfigurations.get(3).getID());
expectedUUIDFor2Results.add(createdConfigurations.get(4).getID());
expectedUUIDFor2Results.add(createdConfigurations.get(3).getHeader().getUUID());
expectedUUIDFor2Results.add(createdConfigurations.get(4).getHeader().getUUID());
for(int i=0; i<names.length; i++) {
@ -377,7 +377,7 @@ public class QueryTest extends ERManagementTest {
}
Configuration expected = createdConfigurations.get(i);
UUID expectedUUID = expected.getID();
UUID expectedUUID = expected.getHeader().getUUID();
for(Boolean polymorphic : polymorphics) {
@ -398,12 +398,12 @@ public class QueryTest extends ERManagementTest {
Assert.assertTrue(list.size()==expectedSize);
if(expectedSize==1) {
Configuration configuration = list.get(0);
UUID gotUUID = configuration.getID();
UUID gotUUID = configuration.getHeader().getUUID();
Assert.assertTrue(gotUUID.compareTo(expectedUUID)==0);
}else {
Set<UUID> gotUUIDs = new HashSet<>();
for(Configuration c : list) {
gotUUIDs.add(c.getID());
gotUUIDs.add(c.getHeader().getUUID());
}
Assert.assertTrue(gotUUIDs.containsAll(expectedUUIDFor2Results));
@ -425,13 +425,13 @@ public class QueryTest extends ERManagementTest {
if(expectedSize==1) {
ConfigurationTemplate configurationTemplate = listPolimorphic.get(0);
Assert.assertTrue(configurationTemplate instanceof Configuration);
UUID gotPolimorphicUUID = configurationTemplate.getID();
UUID gotPolimorphicUUID = configurationTemplate.getHeader().getUUID();
Assert.assertTrue(gotPolimorphicUUID.compareTo(expectedUUID)==0);
}else {
Set<UUID> gotUUIDs = new HashSet<>();
for(ConfigurationTemplate c : listPolimorphic) {
Assert.assertTrue(c instanceof Configuration);
gotUUIDs.add(c.getID());
gotUUIDs.add(c.getHeader().getUUID());
}
Assert.assertTrue(gotUUIDs.containsAll(expectedUUIDFor2Results));
@ -448,7 +448,7 @@ public class QueryTest extends ERManagementTest {
}
} finally {
for(Configuration configuration : createdConfigurations) {
deleteResource(configuration);
ERManagementTest.deleteResource(configuration);
}
}

View File

@ -1,38 +0,0 @@
package org.gcube.informationsystem.resourceregistry.queries.operators;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MathematicsOperatorTest {
protected static Logger logger = LoggerFactory.getLogger(MathematicsOperatorTest.class);
public static final String JSON = "{ \n"
+ " \"values\" : [\n"
+ " {\n"
+ " \"_minus\" : [\n"
+ " \"size\", \n"
+ " \"used\" \n"
+ " ]\n"
+ " },\n"
+ " \"unit\" \n"
+ " ],\n"
+ " \"separator\" : \" \",\n"
+ " \"as\" : \"HD Space Left\"\n"
+ "}";
@Test
public void testGenerateFieldToEmit() throws Exception {
ObjectMapper om = new ObjectMapper();
JsonNode jn = om.readTree(JSON);
String s = MatemathicsOperator.SUM.generateFieldToEmit(jn, "haspersistentmemory20");
logger.debug(s);
}
}

View File

@ -5,16 +5,14 @@ import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.BadRequestException;
import org.gcube.com.fasterxml.jackson.databind.JavaType;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.queries.templates.impl.entities.QueryTemplateImpl;
import org.gcube.informationsystem.queries.templates.impl.properties.TemplateVariableImpl;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
@ -22,8 +20,7 @@ import org.gcube.informationsystem.queries.templates.reference.properties.Templa
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateAlreadyPresentException;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -41,44 +38,39 @@ public class QueryTemplateManagementTest extends ContextTest {
public static final String NAME_VARIABLE_NAME = "$name";
public static final String GROUP_VARIABLE_NAME = "$group";
public static void checkUUIDAndMetadata(IdentifiableElement previous, IdentifiableElement got) {
Assert.assertTrue(got.getID()!= null);
if(previous.getID()!=null) {
Assert.assertTrue(got.getID().compareTo(previous.getID()) == 0);
public static void checkHeader(IdentifiableElement previous, IdentifiableElement got) {
Header gotHeader = got.getHeader();
Header previousHeader = previous.getHeader();
Assert.assertTrue(gotHeader != null);
Assert.assertTrue(gotHeader.getUUID() != null);
String user = SecretManagerProvider.instance.get().getOwner().getId();
Assert.assertTrue(gotHeader.getLastUpdateBy().compareTo(user) == 0);
if(previousHeader != null) {
Assert.assertTrue(gotHeader.getUUID().compareTo(previousHeader.getUUID()) == 0);
Assert.assertTrue(gotHeader.getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(gotHeader.getCreatedBy().compareTo(previousHeader.getCreatedBy()) == 0);
Assert.assertTrue(gotHeader.getCreationTime().compareTo(previousHeader.getCreationTime()) == 0);
}
Metadata gotMetadata = got.getMetadata();
Metadata previousMetadata = previous.getMetadata();
Assert.assertTrue(gotMetadata != null);
String user = ContextTest.getUser();
Assert.assertTrue(gotMetadata.getLastUpdateBy().compareTo(user) == 0);
if(previousMetadata != null) {
Assert.assertTrue(gotMetadata.getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(gotMetadata.getCreatedBy().compareTo(previousMetadata.getCreatedBy()) == 0);
Assert.assertTrue(gotMetadata.getCreationTime().compareTo(previousMetadata.getCreationTime()) == 0);
}
Assert.assertFalse(gotMetadata.getCreationTime().after(gotMetadata.getLastUpdateTime()));
Assert.assertFalse(gotHeader.getCreationTime().after(gotHeader.getLastUpdateTime()));
}
protected void assertions(QueryTemplate expected, QueryTemplate got) {
checkUUIDAndMetadata(expected, got);
checkHeader(expected, got);
Assert.assertTrue(expected.getName().compareTo(got.getName()) == 0);
Assert.assertTrue(expected.getDescription().compareTo(got.getDescription()) == 0);
// Template and TemplateVariable should be compared
}
protected QueryTemplate create(QueryTemplate queryTemplate) throws ResourceRegistryException, IOException {
//list();
list();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
String json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
String created = queryTemplateManagement.create();
@ -86,7 +78,7 @@ public class QueryTemplateManagementTest extends ContextTest {
QueryTemplate createdQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, created);
assertions(queryTemplate, createdQueryTemplate);
// list(createdQueryTemplate);
list(createdQueryTemplate);
return createdQueryTemplate;
}
@ -299,102 +291,4 @@ public class QueryTemplateManagementTest extends ContextTest {
logger.debug("The DB should be now clean");
}
@Test(expected = QueryTemplateAlreadyPresentException.class)
public void doubleCreateTest() throws Exception {
QueryTemplate queryTemplate = getQueryTemplate();
try {
create(queryTemplate);
logger.info("Created {} with name '{}'", QueryTemplate.NAME, queryTemplate.getName());
create(queryTemplate);
throw new Exception("The second create should fails. You should not be here");
} catch (QueryTemplateAlreadyPresentException e) {
logger.info("As expected {} with name '{}' already exists", QueryTemplate.NAME, queryTemplate.getName());
throw e;
}finally {
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.delete();
logger.info("{} with name '{}' successfully deleted", QueryTemplate.NAME, queryTemplate.getName());
logger.debug("The DB should be now clean");
}
}
@Test
public void createUpdateTest() throws Exception {
QueryTemplate queryTemplate = getQueryTemplate();
try {
QueryTemplate createdQueryTemplate = create(queryTemplate);
// test no UUID
logger.info("Created {} with name '{}'", QueryTemplate.NAME, createdQueryTemplate.getName());
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
String updatedDescription = "My 1st udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
String json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
String updated = queryTemplateManagement.createOrUpdate();
logger.info("Updated {} is {}", QueryTemplate.NAME, updated);
QueryTemplate updatedQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, updated);
Assert.assertTrue(updatedQueryTemplate.getDescription().compareTo(updatedDescription)==0);
// test UUID null
queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
updatedDescription = "My 2nd udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
queryTemplate.setID(null);
json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
updated = queryTemplateManagement.createOrUpdate();
logger.info("Updated {} is {}", QueryTemplate.NAME, updated);
updatedQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, updated);
Assert.assertTrue(updatedQueryTemplate.getDescription().compareTo(updatedDescription)==0);
// test UUID same
queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
updatedDescription = "My 3rd udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
queryTemplate.setID(createdQueryTemplate.getID());
json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
updated = queryTemplateManagement.createOrUpdate();
logger.info("Updated {} is {}", QueryTemplate.NAME, updated);
updatedQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, updated);
Assert.assertTrue(updatedQueryTemplate.getDescription().compareTo(updatedDescription)==0);
// test another UUID
queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
updatedDescription = "My 4th udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
queryTemplate.setID(UUID.randomUUID());
json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
try {
updated = queryTemplateManagement.createOrUpdate();
throw new Exception("Trying to udpate the " + QueryTemplate.NAME + " using a different " + QueryTemplate.ID_PROPERTY + " must fails. Please check your code");
}catch (ResourceRegistryException e) {
logger.info("Trying to update {} with name '{}' failed as expected : {} ", QueryTemplate.NAME, queryTemplate.getName(), e.getMessage());
}
}finally {
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.delete();
logger.info("{} with name '{}' successfully deleted", QueryTemplate.NAME, queryTemplate.getName());
logger.debug("The DB should be now clean");
}
}
}

View File

@ -31,7 +31,7 @@ public class AnotherEnhancedTest extends MultiContextTest {
// JsonNode jsonNode = ElementMapper.getObjectMapper().readTree(json);
//
// Map<UUID, JsonNode> expectedInstances = new HashMap<>();
// expectedInstances.put(eService.getUUID(), jsonNode);
// expectedInstances.put(eService.getHeader().getUUID(), jsonNode);
//
// UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(ALTERNATIVE_TEST_SCOPE).getUUID();
//
@ -45,7 +45,7 @@ public class AnotherEnhancedTest extends MultiContextTest {
// IsIdentifiedBy<EService, Facet> gotIsIdentifiedBy = (IsIdentifiedBy<EService, Facet>) eService.getConsistsOf(IsIdentifiedBy.class).get(0);
//
// JsonNode gotIsIdentifiedByJsonNode = ElementMapper.getObjectMapper().readTree(ElementMapper.marshal(gotIsIdentifiedBy));
// expectedInstances.put(gotIsIdentifiedBy.getUUID(), gotIsIdentifiedByJsonNode);
// expectedInstances.put(gotIsIdentifiedBy.getHeader().getUUID(), gotIsIdentifiedByJsonNode);
//
// try {
// ERManagementUtility.addToContextNoPropagationConstraint(expectedInstances, contextUUID, true);

View File

@ -5,7 +5,7 @@ import java.util.UUID;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.resourceregistry.instances.multicontext.MultiContextTest;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl;
import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet;
import org.junit.Assert;
@ -40,28 +40,27 @@ public class FacetManagementTest extends MultiContextTest {
Assert.assertTrue(softwareFacet.getVersion().compareTo(version) == 0);
}
public static void checkUUIDAndMetadata(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getID() != null);
public static void checkHeader(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader() != null);
Assert.assertTrue(er.getHeader().getUUID() != null);
if(uuid != null) {
Assert.assertTrue(er.getID().compareTo(uuid) == 0);
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0);
}
Assert.assertTrue(er.getMetadata() != null);
String user = MetadataUtility.getUser();
Assert.assertTrue(er.getMetadata().getLastUpdateBy().compareTo(user) == 0);
String user = HeaderUtility.getUser();
Assert.assertTrue(er.getHeader().getLastUpdateBy().compareTo(user) == 0);
if(create) {
Assert.assertTrue(er.getMetadata().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getMetadata().getCreationTime().compareTo(er.getMetadata().getLastUpdateTime()) == 0);
Assert.assertTrue(er.getHeader().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
} else {
Assert.assertTrue(er.getMetadata().getCreationTime().before(er.getMetadata().getLastUpdateTime()));
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
}
}
public static void checkAssertion(Facet facet, UUID uuid, boolean create) {
checkUUIDAndMetadata(facet, uuid, create);
checkHeader(facet, uuid, create);
}
//
// protected <F extends Facet> F create(F facet) throws Exception {
@ -76,7 +75,10 @@ public class FacetManagementTest extends MultiContextTest {
// F createdFacet = (F) ElementMapper.unmarshal(facet.getClass(), json);
// logger.debug("Unmarshalled {}", createdFacet);
//
// UUID uuid = facet.getUUID();
// UUID uuid = null;
// if(facet.getHeader() != null) {
// uuid = facet.getHeader().getUUID();
// }
// checkAssertion(createdFacet, uuid, true);
// return createdFacet;
// }
@ -93,14 +95,14 @@ public class FacetManagementTest extends MultiContextTest {
// F updatedFacet = (F) ElementMapper.unmarshal(facet.getClass(), json);
// logger.debug("Unmarshalled {}", updatedFacet);
//
// UUID uuid = facet.getUUID();
// UUID uuid = facet.getHeader().getUUID();
// checkAssertion(updatedFacet, uuid, false);
//
// return updatedFacet;
// }
//
// protected <F extends Facet> F read(F facet) throws Exception {
// UUID uuid = facet.getUUID();
// UUID uuid = facet.getHeader().getUUID();
//
// FacetManagement facetManagement = new FacetManagement();
// String facetType = Utility.getTypeName(facet);
@ -122,7 +124,7 @@ public class FacetManagementTest extends MultiContextTest {
// FacetManagement facetManagement = new FacetManagement();
// String facetType = Utility.getTypeName(facet);
// facetManagement.setElementType(facetType);
// facetManagement.setUUID(facet.getUUID());
// facetManagement.setUUID(facet.getHeader().getUUID());
//
// facetManagement.delete();
//
@ -137,11 +139,11 @@ public class FacetManagementTest extends MultiContextTest {
// FacetManagement facetManagement = new FacetManagement();
// String facetType = Utility.getTypeName(facet);
// facetManagement.setElementType(facetType);
// facetManagement.setUUID(facet.getUUID());
// facetManagement.setUUID(facet.getHeader().getUUID());
//
// facetManagement.addToContext(ContextUtility.getCurrentSecurityContext().getUUID());
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
// Assert.assertTrue(affectedInstances.containsKey(facet.getHeader().getUUID()));
// Assert.assertTrue(affectedInstances.size()==1);
//
// return affectedInstances;
@ -151,11 +153,11 @@ public class FacetManagementTest extends MultiContextTest {
// FacetManagement facetManagement = new FacetManagement();
// String facetType = Utility.getTypeName(facet);
// facetManagement.setElementType(facetType);
// facetManagement.setUUID(facet.getUUID());
// facetManagement.setUUID(facet.getHeader().getUUID());
//
// facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
// Assert.assertTrue(affectedInstances.containsKey(facet.getHeader().getUUID()));
// Assert.assertTrue(affectedInstances.size()==1);
//
// return affectedInstances;

View File

@ -5,10 +5,10 @@ import java.util.Arrays;
import java.util.List;
import java.util.ServiceLoader;
import org.gcube.informationsystem.discovery.Discovery;
import org.gcube.informationsystem.discovery.RegistrationProvider;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.utils.discovery.ElementSpecilizationDiscovery;
import org.gcube.informationsystem.utils.discovery.RegistrationProvider;
import org.gcube.resourcemanagement.model.reference.entities.resources.Actor;
import org.gcube.resourcemanagement.model.reference.entities.resources.ConcreteDataset;
import org.gcube.resourcemanagement.model.reference.entities.resources.Configuration;
@ -49,7 +49,7 @@ public class DiscoveryTest {
}
Package[] packagesArray = packages.stream().toArray(Package[]::new);
Discovery<Resource> resourceDiscovery = new Discovery<>(Resource.class);
ElementSpecilizationDiscovery<Resource> resourceDiscovery = new ElementSpecilizationDiscovery<>(Resource.class);
Arrays.stream(packagesArray).forEach(p -> resourceDiscovery.addPackage(p));
resourceDiscovery.discover();
@ -74,10 +74,10 @@ public class DiscoveryTest {
expected.add(VirtualMachine.class);
expected.add(VirtualService.class);
List<Class<Resource>> found = resourceDiscovery.getDiscoveredElements();
List<Class<? extends Resource>> found = resourceDiscovery.getDiscovered();
for (Class<Resource> resourceClass : found) {
String typeDefinition = TypeMapper.serializeType(resourceClass);
for (Class<? extends Resource> resource : found) {
String typeDefinition = TypeMapper.serializeType(resource);
logger.debug(typeDefinition);
}

View File

@ -14,8 +14,7 @@ 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.Metadata;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
@ -53,7 +52,7 @@ public class SchemaManagementImplTest extends ContextTest {
@Test
public void registerPropertyTypeSchema() throws Exception {
Class<? extends PropertyElement> clz = Metadata.class;
Class<? extends PropertyElement> clz = Header.class;
String json = TypeMapper.serializeType(clz);
logger.debug(json);
//new SchemaManagementImpl().create(json, AccessType.PROPERTY);
@ -284,8 +283,8 @@ public class SchemaManagementImplTest extends ContextTest {
Assert.assertTrue(type.getDescription().compareTo(typeManaged.getDescription())==0);
Assert.assertTrue(type.isAbstract() == typeManaged.isAbstract());
Assert.assertTrue(type.getExtendedTypes().containsAll(typeManaged.getExtendedTypes()));
Assert.assertTrue(typeManaged.getExtendedTypes().containsAll(type.getExtendedTypes()));
Assert.assertTrue(type.getSuperClasses().containsAll(typeManaged.getSuperClasses()));
Assert.assertTrue(typeManaged.getSuperClasses().containsAll(type.getSuperClasses()));
Map<Version, String> typeChangelog = type.getChangelog();
@ -389,15 +388,4 @@ public class SchemaManagementImplTest extends ContextTest {
typeManagement.setTypeName(TestFacet.NAME);
typeManagement.delete(AccessType.FACET);
}
// @Test
public void updateType() throws Exception {
Type type = TypeMapper.createTypeDefinition(PropagationConstraint.class);
logger.info("Going to update {} : {}", type.getName(), TypeMapper.serializeTypeDefinition(type));
String ret = update(PropagationConstraint.class, true);
logger.info("Updated {} : {}", type.getName(), ret);
Type typeManaged = TypeMapper.deserializeTypeDefinition(ret);
compareTypes(type, typeManaged);
}
}

View File

@ -32,7 +32,7 @@ public class TypesCacheTest {
CachedType<?> cachedType = getCachedType(typesCache, typeName);
List<String> superTypes = cachedType.getSuperTypes();
logger.debug("{} typeSuperTypes are {}", typeName, superTypes);
logger.debug("{} superTypes are {}", typeName, superTypes);
for(String superType : superTypes) {
getCachedType(typesCache, superType);
}

View File

@ -1,38 +1,38 @@
{
"type": "EService",
"@class": "EService",
"consistsOf": [
{
"type": "ConsistsOf",
"@class": "ConsistsOf",
"propagationConstraint" : {
"add": "propagate"
},
"target": {
"type": "StateFacet",
"@class": "StateFacet",
"value": "down"
}
},
{
"type": "IsIdentifiedBy",
"@class": "IsIdentifiedBy",
"target": {
"type": "SoftwareFacet",
"@class": "SoftwareFacet",
"name": "data-transfer-service",
"group": "DataTransfer"
}
},
{
"type": "ConsistsOf",
"@class": "ConsistsOf",
"target": {
"type": "AccessPointFacet",
"@class": "AccessPointFacet",
"endpoint": "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
}
}
],
"isRelatedTo" : [
{
"type": "activates",
"@class": "activates",
"source": {
"type": "HostingNode"
"@class": "HostingNode"
}
}
]
@ -76,7 +76,7 @@ SELECT FROM (
)
)
// WHERE type="EService"
// WHERE @class="EService"
@ -111,7 +111,7 @@ SELECT FROM (
) WHERE endpoint="http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
)
)
) WHERE type="EService"
) WHERE @class="EService"
@ -131,7 +131,7 @@ SELECT FROM (
)
) WHERE endpoint="http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
)
) WHERE type="EService"
) WHERE @class="EService"
// Generated from code:
@ -163,7 +163,7 @@ SELECT FROM (
)
// This is validated by the code to get polymorphic result
// WHERE type="EService"
// WHERE @class="EService"
MATCH

View File

@ -14,10 +14,7 @@
<logger name="org.gcube.informationsystem.types" level="INFO" />
<logger name="org.gcube.informationsystem.resourceregistry.dbinitialization" level="INFO" />
<logger name="org.gcube.informationsystem.utils.discovery" level="ERROR" />
<logger name="org.gcube.informationsystem.resourceregistry" level="TRACE" />
<logger name="org.gcube.informationsystem.resourceregistry.contexts" level="INFO" />
<logger name="org.gcube.informationsystem.resourceregistry.types" level="INFO" />
<logger name="org.gcube.informationsystem.resourceregistry.instances" level="TRACE" />
<root level="WARN">
<appender-ref ref="STDOUT" />

View File

@ -1,10 +0,0 @@
[
{
"Id" : "",
"Group": "",
"Name" : "",
"Version" : "",
"Status" : "",
"Host" ""
}
]

View File

@ -1,47 +0,0 @@
{
"type": "EService",
"_emit": {
"id": "ID"
},
"consistsOf": [
{
"type": "IsIdentifiedBy",
"target": {
"type": "SoftwareFacet",
"_emit": {
"group": "Group",
"name": "Name",
"version": "Version"
}
}
},
{
"type": "ConsistsOf",
"target": {
"type": "StateFacet",
"_emit": {
"value": "Status"
}
}
}
],
"isRelatedTo": [
{
"type": "Activates",
"source": {
"type": "HostingNode",
"consistsOf": [
{
"type": "IsIdentifiedBy",
"target": {
"type": "NetworkingFacet",
"_emit": {
"hostName": "Host"
}
}
}
]
}
}
]
}

View File

@ -1,29 +0,0 @@
MATCH
{class: EService, as: eservice0, where: ($currentMatch['@class'] INSTANCEOF 'EService')}
.inE('Activates') { as: activates00, where: ($currentMatch['@class'] INSTANCEOF 'Activates')}
.outV('HostingNode') { as: hostingnode000, where: ($currentMatch['@class'] INSTANCEOF 'HostingNode')}
.outE('IsIdentifiedBy') { as: isidentifiedby0000, where: ($currentMatch['@class'] INSTANCEOF 'IsIdentifiedBy')}
.inV('NetworkingFacet') { as: networkingfacet00000, where: ($currentMatch['@class'] INSTANCEOF 'NetworkingFacet')}
.inE('IsIdentifiedBy') { where: ($matched.isidentifiedby0000 == $currentMatch)}
.outV('HostingNode') { where: ($matched.hostingnode000 == $currentMatch)}
.outE('Activates') { where: ($matched.activates00 == $currentMatch)}
.inV('EService') { where: ($matched.eservice0 == $currentMatch)}
.outE('IsIdentifiedBy') { as: isidentifiedby01, where: ($currentMatch['@class'] INSTANCEOF 'IsIdentifiedBy')}
.inV('SoftwareFacet') { as: softwarefacet010, where: ($currentMatch['@class'] INSTANCEOF 'SoftwareFacet')}
.inE('IsIdentifiedBy') { where: ($matched.isidentifiedby01 == $currentMatch)}
.outV('EService') { where: ($matched.eservice0 == $currentMatch)}
.outE('ConsistsOf') { as: consistsof02, where: ($currentMatch['@class'] INSTANCEOF 'ConsistsOf')}
.inV('StateFacet') { as: statefacet020, where: ($currentMatch['@class'] INSTANCEOF 'StateFacet')}
.inE('ConsistsOf') { where: ($matched.consistsof02 == $currentMatch)}
.outV('EService') { where: ($matched.eservice0 == $currentMatch)}
RETURN
networkingfacet00000.hostName AS `Host`,
softwarefacet010.group AS `Group`,
softwarefacet010.name AS `Name`,
softwarefacet010.version AS `Version`,
statefacet020.value AS `Status`,
eservice0.id AS `ID`

View File

@ -1,18 +0,0 @@
[
{
"id" : "",
"Last Update Time": "",
"HostName" : "",
"Status" : "",
"HD Space Left" : "34 Gb",
"Mem. Available." "1,23 Gb"
},
{
"id" : "",
"Last Update Time": "",
"HostName" : "",
"Status" : "",
"HD Space Left" : "42 Gb",
"Mem. Available." "2,54 Gb"
}
]

View File

@ -1,65 +0,0 @@
{
"type": "HostingNode",
"_emit" : {
"id" : "ID"
},
"metadata" : {
"_emit" : {
"lastUpdateTime" : "Last Update Time"
}
},
"consistsOf": [
{
"type": "IsIdentifiedBy",
"target": {
"type": "NetworkingFacet",
"_emit" : {
"hostName" : "HostName"
}
}
},
{
"type": "ConsistsOf",
"target": {
"type": "StateFacet",
"_emit" : {
"value" : "Status"
}
}
},
{
"type": "HasPersistentMemory",
"target": {
"type": "MemoryFacet",
"_sum" : {
"values" : [
{
"_minus" : [
"size",
"used"
]
},
"unit"
],
"separator" : " ",
"as" : "HD Space Left"
}
}
},
{
"type": "HasVolatileMemory",
"target": {
"type": "MemoryFacet",
"jvmMaxMemory" : null,
"_sum" : {
"values" : [
"size",
"unit"
],
"separator" : " ",
"as" : "Mem. Available."
}
}
}
]
}

View File

@ -1,30 +0,0 @@
MATCH
{class: HostingNode, as: hostingnode0, where: ($currentMatch['@class'] INSTANCEOF 'HostingNode')}
.outE('IsIdentifiedBy') { as: isidentifiedby00, where: ($currentMatch['@class'] INSTANCEOF 'IsIdentifiedBy')}
.inV('NetworkingFacet') { as: networkingfacet000, where: ($currentMatch['@class'] INSTANCEOF 'NetworkingFacet')}
.inE('IsIdentifiedBy') { where: ($matched.isidentifiedby00 == $currentMatch)}
.outV('HostingNode') { where: ($matched.hostingnode0 == $currentMatch)}
.outE('ConsistsOf') { as: consistsof01, where: ($currentMatch['@class'] INSTANCEOF 'ConsistsOf')}
.inV('StateFacet') { as: statefacet010, where: ($currentMatch['@class'] INSTANCEOF 'StateFacet')}
.inE('ConsistsOf') { where: ($matched.consistsof01 == $currentMatch)}
.outV('HostingNode') { where: ($matched.hostingnode0 == $currentMatch)}
.outE('HasPersistentMemory') { as: haspersistentmemory02, where: ($currentMatch['@class'] INSTANCEOF 'HasPersistentMemory')}
.inV('MemoryFacet') { as: memoryfacet020, where: ($currentMatch['@class'] INSTANCEOF 'MemoryFacet')}
.inE('HasPersistentMemory') { where: ($matched.haspersistentmemory02 == $currentMatch)}
.outV('HostingNode') { where: ($matched.hostingnode0 == $currentMatch)}
.outE('HasVolatileMemory') { as: hasvolatilememory03, where: ($currentMatch['@class'] INSTANCEOF 'HasVolatileMemory')}
.inV('MemoryFacet') { as: memoryfacet030, where: (($currentMatch['@class'] INSTANCEOF 'MemoryFacet') AND (jvmMaxMemory IS null))}
.inE('HasVolatileMemory') { where: ($matched.hasvolatilememory03 == $currentMatch)}
.outV('HostingNode') { where: ($matched.hostingnode0 == $currentMatch)}
RETURN
networkingfacet000.hostName AS `HostName`,
statefacet010.value AS `Status`,
((memoryfacet020.size - memoryfacet020.used) + ' ' + memoryfacet020.unit) AS `HD Space Left`,
(memoryfacet030.size + ' ' + memoryfacet030.unit) AS `Mem. Available.`,
hostingnode0.id AS `ID`,
hostingnode0.metadata.lastUpdateTime AS `Last Update Time`

View File

@ -1,20 +1,20 @@
{
"type": "EService",
"@class": "EService",
"consistsOf": [
{
"type": "ConsistsOf",
"@class": "ConsistsOf",
"propagationConstraint" : {
"add": "propagate"
},
"target": {
"type": "StateFacet",
"@class": "StateFacet",
"value": "down"
}
},
{
"type": "IsIdentifiedBy",
"@class": "IsIdentifiedBy",
"target": {
"type": "SoftwareFacet",
"@class": "SoftwareFacet",
"name": "data-transfer-service",
"group": "DataTransfer"
}

View File

@ -1,17 +0,0 @@
SELECT EXPAND(ret) FROM (
MATCH
{class: EService, as: eservice0, where: ($currentMatch['@class'] INSTANCEOF 'EService')}
.outE('ConsistsOf') { as: consistsof00, where: (($currentMatch['@class'] INSTANCEOF 'ConsistsOf') AND (propagationConstraint.add = "propagate"))}
.inV('StateFacet') { as: statefacet000, where: (($currentMatch['@class'] INSTANCEOF 'StateFacet') AND (value = "down"))}
.inE('ConsistsOf') { where: ($matched.consistsof00 == $currentMatch)}
.outV('EService') { where: ($matched.eservice0 == $currentMatch)}
.outE('IsIdentifiedBy') { as: isidentifiedby01, where: ($currentMatch['@class'] INSTANCEOF 'IsIdentifiedBy')}
.inV('SoftwareFacet') { as: softwarefacet010, where: (($currentMatch['@class'] INSTANCEOF 'SoftwareFacet') AND (name = "data-transfer-service" AND group = "DataTransfer"))}
.inE('IsIdentifiedBy') { where: ($matched.isidentifiedby01 == $currentMatch)}
.outV('EService') { where: ($matched.eservice0 == $currentMatch)}
RETURN
DISTINCT(eservice0) as ret
)

View File

@ -0,0 +1 @@
TRAVERSE outV("EService") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM ( TRAVERSE inV("SoftwareFacet") FROM ( TRAVERSE outE("IsIdentifiedBy") FROM ( TRAVERSE outV("EService") FROM ( SELECT FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM StateFacet WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))

View File

@ -1,19 +0,0 @@
SELECT FROM (
TRAVERSE outV("EService") FROM (
TRAVERSE inE("IsIdentifiedBy") FROM (
SELECT FROM (
TRAVERSE inV("SoftwareFacet") FROM (
TRAVERSE outE("IsIdentifiedBy") FROM (
TRAVERSE outV("EService") FROM (
SELECT FROM (
TRAVERSE inE("ConsistsOf") FROM (
SELECT FROM StateFacet WHERE value = "down"
)
) WHERE propagationConstraint.add = "propagate"
)
)
)
) WHERE name = "data-transfer-service" AND group = "DataTransfer"
)
)
) WHERE @class INSTANCEOF "EService"

Some files were not shown because too many files have changed in this diff Show More