Compare commits

...

115 Commits

Author SHA1 Message Date
luca.frosini 30e8c84258 Fixed projection 2023-11-29 14:26:02 +01:00
luca.frosini c324b3ab41 Fixed JSON queries 2023-11-29 13:19:48 +01:00
luca.frosini c5531d7c54 JSON queries has been switched to match queries 2023-11-28 16:57:54 +01:00
luca.frosini 8af757f3db Fixing tests and match queries 2023-11-27 17:44:15 +01:00
luca.frosini 0812a0c94c Improving code 2023-11-24 17:44:27 +01:00
luca.frosini 78ea9c2307 Improving code 2023-11-24 15:36:43 +01:00
luca.frosini 6657543a63 Improving code 2023-11-24 14:30:51 +01:00
luca.frosini 6a1e0e5838 Implementing projection 2023-11-24 14:03:06 +01:00
luca.frosini 5fe0e5771b Implementing projection match query 2023-11-23 17:10:17 +01:00
luca.frosini 9450134790 Implementing projection 2023-11-20 17:34:48 +01:00
luca.frosini f2cf0a4f17 Implementing projection 2023-11-20 16:27:57 +01:00
luca.frosini 24f2ec53c1 Implementing feature 2023-11-17 17:40:10 +01:00
luca.frosini d2b797c19a Implementing the new match query 2023-11-17 17:21:45 +01:00
luca.frosini 46cb4f0975 Added methods to create match query 2023-11-16 14:29:32 +01:00
luca.frosini 816c7693dc Fixed queries 2023-11-16 14:09:57 +01:00
luca.frosini ffd20403da Fixed test 2023-11-16 12:12:04 +01:00
luca.frosini 2dba63771b Renamed .query files in .oquery (o stand for OrientDB) 2023-11-16 12:11:03 +01:00
luca.frosini e0bfef4c49 Changing the generated query to support projection 2023-11-16 12:02:17 +01:00
luca.frosini 2d863b99fc Fixed ServerContextCache issue 2023-11-10 15:44:43 +01:00
luca.frosini 084e223669 Trying to fix Server Context Cache 2023-11-10 14:37:43 +01:00
luca.frosini e8a98dd54a Fixing REST API 2023-11-10 13:50:33 +01:00
luca.frosini 0878cdd7bd Merge remote-tracking branch 'origin/feature/24648' 2023-11-09 17:55:00 +01:00
luca.frosini dd7ad6840e Added pagination support 2023-11-09 17:38:51 +01:00
luca.frosini ca51189cab Cleaning commented code 2023-11-09 17:33:02 +01:00
luca.frosini dfccd87a62 Fixed queries and test 2023-11-09 17:21:21 +01:00
luca.frosini 00e0fc2a55 Improving queries 2023-11-09 12:53:35 +01:00
luca.frosini 996997804a Fixed changelog 2023-11-08 17:24:35 +01:00
luca.frosini 7ce298be17 Full refactor of JsonQuery management 2023-11-08 17:16:18 +01:00
luca.frosini b978185cd5 Added skip limit 2023-11-07 18:01:38 +01:00
luca.frosini 68c742eb09 Removed postfilter because polymorphism support has been added in query 2023-11-06 17:45:00 +01:00
luca.frosini 7409a8d278 Improving Json Queries 2023-11-03 17:56:55 +01:00
luca.frosini c611a839eb Improving offset limit management to properly support paginated result 2023-10-31 15:24:29 +01:00
luca.frosini 1eb1cf6773 Fixing whitespaces 2023-10-31 14:40:23 +01:00
luca.frosini d786ffff98 Fixing context pagination 2023-10-31 14:39:39 +01:00
luca.frosini 08fca98875 Changed the way to paginate results due to missing skip in TRAVERSE
command
2023-09-27 16:23:35 +02:00
luca.frosini e5106cd6c0 Fixed test to be able to be executed on OS different from linux 2023-09-27 16:16:23 +02:00
luca.frosini 849cc923f3 Added pagination support for QueryTemplates 2023-09-27 15:18:28 +02:00
luca.frosini 9851f83ecd Fixed log 2023-09-27 15:18:03 +02:00
luca.frosini 9b3ffcf5b4 Improved Query Readability 2023-09-27 15:17:54 +02:00
luca.frosini c34c5f9a59 Added pagination in JSONQuery 2023-09-27 15:16:58 +02:00
luca.frosini 22bedb9a75 Added complete test for ERElement pagination 2023-09-27 15:13:02 +02:00
luca.frosini 3f1a4f5795 Added pagination to prepared query 2023-09-27 15:12:36 +02:00
luca.frosini 5741f52072 fixed test 2023-09-27 15:11:41 +02:00
luca.frosini 290cb44221 Improved JUnit test to properly verify context pagination 2023-09-27 12:23:11 +02:00
luca.frosini 90e1ca1a28 Added pagination to context listing 2023-09-27 12:22:11 +02:00
luca.frosini af48246afa Added limit offset request check in query and listing methods 2023-09-25 18:01:47 +02:00
luca.frosini ee8bdefa8b Added pagination to contexts 2023-09-22 19:06:05 +02:00
luca.frosini 8c5dcd0341 improved test 2023-09-22 18:49:49 +02:00
luca.frosini 9d9ec44b90 Added the possibility to get unbounded instances using -1 2023-09-22 18:10:20 +02:00
luca.frosini 38668d8a21 Added pagination for instances listing 2023-09-22 16:58:23 +02:00
luca.frosini 31f0120c50 Added check of limit/offset query parameter 2023-09-21 22:13:41 +02:00
luca.frosini 01716b55cd Added libraries to comply with JDK 11 2023-09-21 10:28:01 +02:00
luca.frosini d650c16e29 Renamed functions to improve code 2023-09-21 10:27:28 +02:00
luca.frosini d2ca74cc72 Implementing limit offset 2023-09-18 18:09:00 +02:00
luca.frosini 95b86d8a40 Merged changes made to solve bug #25650 2023-09-18 16:30:43 +02:00
luca.frosini a3a2e3a0a9 Fixed bug #25650 2023-09-15 18:31:53 +02:00
luca.frosini 88c1ee60d8 Improved changelog 2023-09-14 15:10:26 +02:00
luca.frosini 71b780eb2a Extended BaseRequestInfo 2023-09-14 15:10:11 +02:00
luca.frosini 0cb336ded4 Enhanced version 2023-09-13 11:15:20 +02:00
luca.frosini 402ead3696 Removed -SNAPSHOT to release the component 2023-09-05 15:51:47 +02:00
luca.frosini d977e1ef8a Updated changelog 2023-08-28 13:47:50 +02:00
luca.frosini 1332261fc4 Cleaning RequestInfo refs #25211 2023-08-28 13:41:57 +02:00
luca.frosini cbe25a5832 Ignored MacOs File 2023-06-21 11:40:56 +02:00
Luca Frosini e3b6c8add5 Added shadow context class to allow to implements #19428 2023-05-19 16:05:28 +02:00
Luca Frosini dab30f5670 Fixing code 2023-05-17 14:03:59 +02:00
Luca Frosini 76438c6a90 Fixed path 2023-05-16 16:00:45 +02:00
Luca Frosini 46f0bea227 Fixed paths and called methods 2023-05-16 15:12:26 +02:00
Luca Frosini c7b9d21bba Rationalised accounting methods 2023-05-16 14:59:21 +02:00
Luca Frosini c79b579925 fixing query templates details 2023-05-16 14:07:12 +02:00
Luca Frosini f9e474d4cd Fixed code 2023-05-16 11:47:31 +02:00
Luca Frosini 804e2b2343 Fixing server context cache 2023-05-15 17:41:34 +02:00
Luca Frosini 20914f3f06 Fixed cache 2023-05-15 17:33:26 +02:00
Luca Frosini b32f282044 Fixed checked query parameters 2023-05-15 16:47:30 +02:00
Luca Frosini fe6e990605 Fixing get parameters 2023-05-15 16:33:47 +02:00
Luca Frosini 738b693697 Fixing bug 2023-05-15 13:00:59 +02:00
Luca Frosini 01a8480180 Applied changes made in IS Model 2023-05-12 17:55:53 +02:00
Luca Frosini a8fb9de301 Fixing cache 2023-05-10 17:57:10 +02:00
Luca Frosini a21b1d9173 Improving ServerContextCache 2023-05-10 17:43:36 +02:00
Luca Frosini a424844dce Improved Metadata management 2023-05-10 17:25:54 +02:00
Luca Frosini f4600172e2 Managing Context Cache 2023-05-10 17:21:00 +02:00
Luca Frosini 024af70188 Fixed code to properly set UriInfo 2023-05-05 15:48:59 +02:00
Luca Frosini 992b9d23cc Added BaseRest as superclass 2023-05-05 15:34:58 +02:00
Luca Frosini 69bac7493d Added missing query parameter analisys 2023-05-05 11:11:39 +02:00
Luca Frosini 074935d3d2 Add id as first member in serialization 2023-05-04 18:08:59 +02:00
Luca Frosini 8472c7783d Fixed changelog 2023-05-04 15:48:00 +02:00
Luca Frosini 1a621dc3da Fixed changelog 2023-05-03 16:02:06 +02:00
Luca Frosini a3c0f725c6 Extracted RequestInfo interface and renamed class to ServerRequestInfo 2023-05-02 17:24:42 +02:00
Luca Frosini 119ae14dfa Metadata are included only if requested by the client 2023-05-02 14:48:38 +02:00
Luca Frosini 3fbdc1d734 Managing expectedtype property 2023-04-28 17:17:14 +02:00
Luca Frosini 3776bdae50 Reorganizing property order 2023-04-28 14:52:46 +02:00
Luca Frosini 7d7b9478bb Fixed code to comply with uuid property rename to id 2023-04-28 11:43:48 +02:00
Luca Frosini 5638c99feb Ordering Json Properties 2023-04-27 16:30:41 +02:00
Luca Frosini 999603e41a Added log for testing purposes 2023-04-27 12:21:14 +02:00
Luca Frosini 93e3768a64 Providing an order to properties of JSON to improve human readability 2023-04-27 12:20:57 +02:00
Luca Frosini 7b582be333 Refactored due to is-model constant name change 2023-04-27 11:15:01 +02:00
Luca Frosini 0724020bd2 Refactored to use getTypename() function of Element 2023-04-27 11:00:47 +02:00
Luca Frosini 8a23d5898b Refactored due to is-model constant name change 2023-04-27 10:42:07 +02:00
Luca Frosini ff68eb6f28 Changed '@class' to 'type' 2023-04-26 21:44:03 +02:00
Luca Frosini 39556110c2 Switched to use utility 2023-04-21 17:04:14 +02:00
Luca Frosini b1153f7283 Migrated code to use utility 2023-04-21 16:41:35 +02:00
Luca Frosini 40b21420a8 Reorganized utilities and their usage 2023-04-21 15:56:52 +02:00
Luca Frosini 8f67beb172 Fixed getTypeName 2023-04-21 14:30:07 +02:00
Luca Frosini a2b7311ba0 Commented distruptive test 2023-04-21 13:54:26 +02:00
Luca Frosini 6df9da4567 Fixed queries 2023-04-21 11:58:33 +02:00
Luca Frosini f61f240576 Fixing JSON query 2023-04-20 18:46:39 +02:00
Luca Frosini 09eb625a14 Redesigning E/R instance definition 2023-04-20 16:59:19 +02:00
Luca Frosini e2bd5c85d8 Redesigning E/R instance definition 2023-04-20 13:46:46 +02:00
Luca Frosini 967e9c6ec6 Redesigning E/R instance definition 2023-04-20 12:37:48 +02:00
Luca Frosini 237d637809 Redesigning E/R instance definition 2023-04-20 12:09:07 +02:00
Luca Frosini 88fe4e3ff3 Redesigning E/R instance definition 2023-04-20 11:11:52 +02:00
Luca Frosini 5893cfd61a Redesigning E/R instance definition 2023-04-20 08:27:17 +02:00
Luca Frosini 999bbb1ab1 Redesigning E/R instance definition 2023-04-19 16:49:06 +02:00
Luca Frosini 55e6951557 Porting code to redesigned E/R format 2023-04-19 13:14:11 +02:00
Luca Frosini 5c3735d669 Porting code to redesigned E/R format 2023-04-19 11:36:49 +02:00
Luca Frosini 79c0c9a0ab Redesigning E/R instance definition 2023-04-18 17:52:07 +02:00
133 changed files with 5663 additions and 2277 deletions

