Merge remote-tracking branch 'origin/feature/24648'

This commit is contained in:
luca.frosini 2023-11-09 17:55:00 +01:00
commit 0878cdd7bd
57 changed files with 1722 additions and 943 deletions

View File

@ -2,6 +2,12 @@ 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]
@ -15,13 +21,13 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
- 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]
- 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]

16
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry</artifactId>
<version>4.3.0</version>
<version>4.4.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>
@ -101,6 +101,20 @@
<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

@ -85,7 +85,9 @@ public class ServerContextCache extends ContextCache {
@Override
public List<Context> renew() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement();
String contextsJsonString = contextManagement.allFromServer(false);
contextManagement.setForceOffset(0);
contextManagement.setForceLimit(-1);
String contextsJsonString = contextManagement.allFromDatabase(false);
List<Context> contexts = null;
try {
contexts = ElementMapper.unmarshalList(contextsJsonString);
@ -144,7 +146,7 @@ public class ServerContextCache extends ContextCache {
}
@Override
protected void setContexts(List<Context> contexts) {
public void setContexts(List<Context> contexts) {
this.contexts = new ArrayList<>();
this.contextsNoMeta = new ArrayList<>();
this.contextsMetaPrivacy = new ArrayList<>();

View File

@ -1,5 +1,6 @@
package org.gcube.informationsystem.resourceregistry.contexts.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@ -31,8 +32,10 @@ import org.gcube.informationsystem.resourceregistry.contexts.relations.IsParentO
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.QueryConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.ConditionalOperator;
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.types.reference.entities.EntityType;
@ -56,6 +59,16 @@ 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);
@ -63,6 +76,8 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
this.typeName = Context.NAME;
this.forceIncludeMeta = true;
this.forceIncludeAllMeta = true;
this.forceOffset = null;
this.forceLimit = null;
}
public ContextManagement() {
@ -127,13 +142,13 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
select.append(parentId);
select.append(" MAXDEPTH 1) WHERE ");
select.append(Context.NAME_PROPERTY);
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
select.append(ConditionalOperator.EQ.getConditionalOperator());
select.append("\"");
select.append(getName());
select.append("\"");
select.append(QueryLogicalOperator.AND.getLogicalOperator());
select.append(LogicalOperator.AND.getLogicalOperator());
select.append(IdentifiableElement.ID_PROPERTY);
select.append(QueryConditionalOperator.NE.getConditionalOperator());
select.append(ConditionalOperator.NE.getConditionalOperator());
select.append("\"");
select.append(parentContext.uuid);
select.append("\"");
@ -149,11 +164,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
select.append(Context.NAME);
select.append(" WHERE ");
select.append(Context.NAME_PROPERTY);
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
select.append(ConditionalOperator.EQ.getConditionalOperator());
select.append("\"");
select.append(getName());
select.append("\"");
select.append(QueryLogicalOperator.AND.getLogicalOperator());
select.append(LogicalOperator.AND.getLogicalOperator());
select.append("in(\"");
select.append(IsParentOf.NAME);
select.append("\").size() = 0");
@ -412,8 +427,35 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
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);
@ -421,6 +463,9 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
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);
@ -433,7 +478,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
}
public String allFromServer(boolean polymorphic) throws ResourceRegistryException {
public String allFromDatabase(boolean polymorphic) throws ResourceRegistryException {
return super.all(polymorphic);
}
@ -442,9 +487,45 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
try {
ServerContextCache contextCache = ServerContextCache.getInstance();
List<Context> contexts = contextCache.getContexts();
return ElementMapper.marshal(contexts);
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);
} catch (JsonProcessingException | ResourceRegistryException e) {
return allFromServer(polymorphic);
return allFromDatabase(polymorphic);
}
}

View File

@ -83,6 +83,7 @@ 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;
@ -166,6 +167,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(ElementManagement.AT);
this.ignoreStartWithKeys.add(ElementManagement.UNDERSCORE);
this.ignoreStartWithKeys.add(ElementManagement.DOLLAR);
this.reload = false;

View File

@ -52,6 +52,7 @@ 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);
}

View File

@ -1,11 +1,7 @@
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;
@ -26,7 +22,6 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
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;
@ -38,14 +33,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.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;
@ -154,8 +149,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
this.relationManagements = new HashMap<>();
/*
* By the default the system honour the propagation constraints
* so this variable is initialised as true.
* By the default the system honor the propagation constraints
* so this variable is initialized as true.
*/
this.honourPropagationConstraintsInContextSharing = true;
@ -495,212 +490,34 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
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;
}
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);
}
}
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();
}
*/
entityManagement.setAsEntryPoint();
JsonNode node = entityManagement.serializeAsJsonNode();
arrayNode.add(node);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
}
}
try {
return objectMapper.writeValueAsString(arrayNode);
@ -709,7 +526,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
}
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
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();
@ -718,77 +535,89 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
constraint.put(Entity.ID_PROPERTY, referenceUUID.toString());
}
// TODO check types
/*
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
* FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
* SELECT FROM (
* TRAVERSE outV('EService'), inE('isIdentifiedBy') FROM (
* SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'
* )
* )
*
* WHERE type='EService' // Only is not polymorphic
* WHERE @class INSTANCEOF 'EService' // if polymorphic is true
*
* WHERE @class='EService' // if polymorphic is false
*/
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);
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);
boolean first = true;
for(String key : constraint.keySet()) {
if(first) {
selectStringBuilder.append(" WHERE ");
selectStringBuffer.append(" WHERE ");
first = false;
} else {
selectStringBuilder.append(" AND ");
selectStringBuffer.append(" AND ");
}
selectStringBuilder.append(key);
selectStringBuilder.append("=");
selectStringBuffer.append(key);
selectStringBuffer.append("=");
String value = constraint.get(key).trim();
selectStringBuilder.append("'");
selectStringBuilder.append(value);
selectStringBuilder.append("'");
selectStringBuffer.append("'");
selectStringBuffer.append(value);
selectStringBuffer.append("'");
}
selectStringBuilder.append(" ))");
selectStringBuffer.append(" ))");
if(!polymorphic) {
selectStringBuilder.append(" WHERE type='");
selectStringBuilder.append(typeName);
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;
}
String select = selectStringBuilder.toString();
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();
logger.trace(select);
OResultSet resultSet = oDatabaseDocument.command(select,new HashMap<>());
OResultSet resultSet = oDatabaseDocument.command(select, map);
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(),
OrientDBUtility.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(),
@ -816,10 +645,6 @@ 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