2
.gitignore vendored
View File

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

View File

@ -2,17 +2,32 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Resource Registry Service
## [v4.4.0-SNAPSHOT]
- Added query parameters to paginate result of queries [#24648]
- Completely refactored JSON Query management [#24163]
## [v4.3.0]
- Migrated code to reorganized E/R format [#24992]
- Metadata are added only if requested by the client [#25040]
- Restored Encrypted Property Type and removed Vault [#25041]
- Cleaned RequestInfo in RequestFilter class [#25211]
- Solved bug which allow to create two query template with the same name if a null id was provided [#25650]
## [v4.2.0]
- 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]

26
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry</artifactId>
<version>4.2.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>
@ -31,7 +31,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-smartgears-bom</artifactId>
<version>2.3.0</version>
<version>2.5.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -52,7 +52,13 @@
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-utils</artifactId>
<version>[2.1.0, 3.0.0-SNAPSHOT)</version>
<version>[2.2.0, 3.0.0-SNAPSHOT)</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.orientechnologies</groupId>
@ -95,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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,6 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Key;
@ -18,16 +17,12 @@ import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.entities.EntityElement;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.base.reference.relations.RelationElement;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.discovery.Discovery;
import org.gcube.informationsystem.discovery.RegistrationProvider;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
@ -36,7 +31,6 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecuri
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type;
import org.gcube.informationsystem.types.reference.entities.EntityType;
@ -71,7 +65,6 @@ import com.orientechnologies.orient.core.record.OElement;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("unchecked")
public class DatabaseEnvironment {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironment.class);
@ -198,7 +191,7 @@ public class DatabaseEnvironment {
List<Class<? extends Element>> definitionToBeCreated = new ArrayList<>();
definitionToBeCreated.add(PropertyElement.class);
definitionToBeCreated.add(Property.class);
definitionToBeCreated.add(Header.class);
definitionToBeCreated.add(Metadata.class);
definitionToBeCreated.add(PropertyDefinition.class);
definitionToBeCreated.add(PropertyType.class);
definitionToBeCreated.add(LinkedEntity.class);
@ -215,7 +208,7 @@ public class DatabaseEnvironment {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(clz);
if(clz.equals(Property.class) || clz.equals(Header.class) ) {
if(clz.equals(Property.class) || clz.equals(Metadata.class) ) {
((TypeManagement) typeManagement).setSkipTypeDefinitionCreation(true);
}
@ -231,17 +224,17 @@ public class DatabaseEnvironment {
}
/*
* We have already created Property and Header
* because Header is needed to create
* We have already created Property and Metadata
* because Metadata is needed to create
* types for internal use (i.e. Context, EntityType).
*
* For Property and Header we also need
* For Property and Metadata we also need
* to create the instance in TypeSecurityContext
* as we will do for any other Property specialization.
*/
List<Class<? extends Element>> schemaToBeCreated = new ArrayList<>();
schemaToBeCreated.add(Property.class);
schemaToBeCreated.add(Header.class);
schemaToBeCreated.add(Metadata.class);
for(Class<? extends Element> clazz : schemaToBeCreated) {
ElementManagement<? extends OElement,?> erManagement = new PropertyTypeDefinitionManagement();
erManagement.setJson(TypeMapper.serializeType(clazz));
@ -293,8 +286,8 @@ public class DatabaseEnvironment {
KEY = initDbKey(properties);
initContextCacheRenewal();
// Initializing ServerContextCache instance
ServerContextCache.getInstance();
}
protected static Key initDbKey(Properties properties) {
@ -382,26 +375,6 @@ public class DatabaseEnvironment {
}
}
public static void initContextCacheRenewal() {
ContextCacheRenewal contextCacheRenewal = new ContextCacheRenewal() {
@Override
public List<Context> renew() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement();
String contextsJsonString = contextManagement.allFromServer(false);
List<Context> contexts = null;
try {
contexts = ElementMapper.unmarshalList(contextsJsonString);
} catch (IOException e) {
logger.error("Unable to read contexts from DB", e);
}
return contexts;
}
};
ContextCache.getInstance().setContextCacheRenewal(contextCacheRenewal);
}
public static Key getDatabaseKey() {
return KEY;
}

View File

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

View File

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

View File

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

View File

@ -4,6 +4,7 @@ import java.security.Key;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
@ -11,11 +12,11 @@ import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.properties.Vault;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
@ -24,9 +25,11 @@ import org.gcube.informationsystem.resourceregistry.instances.base.ElementManage
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.VaultOrient;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -49,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);
}
@ -60,13 +64,17 @@ public class PropertyElementManagement {
JsonNode jsonNode = jsonNodeOrig.deepCopy();
if(jsonNode.has(Element.SUPERCLASSES_PROPERTY)) {
((ObjectNode) jsonNode).remove(Element.SUPERCLASSES_PROPERTY);
if(jsonNode.has(ModelElement.SUPERTYPES_PROPERTY)) {
((ObjectNode) jsonNode).remove(ModelElement.SUPERTYPES_PROPERTY);
}
if(jsonNode.has(Element.CLASS_PROPERTY)) {
if(jsonNode.has(ModelElement.EXPECTED_TYPE_PROPERTY)) {
((ObjectNode) jsonNode).remove(ModelElement.EXPECTED_TYPE_PROPERTY);
}
String type = TypeUtility.getTypeName(jsonNode);
if(type!=null) {
// Complex type
String type = ElementManagement.getClassProperty(jsonNode);
OClass oClass = null;
try {
@ -84,13 +92,23 @@ public class PropertyElementManagement {
}
try {
Header header = HeaderUtility.getHeader(jsonNode, false);
if(header != null) {
throw new ResourceRegistryException("A property object cannot have an Header");
UUID uuid = UUIDUtility.getUUID(jsonNode);
if(uuid != null) {
throw new ResourceRegistryException("A property object cannot have an UUID");
}
} catch(Exception e) {
logger.warn("An invalid Header has been provided. Anyway property object cannot have an Header.");
throw new ResourceRegistryException("An property object cannot have an Header");
logger.warn("An invalid UUID has been provided. Anyway property object cannot have an UUID.");
throw new ResourceRegistryException("An property object cannot have an UUID");
}
try {
Metadata metadata = MetadataUtility.getMetadata(jsonNode);
if(metadata != null) {
throw new ResourceRegistryException("A property object cannot have a Metadata");
}
} catch(Exception e) {
logger.warn("An invalid Metadata has been provided. Anyway property object cannot have a Metadata.");
throw new ResourceRegistryException("An property object cannot have a Metadata");
}
@ -99,7 +117,7 @@ public class PropertyElementManagement {
* Resource Registry must decrypt the value with the Context Key and Encrypt it with DB key.
* The opposite operation is done when the value is read by clients.
*/
if(oClass.isSubClassOf(EncryptedOrient.NAME)) {
if(oClass.isSubClassOf(Encrypted.NAME)) {
EncryptedOrient encrypted = new EncryptedOrient();
oDocument = encrypted;
oDocument.fromJSON(jsonNode.toString());
@ -111,25 +129,7 @@ public class PropertyElementManagement {
encrypted.setDecryptedValue(decryptedValue, false);
} catch(Exception e) {
throw new ResourceRegistryException("Unable to manage " + EncryptedOrient.NAME + " " + org.gcube.informationsystem.model.reference.properties.Property.NAME);
}
return oDocument;
}
if(oClass.isSubClassOf(Vault.NAME)) {
VaultOrient vault = new VaultOrient();
oDocument = vault;
oDocument.fromJSON(jsonNode.toString());
try {
String contextEncryptedValue = vault.getValue();
// Decrypting with Context Key (default key)
String decryptedValue = StringEncrypter.getEncrypter().decrypt(contextEncryptedValue);
vault.setDecryptedValue(decryptedValue, false);
} catch(Exception e) {
throw new ResourceRegistryException("Unable to manage " + Vault.NAME + " " + org.gcube.informationsystem.model.reference.properties.Property.NAME);
throw new ResourceRegistryException("Unable to manage " + Encrypted.NAME + " " + org.gcube.informationsystem.model.reference.properties.Property.NAME);
}
return oDocument;
}
@ -145,7 +145,7 @@ public class PropertyElementManagement {
public static JsonNode getJsonNode(ODocument oDocument) throws ResourceRegistryException {
try {
String type = oDocument.getClassName();
String json = oDocument.toJSON("class");
String json = OrientDBUtility.toJsonString(oDocument);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
@ -166,7 +166,7 @@ public class PropertyElementManagement {
Collection<String> superClasses = cachedType.getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
((ObjectNode) jsonNode).replace(Element.SUPERCLASSES_PROPERTY, arrayNode);
((ObjectNode) jsonNode).replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
/*
* In case it is an Encrypted type the value is encrypted with the DB Key
@ -174,16 +174,16 @@ public class PropertyElementManagement {
* The opposite operation is done when the value is set from clients.
* see {@link PropertyManagement#getPropertyDocument(JsonNode) getPropertyDocument()}
*/
if(oClass.isSubClassOf(EncryptedOrient.NAME)) {
if(oClass.isSubClassOf(Encrypted.NAME)) {
try {
EncryptedOrient encrypted = null;
String encryptedValue = (String) oDocument.getProperty(EncryptedOrient.VALUE);
String encryptedValue = (String) oDocument.getProperty(Encrypted.VALUE);
if(oDocument instanceof EncryptedOrient) {
encrypted = (EncryptedOrient) oDocument;
if(encrypted.getDbEncryptedValue().compareTo(encryptedValue)==0) {
((ObjectNode) jsonNode).put(EncryptedOrient.VALUE, encrypted.getContextEncryptedValue());
((ObjectNode) jsonNode).put(Encrypted.VALUE, encrypted.getContextEncryptedValue());
}
}else {
encrypted = new EncryptedOrient();
@ -197,7 +197,7 @@ public class PropertyElementManagement {
String contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue);
// Setting the value encrypted with DB key
((ObjectNode) jsonNode).put(EncryptedOrient.VALUE, contextEncryptedValue);
((ObjectNode) jsonNode).put(Encrypted.VALUE, contextEncryptedValue);
}
}catch (Exception e) {
@ -205,38 +205,6 @@ public class PropertyElementManagement {
}
}
if(oClass.isSubClassOf(Vault.NAME)) {
try {
VaultOrient vaultOrient = null;
String encryptedValue = (String) oDocument.getProperty(Vault.VALUE);
if(oDocument instanceof VaultOrient) {
vaultOrient = (VaultOrient) oDocument;
if(vaultOrient.getDbEncryptedValue().compareTo(encryptedValue)==0) {
((ObjectNode) jsonNode).put(Vault.VALUE, vaultOrient.getContextEncryptedValue());
}
}else {
vaultOrient = new VaultOrient();
oDocument = (ODocument) vaultOrient;
// Decrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey();
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encryptedValue, databaseKey);
// Encrypting with Context Key (default key)
String contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue);
// Setting the value encrypted with DB key
((ObjectNode) jsonNode).put(Vault.VALUE, contextEncryptedValue);
}
}catch (Exception e) {
throw new ResourceRegistryException("Errror while managing " + EncryptedOrient.NAME+ " "+ Property.NAME, e);
}
}
return jsonNode;
} catch (ResourceRegistryException e) {

View File

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

View File

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

View File

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

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;
@ -18,19 +14,17 @@ import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
@ -39,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.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
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;
@ -147,8 +141,6 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
protected EntityManagement(AccessType accessType) {
super(accessType);
this.ignoreKeys.add(Entity.HEADER_PROPERTY);
this.ignoreStartWithKeys.add(IN_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(OUT_PREFIX.toLowerCase());
this.ignoreStartWithKeys.add(IN_PREFIX.toUpperCase());
@ -157,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;
@ -173,7 +165,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
try {
retrieveElementFromAnyContext();
throw getSpecificAvailableInAnotherContextException(typeName == null ? accessType.getName()
: typeName + " with UUID " + uuid + " is available in another "
: typeName + " with ID " + uuid + " is available in another "
+ Context.class.getSimpleName());
} catch(AvailableInAnotherContextException e1) {
throw e1;
@ -215,7 +207,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". ");
errorMessage.append(Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
relationManagements.put(id, relationManagement);
@ -287,7 +279,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
logger.debug("Created {} is {}", OVertex.class.getSimpleName(),
Utility.toJsonString((OVertex) element, true));
OrientDBUtility.getAsStringForLogging((OVertex) element));
return element;
} catch(ResourceRegistryException e) {
@ -314,7 +306,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the instance is added in internalAddToContext() function after
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
* the update of Metadata i.e. modifiedBy, lastUpdateTime
*/
if(honourPropagationConstraintsInContextSharing) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
@ -338,7 +330,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
setOperation(Operation.ADD_TO_CONTEXT);
reallyAddToContext();
if(!skipped) {
HeaderUtility.updateModifiedByAndLastUpdate(element);
MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
@ -353,7 +345,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
@Override
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
@ -402,7 +394,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
try {
setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext();
HeaderUtility.updateModifiedByAndLastUpdate(element);
MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
@ -442,7 +434,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
/*
* DO NOT UNCOMMENT
* the instance is added internalAddToContext() function after
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* affectedInstances.put(uuid, serializeSelfOnly());
*/
}
@ -498,208 +490,32 @@ 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) {
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) vertex);
try {
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {
return objectMapper.writeValueAsString(arrayNode);
} catch(JsonProcessingException e) {
throw new ResourceRegistryException(e);
}
}
public boolean propertyMatchRequestedValue(OVertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
return requestedValue.compareTo(instanceValue.toString())==0;
/*
OClass oClass = ElementManagement.getOClass(v);
OProperty oProperty = oClass.getProperty(key);
if(oProperty==null){
// It is an additional property
return requestedValue.compareTo(instanceValue.toString())==0;
}
OType oType = oProperty.getType();
switch (oType) {
case BOOLEAN:
Boolean requested = Boolean.valueOf(requestedValue.toLowerCase());
return requested == (Boolean) instanceValue;
case STRING:
return requestedValue.compareTo((String) instanceValue)==0;
default:
return false;
}
*/
}
/*
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<?> references = null;
if(referenceUUID != null) {
OElement element = null;
try {
element = ElementManagementUtility.getAnyElementByUUID(oDatabaseDocument, referenceUUID);
}catch (ResourceRegistryException e) {
String error = String.format("No instace with UUID %s exists", referenceUUID.toString());
throw new InvalidQueryException(error);
}
if(element instanceof OVertex) {
EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) element);
String elementType = entityManagement.getTypeName();
if(elementType.compareTo(referenceType) != 0) {
if(polymorphic && getOClass().isSubClassOf(referenceType)) {
// OK
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
}
List<OVertex> vertexes = new ArrayList<>();
vertexes.add((OVertex) element);
references = vertexes;
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
} else {
references = oDatabaseDocument.browseClass(referenceType, polymorphic);
}
Set<ORID> analysed = new HashSet<>();
for(Object r : references) {
OVertex v = (OVertex) r;
boolean skip = false;
// checking if the constraints are satisfied
for(String key : constraint.keySet()) {
String value = constraint.get(key);
Object o = v.getProperty(key);
if(value==null) {
if(o==null) {
//ok
}else {
skip = true;
break;
}
}else {
if(o==null) {
// The vertex has not a required property to be tested
// or the property is null
skip = true;
break;
}else {
skip = !propertyMatchRequestedValue(v, key, value, o);
if(skip) {
break;
}
}
}
}
if(skip) {
if(++position < offset) {
continue;
}
List<ODirection> directions = new ArrayList<>();
if(direction==ODirection.BOTH) {
directions.add(ODirection.IN);
directions.add(ODirection.OUT);
}else {
directions.add(direction);
}
for(ODirection d : directions) {
Iterable<OEdge> edges = v.getEdges(d.opposite(), relationType);
for(OEdge edge : edges) {
OVertex vertex = edge.getVertex(d);
ORID vertexORID = vertex.getIdentity();
if(analysed.contains(vertexORID)) {
continue;
}
analysed.add(vertexORID);
if(v.getIdentity().compareTo(vertexORID) == 0) {
continue;
}
OClass oClass = ElementManagementUtility.getOClass(vertex);
/*
* If the requested type (i.e. elementType)
* differs form the resulting type (i.e. oClass.getName())
* we need to evaluate if polymorphism is requested and
* if the resulting type is a subclass of the requested type
*
*/
if(oClass.getName().compareTo(typeName)!=0) {
if(polymorphic && oClass.isSubClassOf(typeName)) {
// OK
} else {
// excluding from results
continue;
}
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex);
try {
if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
continue;
}
/*
JsonNode jsonNode;
if(includeRelationInResult) {
RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
oDatabaseDocument, edge);
jsonNode = relationManagement.serializeAsJsonNode();
}else {
jsonNode = entityManagement.serializeAsJsonNode();
}
*/
JsonNode node = entityManagement.serializeAsJsonNode();
arrayNode.add(node);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
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);
}
}
@ -710,102 +526,115 @@ 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();
if(referenceUUID != null) {
constraint.put(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY, referenceUUID.toString());
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 @class='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 @class='");
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(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
if(oClass.isSubClassOf(typeName)) {
continue;
}
}
OVertex vertex = (OVertex) element;
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex);
try {
if(constraint.containsKey(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY)) {
String uuid = constraint.get(Entity.HEADER_PROPERTY + "." + Header.UUID_PROPERTY);
if(constraint.containsKey(Entity.ID_PROPERTY)) {
String uuid = constraint.get(Entity.ID_PROPERTY);
if(entityManagement.getUUID().compareTo(UUID.fromString(uuid)) == 0) {
continue;
}
}
entityManagement.setAsEntryPoint();
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -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

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

View File

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

View File

@ -19,7 +19,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isr
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
@ -88,10 +88,10 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e;
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}

View File

@ -21,7 +21,6 @@ import org.gcube.informationsystem.model.reference.properties.PropagationConstra
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
@ -29,6 +28,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
@ -39,10 +39,12 @@ 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.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.PropagationConstraintOrient;
import org.gcube.informationsystem.resourceregistry.utils.Utility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
@ -219,7 +221,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else {
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
}
@ -231,7 +233,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else {
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
@ -253,10 +255,10 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
propagationConstraint = (PropagationConstraint) oDocument;
} else {
try {
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, oDocument.toJSON());
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, OrientDBUtility.toJsonString(oDocument));
} catch(Exception e) {
logger.warn("Unable to recreate {}. {}", PropagationConstraint.NAME,
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -406,21 +408,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
AddConstraint addConstraint = AddConstraint.unpropagate;
try {
propagationConstraint = Utility.getPropertyDocument(PropagationConstraint.class, element,
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.ADD_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.ADD_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error);
throw new ResourceRegistryException(error, e);
}
@ -444,7 +446,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the relation instance is added in internalAddToContext() function after
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
* the update of Metadata i.e. modifiedBy, lastUpdateTime
*/
break;
@ -461,7 +463,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
* the relation instance is added in internalAddToContext() function after
* the update of Header metadata i.e. modifiedBy, lastUpdateTime
* the update of Metadata i.e. modifiedBy, lastUpdateTime
*/
}
}
@ -473,7 +475,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
operation = Operation.ADD_TO_CONTEXT;
reallyAddToContext();
if(!skipped && propagationConstraint.getAddConstraint()==PropagationConstraint.AddConstraint.propagate) {
HeaderUtility.updateModifiedByAndLastUpdate(element);
MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
}
@ -510,7 +512,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
@Override
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
@ -561,21 +563,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
RemoveConstraint removeConstraint = RemoveConstraint.keep;
try {
propagationConstraint = Utility.getPropertyDocument(PropagationConstraint.class, element,
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.REMOVE_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.REMOVE_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error, e);
@ -650,7 +652,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
try {
setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext();
HeaderUtility.updateModifiedByAndLastUpdate(element);
MetadataUtility.updateModifiedByAndLastUpdate(element);
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
} catch(ResourceRegistryException e) {
@ -722,29 +724,22 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
DeleteConstraint deleteConstraint = DeleteConstraint.keep;
try {
PropagationConstraint propagationConstraint = Utility.getPropertyDocument(PropagationConstraint.class,
PropagationConstraint propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class,
element, Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getDeleteConstraint() != null) {
deleteConstraint = propagationConstraint.getDeleteConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.DELETE_PROPERTY, Utility.toJsonString(element, true),
Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.DELETE_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error);
// logger.error(error);
// TODO Added for backward compatibility
deleteConstraint = DeleteConstraint.values()[propagationConstraint.getRemoveConstraint().ordinal()];
/*
* TODO Restore the exception raising and remove the line above
*
* throw new ResourceRegistryException(error);
*/
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
Utility.toJsonString(element, true), deleteConstraint, Utility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.getAsStringForException(element), deleteConstraint, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
// pre-loading target entity because after deleting the relation we will not be able to get it
@ -784,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)) {
@ -799,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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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 operatorKey;
protected final String dbOperator;
protected final String description;
private LogicalOperator(String operatorKey, String dbOperator, String description) {
this.operatorKey = operatorKey;
this.dbOperator = dbOperator;
this.description = description;
}
public String getOperatorKey() {
return operatorKey;
}
public String getDbOperator() {
return dbOperator;
}
public String getDescription() {
return description;
}
private static Set<String> operators;
private static Map<String,LogicalOperator> operatorByKey;
static {
LogicalOperator.operators = new HashSet<>();
LogicalOperator.operatorByKey = new HashMap<>();
for(LogicalOperator logicalOperator : LogicalOperator.values()) {
LogicalOperator.operators.add(logicalOperator.getOperatorKey());
LogicalOperator.operatorByKey.put(logicalOperator.getOperatorKey(), logicalOperator);
}
}
public static Set<String> getOperators() {
return LogicalOperator.operators;
}
public static LogicalOperator getOperator(String key) {
return operatorByKey.get(key);
}
}

View File

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

View File

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

View File

@ -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

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

View File

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

View File

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

View File

@ -5,6 +5,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
@ -14,13 +15,14 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -28,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;
@ -40,6 +43,8 @@ import org.gcube.informationsystem.resourceregistry.instances.model.entities.Res
import org.gcube.informationsystem.resourceregistry.queries.Query;
import org.gcube.informationsystem.resourceregistry.queries.QueryImpl;
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type;
@ -56,6 +61,11 @@ public class Access extends BaseRest {
public static final String RELATION_TYPE_PATH_PARAMETER = "RELATION_TYPE_NAME";
public static final String REFERENCE_TYPE_PATH_PARAMETER = "REFERENCE_TYPE_NAME";
public static final String RAW_QUERY_METHOD = "raw";
public static final String GRAPH_QUERY_METHOD = "graph";
public static final String JSON_QUERY_METHOD = "json";
public static final String PREPARED_QUERY_METHOD = "prepared";
public Access() {
super();
}
@ -68,7 +78,12 @@ public class Access extends BaseRest {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String getAllContexts() throws ResourceRegistryException {
logger.info("Requested to read all {}s", org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
CalledMethodProvider.instance.set("listContexts");
setAccountingMethod(Method.LIST, org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
@ -87,13 +102,18 @@ public class Access extends BaseRest {
uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString();
}
logger.info("Requested to read {} with id {} ", org.gcube.informationsystem.contexts.reference.entities.Context.NAME, uuid);
CalledMethodProvider.instance.set("readContext");
setAccountingMethod(Method.READ, org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
return contextManagement.readAsString();
}
/*
* GET /access/types/{TYPE_NAME}[?polymorphic=false]
* e.g. GET /access/types/ContactFacet?polymorphic=true
@ -105,7 +125,11 @@ public class Access extends BaseRest {
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
throws SchemaNotFoundException, ResourceRegistryException {
logger.info("Requested Schema for type {}", type);
CalledMethodProvider.instance.set("readType");
setAccountingMethod(Method.READ, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeName(type);
@ -116,6 +140,72 @@ public class Access extends BaseRest {
throw new ResourceRegistryException(e);
}
}
/*
* GET /access/query-templates
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART)
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String allQueryTemplates() throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", QueryTemplate.NAME);
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
}
/*
* GET /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. GET /access/query-templates/GetAllEServiceWithState
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String readQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.READ, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
return queryTemplateManagement.read();
}
/*
* POST /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. POST /access/query-templates/GetAllEServiceWithState
*
* params = { "$state" : "ready" }
*
*/
@POST
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String runQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
queryTemplateManagement.setParams(params);
return queryTemplateManagement.run();
}
/*
* GET /access/instances/{TYPE_NAME}[?polymorphic=true]
@ -129,10 +219,11 @@ public class Access extends BaseRest {
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
CalledMethodProvider.instance.set("listInstances");
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
checkHierarchicalMode();
checkIncludeInstancesContexts();
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
@ -149,10 +240,10 @@ public class Access extends BaseRest {
public Response instanceExists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to check if {} with id {} exists", type, uuid);
CalledMethodProvider.instance.set("existInstance");
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
checkHierarchicalMode();
checkIncludeInstancesContexts();
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
@ -186,10 +277,10 @@ public class Access extends BaseRest {
public String getInstance(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read {} with id {}", type, uuid);
CalledMethodProvider.instance.set("readInstance");
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
checkHierarchicalMode();
checkIncludeInstancesContexts();
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
@ -198,9 +289,7 @@ public class Access extends BaseRest {
erManagement.setUUID(UUID.fromString(uuid));
return erManagement.read().toString();
}
/*
* GET /access/instances/{TYPE_NAME}/{UUID}/contexts
* e.g. GET /access/instances/ContactFacet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86/contexts
@ -212,13 +301,14 @@ public class Access extends BaseRest {
public String getInstanceContexts(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String instanceId) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
CalledMethodProvider.instance.set("getInstanceContexts");
setAccountingMethod(InstancesManager.GET_INSTANCE_CONTEXTS_METHOD);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(instanceId));
return erManagement.getContexts();
}
/**
* It includeSubtypes to query Entities and Relations in the current Context.<br />
* It accepts idempotent query only.. <br />
@ -231,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
@ -243,10 +336,19 @@ public class Access extends BaseRest {
@QueryParam(AccessPath.RAW_QUERY_PARAMETER) @DefaultValue(AccessPath.RAW_QUERY_PARAMETER_DEFAULT_VALUE) Boolean raw)
throws InvalidQueryException {
logger.info("Requested query (Raw {}):\n{}", raw, query);
CalledMethodProvider.instance.set("graphQuery");
if(raw) {
setAccountingMethod(Method.QUERY, RAW_QUERY_METHOD);
}else {
setAccountingMethod(Method.QUERY, GRAPH_QUERY_METHOD);
}
checkHierarchicalMode();
checkIncludeInstancesContexts();
ServerRequestInfo serverRequestInfo = initRequestInfo();
if(raw) {
// TODO Check if the role allow to request raw data
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
}else {
serverRequestInfo.checkAllBooleanQueryParameters();
}
Query queryManager = new QueryImpl();
return queryManager.query(query, raw);
@ -258,30 +360,30 @@ public class Access extends BaseRest {
* Content Body example:
*
* {
* "@class": "EService",
* "": "EService",
* "consistsOf": [
* {
* "@class": "ConsistsOf",
* "": "ConsistsOf",
* "propagationConstraint" : {
* "add": "propagate"
* },
* "target": {
* "@class": "StateFacet",
* "": "StateFacet",
* "value": "down"
* }
* },
* {
* "@class": "IsIdentifiedBy",
* "": "IsIdentifiedBy",
* "target": {
* "@class": "SoftwareFacet",
* "": "SoftwareFacet",
* "name": "data-transfer-service",
* "group": "DataTransfer"
* }
* },
* {
* "@class": "ConsistsOf",
* "": "ConsistsOf",
* "target": {
* "@class": "AccessPointFacet",
* "": "AccessPointFacet",
* "endpoint": "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
* }
* }
@ -297,10 +399,11 @@ public class Access extends BaseRest {
@Path(AccessPath.QUERY_PATH_PART)
public String jsonQuery(String jsonQuery) throws InvalidQueryException, ResourceRegistryException {
logger.info("Requested json query \n{}", jsonQuery);
CalledMethodProvider.instance.set("jsonQuery");
setAccountingMethod(Method.QUERY, JSON_QUERY_METHOD);
checkHierarchicalMode();
checkIncludeInstancesContexts();
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
JsonQuery jsonQueryManager = new JsonQuery();
jsonQueryManager.setJsonQuery(jsonQuery);
@ -323,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"})
@ -348,10 +451,11 @@ public class Access extends BaseRest {
logger.info("Requested {} instances having a(n) {} ({}={}} with {} ({}={}). Request URI is {})", resourcetype, relationType,
AccessPath._DIRECTION_QUERY_PARAMETER, direction, referenceType, AccessPath._POLYMORPHIC_QUERY_PARAMETER, polymorphic, uriInfo.getRequestUri());
CalledMethodProvider.instance.set("query");
setAccountingMethod(Method.QUERY, PREPARED_QUERY_METHOD);
checkHierarchicalMode();
checkIncludeInstancesContexts();
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement erManagement = ElementManagementUtility.getERManagement(resourcetype);

View File

@ -1,12 +1,11 @@
package org.gcube.informationsystem.resourceregistry.rest;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -17,56 +16,39 @@ public class BaseRest {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
public BaseRest() {
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
}
@Context
protected UriInfo uriInfo;
protected boolean isRequesterAllowedToPerformHierarchicalRequests() {
// TODO check is the user has the role to query in hierarchic mode
return true;
public BaseRest() {
}
protected void setAccountingMethod(String method) {
CalledMethodProvider.instance.set(method);
}
protected void checkHierarchicalMode() {
try {
List<String> hierarchicalQueryParameterList = uriInfo.getQueryParameters().get(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
if(hierarchicalQueryParameterList!=null && hierarchicalQueryParameterList.size()>0) {
String hierarchicalBooleanString = hierarchicalQueryParameterList.get(0);
boolean hierarchical = Boolean.valueOf(hierarchicalBooleanString);
boolean h = hierarchical && isRequesterAllowedToPerformHierarchicalRequests();
if(h) {
logger.info("The request was performed in hierarchical mode and the requester is allowed. Going to set hierarchical mode.");
ContextUtility.getHierarchicalMode().set(h);
}
}
}catch (Throwable t) {
logger.warn("Unable to properly set the Hierarchical Mode is set", t.getMessage());
}
protected void setAccountingMethod(Method method, String type) {
StringBuffer accountingMethod = new StringBuffer();
accountingMethod.append(method.getPrefix());
accountingMethod.append(type);
accountingMethod.append(method.getSuffix());
setAccountingMethod(accountingMethod.toString());
}
protected boolean isRequesterAllowedToRequestInstancesContexts() {
// TODO check is the user has the role to query in get instance Contexts
return true;
private ServerRequestInfo initRequestInfo(ServerRequestInfo requestInfo) {
requestInfo.setUriInfo(uriInfo);
RequestUtility.getRequestInfo().set(requestInfo);
return requestInfo;
}
protected void checkIncludeInstancesContexts() {
try {
List<String> includeContextsQueryParameterList = uriInfo.getQueryParameters().get(InstancePath.INCLUDE_CONTEXTS_IN_HEADER_QUERY_PARAMETER);
if(includeContextsQueryParameterList!=null && includeContextsQueryParameterList.size()>0) {
String includeContextsBooleanString = includeContextsQueryParameterList.get(0);
boolean includeContexts = Boolean.valueOf(includeContextsBooleanString);
boolean i = includeContexts && isRequesterAllowedToRequestInstancesContexts();
if(i) {
logger.info("The requet to include the contexts in header is allowed.");
ContextUtility.getIncludeInstanceContexts().set(true);
}
}
}catch (Throwable t) {
logger.warn("Unable to properly set the Hierarchical Mode is set", t.getMessage());
}
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,28 +18,22 @@ import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Path(ContextPath.CONTEXTS_PATH_PART)
public class ContextManager {
public class ContextManager extends BaseRest {
public static final String CONTEXT_UUID_PATH_PARAMETER = "CONTEXT_UUID";
/**
* Logger
*/
private static Logger logger = LoggerFactory.getLogger(ContextManager.class);
public ContextManager() {
ContextUtility.getHierarchicalMode().set(false);
ContextUtility.getIncludeInstanceContexts().set(false);
super();
}
/*
@ -51,7 +45,12 @@ public class ContextManager {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String all() throws ContextNotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", Context.NAME);
CalledMethodProvider.instance.set("listContexts");
setAccountingMethod(Method.LIST, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
@ -72,7 +71,11 @@ public class ContextManager {
uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString();
}
logger.info("Requested to read {} with id {} ", Context.NAME, uuid);
CalledMethodProvider.instance.set("readContext");
setAccountingMethod(Method.READ, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
@ -93,7 +96,11 @@ public class ContextManager {
public String updateCreate(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid, String json)
throws ResourceRegistryException {
logger.info("Requested to update/create {} with json {} ", Context.NAME, json);
CalledMethodProvider.instance.set("updateContext");
setAccountingMethod(Method.UPDATE, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));

View File

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

View File

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

View File

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

View File

@ -16,6 +16,7 @@ import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.GCubeSecret;
import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -49,6 +50,7 @@ public class RequestFilter implements ContainerRequestFilter, ContainerResponseF
SecretManagerProvider.instance.set(secretManager);
RequestUtility.getRequestInfo().remove();
}
@Override
@ -56,6 +58,7 @@ public class RequestFilter implements ContainerRequestFilter, ContainerResponseF
throws IOException {
logger.trace("ResponseFilter");
SecretManagerProvider.instance.remove();
RequestUtility.getRequestInfo().remove();
}
}

View File

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

View File

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

View File

@ -227,7 +227,7 @@ public class TypeManagement {
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
Type type, String baseType) throws SchemaException, SchemaNotFoundException {
Set<String> superClasses = type.getSuperClasses();
Set<String> superClasses = type.getExtendedTypes();
if(baseType != null) {
if(superClasses == null || superClasses.size() == 0) {
throw new RuntimeException(
@ -442,8 +442,8 @@ public class TypeManagement {
private boolean superClassesMatch(Type actualTypeDefinition, Type newTypeDefinition) {
// Checking superclasses. Must be the same. If differs the operation will be aborted.
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getSuperClasses());
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getSuperClasses());
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getExtendedTypes());
if(actualSuperClasses.size()!=newSuperClasses.size()) {
return false;
@ -454,7 +454,7 @@ public class TypeManagement {
return false;
}
actualSuperClasses = new HashSet<>(actualTypeDefinition.getSuperClasses());
actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
newSuperClasses.removeAll(actualSuperClasses);
if(newSuperClasses.size()>0) {
return false;
@ -463,7 +463,6 @@ public class TypeManagement {
return true;
}
// TODO
protected void updateTypeSchema(Type actualTypeDefinition, Type newTypeDefinition, AccessType baseElementAccessType)
throws SchemaNotFoundException, SchemaException {
@ -483,10 +482,10 @@ public class TypeManagement {
if(!superClassesMatch(actualTypeDefinition, newTypeDefinition)){
StringBuffer error = new StringBuffer();
error.append("The new type definition has a different set of superclasses. Actual version superclasses are: ");
error.append(actualTypeDefinition.getSuperClasses());
error.append(". New version superclasses are: ");
error.append(newTypeDefinition.getSuperClasses());
error.append("The new type definition has a different set of supertypes. Actual version supertypes are: ");
error.append(actualTypeDefinition.getExtendedTypes());
error.append(". New version supertypes are: ");
error.append(newTypeDefinition.getExtendedTypes());
error.append(". This kind update is not supported for a type.");
throw new SchemaException(error.toString());
}
@ -513,9 +512,6 @@ public class TypeManagement {
newTypeDefinition.getName());
}
if(!(newTypeDefinition instanceof ResourceType)) {
// A Resource cannot contains any properties.
@ -537,7 +533,9 @@ public class TypeManagement {
String propertyName = newPropertyDefinition.getName();
if(propertyName.compareTo(IdentifiableElement.HEADER_PROPERTY)==0 || propertyName.compareTo(Relation.PROPAGATION_CONSTRAINT_PROPERTY)==0) {
if(propertyName.compareTo(IdentifiableElement.ID_PROPERTY)==0 ||
propertyName.compareTo(IdentifiableElement.METADATA_PROPERTY)==0 ||
propertyName.compareTo(Relation.PROPAGATION_CONSTRAINT_PROPERTY)==0) {
continue;
}

View File

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

View File

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

View File

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

View File

@ -1,16 +1,26 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class EncryptedOrient extends ODocument {
public class EncryptedOrient extends ODocument implements Encrypted {
public static final String NAME = "Encrypted";
public static final String VALUE = "value";
@ -26,6 +36,30 @@ public class EncryptedOrient extends ODocument {
protected EncryptedOrient(String iClassName) {
super(iClassName);
}
@Override
public String getTypeName() {
return TypeUtility.getTypeName(this.getClass());
}
@Override
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {
List<String> list = new ArrayList<>();
list.add(TypeUtility.getTypeName(Property.class));
return list;
}
}
@Override
public String getExpectedtype() {
return null;
}
public String getEncryptedValue() {
return this.field(EncryptedOrient.VALUE);
@ -35,12 +69,6 @@ public class EncryptedOrient extends ODocument {
this.field(EncryptedOrient.VALUE, encryptedValue);
}
@Override
public String toJSON(String iFormat) {
return super.toJSON(iFormat);
}
public String getDecryptedValue() {
return decryptedValue;
}
@ -71,5 +99,42 @@ public class EncryptedOrient extends ODocument {
}
}
@Override
public Map<String, Object> getAdditionalProperties() {
return null;
}
@Override
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
}
@Override
public Object getAdditionalProperty(String key) {
return null;
}
@Override
public void setAdditionalProperty(String key, Object value) {
}
@Override
public String getValue() {
return getEncryptedValue();
}
@Override
public void setValue(String value) {
setEncryptedValue(value);
}
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = OrientDBUtility.replaceType(ret);
return ret;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,96 +0,0 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.security.Key;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.model.reference.properties.Vault;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class VaultOrient extends ODocument implements org.gcube.informationsystem.model.reference.properties.Vault {
protected String decryptedValue;
protected String dbEncryptedValue;
protected String contextEncryptedValue;
public VaultOrient() {
super(Vault.NAME);
}
protected VaultOrient(String iClassName) {
super(iClassName);
}
@Override
public String getValue() {
return this.field(Vault.VALUE);
}
@Override
public void setValue(String value) {
this.field(Vault.VALUE, value);
}
@Override
public String toJSON(String iFormat) {
return super.toJSON(iFormat);
}
public String getDecryptedValue() {
return decryptedValue;
}
public String getDbEncryptedValue() {
return dbEncryptedValue;
}
public String getContextEncryptedValue() {
return contextEncryptedValue;
}
public void setDecryptedValue(String decryptedValue, boolean setEncryptedForContext) throws Exception {
this.decryptedValue = decryptedValue;
// Encrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey();
this.dbEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue, databaseKey);
// Encrypting with Context Key (default key)
this.contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue);
if(setEncryptedForContext) {
setValue(contextEncryptedValue);
}else {
setValue(dbEncryptedValue);
}
}
@Override
public Map<String, Object> getAdditionalProperties() {
return null;
}
@Override
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
}
@Override
public Object getAdditionalProperty(String key) {
return null;
}
@Override
public void setAdditionalProperty(String key, Object value) {
}
}

View File

@ -13,9 +13,9 @@ import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.authorization.utils.secret.SecretUtility;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.KeycloakClientHelper;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
@ -39,14 +39,13 @@ public class ContextTest {
public static final String NEXTNEXT;
public static final String DEVSEC;
public static final String DEVVRE;
protected static final Properties properties;
protected static final String CLIENT_ID_PROPERTY_KEY = "client_id";
protected static final String CLIENT_SECRET_PROPERTY_KEY = "client_secret";
protected static final String clientID;
protected static final String clientSecret;
public static final String TYPE_PROPERTY_KEY = "type";
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String PASSWORD_PROPERTY_KEY = "password";
public static final String CLIENT_ID_PROPERTY_KEY = "clientId";
static {
GCUBE = "/gcube";
@ -64,16 +63,16 @@ public class ContextTest {
try {
// load the properties file
properties.load(input);
clientID = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
clientSecret = properties.getProperty(CLIENT_SECRET_PROPERTY_KEY);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private enum Type{
USER, CLIENT_ID
};
public static void set(Secret secret) throws Exception {
SecretManagerProvider.instance.reset();
SecretManager secretManager = new SecretManager();
@ -83,15 +82,56 @@ public class ContextTest {
}
public static void setContextByName(String fullContextName) throws Exception {
logger.debug("Going to set credentials for context {}", fullContextName);
Secret secret = getSecretByContextName(fullContextName);
set(secret);
}
private static TokenResponse getJWTAccessToken(String context) throws Exception {
ScopeProvider.instance.set(context);
TokenResponse tr = KeycloakClientFactory.newInstance().queryUMAToken(clientID, clientSecret, context, null);
return tr;
Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString());
TokenResponse tr = null;
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
switch (type) {
case CLIENT_ID:
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
String clientSecret = properties.getProperty(root);
tr = KeycloakClientFactory.newInstance().queryUMAToken(context, clientId, clientSecret, context, null);
break;
case USER:
default:
String username = properties.getProperty(USERNAME_PROPERTY_KEY);
String password = properties.getProperty(PASSWORD_PROPERTY_KEY);
switch (root) {
case "/gcube":
default:
clientId = "next.d4science.org";
break;
case "/pred4s":
clientId = "pre.d4science.org";
break;
case "/d4science.research-infrastructures.eu":
clientId = "services.d4science.org";
break;
}
clientSecret = null;
tr = KeycloakClientHelper.getTokenForUser(context, username, password);
break;
}
return tr;
}
public static Secret getSecretByContextName(String context) throws Exception {
@ -111,7 +151,7 @@ public class ContextTest {
}
public static String getUser() {
String user = Header.UNKNOWN_USER;
String user = Metadata.UNKNOWN_USER;
try {
user = SecretManagerProvider.instance.get().getUser().getUsername();
} catch(Exception 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;
@ -10,9 +12,7 @@ import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.contexts.impl.entities.ContextImpl;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
@ -22,8 +22,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSec
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
@ -46,32 +45,32 @@ public class ContextManagementTest extends ContextTest {
public static final String CTX_NAME_B = "B";
public static final String CTX_NAME_C = "C";
public static void checkHeader(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader() != null);
Assert.assertTrue(er.getHeader().getUUID() != null);
public static void checkUUUIDAndMetadata(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getMetadata() != null);
Assert.assertTrue(er.getID() != null);
if(uuid != null) {
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0);
Assert.assertTrue(er.getID().compareTo(uuid) == 0);
}
String user = HeaderUtility.getUser();
Assert.assertTrue(er.getHeader().getLastUpdateBy().compareTo(user) == 0);
String user = MetadataUtility.getUser();
Assert.assertTrue(er.getMetadata().getLastUpdateBy().compareTo(user) == 0);
if(create) {
Assert.assertTrue(er.getHeader().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
Assert.assertTrue(er.getMetadata().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getMetadata().getCreationTime().compareTo(er.getMetadata().getLastUpdateTime()) == 0);
} else {
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
Assert.assertTrue(er.getMetadata().getCreationTime().before(er.getMetadata().getLastUpdateTime()));
}
}
protected void assertions(Context pre, Context post, boolean checkParent, boolean create)
throws ResourceRegistryException {
if(checkParent) {
if(pre.getHeader() != null) {
checkHeader(post, pre.getHeader().getUUID(), create);
if(pre.getMetadata() != null) {
checkUUUIDAndMetadata(post, pre.getID(), create);
} else {
checkHeader(post, null, create);
checkUUUIDAndMetadata(post, null, create);
}
}
@ -149,7 +148,7 @@ public class ContextManagementTest extends ContextTest {
logger.debug("Created {}", contextString);
Context c = ElementMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, true);
roleUserAssertions(c.getHeader().getUUID(), null, false);
roleUserAssertions(c.getID(), null, false);
return c;
}
@ -160,7 +159,7 @@ public class ContextManagementTest extends ContextTest {
logger.debug("Updated {}", contextString);
Context c = ElementMapper.unmarshal(Context.class, contextString);
assertions(context, c, true, false);
roleUserAssertions(c.getHeader().getUUID(), null, false);
roleUserAssertions(c.getID(), null, false);
return c;
}
@ -181,7 +180,7 @@ public class ContextManagementTest extends ContextTest {
}
protected void delete(Context context) throws ResourceRegistryException {
delete(context.getHeader().getUUID());
delete(context.getID());
}
protected void invalidCreate(Context context) throws ResourceRegistryException, IOException {
@ -421,7 +420,7 @@ public class ContextManagementTest extends ContextTest {
delete(contextA5);
} catch(ContextNotFoundException e) {
logger.debug("The context with uuid {} was not found. (Was already deleted)",
contextA5.getHeader().getUUID());
contextA5.getID());
}
delete(contextB3);
@ -436,7 +435,7 @@ public class ContextManagementTest extends ContextTest {
// ________A1________
Context contextC = new ContextImpl(CTX_NAME_C);
contextC.setHeader(new HeaderImpl(contextA1.getHeader().getUUID()));
contextC.setID(contextA1.getID());
invalidCreate(contextC);
delete(contextA1);
@ -444,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);
@ -472,16 +477,16 @@ public class ContextManagementTest extends ContextTest {
@Test
public void testGetAll() throws Exception {
List<Context> contexts = getAll();
contexts = ContextCache.getInstance().getContexts();
contexts = ServerContextCache.getInstance().getContexts();
for(Context context : contexts) {
logger.trace(ElementMapper.marshal(context));
logger.info(ElementMapper.marshal(context));
List<IsParentOf> children = context.getChildren();
for(IsParentOf child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
Assert.assertTrue(childContext.getParent().getSource() == context);
}
roleUserAssertions(context.getHeader().getUUID(), null, false);
roleUserAssertions(context.getID(), null, false);
}
}
@ -497,24 +502,22 @@ public class ContextManagementTest extends ContextTest {
delete(context);
}
@Test
public void testContextCache() throws Exception {
DatabaseEnvironment.initContextCacheRenewal();
List<Context> contexts = getAll();
logger.debug("{}", contexts);
logger.info("{}", contexts);
ContextCache contextCache = ContextCache.getInstance();
ServerContextCache contextCache = ServerContextCache.getInstance();
Map<UUID, String> uuidToContextFullName = contextCache.getUUIDToContextFullNameAssociation();
logger.debug("{}", uuidToContextFullName);
List<Context> contextsFromCache = contextCache.getContexts();
for(Context c : contextsFromCache) {
UUID uuid = c.getHeader().getUUID();
UUID uuid = c.getID();
if(c.getParent()!=null) {
IsParentOf isParentOf = c.getParent();
Context parentContext = isParentOf.getSource();
UUID parentUUID = parentContext.getHeader().getUUID();
UUID parentUUID = parentContext.getID();
Assert.assertTrue(parentContext.getName().compareTo(contextCache.getContextByUUID(parentUUID).getName())==0);
List<IsParentOf> children = parentContext.getChildren();
boolean found = false;
@ -525,9 +528,9 @@ public class ContextManagementTest extends ContextTest {
}
}
Assert.assertTrue(found);
logger.debug("{} : {} (parent {} : {})", c.getHeader().getUUID(), contextCache.getContextFullNameByUUID(uuid), parentUUID, contextCache.getContextFullNameByUUID(parentUUID));
logger.debug("{} : {} (parent {} : {})", c.getID(), contextCache.getContextFullNameByUUID(uuid), parentUUID, contextCache.getContextFullNameByUUID(parentUUID));
}else {
logger.debug("{} : {}", c.getHeader().getUUID(), contextCache.getContextFullNameByUUID(uuid));
logger.debug("{} : {}", c.getID(), contextCache.getContextFullNameByUUID(uuid));
}
}
@ -535,10 +538,100 @@ public class ContextManagementTest extends ContextTest {
logger.debug("Current context : {}", currentContext);
for(Context c : contexts) {
UUID uuid = c.getHeader().getUUID();
UUID uuid = c.getID();
Context context = read(uuid);
String fullName = ContextCache.getInstance().getContextFullNameByUUID(uuid);
String fullName = ServerContextCache.getInstance().getContextFullNameByUUID(uuid);
logger.debug("{} - {} : {}", uuid, fullName, context);
}
}
@Test
public void testLimitOffset() throws Exception {
int limit = 2;
int offset = limit * 0;
List<Context> contexts = getAll(offset, limit);
logger.info("Going to check {}s pagination validity", Context.NAME);
if(contexts.size()==0) {
return;
}
Assert.assertTrue(contexts.size() <= limit);
if(contexts.size()< limit) {
return;
}
Set<UUID> uuids = new HashSet<>();
for(Context context : contexts) {
UUID uuid = context.getID();
uuids.add(uuid);
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
}
offset = limit * 1;
contexts = getAll(offset, limit);
if(contexts.size()>0) {
Assert.assertTrue(contexts.size() <= limit);
for(Context context : contexts) {
UUID uuid = context.getID();
Assert.assertFalse(uuids.contains(uuid));
uuids.add(uuid);
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
}
if(contexts.size()<limit) {
return;
}
int doubleLimit = limit*2;
offset = 0;
contexts = getAll(0, doubleLimit);
Assert.assertTrue(contexts.size() <= doubleLimit);
for(Context context : contexts) {
UUID uuid = context.getID();
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, doubleLimit, Context.NAME, uuid, context.getName());
Assert.assertTrue(uuids.contains(uuid));
}
}
logger.info("Going to check all {}s", Context.NAME);
List<Context> all = getAll();
uuids = new HashSet<>();
int i = -1;
while(true) {
offset = ++i * limit;
contexts = getAll(offset, limit);
for(Context context : contexts) {
UUID uuid = context.getID();
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
uuids.add(uuid);
}
if(contexts.size()<limit) {
break;
}
}
Assert.assertTrue(all.size()==uuids.size());
for(Context context : all) {
UUID uuid = context.getID();
Assert.assertTrue(uuids.contains(uuid));
logger.info("Using getAll() found {} with UUID {} and name {}", Context.NAME, uuid, context.getName());
}
logger.info("{} pagination seems properly working", Context.NAME);
}
}

View File

@ -8,35 +8,42 @@ import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.impl.properties.VaultImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.DeleteConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.properties.Vault;
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.api.utils.Utility;
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;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.utils.HeaderUtility;
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;
@ -74,6 +81,7 @@ import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVola
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Activates;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -84,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 {
@ -107,8 +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);
@ -116,28 +132,28 @@ 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();
IdentifierFacet identifierFacet = new IdentifierFacetImpl();
identifierFacet.setType(IdentificationType.STRING);
identifierFacet.setIdentificationType(IdentificationType.STRING);
identifierFacet.setValue("MyID");
identifierFacet.setPersistent(false);
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();
@ -163,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;
@ -217,75 +233,81 @@ public class ERManagementTest extends ContextTest {
return hostingNode;
}
public static void checkHeader(IdentifiableElement identifiableElement, IdentifiableElement createdIdentifiableElement) {
Header createdHeader = createdIdentifiableElement.getHeader();
Assert.assertTrue(createdHeader!=null);
UUID createdUUID = createdHeader.getUUID();
Assert.assertTrue(createdUUID!=null);
String createdBy = createdHeader.getCreatedBy();
Assert.assertTrue(createdBy!=null);
String lastUpdateBy = createdHeader.getLastUpdateBy();
Assert.assertTrue(lastUpdateBy!=null);
Date creationTime = createdHeader.getCreationTime();
Assert.assertTrue(creationTime!=null);
Date lastUpdateTime = createdHeader.getLastUpdateTime();
Assert.assertTrue(lastUpdateTime!=null);
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);
}
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
Assert.assertTrue(createdMetadata != null);
String createdBy = createdMetadata.getCreatedBy();
Assert.assertTrue(createdBy != null);
String lastUpdateBy = createdMetadata.getLastUpdateBy();
Assert.assertTrue(lastUpdateBy != null);
Date creationTime = createdMetadata.getCreationTime();
Assert.assertTrue(creationTime != null);
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
Assert.assertTrue(lastUpdateTime != null);
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
Header header = identifiableElement.getHeader();
if(header!=null) {
if(header.getUUID()!=null) {
Assert.assertTrue(createdUUID.compareTo(header.getUUID())==0);
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(header.getCreatedBy()!=null) {
Assert.assertTrue(createdBy.compareTo(header.getCreatedBy())==0);
}else {
Assert.assertTrue(createdBy.compareTo(HeaderUtility.getUser())==0);
if (metadata.getLastUpdateBy() != null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy()) == 0);
} else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser()) == 0);
}
if(header.getLastUpdateBy()!=null) {
Assert.assertTrue(lastUpdateBy.compareTo(header.getLastUpdateBy())==0);
}else {
Assert.assertTrue(lastUpdateBy.compareTo(HeaderUtility.getUser())==0);
}
if(header.getLastUpdateTime()!=null) {
Assert.assertTrue(lastUpdateTime.after(header.getLastUpdateTime()));
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) {
checkHeader(consistsOf, gotConsistsOf);
if(consistsOf.getPropagationConstraint()==null) {
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf,
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
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(Element.SUPERCLASSES_PROPERTY);
additionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
gotAdditionalProperties.remove(Element.SUPERCLASSES_PROPERTY);
Assert.assertTrue(additionalProperties.size()==gotAdditionalProperties.size());
for(String key : additionalProperties.keySet()) {
gotAdditionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
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);
@ -293,88 +315,123 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(additionalProperty.equals(gotAdditionalProperty));
}
}
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
checkHeader(facet, gotFacet);
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());
checkHeader(resource, gotResource);
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);
}
}
public static <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
protected static <R extends Resource> void checkResourceNoMeta(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
Assert.assertNull(gotResource.getMetadata());
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(Utility.getTypeName(r));
resourceManagement.setElementType(r.getTypeName());
resourceManagement.setJson(ElementMapper.marshal(r));
if(r.getHeader()!=null && r.getHeader().getUUID()!=null) {
resourceManagement.setUUID(r.getHeader().getUUID());
if (r.getID() != null) {
resourceManagement.setUUID(r.getID());
}
return resourceManagement;
}
public static <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(Utility.getTypeName(isRelatedTo));
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
if(isRelatedTo.getHeader()!=null && isRelatedTo.getHeader().getUUID()!=null) {
isRelatedToManagement.setUUID(isRelatedTo.getHeader().getUUID());
if (isRelatedTo.getID() != null) {
isRelatedToManagement.setUUID(isRelatedTo.getID());
}
return isRelatedToManagement;
}
public static <R extends Resource> R createResource(R r) throws Exception {
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 static EService createEService() throws Exception {
public EService createEService() throws Exception {
EService eService = ERManagementTest.instantiateValidEService();
return createResource(eService);
}
public static HostingNode createHostingNode() throws Exception {
public HostingNode createHostingNode() throws Exception {
return createHostingNode(null);
}
public static HostingNode createHostingNode(EService eService) throws Exception {
public HostingNode createHostingNode(EService eService) throws Exception {
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
}
public static 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);
@ -384,13 +441,13 @@ public class ERManagementTest extends ContextTest {
}
return createResource(hostingNode);
}
public static Configuration createConfiguration() throws Exception {
public Configuration createConfiguration() throws Exception {
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
return createResource(configuration);
}
public static Map<String, Resource> createHostingNodeAndEService() throws Exception {
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
Map<String, Resource> map = new HashMap<>();
EService eService = createEService();
@ -401,117 +458,145 @@ public class ERManagementTest extends ContextTest {
return map;
}
public static <R extends Resource> void deleteResource(R r) throws Exception {
if(r!=null) {
public <R extends Resource> void deleteResource(R r) throws Exception {
if (r != null) {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.delete();
}
}
@Test
public void testCreateEService() throws Exception {
EService eService = null;
try {
eService = createEService();
}finally {
} finally {
deleteResource(eService);
}
}
@Test
public void testCreateAndReadEService() throws Exception {
EService eService = null;
try {
eService = createEService();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
EService readEService = (EService) readResource(eService.getID());
checkResource(eService, readEService);
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceRootMetaOnly(eService, readEService);
requestInfo.setIncludeMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceNoMeta(eService, readEService);
} finally {
deleteResource(eService);
}
}
protected Resource readResource(UUID uuid) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
String json = resourceManagement.read().toString();
logger.debug(json);
return ElementMapper.unmarshal(Resource.class, json);
}
/*
@Test
public void testReadResource() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e"));
String read = resourceManagement.read().toString();
logger.debug(read);
}
*/
* @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 = ERManagementTest.createHostingNodeAndEService();
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(Utility.getTypeName(consistsOf));
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.getHeader().getUUID();
UUID uuid = createdCpuFacet.getID();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(Utility.getTypeName(createdCpuFacet));
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);
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(readCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getHeader().getUUID()) == 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(Utility.getTypeName(readCpuFacet));
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);
@ -520,14 +605,14 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(newVendor) == 0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID()) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
String user = ContextTest.getUser();
Assert.assertTrue(updatedCpuFacet.getHeader().getLastUpdateBy().compareTo(user) == 0);
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(Utility.getTypeName(updatedCpuFacet));
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);
@ -536,12 +621,12 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(readUpdatedCpuFacet.getVendor()) == 0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getHeader().getUUID()) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(Utility.getTypeName(readCpuFacet));
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.delete();
} finally {
deleteResource(eService);
@ -555,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");
@ -566,17 +651,17 @@ public class ERManagementTest extends ContextTest {
authorization.setSchema(uri);
accessPointFacet.setAuthorization(authorization);
String additionlaPropertyKey = "Test";
String additionalPropertyKey = "Test";
String additionlaPropertyValue = "MyTest";
accessPointFacet.setAdditionalProperty(additionlaPropertyKey, additionlaPropertyValue);
accessPointFacet.setAdditionalProperty(additionalPropertyKey, additionlaPropertyValue);
Vault vault = new VaultImpl();
Encrypted encrypted = new EncryptedImpl();
String plainValue = "Encrypted";
String encryptedValue = StringEncrypter.getEncrypter().encrypt(plainValue);
vault.setValue(encryptedValue);
encrypted.setValue(encryptedValue);
String encryptedKey = "Enc";
accessPointFacet.setAdditionalProperty(encryptedKey, vault);
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
configuration.addFacet(accessPointFacet);
String marshalled = ElementMapper.marshal(configuration);
@ -585,40 +670,41 @@ 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 Vault);
Vault vlt = (Vault) apf.getAdditionalProperty(encryptedKey);
String encValue = vlt.getValue();
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
String encValue = enc.getValue();
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
Assert.assertTrue(((String) apf.getAdditionalProperty(additionlaPropertyKey)).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);
}finally {
} catch (Throwable e) {
throw e;
} finally {
deleteResource(eService);
}
}
@ -636,7 +722,7 @@ public class ERManagementTest extends ContextTest {
// EService eService = ElementMapper.unmarshal(EService.class, fileInputStream);
//
// ResourceManagement resourceManagement = new ResourceManagement();
// resourceManagement.setUUID(eService.getHeader().getUUID());
// resourceManagement.setUUID(eService.getUUID());
// resourceManagement.setJson(ElementMapper.marshal(eService));
//
// resourceManagement.update();
@ -650,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

@ -3,8 +3,8 @@ package org.gcube.informationsystem.resourceregistry.instances;
import java.security.Key;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.model.impl.properties.VaultImpl;
import org.gcube.informationsystem.model.reference.properties.Vault;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
@ -30,11 +30,11 @@ public class EncryptionTest extends ERManagementTest {
@Test
public void test() throws Exception {
Vault vault = new VaultImpl();
Encrypted encrypted = new EncryptedImpl();
String contextEncryptedValue = StringEncrypter.getEncrypter().encrypt(PLAIN_VALUE);
vault.setValue(contextEncryptedValue);
encrypted.setValue(contextEncryptedValue);
String getContextEncryptedValue = vault.getValue();
String getContextEncryptedValue = encrypted.getValue();
Assert.assertTrue(getContextEncryptedValue.compareTo(getContextEncryptedValue)==0);
@ -47,9 +47,9 @@ public class EncryptionTest extends ERManagementTest {
String dbEncryptedValue = StringEncrypter.getEncrypter().encrypt(decryptedValue, databaseKey);
// Setting the value encrypted with DB key
vault.setValue(dbEncryptedValue);
encrypted.setValue(dbEncryptedValue);
String getDBEncryptedValue = vault.getValue();
String getDBEncryptedValue = encrypted.getValue();
Assert.assertTrue(getDBEncryptedValue.compareTo(dbEncryptedValue)==0);
decryptedValue = StringEncrypter.getEncrypter().decrypt(getDBEncryptedValue, databaseKey);
@ -69,11 +69,11 @@ public class EncryptionTest extends ERManagementTest {
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
Vault vault = new VaultImpl();
Encrypted encrypted = new EncryptedImpl();
String encryptedValue = StringEncrypter.getEncrypter().encrypt(PLAIN_VALUE);
vault.setValue(encryptedValue);
encrypted.setValue(encryptedValue);
String additionalKey = "test";
cpuFacet.setAdditionalProperty(additionalKey, vault);
cpuFacet.setAdditionalProperty(additionalKey, encrypted);
configuration.addFacet(cpuFacet);
ResourceManagement resourceManagement = new ResourceManagement();
@ -86,7 +86,7 @@ public class EncryptionTest extends ERManagementTest {
Configuration createdConfiguration = ElementMapper.unmarshal(Configuration.class, configurationJsonString);
CPUFacet readCpuFacet = createdConfiguration.getFacets(CPUFacet.class).get(0);
String gotEncryptedValue = ((Vault) readCpuFacet.getAdditionalProperty(additionalKey)).getValue();
String gotEncryptedValue = ((Encrypted) readCpuFacet.getAdditionalProperty(additionalKey)).getValue();
Assert.assertTrue(gotEncryptedValue.compareTo(encryptedValue) == 0);
String gotPlainValue = StringEncrypter.getEncrypter().decrypt(gotEncryptedValue);
Assert.assertTrue(gotPlainValue.compareTo(PLAIN_VALUE) == 0);

View File

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

View File

@ -33,18 +33,17 @@ import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.UUIDManager;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.MemoryFacetImpl;
@ -91,11 +90,10 @@ public class SmartgearResourcesTest extends ERManagementTest {
@Test
public void testHostingNodeOperations() throws ResourceRegistryException,
IOException, URISyntaxException {
UUID uuid = UUID.randomUUID();
UUID uuid = UUIDManager.getInstance().generateValidUUID();
HostingNode hostingNode = new HostingNodeImpl();
Header header = new HeaderImpl(uuid);
hostingNode.setHeader(header);
hostingNode.setID(uuid);
NetworkingFacet networkingFacet = new NetworkingFacetImpl();
try {
@ -447,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<>();
@ -455,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;
@ -533,6 +562,11 @@ public class SmartgearResourcesTest extends ERManagementTest {
}
}
}
if(cpuFacets.size()==0) {
return getFakeCPUFacets();
}
return cpuFacets;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -13,10 +13,10 @@ import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.properties.Vault;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.model.reference.relations.Relation;
@ -53,7 +53,7 @@ public class SchemaManagementImplTest extends ContextTest {
@Test
public void registerPropertyTypeSchema() throws Exception {
Class<? extends PropertyElement> clz = Header.class;
Class<? extends PropertyElement> clz = Metadata.class;
String json = TypeMapper.serializeType(clz);
logger.debug(json);
//new SchemaManagementImpl().create(json, AccessType.PROPERTY);
@ -243,8 +243,8 @@ public class SchemaManagementImplTest extends ContextTest {
}
@Test(expected=SchemaAlreadyPresentException.class)
public void createVaultType() throws Exception {
create(Vault.class);
public void createEncryptedType() throws Exception {
create(Encrypted.class);
}
@Test(expected=SchemaAlreadyPresentException.class)
@ -284,8 +284,8 @@ public class SchemaManagementImplTest extends ContextTest {
Assert.assertTrue(type.getDescription().compareTo(typeManaged.getDescription())==0);
Assert.assertTrue(type.isAbstract() == typeManaged.isAbstract());
Assert.assertTrue(type.getSuperClasses().containsAll(typeManaged.getSuperClasses()));
Assert.assertTrue(typeManaged.getSuperClasses().containsAll(type.getSuperClasses()));
Assert.assertTrue(type.getExtendedTypes().containsAll(typeManaged.getExtendedTypes()));
Assert.assertTrue(typeManaged.getExtendedTypes().containsAll(type.getExtendedTypes()));
Map<Version, String> typeChangelog = type.getChangelog();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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

@ -0,0 +1,12 @@
{
"type": "HostingNode",
"consistsOf": [
{
"type": "ConsistsOf",
"target": {
"type": "StateFacet",
"value": "certified"
}
}
]
}

View File

@ -0,0 +1,12 @@
SELECT EXPAND(ret) FROM (
MATCH
{class: HostingNode, as: hostingnode0, where: ($currentMatch['@class'] INSTANCEOF 'HostingNode')}
.outE('ConsistsOf') { as: consistsof00, where: ($currentMatch['@class'] INSTANCEOF 'ConsistsOf')}
.inV('StateFacet') { as: statefacet000, where: (($currentMatch['@class'] INSTANCEOF 'StateFacet') AND (value = "certified"))}
.inE('ConsistsOf') { where: ($matched.consistsof00 == $currentMatch)}
.outV('HostingNode') { where: ($matched.hostingnode0 == $currentMatch)}
RETURN
DISTINCT(hostingnode0) as ret
)

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,43 +1,39 @@
{
"@class": "EService",
"type": "EService",
"consistsOf": [
{
"@class": "ConsistsOf",
"type": "ConsistsOf",
"propagationConstraint" : {
"add": "propagate"
},
"target": {
"@class": "StateFacet",
"type": "StateFacet",
"value": "down"
}
},
{
"@class": "IsIdentifiedBy",
"type": "IsIdentifiedBy",
"target": {
"@class": "SoftwareFacet",
"type": "SoftwareFacet",
"name": "data-transfer-service",
"group": "DataTransfer"
}
},
{
"@class": "ConsistsOf",
"type": "ConsistsOf",
"target": {
"@class": "AccessPointFacet",
"endpoint": "http://pc-frosini.isti.cnr.it:8080/data-transfer-service/gcube/service"
"type": "AccessPointFacet",
"endpoint": "http://smartexecutor1.dev.int.d4science.net:80/data-transfer-service/gcube/resource"
}
}
],
"isRelatedTo" : [
{
"@class": "Activates",
"header": {
"uuid": "d3f58e52-5346-47bc-b736-9d77a0b554ce"
},
"type": "Activates",
"id": "bd89a311-780d-4efe-93e5-08281e53bce7",
"source": {
"@class": "HostingNode",
"header": {
"uuid" : "5fbc1a56-d450-4f0f-85c1-9b1684581717"
}
"type": "HostingNode",
"id" : "44fac329-eed5-4f18-90ba-a54d5aad316e"
}
}
]

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