@ -39,6 +39,8 @@ 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;
@ -777,11 +779,23 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
}
protected Collection<JsonNode> serializeEdges(Iterable<ODocument> edges, boolean postFilterPolymorphic)
private 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)) {
@ -792,6 +806,9 @@ 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

@ -37,7 +37,7 @@ public class QueryImpl implements Query {
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.begin();
logger.debug("Going to execute query '{} limit {}'", query);
logger.debug("Going to execute query '{}'", query);
OResultSet resultSet = oDatabaseDocument.query(query);

View File

@ -23,7 +23,8 @@ 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.types.CachedType;
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.OrientDBUtility;
import org.gcube.informationsystem.utils.TypeUtility;
@ -42,8 +43,6 @@ 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;
@ -98,7 +97,6 @@ public class JsonQuery {
return jsonQueryERElement;
}
public StringBuffer createQuery() throws SchemaException, InvalidQueryException, ResourceRegistryException {
entryPoint = getJsonQueryERElement(jsonQuery);
entryPoint.setEntryPoint(true);
@ -114,11 +112,24 @@ 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(" limit :limit");
stringBuffer.append(" SKIP :offset");
stringBuffer.append(" LIMIT :limit");
Map<String, Object> map = new HashMap<>();
map.put("limit", JsonQuery.UNBOUNDED_LIMIT);
map.put("offset", offset);
map.put("limit", limit);
String query = stringBuffer.toString();
logger.trace("Going to execute the following query:\n{} \n from the JSONQuery\n{}", query, objectMapper.writeValueAsString(jsonQuery));
@ -129,34 +140,17 @@ public class JsonQuery {
while(resultSet.hasNext()) {
OResult oResult = resultSet.next();
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
try {
JsonNode jsonNodeResult = null;
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
element);
// To support polymorphism we do not include ="TypeName" in query. So we need post processing filtering of results
String requestedType = entryPoint.getType();
String gotType = erManagement.getTypeName();
if(requestedType.compareTo(gotType)==0) {
erManagement.setAsEntryPoint();
jsonNodeResult = erManagement.serializeAsJsonNode();
arrayNode.add(jsonNodeResult);
continue;
}
CachedType<?> cachedType = TypesCache.getInstance().getCachedType(gotType);
if(cachedType.getSuperTypes().contains(requestedType)) {
erManagement.setAsEntryPoint();
jsonNodeResult = erManagement.serializeAsJsonNode();
arrayNode.add(jsonNodeResult);
continue;
}
erManagement.setAsEntryPoint();
jsonNodeResult = erManagement.serializeAsJsonNode();
arrayNode.add(jsonNodeResult);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
element.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);

View File

@ -16,14 +16,16 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
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.QueryConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.ConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.LogicalOperator;
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 {
// private Logger logger = LoggerFactory.getLogger(this.getClass());
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public static void validateType(String type, AccessType requiredAccessType) throws SchemaException, ResourceRegistryException {
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
@ -42,12 +44,23 @@ public abstract class JsonQueryERElement {
protected Direction direction;
protected boolean entryPoint;
/**
* 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.jsonNode = jsonQuery;
this.size = jsonNode.size();
this.accessType = accessType;
this.entryPoint = false;
this.traverseBack = true;
this.fieldNamesToRemove = new HashSet<>();
this.fieldNamesToRemove.add(Element.TYPE_PROPERTY);
@ -75,16 +88,25 @@ public abstract class JsonQueryERElement {
public void setEntryPoint(boolean entryPoint) {
this.entryPoint = entryPoint;
this.traverseBack = !entryPoint;
}
public boolean isTraverseBack() {
return traverseBack;
}
public void setTraverseBack(boolean traverseBack) {
this.traverseBack = traverseBack;
}
public abstract StringBuffer analize(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException;
protected StringBuffer addConstraints(JsonNode jsonNode, QueryLogicalOperator queryLogicalOperator, String fieldNamePrefix) throws InvalidQueryException {
protected StringBuffer addConstraints(JsonNode jsonNode, LogicalOperator queryLogicalOperator, String fieldNamePrefix) throws InvalidQueryException {
StringBuffer stringBuffer = new StringBuffer();
if(queryLogicalOperator==null) {
queryLogicalOperator = QueryLogicalOperator.AND;
queryLogicalOperator = LogicalOperator.AND;
}
JsonNode copiedJsonNode = jsonNode.deepCopy();
@ -130,18 +152,18 @@ public abstract class JsonQueryERElement {
protected StringBuffer evaluateNode(JsonNode jsonNode, String fieldName, String fieldNamePrefix) throws InvalidQueryException {
StringBuffer stringBuffer = new StringBuffer();
if(QueryLogicalOperator.getOperators().contains(fieldName)) {
QueryLogicalOperator queryLogicalOperator = QueryLogicalOperator.getQueryLogicalOperator(fieldName);
if(LogicalOperator.getOperators().contains(fieldName)) {
LogicalOperator queryLogicalOperator = LogicalOperator.getQueryLogicalOperator(fieldName);
stringBuffer.append("(");
stringBuffer.append(addConstraints(jsonNode, queryLogicalOperator, fieldNamePrefix));
stringBuffer.append(")");
return stringBuffer;
}
if(QueryConditionalOperator.getOperators().contains(fieldName)) {
QueryConditionalOperator queryConditionalOperator = QueryConditionalOperator.getQueryComparisonOperator(fieldName);
if(ConditionalOperator.getOperators().contains(fieldName)) {
ConditionalOperator queryConditionalOperator = ConditionalOperator.getQueryComparisonOperator(fieldName);
if(queryConditionalOperator == QueryConditionalOperator.IN) {
if(queryConditionalOperator == ConditionalOperator.IN) {
throw new UnsupportedOperationException();
}
@ -171,13 +193,13 @@ public abstract class JsonQueryERElement {
if(jsonNode.isTextual() || jsonNode.isNumber()) {
StringBuffer key = getKey(fieldName, fieldNamePrefix);
StringBuffer value = getValue(jsonNode);
stringBuffer.append(addCondition(QueryConditionalOperator.EQ, key, value));
stringBuffer.append(addCondition(ConditionalOperator.EQ, key, value));
}
return stringBuffer;
}
protected StringBuffer addCondition(QueryConditionalOperator queryConditionalOperator, StringBuffer key, StringBuffer value) {
protected StringBuffer addCondition(ConditionalOperator queryConditionalOperator, StringBuffer key, StringBuffer value) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(key);
stringBuffer.append(queryConditionalOperator.getConditionalOperator());

View File

@ -7,36 +7,37 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
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.relations.JsonQueryConsistsOf;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class JsonQueryFacet extends JsonQueryEntity {
public final static String _IN = "_in";
public final static String _SOURCE = "_source";
public JsonQueryFacet(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
super(jsonQuery, AccessType.FACET);
fieldNamesToRemove.add(JsonQueryFacet._IN);
fieldNamesToRemove.add(JsonQueryFacet._SOURCE);
}
@Override
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
StringBuffer newBuffer = new StringBuffer();
int size = jsonNode.size();
boolean entry = entryPoint;
if(jsonNode.has(_IN)) {
boolean traverseBackLocal = traverseBack;
if(jsonNode.has(_SOURCE)) {
if(!entryPoint) {
throw new InvalidQueryException(_IN + " property cannot be used in a facet if it is not the entry object");
throw new InvalidQueryException(_SOURCE + " property cannot be used in a facet if it is not the entry object");
}
JsonNode consistsOfNode = jsonNode.get(_IN);
JsonNode consistsOfNode = jsonNode.get(_SOURCE);
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfNode);
jsonQueryConsistsOf.setEntryPoint(entryPoint);
jsonQueryConsistsOf.setTraverseBack(traverseBackLocal);
jsonQueryConsistsOf.setDirection(Direction.OUT);
stringBuffer = jsonQueryConsistsOf.analize(stringBuffer);
entry = false;
traverseBackLocal = true;
/* Need to substract 1 from size otherwise
* it add WHERE at the end because _in
@ -47,24 +48,41 @@ public class JsonQueryFacet extends JsonQueryEntity {
newBuffer.append("SELECT FROM ");
if(!entry) {
if(traverseBackLocal) {
newBuffer.append("( ");
newBuffer.append("TRAVERSE inV(\"");
}
newBuffer.append(type);
if(!entry) {
if(traverseBackLocal) {
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
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;

View File

@ -9,6 +9,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
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)
@ -17,42 +18,74 @@ public class JsonQueryResource extends JsonQueryEntity {
public JsonQueryResource(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
super(jsonQuery, AccessType.RESOURCE);
fieldNamesToRemove.add(Resource.CONSISTS_OF_PROPERTY);
fieldNamesToRemove.add(Resource.IS_RELATED_TO_PROPERTY);
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;
}
@Override
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
boolean initFound = false;
int size = jsonNode.size();
boolean wrapInnerQuery = false;
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;
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;
initFound = true;
wrapInnerQuery = true;
}
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.setEntryPoint(entryPoint && i==0);
jsonQueryIsRelatedTo.setDirectionByJson();
jsonQueryIsRelatedTo.setTraverseBack( (!(!traverseBack) && i==0) );
stringBuffer = jsonQueryIsRelatedTo.analize(stringBuffer);
}
wrapInnerQuery = true;
}
ArrayNode consistsOfArray = (ArrayNode) jsonNode.get(Resource.CONSISTS_OF_PROPERTY);
@ -63,42 +96,19 @@ public class JsonQueryResource extends JsonQueryEntity {
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfJsonNode);
jsonQueryConsistsOf.setRequestedResourceType(type);
jsonQueryConsistsOf.setDirection(Direction.IN);
jsonQueryConsistsOf.setEntryPoint(entryPoint && !initFound && i==0);
jsonQueryConsistsOf.setTraverseBack(!((!traverseBack) && !wrapInnerQuery && i==0));
stringBuffer = jsonQueryConsistsOf.analize(stringBuffer);
}
initFound = true; // Must be set after the cycle and not before
wrapInnerQuery = true; // Must be set after the cycle and not before
}
if(entryPoint) {
if(!initFound) {
stringBuffer = new StringBuffer();
stringBuffer.append("SELECT FROM ");
stringBuffer.append(type);
if(size > 1) {
stringBuffer.append(" WHERE ");
stringBuffer.append(addConstraints(jsonNode, null, null));
}
}else {
if(size > 1) {
StringBuffer newBuffer = new StringBuffer();
newBuffer.append("SELECT FROM ( ");
newBuffer.append(stringBuffer);
newBuffer.append(")");
newBuffer.append(" WHERE ");
newBuffer.append(addConstraints(jsonNode, null, null));
stringBuffer = newBuffer;
}
}
}else {
if(initFound && size > 1) {
StringBuffer newBuffer = new StringBuffer();
newBuffer.append("SELECT FROM ( ");
newBuffer.append(stringBuffer);
newBuffer.append(")");
newBuffer.append(" WHERE ");
newBuffer.append(addConstraints(jsonNode, null, null));
stringBuffer = newBuffer;
}
// The Resource has no other referenced ER inside
if(!wrapInnerQuery) {
return createSelect(stringBuffer, wrapInnerQuery);
}
if(entryPoint || size>1) {
return createSelect(stringBuffer, wrapInnerQuery);
}
return stringBuffer;

View File

@ -8,6 +8,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
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)
@ -29,30 +30,58 @@ 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 analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
StringBuffer consistsOfBuffer = new StringBuffer();
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
}
boolean wrapInnerQuery = false;
int size = jsonNode.size();
if(size > 2) {
consistsOfBuffer.append("SELECT FROM ( "); // Open ( SELECT
}
consistsOfBuffer.append("TRAVERSE ");
consistsOfBuffer.append(direction.name().toLowerCase());
consistsOfBuffer.append("E(\"");
consistsOfBuffer.append(type);
consistsOfBuffer.append("\") FROM ( "); // Open ( 2
if(!entryPoint) {
if(traverseBack) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
@ -62,34 +91,49 @@ public class JsonQueryConsistsOf extends JsonQueryRelation {
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
wrapInnerQuery = true;
}
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
--size;
JsonNode facetJsonNode = jsonNode.get(ConsistsOf.TARGET_PROPERTY);
JsonQueryFacet jsonQueryFacet = new JsonQueryFacet(facetJsonNode);
jsonQueryFacet.setEntryPoint(entryPoint);
jsonQueryFacet.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
stringBuffer = jsonQueryFacet.analize(stringBuffer);
} else if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
wrapInnerQuery = true;
}
if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
--size;
JsonNode resourceJsonNode = jsonNode.get(ConsistsOf.SOURCE_PROPERTY);
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
jsonQueryResource.setEntryPoint(entryPoint);
jsonQueryResource.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
stringBuffer = jsonQueryResource.analize(stringBuffer);
wrapInnerQuery = true;
}
consistsOfBuffer.append(stringBuffer);
consistsOfBuffer.append(")"); // Close ) 2
// Size 2 means that only 'type' and 'target' properties are present
if(size > 2) {
consistsOfBuffer.append(") WHERE "); // Close ) SELECT
consistsOfBuffer.append(addConstraints(jsonNode, null, null));
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(!jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
consistsOfBuffer.append(")"); // Close ) 1
if(entryPoint || size>1) {
stringBuffer = createSelect(stringBuffer, wrapInnerQuery);
}
return consistsOfBuffer;
if(!entryPoint && requestedResourceType!=null) {
stringBuffer = traverseBackToCallerResource(stringBuffer);
}
return stringBuffer;
}
}

View File

@ -1,5 +1,7 @@
package org.gcube.informationsystem.resourceregistry.queries.json.base.relations;
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;
@ -8,6 +10,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
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.entities.JsonQueryResource;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
/**
* @author Luca Frosini (ISTI - CNR)
@ -18,6 +21,7 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
public JsonQueryIsRelatedTo(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
super(jsonQuery, AccessType.IS_RELATED_TO);
direction = null;
}
public String getRequestedResourceType() {
@ -27,39 +31,98 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
public void setRequestedResourceType(String requestedResourceType) {
this.requestedResourceType = requestedResourceType;
}
private StringBuffer traverseThisEdge(StringBuffer stringBuffer) throws InvalidQueryException {
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 ");
int size = jsonNode.size();
if(wrapInnerQuery) {
buffer.append("( ");
buffer.append(stringBuffer);
buffer.append(")");
}else {
buffer.append(type);
}
// Remove type from size
--size;
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;
}
public void setDirectionByJson() 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)) {
--size;
logger.trace("{} for type {} has {} property", IsRelatedTo.NAME, type, IsRelatedTo.SOURCE_PROPERTY);
direction = Direction.OUT;
found = true;
}
if(jsonNode.has(IsRelatedTo.TARGET_PROPERTY)) {
--size;
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;
}
}
@Override
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. ");
}
if(size > 0) {
buffer.append("SELECT FROM ");
if(entryPoint) {
buffer.append(type);
}else {
buffer.append(" ( "); // Open ( SELECT
}
}else {
if(entryPoint) {
buffer.append("SELECT FROM ");
buffer.append(type);
}
}
boolean wrapInnerQuery = false;
if(!entryPoint) {
if(traverseBack) {
StringBuffer buffer = new StringBuffer();
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
buffer.append("E(\"");
@ -67,80 +130,64 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
stringBuffer = buffer;
wrapInnerQuery = true;
}
Direction wrapDirection = direction;
stringBuffer = buffer;
// Size 0 means that only 'type' 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
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
JsonNode sourceJsonNode = jsonNode.get(IsRelatedTo.SOURCE_PROPERTY);
JsonNode targetJsonNode = jsonNode.get(IsRelatedTo.TARGET_PROPERTY);
JsonNode resourceJsonNode = null;
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(requestedResourceType!=null) {
buffer.append("TRAVERSE ");
buffer.append(direction.opposite().name().toLowerCase());
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("\") 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);
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.analize(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;
}
boolean entryPointOldValue = entryPoint;
// It is no more and entry point for the function traverseThisEdge
entryPoint = false;
stringBuffer = traverseThisEdge(stringBuffer);
// Restoring entryPoint indication
entryPoint = entryPointOldValue;
--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.analize(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);
}
return stringBuffer;

View File

@ -0,0 +1,82 @@
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.gcube.informationsystem.types.PropertyTypeName.BaseTypeGroup;
/**
* @author Luca Frosini (ISTI - CNR)
* See https://www.orientdb.com/docs/3.0.x/sql/SQL-Where.html
*/
public enum ConditionalOperator {
EQ("_eq", " = ", BaseTypeGroup.ANY, "Matches values that are equal to a specified value. E.g. `name = 'Luke'`"),
GT("_gt", " > ", BaseTypeGroup.ANY, "Matches values that are greater than a specified value. "),
GTE("_gte", " >= ", BaseTypeGroup.ANY, "Matches values that are greater than or equal to a specified value."),
LT("_lt", " < ", BaseTypeGroup.ANY, "Matches values that are less than a specified value."),
LTE("_lte", " <= ", BaseTypeGroup.ANY, "Matches values that are less than or equal to a specified value."),
NE("_ne", " <> ", BaseTypeGroup.ANY, "Matches all values that are not equal to a specified value."),
BETWEEN("_between", " BETWEEN ", BaseTypeGroup.ANY, "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 ", BaseTypeGroup.ANY, "Used to test if a value is NULL"),
LIKE("_like", " LIKE ", BaseTypeGroup.STRING, "Similar to equals, but allow the wildcard '%' that means 'any'. E.g. `name LIKE 'Luk%'`"),
CONTAINS_TEXT("_containsText", " CONTAINSTEXT ", BaseTypeGroup.STRING, "The string contains such text. E.g. `text CONTAINSTEXT 'jay'`"),
MATCHES("_matches", " MATCHES ", BaseTypeGroup.STRING, "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 ", BaseTypeGroup.COLLECTION, "Matches any of the values specified in an array. E.g. `name in ['European','Asiatic']`"),
CONTAINS("_contains", " CONTAINS ", BaseTypeGroup.COLLECTION, "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 ", BaseTypeGroup.COLLECTION, "True if all the elements of the collection satisfy the next condition. E.g. `children CONTAINSALL (name = 'Luke')`"),
CONTAINS_ANY("_containsAny", " CONTAINSANY ", BaseTypeGroup.COLLECTION, "True if all the elements of the collection satisfy the next condition. E.g. `children CONTAINSANY (name = 'Luke')`"),
CONTAINS_KEY("_containsKey", " CONTAINSKEY ", BaseTypeGroup.MAP, "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 ", BaseTypeGroup.MAP , "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`");
protected final String operator;
protected final String conditionalOperator;
protected final BaseTypeGroup allowed;
protected final String description;
private ConditionalOperator(String operator, String conditionalOperator, BaseTypeGroup allowed, String description) {
this.operator = operator;
this.conditionalOperator = conditionalOperator;
this.allowed = allowed;
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,ConditionalOperator> operatorByKey;
static {
ConditionalOperator.operators = new HashSet<>();
ConditionalOperator.operatorByKey = new HashMap<>();
for(ConditionalOperator queryComparisonOperator : ConditionalOperator.values()) {
ConditionalOperator.operators.add(queryComparisonOperator.getOperator());
ConditionalOperator.operatorByKey.put(queryComparisonOperator.getOperator(), queryComparisonOperator);
}
}
public static Set<String> getOperators() {
return ConditionalOperator.operators;
}
public static ConditionalOperator getQueryComparisonOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -0,0 +1,60 @@
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 operator;
protected final String logicalOperator;
protected final String description;
private LogicalOperator(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,LogicalOperator> operatorByKey;
static {
LogicalOperator.operators = new HashSet<>();
LogicalOperator.operatorByKey = new HashMap<>();
for(LogicalOperator queryLogicalOperator : LogicalOperator.values()) {
LogicalOperator.operators.add(queryLogicalOperator.getOperator());
LogicalOperator.operatorByKey.put(queryLogicalOperator.getOperator(), queryLogicalOperator);
}
}
public static Set<String> getOperators() {
return LogicalOperator.operators;
}
public static LogicalOperator getQueryLogicalOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -0,0 +1,68 @@
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 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 final String operator;
protected final String matemathicsOperator;
protected final String description;
private MatemathicsOperator(String operator, String matemathicsOperator, String description) {
this.operator = operator;
this.matemathicsOperator = matemathicsOperator;
this.description = description;
}
public String getOperator() {
return operator;
}
public String getMatemathicsOperator() {
return matemathicsOperator;
}
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 queryLogicalOperator : MatemathicsOperator.values()) {
MatemathicsOperator.operators.add(queryLogicalOperator.getOperator());
MatemathicsOperator.operatorByKey.put(queryLogicalOperator.getOperator(), queryLogicalOperator);
}
}
public static Set<String> getOperators() {
return MatemathicsOperator.operators;
}
public static MatemathicsOperator getQueryLogicalOperator(String key) {
return operatorByKey.get(key);
}
}

View File

@ -1,64 +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)
*/
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

@ -1,59 +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)
*/
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

@ -3,8 +3,6 @@ package org.gcube.informationsystem.resourceregistry.queries.templates;
import java.util.HashMap;
import java.util.UUID;
import javax.ws.rs.BadRequestException;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
@ -30,6 +28,8 @@ import org.gcube.informationsystem.resourceregistry.instances.base.ElementManage
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.types.reference.entities.EntityType;
@ -348,13 +348,28 @@ 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);

View File

@ -4,8 +4,7 @@ import java.util.List;
import javax.ws.rs.core.UriInfo;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
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;
@ -14,39 +13,19 @@ import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ServerRequestInfo implements RequestInfo {
public class ServerRequestInfo extends BaseRequestInfo implements RequestInfo {
protected static Logger logger = LoggerFactory.getLogger(ServerRequestInfo.class);
protected UriInfo uriInfo;
/**
* Track if the request requested to include {@link Metadata}
*/
protected boolean includeMeta;
/**
* Track if the request requested to include {@link Metadata} in all
* {@link IdentifiableElement} or just in the root instance
*/
protected boolean allMeta;
/**
* Track if hierarchicalMode has been requested
*/
protected boolean hierarchicalMode;
/**
* Track if the request requested to include contexts
*/
protected boolean includeContexts;
public ServerRequestInfo() {
this.includeMeta = false;
this.allMeta = false;
this.hierarchicalMode = false;
this.includeContexts = false;
super();
this.uriInfo = null;
}
public ServerRequestInfo(int offset, int limit) {
super(offset, limit);
this.uriInfo = null;
}
@ -76,6 +55,14 @@ public class ServerRequestInfo implements RequestInfo {
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;
@ -88,27 +75,35 @@ public class ServerRequestInfo implements RequestInfo {
* 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 independetly if
* the value has been 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 toBeSet = bool && isAllowed(queryParameterKey);
public boolean setIfAllowed(String queryParameterKey, boolean bool, boolean forceAllowed) {
switch (queryParameterKey) {
case InstancePath.INCLUDE_META_QUERY_PARAMETER:
includeMeta = toBeSet;
if(forceAllowed || isAllowed(queryParameterKey)) {
includeMeta = bool;
}
return includeMeta;
case InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER:
allMeta = toBeSet;
if(forceAllowed || isAllowed(queryParameterKey)) {
allMeta = bool;
}
return allMeta;
case InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER:
includeContexts = toBeSet;
if(forceAllowed || isAllowed(queryParameterKey)) {
includeContexts = bool;
}
return includeContexts;
case InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER:
hierarchicalMode = toBeSet;
if(forceAllowed || isAllowed(queryParameterKey)) {
hierarchicalMode = bool;
}
return hierarchicalMode;
default:
@ -118,7 +113,59 @@ public class ServerRequestInfo implements RequestInfo {
return false;
}
public void checkQueryParameter(String queryParameterKey) {
/**
* 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) {
@ -127,7 +174,26 @@ public class ServerRequestInfo implements RequestInfo {
setIfAllowed(queryParameterKey, bool);
}
}catch (Throwable t) {
logger.warn("Unable to properly set the Hierarchical Mode is set", t.getMessage());
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());
}
}
@ -135,59 +201,28 @@ public class ServerRequestInfo implements RequestInfo {
this.uriInfo = uriInfo;
}
public void checkAllQueryParameters() {
checkIncludeQueryParameters();
checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
public void checkAllBooleanQueryParameters() {
checkAllIncludeQueryParameters();
checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
}
public void checkIncludeQueryParameters() {
public void checkAllIncludeQueryParameters() {
checkIncludeAllMetaQueryParameters();
checkQueryParameter(InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER);
checkBooleanQueryParameter(InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER);
}
public void checkIncludeAllMetaQueryParameters() {
checkQueryParameter(InstancePath.INCLUDE_META_QUERY_PARAMETER);
checkQueryParameter(InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER);
checkBooleanQueryParameter(InstancePath.INCLUDE_META_QUERY_PARAMETER);
checkBooleanQueryParameter(InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER);
}
@Override
public boolean includeMeta() {
return includeMeta;
}
@Override
public void setIncludeMeta(boolean includeMeta) {
this.includeMeta = includeMeta;
}
@Override
public boolean allMeta() {
return allMeta;
}
@Override
public void setAllMeta(boolean allMeta) {
this.allMeta = allMeta;
public void checkLimitOffset(int offset, int limit) {
checkIntegerQueryParameter(InstancePath.OFFSET_QUERY_PARAMETER, offset);
checkIntegerQueryParameter(InstancePath.LIMIT_QUERY_PARAMETER, limit);
}
@Override
public boolean isHierarchicalMode() {
return hierarchicalMode;
}
@Override
public void setHierarchicalMode(boolean hierarchicalMode) {
this.hierarchicalMode = hierarchicalMode;
}
@Override
public boolean includeContexts() {
return includeContexts;
}
@Override
public void setIncludeContexts(boolean includeContexts) {
this.includeContexts = includeContexts;
public void checkLimitOffset() {
checkLimitOffset(DEFAULT_OFFSET, DEFAULT_LIMIT);
}
}

View File

@ -30,6 +30,7 @@ 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;
@ -79,9 +80,10 @@ public class Access extends BaseRest {
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();
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
@ -104,7 +106,7 @@ public class Access extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
@ -127,7 +129,7 @@ public class Access extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeName(type);
@ -152,7 +154,8 @@ public class Access extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
@ -172,7 +175,7 @@ public class Access extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -195,7 +198,7 @@ public class Access extends BaseRest {
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -219,7 +222,8 @@ public class Access extends BaseRest {
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
@ -239,7 +243,7 @@ public class Access extends BaseRest {
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
@ -276,7 +280,7 @@ public class Access extends BaseRest {
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
@ -317,6 +321,9 @@ 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
@ -338,9 +345,9 @@ public class Access extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
if(raw) {
// TODO Check if the role allow to request raw data
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
}else {
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
}
Query queryManager = new QueryImpl();
@ -395,7 +402,8 @@ public class Access extends BaseRest {
setAccountingMethod(Method.QUERY, JSON_QUERY_METHOD);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
JsonQuery jsonQueryManager = new JsonQuery();
jsonQueryManager.setJsonQuery(jsonQuery);
@ -418,12 +426,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"})
@ -446,7 +454,8 @@ public class Access extends BaseRest {
setAccountingMethod(Method.QUERY, PREPARED_QUERY_METHOD);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement erManagement = ElementManagementUtility.getERManagement(resourcetype);

View File

@ -35,15 +35,20 @@ public class BaseRest {
setAccountingMethod(accountingMethod.toString());
}
protected ServerRequestInfo initRequestInfo() {
ServerRequestInfo requestInfo = new ServerRequestInfo();
private ServerRequestInfo initRequestInfo(ServerRequestInfo requestInfo) {
requestInfo.setUriInfo(uriInfo);
RequestUtility.getRequestInfo().set(requestInfo);
return requestInfo;
}
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);
}
}

View File

@ -18,6 +18,7 @@ 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;
@ -46,9 +47,9 @@ public class ContextManager extends BaseRest {
logger.info("Requested to read all {}s", Context.NAME);
setAccountingMethod(Method.LIST, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
@ -73,7 +74,7 @@ public class ContextManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
@ -98,7 +99,7 @@ public class ContextManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));

View File

@ -59,7 +59,8 @@ public class InstancesManager extends BaseRest {
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
@ -80,7 +81,7 @@ public class InstancesManager extends BaseRest {
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
@ -118,7 +119,7 @@ public class InstancesManager extends BaseRest {
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
erManagement.setElementType(type);
@ -144,7 +145,7 @@ public class InstancesManager extends BaseRest {
setAccountingMethod(Method.UPDATE, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeQueryParameters();
serverRequestInfo.checkAllIncludeQueryParameters();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);

View File

@ -46,7 +46,8 @@ public class QueryTemplateManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
@ -93,7 +94,7 @@ public class QueryTemplateManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -115,7 +116,7 @@ public class QueryTemplateManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -139,7 +140,7 @@ public class QueryTemplateManager extends BaseRest {
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);

View File

@ -89,7 +89,7 @@ public class SharingManager extends BaseRest {
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeQueryParameters();
serverRequestInfo.checkAllIncludeQueryParameters();
try {
StringBuffer calledMethod = new StringBuffer();
@ -171,7 +171,7 @@ public class SharingManager extends BaseRest {
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeQueryParameters();
serverRequestInfo.checkAllIncludeQueryParameters();
StringBuffer calledMethod = new StringBuffer();
if(dryRun==null) {

View File

@ -54,7 +54,7 @@ public class TypeManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement schemaManagement = new TypeManagement();
schemaManagement.setTypeName(typeName);
@ -80,7 +80,7 @@ public class TypeManager extends BaseRest {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement schemaManagement = new TypeManagement();
schemaManagement.setTypeName(type);

View File

@ -1,4 +1,4 @@
package org.gcube.informationsystem.resourceregistry.utils;
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashMap;
import java.util.UUID;

View File

@ -63,7 +63,6 @@ public class ContextTest {
try {
// load the properties file
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}

View File

@ -1,8 +1,10 @@
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;
@ -441,7 +443,13 @@ 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);
@ -494,11 +502,10 @@ public class ContextManagementTest extends ContextTest {
delete(context);
}
@Test
public void testContextCache() throws Exception {
List<Context> contexts = getAll();
logger.debug("{}", contexts);
logger.info("{}", contexts);
ServerContextCache contextCache = ServerContextCache.getInstance();
Map<UUID, String> uuidToContextFullName = contextCache.getUUIDToContextFullNameAssociation();
@ -537,4 +544,94 @@ public class ContextManagementTest extends ContextTest {
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,8 +8,10 @@ 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;
@ -17,6 +19,7 @@ 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;
@ -30,6 +33,8 @@ 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.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;
@ -38,6 +43,7 @@ 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.resourcemanagement.model.impl.entities.facets.AccessPointFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
@ -86,12 +92,12 @@ import org.slf4j.LoggerFactory;
public class ERManagementTest extends ContextTest {
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
public static final String GROUP = "InformationSystem";
public static final String NAME = "resource-registry";
public static final String VERSION = "1.0.0";
public static final String NEW_VERSION = "2.0.0";
// @Before
// @After
// public void cleanInstances() throws Exception {
@ -109,14 +115,16 @@ 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();
softwareFacet.setGroup(GROUP);
@ -124,13 +132,13 @@ public class ERManagementTest extends ContextTest {
softwareFacet.setVersion(VERSION);
return softwareFacet;
}
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, SoftwareFacet gotSoftwareFacet) {
Assert.assertTrue(gotSoftwareFacet.getGroup().compareTo(softwareFacet.getGroup()) == 0);
Assert.assertTrue(gotSoftwareFacet.getName().compareTo(softwareFacet.getName()) == 0);
Assert.assertTrue(gotSoftwareFacet.getVersion().compareTo(softwareFacet.getVersion()) == 0);
}
public static Configuration instantiateValidConfiguration() throws Exception {
Configuration configuration = new ConfigurationImpl();
@ -142,10 +150,10 @@ public class ERManagementTest extends ContextTest {
IsIdentifiedBy<Configuration, IdentifierFacet> isIdentifiedBy = new IsIdentifiedByImpl<Configuration, IdentifierFacet>(
configuration, identifierFacet);
configuration.addFacet(isIdentifiedBy);
return configuration;
}
public static EService instantiateValidEService() throws Exception {
EService eService = new EServiceImpl();
@ -171,8 +179,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;
@ -225,76 +233,81 @@ public class ERManagementTest extends ContextTest {
return hostingNode;
}
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement, IdentifiableElement createdIdentifiableElement) {
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement,
IdentifiableElement createdIdentifiableElement) {
UUID createdUUID = createdIdentifiableElement.getID();
Assert.assertTrue(createdUUID!=null);
if(identifiableElement.getID()!=null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID())==0);
Assert.assertTrue(createdUUID != null);
if (identifiableElement.getID() != null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID()) == 0);
}
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
Assert.assertTrue(createdMetadata!=null);
Assert.assertTrue(createdMetadata != null);
String createdBy = createdMetadata.getCreatedBy();
Assert.assertTrue(createdBy!=null);
Assert.assertTrue(createdBy != null);
String lastUpdateBy = createdMetadata.getLastUpdateBy();
Assert.assertTrue(lastUpdateBy!=null);
Assert.assertTrue(lastUpdateBy != null);
Date creationTime = createdMetadata.getCreationTime();
Assert.assertTrue(creationTime!=null);
Assert.assertTrue(creationTime != null);
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
Assert.assertTrue(lastUpdateTime!=null);
Assert.assertTrue(lastUpdateTime != null);
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
Metadata metadata = identifiableElement.getMetadata();
if(metadata!=null) {
if(metadata.getCreatedBy()!=null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy())==0);
}else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser())==0);
if (metadata != null) {
if (metadata.getCreatedBy() != null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy()) == 0);
} else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser()) == 0);
}
if(metadata.getLastUpdateBy()!=null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy())==0);
}else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser())==0);
if (metadata.getLastUpdateBy() != null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy()) == 0);
} else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser()) == 0);
}
if(metadata.getLastUpdateTime()!=null) {
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime()) || lastUpdateTime.compareTo(metadata.getLastUpdateTime())==0);
if (metadata.getLastUpdateTime() != null) {
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime())
|| lastUpdateTime.compareTo(metadata.getLastUpdateTime()) == 0);
}
}
}
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint, PropagationConstraint gotPropagationConstraint) {
Assert.assertTrue(propagationConstraint.getAddConstraint()==gotPropagationConstraint.getAddConstraint());
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==gotPropagationConstraint.getRemoveConstraint());
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint,
PropagationConstraint gotPropagationConstraint) {
Assert.assertTrue(propagationConstraint.getAddConstraint() == gotPropagationConstraint.getAddConstraint());
Assert.assertTrue(
propagationConstraint.getRemoveConstraint() == gotPropagationConstraint.getRemoveConstraint());
}
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf, ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf,
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
if(consistsOf.getPropagationConstraint()==null) {
if (consistsOf.getPropagationConstraint() == null) {
PropagationConstraint propagationConstraint = gotConsistsOf.getPropagationConstraint();
Assert.assertTrue(propagationConstraint.getAddConstraint()==AddConstraint.propagate);
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==RemoveConstraint.cascade);
Assert.assertTrue(propagationConstraint.getAddConstraint() == AddConstraint.propagate);
Assert.assertTrue(propagationConstraint.getRemoveConstraint() == RemoveConstraint.cascade);
checkPropagationConstraint(propagationConstraint, gotConsistsOf.getPropagationConstraint());
}else {
} else {
checkPropagationConstraint(consistsOf.getPropagationConstraint(), gotConsistsOf.getPropagationConstraint());
}
Map<String, Object> additionalProperties = new HashMap<>(consistsOf.getAdditionalProperties());
additionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
gotAdditionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Assert.assertTrue(additionalProperties.size()==gotAdditionalProperties.size());
for(String key : additionalProperties.keySet()) {
Assert.assertTrue(additionalProperties.size() == gotAdditionalProperties.size());
for (String key : additionalProperties.keySet()) {
Assert.assertTrue(gotAdditionalProperties.containsKey(key));
Object additionalProperty = additionalProperties.get(key);
Object gotAdditionalProperty = gotAdditionalProperties.get(key);
@ -302,124 +315,123 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(additionalProperty.equals(gotAdditionalProperty));
}
}
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
checkUUIDAndMetadata(facet, gotFacet);
Class<? extends Facet> clz = facet.getClass();
Class<? extends Facet> gotClz = gotFacet.getClass();
Assert.assertTrue(clz==gotClz);
if(clz == SoftwareFacet.class) {
Assert.assertTrue(clz == gotClz);
if (clz == SoftwareFacet.class) {
checkSoftwareFacetAssertion((SoftwareFacet) facet, (SoftwareFacet) gotFacet);
}
}
protected static <R extends Resource> void checkResource(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> consistsOf : resourceConsistsOf) {
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();
Facet gotFacet = gotConsistsOf.getTarget();
checkFacet(facet, gotFacet);
}
}
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) {
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) {
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 {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(r.getTypeName());
resourceManagement.setJson(ElementMapper.marshal(r));
if(r.getID()!=null) {
if (r.getID() != null) {
resourceManagement.setUUID(r.getID());
}
return resourceManagement;
}
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(
IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
if(isRelatedTo.getID()!=null) {
if (isRelatedTo.getID() != null) {
isRelatedToManagement.setUUID(isRelatedTo.getID());
}
return isRelatedToManagement;
}
public <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 {
EService eService = ERManagementTest.instantiateValidEService();
return createResource(eService);
}
public HostingNode createHostingNode() throws Exception {
return createHostingNode(null);
}
public HostingNode createHostingNode(EService eService) throws Exception {
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
}
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint, DeleteConstraint deleteConstraint) throws Exception {
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint,
DeleteConstraint deleteConstraint) throws Exception {
HostingNode hostingNode = ERManagementTest.instantiateValidHostingNode();
if(eService!=null) {
if (eService != null) {
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
propagationConstraint.setRemoveConstraint(removeConstraint);
propagationConstraint.setDeleteConstraint(deleteConstraint);
@ -429,12 +441,12 @@ public class ERManagementTest extends ContextTest {
}
return createResource(hostingNode);
}
public Configuration createConfiguration() throws Exception {
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
return createResource(configuration);
}
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
Map<String, Resource> map = new HashMap<>();
@ -446,24 +458,23 @@ public class ERManagementTest extends ContextTest {
return map;
}
public <R extends Resource> void deleteResource(R r) throws Exception {
if(r!=null) {
if (r != null) {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.delete();
}
}
@Test
public void testCreateEService() throws Exception {
EService eService = null;
try {
eService = createEService();
}finally {
} finally {
deleteResource(eService);
}
}
@Test
@ -472,28 +483,27 @@ public class ERManagementTest extends ContextTest {
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 {
} finally {
deleteResource(eService);
}
}
protected Resource readResource(UUID uuid) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
@ -501,73 +511,70 @@ public class ERManagementTest extends ContextTest {
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 {
* readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e")); }
*/
/*
@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
public void testCreateHostingNode() throws Exception {
HostingNode hostingNode = null;
try {
hostingNode = createHostingNode();
}finally {
} finally {
deleteResource(hostingNode);
}
}
@Test
public void testCreateHostingNodeAndEService() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
deleteResource(map.get(HostingNode.NAME));
}
@Test
public void testCreateReadUpdateDeleteFacet() throws Exception {
EService eService = createEService();
try {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
ConsistsOf<EService, CPUFacet> consistsOf = new ConsistsOfImpl<EService, CPUFacet>(eService, cpuFacet);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(consistsOf.getTypeName());
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();
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(createdCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor()) == 0);
UUID uuid = createdCpuFacet.getID();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(createdCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
String readJson = facetManagement.read().toString();
CPUFacet readCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readJson);
logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet);
@ -575,21 +582,21 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getID()) == 0);
String newVendor = "Intel";
String newClockSpeed = "2 GHz";
readCpuFacet.setVendor(newVendor);
readCpuFacet.setClockSpeed(newClockSpeed);
String additionPropertyKey = "My";
String additionPropertyValue = "Test";
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.setJson(ElementMapper.marshal(readCpuFacet));
String updatedJson = facetManagement.update();
CPUFacet updatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, updatedJson);
logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, updatedCpuFacet);
@ -601,11 +608,11 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
String user = ContextTest.getUser();
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(updatedCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
String readUpdatedJson = facetManagement.read().toString();
CPUFacet readUpdatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readUpdatedJson);
logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet);
@ -615,11 +622,11 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.delete();
} finally {
deleteResource(eService);
@ -633,7 +640,7 @@ public class ERManagementTest extends ContextTest {
* not impose any particular constraint except the IdentifierFact
*/
Configuration configuration = instantiateValidConfiguration();
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEndpoint(new URI("https://localhost"));
accessPointFacet.setEntryName("port1");
@ -654,7 +661,7 @@ public class ERManagementTest extends ContextTest {
encrypted.setValue(encryptedValue);
String encryptedKey = "Enc";
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
configuration.addFacet(accessPointFacet);
String marshalled = ElementMapper.marshal(configuration);
@ -663,7 +670,7 @@ public class ERManagementTest extends ContextTest {
Configuration createdConfiguration = createResource(configuration);
AccessPointFacet apf = configuration.getFacets(AccessPointFacet.class).get(0);
Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema);
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
@ -671,33 +678,33 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
Assert.assertTrue(((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
Assert.assertTrue(
((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
deleteResource(createdConfiguration);
}
@Test
public void testUpdateFacetValue() throws Exception {
EService eService =null;
EService eService = null;
try {
eService = createEService();
eService = createEService();
final String newVersion = "1.2.0";
eService.getFacets(SoftwareFacet.class).get(0).setVersion(newVersion);
ResourceManagement resourceManagement = getResourceManagement(eService);
String json = resourceManagement.update();
EService updatedEService = ElementMapper.unmarshal(EService.class, json);
checkResource(eService, updatedEService);
SoftwareFacet softwareFacet = updatedEService.getFacets(SoftwareFacet.class).get(0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
} catch (Throwable e) {
throw e;
}finally {
} finally {
deleteResource(eService);
}
}
@ -729,5 +736,126 @@ public class ERManagementTest extends ContextTest {
String ret = resourceManagement.all(true);
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

@ -445,6 +445,37 @@ 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<>();
@ -453,7 +484,7 @@ public class SmartgearResourcesTest extends ERManagementTest {
if (!file.exists()) {
logger.warn("cannot acquire CPU info (no /proc/cpuinfo)");
return cpuFacets;
return getFakeCPUFacets();
}
BufferedReader input = null;
@ -531,6 +562,11 @@ public class SmartgearResourcesTest extends ERManagementTest {
}
}
}
if(cpuFacets.size()==0) {
return getFakeCPUFacets();
}
return cpuFacets;
}
}

View File

@ -5,11 +5,17 @@ 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;
@ -75,7 +81,7 @@ public class JsonQueryTest extends ContextTest {
@Test
public void testSingleCreateQuery() throws Exception {
File queriesDirectory = getQueriesDirectory();
File jsonQueryFile = new File(queriesDirectory, "query6.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());
@ -102,11 +108,10 @@ public class JsonQueryTest extends ContextTest {
logger.info("Result : {}", result);
}
// @Test
public void testSingleQuery() throws Exception {
public List<Entity> testSingleQuery(int offset, int limit) throws Exception {
ContextTest.setContextByName(DEVVRE);
File queriesDirectory = getQueriesDirectory();
File jsonQueryFile = new File(queriesDirectory, "query3.json");
File jsonQueryFile = new File(queriesDirectory, "query1.json");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
logger.info("Going to test the following JSON query {}", jsonNode.toString());
@ -115,6 +120,72 @@ 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);
}
}
}

View File

@ -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);
@ -337,7 +337,7 @@ public class QueryTest extends ERManagementTest {
@Test
public void getAllResourcesHavingFacet() throws ObjectNotFound, Exception {
String[] names = new String[]{"MyTest", "MyTest", "Aux", "MyID", "MyID"};
Object[] additionalProperties = new Object[] {5, 5.0, false, "test", null};
Object[] additionalProperties = new Object[] {5, 6.0, false, "test", null};
List<Configuration> createdConfigurations = new ArrayList<>();

View File

@ -14,7 +14,9 @@
<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.types" level="TRACE" />
<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">

View File

@ -0,0 +1,19 @@
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"

View File

@ -1 +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"))
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"

View File

@ -0,0 +1,41 @@
SELECT FROM (
TRAVERSE outV("EService") FROM (
TRAVERSE inE("ConsistsOf") FROM (
SELECT FROM (
TRAVERSE inV("AccessPointFacet") FROM (
TRAVERSE outE("ConsistsOf") 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 (
TRAVERSE inV("StateFacet") FROM (
TRAVERSE outE("ConsistsOf") FROM (
TRAVERSE inV("EService") FROM (
SELECT FROM (
TRAVERSE outE("Activates") FROM (
SELECT FROM HostingNode WHERE id = "5fbc1a56-d450-4f0f-85c1-9b1684581717"
)
) WHERE id = "d3f58e52-5346-47bc-b736-9d77a0b554ce"
)
)
)
) WHERE value = "down"
)
) WHERE propagationConstraint.add = "propagate"
)
)
)
) WHERE name = "data-transfer-service" AND group = "DataTransfer"
)
)
)
)
) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
)
)
) WHERE @class INSTANCEOF "EService"

View File

@ -1 +1 @@
TRAVERSE outV("EService") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("AccessPointFacet") FROM ( TRAVERSE outE("ConsistsOf") 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 ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE inV("EService") FROM ( TRAVERSE outE("Activates") FROM ( SELECT FROM ( TRAVERSE outV("HostingNode") FROM ( SELECT FROM Activates WHERE id = "d3f58e52-5346-47bc-b736-9d77a0b554ce")) WHERE id = "5fbc1a56-d450-4f0f-85c1-9b1684581717"))))) WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))))) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"))
SELECT FROM ( TRAVERSE outV("EService") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("AccessPointFacet") FROM ( TRAVERSE outE("ConsistsOf") 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 ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE inV("EService") FROM ( SELECT FROM ( TRAVERSE outE("Activates") FROM ( SELECT FROM HostingNode WHERE id = "5fbc1a56-d450-4f0f-85c1-9b1684581717")) WHERE id = "d3f58e52-5346-47bc-b736-9d77a0b554ce")))) WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))))) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"))) WHERE @class INSTANCEOF "EService"

View File

@ -0,0 +1,43 @@
SELECT FROM (
TRAVERSE outV("EService") FROM (
TRAVERSE inE("ConsistsOf") FROM (
SELECT FROM (
TRAVERSE inV("AccessPointFacet") FROM (
TRAVERSE outE("ConsistsOf") 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 (
TRAVERSE inV("StateFacet") FROM (
TRAVERSE outE("ConsistsOf") FROM (
TRAVERSE inV("EService") FROM (
TRAVERSE outE("Activates") FROM (
TRAVERSE outV("HostingNode") FROM (
TRAVERSE inE("ConsistsOf") FROM (
SELECT FROM CPUFacet WHERE vendor = "GenuineIntel"
)
)
)
)
)
)
) WHERE value = "down"
)
) WHERE propagationConstraint.add = "propagate"
)
)
)
) WHERE name = "data-transfer-service" AND group = "DataTransfer"
)
)
)
)
) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
)
)
) WHERE @class INSTANCEOF "EService"

View File

@ -1 +1 @@
TRAVERSE outV("EService") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("AccessPointFacet") FROM ( TRAVERSE outE("ConsistsOf") 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 ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE inV("EService") FROM ( TRAVERSE outE("Activates") FROM ( TRAVERSE outV("HostingNode") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("CPUFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE outV("HostingNode") FROM ( SELECT FROM Activates)))) WHERE vendor = "GenuineIntel"))))))) WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))))) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"))
SELECT FROM ( TRAVERSE outV("EService") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("AccessPointFacet") FROM ( TRAVERSE outE("ConsistsOf") 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 ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE inV("EService") FROM ( TRAVERSE outE("Activates") FROM ( TRAVERSE outV("HostingNode") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM CPUFacet WHERE vendor = "GenuineIntel"))))))) WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))))) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"))) WHERE @class INSTANCEOF "EService"

View File

@ -1,7 +1,7 @@
{
"type": "StateFacet",
"value": "down",
"_in": {
"_source": {
"type": "ConsistsOf",
"source" : {
"type" : "EService",

View File

@ -1 +1 @@
SELECT FROM ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( SELECT FROM EService WHERE id = "0255b7ec-e3da-4071-b456-9a2907ece1db"))) WHERE value = "down"
SELECT FROM ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( SELECT FROM EService WHERE id = "0255b7ec-e3da-4071-b456-9a2907ece1db"))) WHERE value = "down" AND @class INSTANCEOF "StateFacet"

View File

@ -1,16 +1,16 @@
{
"type": "StateFacet",
"value": "down",
"_in": {
"_source": {
"type": "ConsistsOf",
"source" : {
"type" : "EService",
"$or": [
{"$and": {
"_or": [
{"_and": {
"id" : "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925",
"metadata" :{ "createdBy": {"$ne": "luca.frosini"} }
"metadata" :{ "createdBy": {"_ne": "luca.frosini"} }
}},
{"$and": {
{"_and": {
"id" : "0255b7ec-e3da-4071-b456-9a2907ece1db",
"metadata" : { "createdBy": "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080" }
}}

View File

@ -1 +1 @@
SELECT FROM ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( SELECT FROM EService WHERE ((id = "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925" AND metadata.createdBy <> "luca.frosini") OR (id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND metadata.createdBy = "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080"))))) WHERE value = "down"
SELECT FROM ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( SELECT FROM EService WHERE ((id = "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925" AND metadata.createdBy <> "luca.frosini") OR (id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND metadata.createdBy = "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080"))))) WHERE value = "down" AND @class INSTANCEOF "StateFacet"

View File

@ -0,0 +1,47 @@
SELECT FROM (
TRAVERSE outV("EService") FROM (
TRAVERSE inE("ConsistsOf") FROM (
SELECT FROM (
TRAVERSE inV("AccessPointFacet") FROM (
TRAVERSE outE("ConsistsOf") 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 (
TRAVERSE inV("StateFacet") FROM (
TRAVERSE outE("ConsistsOf") FROM (
TRAVERSE inV("EService") FROM (
SELECT FROM (
TRAVERSE outE("Activates") FROM (
SELECT FROM (
TRAVERSE outV("HostingNode") FROM (
TRAVERSE inE("ConsistsOf") FROM (
SELECT FROM CPUFacet WHERE vendor = "GenuineIntel"
)
)
) WHERE id = "5fbc1a56-d450-4f0f-85c1-9b1684581717"
)
) WHERE id = "d3f58e52-5346-47bc-b736-9d77a0b554ce"
)
)
)
) WHERE value = "down"
)
) WHERE propagationConstraint.add = "propagate"
)
)
)
) WHERE name = "data-transfer-service" AND group = "DataTransfer"
)
)
)
)
) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
)
)
) WHERE id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND @class INSTANCEOF "EService"

View File

@ -1 +1 @@
SELECT FROM ( TRAVERSE outV("EService") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("AccessPointFacet") FROM ( TRAVERSE outE("ConsistsOf") 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 ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE inV("EService") FROM ( TRAVERSE outE("Activates") FROM ( SELECT FROM ( TRAVERSE outV("HostingNode") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("CPUFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE outV("HostingNode") FROM ( SELECT FROM Activates WHERE id = "d3f58e52-5346-47bc-b736-9d77a0b554ce")))) WHERE vendor = "GenuineIntel"))) WHERE id = "5fbc1a56-d450-4f0f-85c1-9b1684581717"))))) WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))))) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"))) WHERE id = "0255b7ec-e3da-4071-b456-9a2907ece1db"
SELECT FROM ( TRAVERSE outV("EService") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM ( TRAVERSE inV("AccessPointFacet") FROM ( TRAVERSE outE("ConsistsOf") 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 ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE inV("EService") FROM ( SELECT FROM ( TRAVERSE outE("Activates") FROM ( SELECT FROM ( TRAVERSE outV("HostingNode") FROM ( TRAVERSE inE("ConsistsOf") FROM ( SELECT FROM CPUFacet WHERE vendor = "GenuineIntel"))) WHERE id = "5fbc1a56-d450-4f0f-85c1-9b1684581717")) WHERE id = "d3f58e52-5346-47bc-b736-9d77a0b554ce")))) WHERE value = "down")) WHERE propagationConstraint.add = "propagate")))) WHERE name = "data-transfer-service" AND group = "DataTransfer"))))) WHERE endpoint = "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"))) WHERE id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND @class INSTANCEOF "EService"

View File

@ -0,0 +1,11 @@
SELECT FROM (
TRAVERSE inV("StateFacet") FROM (
TRAVERSE outE("ConsistsOf") FROM (
SELECT FROM EService
WHERE (
(id = "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925" AND metadata.createdBy <> "luca.frosini") OR
(id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND metadata.createdBy = "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080")
)
)
)
) WHERE @class INSTANCEOF "StateFacet"

View File

@ -1,15 +1,15 @@
{
"type": "StateFacet",
"_in": {
"_source": {
"type": "ConsistsOf",
"source" : {
"type" : "EService",
"$or": [
{"$and": {
"_or": [
{"_and": {
"id" : "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925",
"metadata" :{ "createdBy": {"$ne": "luca.frosini"} }
"metadata" :{ "createdBy": {"_ne": "luca.frosini"} }
}},
{"$and": {
{"_and": {
"id" : "0255b7ec-e3da-4071-b456-9a2907ece1db",
"metadata" : { "createdBy": "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080" }
}}

View File

@ -1 +1 @@
SELECT FROM ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( SELECT FROM EService WHERE ((id = "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925" AND metadata.createdBy <> "luca.frosini") OR (id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND metadata.createdBy = "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080")))))
SELECT FROM ( TRAVERSE inV("StateFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( SELECT FROM EService WHERE ((id = "aec0ef31-c735-4a4c-b2f4-57dfbd2fe925" AND metadata.createdBy <> "luca.frosini") OR (id = "0255b7ec-e3da-4071-b456-9a2907ece1db" AND metadata.createdBy = "DataTransfer:data-transfer-service:pc-frosini.isti.cnr.it_8080"))))) WHERE @class INSTANCEOF "StateFacet"

View File

@ -0,0 +1,23 @@
SELECT FROM (
TRAVERSE inE("CallsFor") FROM (
TRAVERSE outV("VirtualService") FROM (
TRAVERSE inE("IsIdentifiedBy") FROM (
SELECT FROM (
TRAVERSE inV("SoftwareFacet") FROM (
TRAVERSE outE("IsIdentifiedBy") FROM (
TRAVERSE inV("VirtualService") FROM (
TRAVERSE outE("CallsFor") FROM (
TRAVERSE outV("EService") FROM (
TRAVERSE inE("IsIdentifiedBy") FROM (
SELECT FROM SoftwareFacet WHERE group = "org.gcube.data-catalogue" AND name = "gcat"
)
)
)
)
)
)
) WHERE group = "org.gcube.data-catalogue" AND name = "catalogue-virtual-service"
)
)
)
) WHERE @class INSTANCEOF "CallsFor"

View File

@ -1 +1 @@
TRAVERSE inE("CallsFor") FROM ( TRAVERSE outV("VirtualService") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM ( TRAVERSE inV("SoftwareFacet") FROM ( TRAVERSE outE("IsIdentifiedBy") FROM ( TRAVERSE inV("VirtualService") FROM ( TRAVERSE outE("CallsFor") 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 CallsFor)))) WHERE group = "org.gcube.data-catalogue" AND name = "gcat"))))))) WHERE group = "org.gcube.data-catalogue" AND name = "catalogue-virtual-service")))
SELECT FROM ( TRAVERSE inE("CallsFor") FROM ( TRAVERSE outV("VirtualService") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM ( TRAVERSE inV("SoftwareFacet") FROM ( TRAVERSE outE("IsIdentifiedBy") FROM ( TRAVERSE inV("VirtualService") FROM ( TRAVERSE outE("CallsFor") FROM ( TRAVERSE outV("EService") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM SoftwareFacet WHERE group = "org.gcube.data-catalogue" AND name = "gcat"))))))) WHERE group = "org.gcube.data-catalogue" AND name = "catalogue-virtual-service")))) WHERE @class INSTANCEOF "CallsFor"

View File

@ -0,0 +1,25 @@
SELECT FROM (
TRAVERSE inV("SimpleFacet") FROM (
TRAVERSE outE("ConsistsOf") FROM (
TRAVERSE outV("Configuration") FROM (
TRAVERSE inE("IsIdentifiedBy") FROM (
SELECT FROM (
TRAVERSE inV("IdentifierFacet") FROM (
TRAVERSE outE("IsIdentifiedBy") FROM (
TRAVERSE inV("Configuration") FROM (
TRAVERSE outE("IsCustomizedBy") FROM (
TRAVERSE outV("VirtualService") FROM (
TRAVERSE inE("IsIdentifiedBy") FROM (
SELECT FROM SoftwareFacet WHERE group = "org.gcube.data-catalogue" AND name = "catalogue-virtual-service"
)
)
)
)
)
)
) WHERE value = "gcat-configuration"
)
)
)
)
) WHERE @class INSTANCEOF "SimpleFacet"

View File

@ -1,6 +1,6 @@
{
"type": "SimpleFacet",
"_in": {
"_source": {
"type": "ConsistsOf",
"source": {
"type": "Configuration",

View File

@ -1 +1 @@
SELECT FROM ( TRAVERSE inV("SimpleFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE outV("Configuration") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM ( TRAVERSE inV("IdentifierFacet") FROM ( TRAVERSE outE("IsIdentifiedBy") FROM ( TRAVERSE inV("Configuration") FROM ( TRAVERSE outE("IsCustomizedBy") FROM ( TRAVERSE outV("VirtualService") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM ( TRAVERSE inV("SoftwareFacet") FROM ( TRAVERSE outE("IsIdentifiedBy") FROM ( TRAVERSE outV("VirtualService") FROM ( SELECT FROM IsCustomizedBy)))) WHERE group = "org.gcube.data-catalogue" AND name = "catalogue-virtual-service"))))))) WHERE value = "gcat-configuration")))))
SELECT FROM ( TRAVERSE inV("SimpleFacet") FROM ( TRAVERSE outE("ConsistsOf") FROM ( TRAVERSE outV("Configuration") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM ( TRAVERSE inV("IdentifierFacet") FROM ( TRAVERSE outE("IsIdentifiedBy") FROM ( TRAVERSE inV("Configuration") FROM ( TRAVERSE outE("IsCustomizedBy") FROM ( TRAVERSE outV("VirtualService") FROM ( TRAVERSE inE("IsIdentifiedBy") FROM ( SELECT FROM SoftwareFacet WHERE group = "org.gcube.data-catalogue" AND name = "catalogue-virtual-service"))))))) WHERE value = "gcat-configuration"))))) WHERE @class INSTANCEOF "SimpleFacet"