Compare commits
164 Commits
porting-to
...
master
Author | SHA1 | Date |
---|---|---|
Luca Frosini | aca1ffde5c | |
Luca Frosini | ca1e91c6c4 | |
Luca Frosini | b32188741c | |
Luca Frosini | 70b9d23fa8 | |
Luca Frosini | bcb55ea4e9 | |
Luca Frosini | 6160f73bc2 | |
Luca Frosini | 47ade46b63 | |
Luca Frosini | 24bdfca564 | |
Luca Frosini | 95d6cdd699 | |
Luca Frosini | 26aa96ae37 | |
Luca Frosini | 4a557031d6 | |
Luca Frosini | c2ed490fd9 | |
Luca Frosini | 244cec6854 | |
Luca Frosini | f874c01d7a | |
Luca Frosini | 7cdd897f4e | |
Luca Frosini | 8154011cc6 | |
Luca Frosini | 84ebc54546 | |
Luca Frosini | 40fa20a871 | |
Luca Frosini | 2ff9841de2 | |
Luca Frosini | 39373982ed | |
Luca Frosini | 2790457fca | |
Luca Frosini | f6601cac8e | |
Luca Frosini | 833d2bd2cb | |
Luca Frosini | f205927545 | |
Luca Frosini | 027da0216e | |
Luca Frosini | 9777ecc7b8 | |
Luca Frosini | bc511f48bf | |
Luca Frosini | 8110a24257 | |
Luca Frosini | 0ead00f884 | |
Luca Frosini | 4fe825cbfb | |
Luca Frosini | cf3e5c9b98 | |
Luca Frosini | 3b062d2774 | |
Luca Frosini | ef6975a2b5 | |
Luca Frosini | 05299464ae | |
Luca Frosini | 292272a72e | |
Luca Frosini | 84fbf0ea4e | |
Luca Frosini | d4201c68c6 | |
Luca Frosini | 8ca83520bd | |
Luca Frosini | f65b6aee17 | |
Luca Frosini | b47a1b9ba7 | |
Luca Frosini | 648fd0a8ae | |
Luca Frosini | 64a2ced9ec | |
Luca Frosini | cd8627cf32 | |
Luca Frosini | fb230cee94 | |
Luca Frosini | e29a78cd2d | |
Luca Frosini | 847edc72ef | |
Luca Frosini | e98a049ab4 | |
Luca Frosini | 4fa38c24dd | |
Luca Frosini | aeba8ba06a | |
Luca Frosini | 28ea920a05 | |
Luca Frosini | 7dd3f13d7d | |
Luca Frosini | 8902f6b17b | |
Luca Frosini | 281285761f | |
Luca Frosini | 3ec9670319 | |
Luca Frosini | 4766ad2f80 | |
Luca Frosini | ec3a17b2d9 | |
Luca Frosini | 66224d73f4 | |
Luca Frosini | 5c195f8723 | |
Luca Frosini | 0eb2cf9456 | |
Luca Frosini | 334a8aff37 | |
Luca Frosini | e1ef53f2ef | |
Luca Frosini | d9cc910fa9 | |
Luca Frosini | dafc4e5639 | |
Luca Frosini | 924b370a81 | |
Luca Frosini | ae2ec3ca5d | |
Luca Frosini | 2360949ad3 | |
Luca Frosini | 48f7b1a73b | |
Luca Frosini | bf09efc8fd | |
Luca Frosini | 99980cc20c | |
Luca Frosini | fb7ca52744 | |
Luca Frosini | a3b66f300e | |
Luca Frosini | 69ad3803eb | |
Luca Frosini | e42b2bde0a | |
Luca Frosini | 4ffaf4b082 | |
Luca Frosini | 984a1e5497 | |
Luca Frosini | 47092cf13e | |
Luca Frosini | 7b1631e8be | |
Luca Frosini | 8b49c4ffd2 | |
Luca Frosini | 8f701c10a5 | |
Luca Frosini | 8e4f173917 | |
Luca Frosini | f85fb9948f | |
Luca Frosini | b27a2695cf | |
Luca Frosini | 1da984cac0 | |
Luca Frosini | 6080c0ee41 | |
Luca Frosini | 7865bd81cc | |
Luca Frosini | c6049a122b | |
Luca Frosini | 1e31a71fce | |
Luca Frosini | 0917263f27 | |
luca.frosini | 30e8c84258 | |
luca.frosini | c324b3ab41 | |
luca.frosini | c5531d7c54 | |
luca.frosini | 8af757f3db | |
luca.frosini | 0812a0c94c | |
luca.frosini | 78ea9c2307 | |
luca.frosini | 6657543a63 | |
luca.frosini | 6a1e0e5838 | |
luca.frosini | 5fe0e5771b | |
luca.frosini | 9450134790 | |
luca.frosini | f2cf0a4f17 | |
luca.frosini | 24f2ec53c1 | |
luca.frosini | d2b797c19a | |
luca.frosini | 46cb4f0975 | |
luca.frosini | 816c7693dc | |
luca.frosini | ffd20403da | |
luca.frosini | 2dba63771b | |
luca.frosini | e0bfef4c49 | |
luca.frosini | 2d863b99fc | |
luca.frosini | 084e223669 | |
luca.frosini | e8a98dd54a | |
luca.frosini | 0878cdd7bd | |
luca.frosini | dd7ad6840e | |
luca.frosini | ca51189cab | |
luca.frosini | dfccd87a62 | |
luca.frosini | 00e0fc2a55 | |
luca.frosini | 996997804a | |
luca.frosini | 7ce298be17 | |
luca.frosini | b978185cd5 | |
luca.frosini | 68c742eb09 | |
luca.frosini | 7409a8d278 | |
luca.frosini | c611a839eb | |
luca.frosini | 1eb1cf6773 | |
luca.frosini | d786ffff98 | |
luca.frosini | 08fca98875 | |
luca.frosini | e5106cd6c0 | |
luca.frosini | 849cc923f3 | |
luca.frosini | 9851f83ecd | |
luca.frosini | 9b3ffcf5b4 | |
luca.frosini | c34c5f9a59 | |
luca.frosini | 22bedb9a75 | |
luca.frosini | 3f1a4f5795 | |
luca.frosini | 5741f52072 | |
luca.frosini | 290cb44221 | |
luca.frosini | 90e1ca1a28 | |
luca.frosini | af48246afa | |
luca.frosini | ee8bdefa8b | |
luca.frosini | 8c5dcd0341 | |
luca.frosini | 9d9ec44b90 | |
luca.frosini | 38668d8a21 | |
luca.frosini | 31f0120c50 | |
luca.frosini | 01716b55cd | |
luca.frosini | d650c16e29 | |
luca.frosini | d2ca74cc72 | |
luca.frosini | 95b86d8a40 | |
luca.frosini | a3a2e3a0a9 | |
luca.frosini | 88c1ee60d8 | |
luca.frosini | 71b780eb2a | |
luca.frosini | 0cb336ded4 | |
luca.frosini | 402ead3696 | |
luca.frosini | d977e1ef8a | |
luca.frosini | 1332261fc4 | |
luca.frosini | cbe25a5832 | |
Luca Frosini | e3b6c8add5 | |
Luca Frosini | dab30f5670 | |
Luca Frosini | 76438c6a90 | |
Luca Frosini | 46f0bea227 | |
Luca Frosini | c7b9d21bba | |
Luca Frosini | c79b579925 | |
Luca Frosini | f9e474d4cd | |
Luca Frosini | 804e2b2343 | |
Luca Frosini | 20914f3f06 | |
Luca Frosini | b32f282044 | |
Luca Frosini | fe6e990605 | |
Luca Frosini | 738b693697 | |
Luca Frosini | 01a8480180 |
|
@ -1,3 +1,7 @@
|
||||||
target
|
target
|
||||||
.classpath
|
.classpath
|
||||||
.project
|
.project
|
||||||
|
/.DS_Store
|
||||||
|
/bin/
|
||||||
|
/.apt_generated/
|
||||||
|
/.apt_generated_tests/
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
/org.eclipse.core.resources.prefs
|
/org.eclipse.core.resources.prefs
|
||||||
/org.eclipse.jdt.core.prefs
|
/org.eclipse.jdt.core.prefs
|
||||||
/org.eclipse.m2e.core.prefs
|
/org.eclipse.m2e.core.prefs
|
||||||
|
/org.eclipse.jdt.apt.core.prefs
|
||||||
|
|
18
CHANGELOG.md
18
CHANGELOG.md
|
@ -2,24 +2,36 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
||||||
|
|
||||||
# Changelog for Resource Registry Service
|
# Changelog for Resource Registry Service
|
||||||
|
|
||||||
## [v4.3.0-SNAPSHOT]
|
## [v4.4.0-SNAPSHOT]
|
||||||
|
|
||||||
|
- Added query parameters to paginate result of queries [#24648]
|
||||||
|
- Completely refactored JSON Query management [#24163]
|
||||||
|
- Additional fields (schema mixed) can be added to Context [#26102]
|
||||||
|
- Added state to Context
|
||||||
|
- Added roles checks to manage Contexts
|
||||||
|
- Added roles check to add isntances to non active Contexts
|
||||||
|
|
||||||
|
|
||||||
|
## [v4.3.0]
|
||||||
|
|
||||||
- Migrated code to reorganized E/R format [#24992]
|
- Migrated code to reorganized E/R format [#24992]
|
||||||
- Metadata are added only if requested by the client [#25040]
|
- Metadata are added only if requested by the client [#25040]
|
||||||
- Restored Encrypted Property Type and removed Vault [#25041]
|
- 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]
|
## [v4.2.0]
|
||||||
|
|
||||||
- Fixed bug on JSONQuery for Facets which does not have any properties to match [#24237]
|
- 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 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]
|
- Enabled array properties [#24225]
|
||||||
- Using delete in propagation contraint as action indication for delete operation [#24301]
|
- 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]
|
- Fixed default value of propagation constraint of remove action for ConsistsOf to 'cascade' [#24223]
|
||||||
- Removed Encrypted Property Type and added Vault instead [#24655]
|
- Removed Encrypted Property Type and added Vault instead [#24655]
|
||||||
- Enhanced gcube-smartgears-bom version
|
- Enhanced gcube-smartgears-bom version
|
||||||
|
|
||||||
|
|
||||||
## [v4.1.0]
|
## [v4.1.0]
|
||||||
|
|
||||||
|
|
26
pom.xml
26
pom.xml
|
@ -10,7 +10,7 @@
|
||||||
|
|
||||||
<groupId>org.gcube.information-system</groupId>
|
<groupId>org.gcube.information-system</groupId>
|
||||||
<artifactId>resource-registry</artifactId>
|
<artifactId>resource-registry</artifactId>
|
||||||
<version>4.3.0-SNAPSHOT</version>
|
<version>4.4.0-SNAPSHOT</version>
|
||||||
<name>Resource Registry Service</name>
|
<name>Resource Registry Service</name>
|
||||||
<description>The Resource Registry is a web-service which represent the core component of the gCube Information System</description>
|
<description>The Resource Registry is a web-service which represent the core component of the gCube Information System</description>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
|
@ -31,7 +31,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.gcube.distribution</groupId>
|
<groupId>org.gcube.distribution</groupId>
|
||||||
<artifactId>gcube-smartgears-bom</artifactId>
|
<artifactId>gcube-smartgears-bom</artifactId>
|
||||||
<version>2.5.0-SNAPSHOT</version>
|
<version>2.5.0</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
@ -52,7 +52,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.gcube.common</groupId>
|
<groupId>org.gcube.common</groupId>
|
||||||
<artifactId>authorization-utils</artifactId>
|
<artifactId>authorization-utils</artifactId>
|
||||||
<version>[2.1.0, 3.0.0-SNAPSHOT)</version>
|
<version>[2.2.0, 3.0.0-SNAPSHOT)</version>
|
||||||
<exclusions>
|
<exclusions>
|
||||||
<exclusion>
|
<exclusion>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
|
@ -101,12 +101,32 @@
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- END Jersey -->
|
<!-- 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>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Test Dependencies -->
|
<!-- Test Dependencies -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.gcube.common</groupId>
|
||||||
|
<artifactId>d4science-iam-client</artifactId>
|
||||||
|
<version>[1.0.0-SNAPSHOT, 2.0.0)</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.gcube.resource-management</groupId>
|
<groupId>org.gcube.resource-management</groupId>
|
||||||
<artifactId>gcube-model</artifactId>
|
<artifactId>gcube-model</artifactId>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.instances.base;
|
package org.gcube.informationsystem.resourceregistry.base;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.text.DateFormat;
|
import java.text.DateFormat;
|
||||||
|
@ -14,7 +14,7 @@ import java.util.Map.Entry;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import javax.activation.UnsupportedDataTypeException;
|
import javax.ws.rs.WebApplicationException;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
@ -25,12 +25,15 @@ import org.gcube.com.fasterxml.jackson.databind.node.JsonNodeType;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.TextNode;
|
import org.gcube.com.fasterxml.jackson.databind.node.TextNode;
|
||||||
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
|
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
|
||||||
|
import org.gcube.common.authorization.utils.manager.SecretManager;
|
||||||
|
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
||||||
|
import org.gcube.common.authorization.utils.user.User;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Element;
|
import org.gcube.informationsystem.base.reference.Element;
|
||||||
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
||||||
import org.gcube.informationsystem.model.reference.ERElement;
|
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.Metadata;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Property;
|
|
||||||
import org.gcube.informationsystem.model.reference.relations.Relation;
|
import org.gcube.informationsystem.model.reference.relations.Relation;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
||||||
|
@ -39,15 +42,16 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.properties.PropertyElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.properties.PropertyElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.MetadataOrient;
|
import org.gcube.informationsystem.resourceregistry.utils.MetadataOrient;
|
||||||
|
@ -82,6 +86,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
public final static String AT = "@";
|
public final static String AT = "@";
|
||||||
public final static String UNDERSCORE = "_";
|
public final static String UNDERSCORE = "_";
|
||||||
|
public final static String DOLLAR = "$";
|
||||||
|
|
||||||
protected final Set<String> ignoreKeys;
|
protected final Set<String> ignoreKeys;
|
||||||
protected final Set<String> ignoreStartWithKeys;
|
protected final Set<String> ignoreStartWithKeys;
|
||||||
|
@ -147,24 +152,27 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
protected Operation operation;
|
protected Operation operation;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A Delete operation has a cascade impact we could want to know the impact
|
* A Delete an addToContext and a RemoveFromContext operation has a cascade impact
|
||||||
* Instances affected by a delete
|
* we want to know the impact, i.e. instances involved
|
||||||
*/
|
*/
|
||||||
protected final Map<UUID,JsonNode> affectedInstances;
|
protected final Map<UUID,JsonNode> affectedInstances;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
protected ElementManagement(AccessType accessType) {
|
protected ElementManagement(AccessType accessType) {
|
||||||
this.accessType = accessType;
|
this.accessType = accessType;
|
||||||
|
|
||||||
this.ignoreKeys = new HashSet<String>();
|
this.ignoreKeys = new HashSet<String>();
|
||||||
this.ignoreKeys.add(Element.TYPE_PROPERTY);
|
this.ignoreKeys.add(Element.TYPE_PROPERTY);
|
||||||
this.ignoreKeys.add(Element.SUPERTYPES_PROPERTY);
|
this.ignoreKeys.add(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
this.ignoreKeys.add(Element.EXPECTED_TYPE_PROPERTY);
|
this.ignoreKeys.add(ModelElement.EXPECTED_TYPE_PROPERTY);
|
||||||
this.ignoreKeys.add(IdentifiableElement.ID_PROPERTY);
|
this.ignoreKeys.add(IdentifiableElement.ID_PROPERTY);
|
||||||
this.ignoreKeys.add(IdentifiableElement.METADATA_PROPERTY);
|
this.ignoreKeys.add(IdentifiableElement.METADATA_PROPERTY);
|
||||||
|
|
||||||
this.ignoreStartWithKeys = new HashSet<String>();
|
this.ignoreStartWithKeys = new HashSet<String>();
|
||||||
this.ignoreStartWithKeys.add(ElementManagement.AT);
|
this.ignoreStartWithKeys.add(ElementManagement.AT);
|
||||||
this.ignoreStartWithKeys.add(ElementManagement.UNDERSCORE);
|
this.ignoreStartWithKeys.add(ElementManagement.UNDERSCORE);
|
||||||
|
this.ignoreStartWithKeys.add(ElementManagement.DOLLAR);
|
||||||
|
|
||||||
this.reload = false;
|
this.reload = false;
|
||||||
|
|
||||||
|
@ -181,6 +189,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
this.forceIncludeMeta = false;
|
this.forceIncludeMeta = false;
|
||||||
this.forceIncludeAllMeta = false;
|
this.forceIncludeAllMeta = false;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isForceIncludeMeta() {
|
public boolean isForceIncludeMeta() {
|
||||||
|
@ -243,17 +252,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
return accessType;
|
return accessType;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected SecurityContext workingContext;
|
protected Environment workingEnvironment;
|
||||||
|
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected abstract Environment getWorkingEnvironment() throws ResourceRegistryException;
|
||||||
if(workingContext == null) {
|
|
||||||
workingContext = ContextUtility.getCurrentSecurityContext();
|
|
||||||
}
|
|
||||||
return workingContext;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWorkingContext(SecurityContext workingContext) {
|
public void setWorkingEnvironment(Environment workingContext) {
|
||||||
this.workingContext = workingContext;
|
this.workingEnvironment = workingContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUUID(UUID uuid) throws ResourceRegistryException {
|
public void setUUID(UUID uuid) throws ResourceRegistryException {
|
||||||
|
@ -441,7 +445,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
List<String> keysToAddFirst = new ArrayList<>();
|
List<String> keysToAddFirst = new ArrayList<>();
|
||||||
keysToAddFirst.add(Element.TYPE_PROPERTY);
|
keysToAddFirst.add(Element.TYPE_PROPERTY);
|
||||||
keysToAddFirst.add(Element.SUPERTYPES_PROPERTY);
|
keysToAddFirst.add(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
keysToAddFirst.add(IdentifiableElement.ID_PROPERTY);
|
keysToAddFirst.add(IdentifiableElement.ID_PROPERTY);
|
||||||
keysToAddFirst.add(IdentifiableElement.METADATA_PROPERTY);
|
keysToAddFirst.add(IdentifiableElement.METADATA_PROPERTY);
|
||||||
keysToAddFirst.add(ERElement.CONTEXTS_PROPERTY);
|
keysToAddFirst.add(ERElement.CONTEXTS_PROPERTY);
|
||||||
|
@ -453,10 +457,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
objectNode.put(Element.TYPE_PROPERTY, getTypeName());
|
objectNode.put(Element.TYPE_PROPERTY, getTypeName());
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case Element.SUPERTYPES_PROPERTY:
|
case ModelElement.SUPERTYPES_PROPERTY:
|
||||||
Collection<String> supertypes = getCachedType().getSuperTypes();
|
Collection<String> supertypes = getCachedType().getSuperTypes();
|
||||||
ArrayNode arrayNode = objectMapper.valueToTree(supertypes);
|
ArrayNode arrayNode = objectMapper.valueToTree(supertypes);
|
||||||
objectNode.replace(Element.SUPERTYPES_PROPERTY, arrayNode);
|
if(arrayNode==null || arrayNode.size()==0) {
|
||||||
|
objectNode.remove(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
|
}else {
|
||||||
|
objectNode.replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case IdentifiableElement.METADATA_PROPERTY:
|
case IdentifiableElement.METADATA_PROPERTY:
|
||||||
|
@ -543,7 +551,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
MetadataUtility.addMetadata(element);
|
MetadataUtility.addMetadata(element);
|
||||||
|
|
||||||
getWorkingContext().addElement(element, oDatabaseDocument);
|
getWorkingEnvironment().addElement(element, oDatabaseDocument);
|
||||||
|
|
||||||
element.save();
|
element.save();
|
||||||
|
|
||||||
|
@ -572,6 +580,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
sanityCheck();
|
sanityCheck();
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
|
} catch(WebApplicationException e) {
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
|
@ -663,10 +673,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
public String all(boolean polymorphic) throws ResourceRegistryException {
|
public String all(boolean polymorphic) throws ResourceRegistryException {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
setOperation(Operation.QUERY);
|
setOperation(Operation.QUERY);
|
||||||
return reallyGetAll(polymorphic);
|
return reallyGetAll(polymorphic);
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
|
@ -685,15 +697,18 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
public boolean exists() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
setOperation(Operation.EXISTS);
|
setOperation(Operation.EXISTS);
|
||||||
|
|
||||||
getElement();
|
getElement();
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to find {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to find {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e);
|
logger.error("Unable to find {} with UUID {}", accessType.getName(), uuid, e);
|
||||||
|
@ -713,16 +728,20 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
|
Environment environment = getWorkingEnvironment();
|
||||||
|
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
boolean update = false;
|
boolean update = false;
|
||||||
|
setAsEntryPoint();
|
||||||
|
setOperation(Operation.UPDATE);
|
||||||
try {
|
try {
|
||||||
setAsEntryPoint();
|
|
||||||
getElement();
|
getElement();
|
||||||
|
// TODO environment.isUserAllowed(operation);
|
||||||
update = true;
|
update = true;
|
||||||
internalUpdate();
|
internalUpdate();
|
||||||
} catch(NotFoundException e) {
|
} catch(NotFoundException e) {
|
||||||
setAsEntryPoint();
|
setOperation(Operation.CREATE);
|
||||||
|
// TODO environment.isUserAllowed(operation);
|
||||||
String calledMethod = CalledMethodProvider.instance.get();
|
String calledMethod = CalledMethodProvider.instance.get();
|
||||||
calledMethod = calledMethod.replace("update", "create");
|
calledMethod = calledMethod.replace("update", "create");
|
||||||
CalledMethodProvider.instance.set(calledMethod);
|
CalledMethodProvider.instance.set(calledMethod);
|
||||||
|
@ -739,8 +758,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
return serializeAsJsonNode().toString();
|
return serializeAsJsonNode().toString();
|
||||||
|
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to update {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
|
if(oDatabaseDocument != null) {
|
||||||
|
oDatabaseDocument.rollback();
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to update {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
if(oDatabaseDocument != null) {
|
if(oDatabaseDocument != null) {
|
||||||
oDatabaseDocument.rollback();
|
oDatabaseDocument.rollback();
|
||||||
}
|
}
|
||||||
|
@ -766,7 +791,9 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
|
Environment environment = getWorkingEnvironment();
|
||||||
|
// TODO environment.isUserAllowed(Operation.CREATE);
|
||||||
|
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
|
||||||
|
@ -778,8 +805,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
return serializeAsJsonNode().toString();
|
return serializeAsJsonNode().toString();
|
||||||
|
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to create {}. Reason {}", accessType.getName(), e.getMessage());
|
||||||
|
if(oDatabaseDocument != null) {
|
||||||
|
oDatabaseDocument.rollback();
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to create {}", accessType.getName());
|
logger.error("Unable to create {}. Reason {}", accessType.getName(), e.getMessage());
|
||||||
if(oDatabaseDocument != null) {
|
if(oDatabaseDocument != null) {
|
||||||
oDatabaseDocument.rollback();
|
oDatabaseDocument.rollback();
|
||||||
}
|
}
|
||||||
|
@ -805,16 +838,21 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
|
Environment environment = getWorkingEnvironment();
|
||||||
|
setOperation(Operation.READ);
|
||||||
|
// TODO environment.isUserAllowed(operation);
|
||||||
|
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
setOperation(Operation.READ);
|
|
||||||
|
|
||||||
getElement();
|
getElement();
|
||||||
|
|
||||||
return serializeAsJsonNode().toString();
|
return serializeAsJsonNode().toString();
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to read {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to read {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e);
|
logger.error("Unable to read {} with UUID {}", accessType.getName(), uuid, e);
|
||||||
|
@ -831,10 +869,11 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
}
|
}
|
||||||
|
|
||||||
public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
public String update() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
||||||
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
|
Environment environment = getWorkingEnvironment();
|
||||||
|
// TODO environment.isUserAllowed(Operation.UPDATE);
|
||||||
|
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
|
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
@ -848,8 +887,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
|
|
||||||
return serializeAsJsonNode().toString();
|
return serializeAsJsonNode().toString();
|
||||||
|
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to update {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
|
if(oDatabaseDocument != null) {
|
||||||
|
oDatabaseDocument.rollback();
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to update {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to update {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
if(oDatabaseDocument != null) {
|
if(oDatabaseDocument != null) {
|
||||||
oDatabaseDocument.rollback();
|
oDatabaseDocument.rollback();
|
||||||
}
|
}
|
||||||
|
@ -875,8 +920,10 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
logger.trace("Going to delete {} instance with UUID {}", accessType.getName(), uuid);
|
logger.trace("Going to delete {} instance with UUID {}", accessType.getName(), uuid);
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
// oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
|
Environment environment = getWorkingEnvironment();
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
|
setOperation(Operation.DELETE);
|
||||||
|
// TODO environment.isUserAllowed(operation);
|
||||||
|
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
|
||||||
|
@ -888,8 +935,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
}else {
|
}else {
|
||||||
oDatabaseDocument.rollback();
|
oDatabaseDocument.rollback();
|
||||||
}
|
}
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to delete {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
|
if(oDatabaseDocument != null) {
|
||||||
|
oDatabaseDocument.rollback();
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to delete {} with UUID {}", accessType.getName(), uuid);
|
logger.error("Unable to delete {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
|
||||||
if(oDatabaseDocument != null) {
|
if(oDatabaseDocument != null) {
|
||||||
oDatabaseDocument.rollback();
|
oDatabaseDocument.rollback();
|
||||||
}
|
}
|
||||||
|
@ -911,21 +964,25 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public Set<String> getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException {
|
public Set<String> getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException {
|
||||||
logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid);
|
logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid);
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument instanceDB = this.oDatabaseDocument;
|
||||||
try {
|
try {
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
setOperation(Operation.GET_METADATA);
|
||||||
|
// TODO adminEnvironment.isUserAllowed(operation);
|
||||||
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
setOperation(Operation.GET_METADATA);
|
|
||||||
|
|
||||||
Set<String> contexts = SecurityContext.getContexts(getElement());
|
Set<String> contexts = InstanceEnvironment.getContexts(getElement());
|
||||||
return contexts;
|
return contexts;
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
logger.error("Unable to get contexts for {} with UUID {}. Reason {}", typeName, uuid, e.getMessage());
|
||||||
|
throw e;
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to get contexts for {} with UUID {}", typeName, uuid, e);
|
logger.error("Unable to get contexts for {} with UUID {}. Reason {}", typeName, uuid, e.getMessage());
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to get contexts for {} with UUID {}", typeName, uuid, e);
|
logger.error("Unable to get contexts for {} with UUID {}", typeName, uuid, e);
|
||||||
|
@ -938,6 +995,10 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
if(current!=null) {
|
if(current!=null) {
|
||||||
current.activateOnCurrentThread();
|
current.activateOnCurrentThread();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(instanceDB!=null) {
|
||||||
|
this.oDatabaseDocument = instanceDB;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -975,64 +1036,6 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
return getContextsAsObjectNode(objectMapper);
|
return getContextsAsObjectNode(objectMapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Object getObjectFromJsonNode(JsonNode value)
|
|
||||||
throws UnsupportedDataTypeException, ResourceRegistryException {
|
|
||||||
JsonNodeType jsonNodeType = value.getNodeType();
|
|
||||||
|
|
||||||
switch(jsonNodeType) {
|
|
||||||
case OBJECT:
|
|
||||||
return PropertyElementManagement.getPropertyDocument(value);
|
|
||||||
|
|
||||||
case ARRAY:
|
|
||||||
/*
|
|
||||||
* Due to bug https://github.com/orientechnologies/orientdb/issues/7354
|
|
||||||
* we should not support ArrayList
|
|
||||||
*/
|
|
||||||
List<Object> list = new ArrayList<>();
|
|
||||||
ArrayNode arrayNode = (ArrayNode) value;
|
|
||||||
for(JsonNode node : arrayNode) {
|
|
||||||
list.add(getObjectFromJsonNode(node));
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
|
|
||||||
case BINARY:
|
|
||||||
break;
|
|
||||||
|
|
||||||
case BOOLEAN:
|
|
||||||
return value.asBoolean();
|
|
||||||
|
|
||||||
case NULL:
|
|
||||||
break;
|
|
||||||
|
|
||||||
case NUMBER:
|
|
||||||
if(value.isDouble() || value.isFloat()) {
|
|
||||||
return value.asDouble();
|
|
||||||
}
|
|
||||||
if(value.isBigInteger() || value.isShort() || value.isInt()) {
|
|
||||||
return value.asInt();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(value.isLong()) {
|
|
||||||
return value.asLong();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case STRING:
|
|
||||||
return value.asText();
|
|
||||||
|
|
||||||
case MISSING:
|
|
||||||
break;
|
|
||||||
|
|
||||||
case POJO:
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String,JsonNode> getPropertyMap(JsonNode jsonNode, Set<String> ignoreKeys,
|
public Map<String,JsonNode> getPropertyMap(JsonNode jsonNode, Set<String> ignoreKeys,
|
||||||
Set<String> ignoreStartWith) throws JsonProcessingException, IOException {
|
Set<String> ignoreStartWith) throws JsonProcessingException, IOException {
|
||||||
|
|
||||||
|
@ -1087,7 +1090,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
Object object = null;
|
Object object = null;
|
||||||
|
|
||||||
if(oProperty.getLinkedType()!=null) {
|
if(oProperty.getLinkedType()!=null) {
|
||||||
object = getObjectFromJsonNode(elementOfArray);
|
object = ElementManagementUtility.getObjectFromJsonNode(elementOfArray);
|
||||||
}else {
|
}else {
|
||||||
object = PropertyElementManagement.getPropertyDocument(elementOfArray);
|
object = PropertyElementManagement.getPropertyDocument(elementOfArray);
|
||||||
}
|
}
|
||||||
|
@ -1104,7 +1107,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
Object object = null;
|
Object object = null;
|
||||||
|
|
||||||
if(oProperty.getLinkedType()!=null) {
|
if(oProperty.getLinkedType()!=null) {
|
||||||
object = getObjectFromJsonNode(elementOfSet);
|
object = ElementManagementUtility.getObjectFromJsonNode(elementOfSet);
|
||||||
}else {
|
}else {
|
||||||
object = PropertyElementManagement.getPropertyDocument(elementOfSet);
|
object = PropertyElementManagement.getPropertyDocument(elementOfSet);
|
||||||
}
|
}
|
||||||
|
@ -1120,7 +1123,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
String fieldKey = fieldNames.next();
|
String fieldKey = fieldNames.next();
|
||||||
Object object = null;
|
Object object = null;
|
||||||
if(oProperty.getLinkedType()!=null) {
|
if(oProperty.getLinkedType()!=null) {
|
||||||
object = getObjectFromJsonNode(value.get(fieldKey));
|
object = ElementManagementUtility.getObjectFromJsonNode(value.get(fieldKey));
|
||||||
}else {
|
}else {
|
||||||
object = PropertyElementManagement.getPropertyDocument(value.get(fieldKey));
|
object = PropertyElementManagement.getPropertyDocument(value.get(fieldKey));
|
||||||
}
|
}
|
||||||
|
@ -1134,12 +1137,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
if(value.getNodeType() == JsonNodeType.OBJECT) {
|
if(value.getNodeType() == JsonNodeType.OBJECT) {
|
||||||
element.setProperty(key, value.toString());
|
element.setProperty(key, value.toString());
|
||||||
}else {
|
}else {
|
||||||
element.setProperty(key, getObjectFromJsonNode(value));
|
element.setProperty(key, ElementManagementUtility.getObjectFromJsonNode(value));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
Object obj = getObjectFromJsonNode(value);
|
Object obj = ElementManagementUtility.getObjectFromJsonNode(value);
|
||||||
if(obj != null) {
|
if(obj != null) {
|
||||||
element.setProperty(key, obj);
|
element.setProperty(key, obj);
|
||||||
}
|
}
|
||||||
|
@ -1170,7 +1173,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
OProperty oProperty = oClass.getProperty(key);
|
OProperty oProperty = oClass.getProperty(key);
|
||||||
|
|
||||||
if(oProperty==null) {
|
if(oProperty==null) {
|
||||||
Object object = getObjectFromJsonNode(value);
|
Object object = ElementManagementUtility.getObjectFromJsonNode(value);
|
||||||
if(object != null) {
|
if(object != null) {
|
||||||
if(object instanceof ODocument) {
|
if(object instanceof ODocument) {
|
||||||
element.setProperty(key, object, OType.EMBEDDED);
|
element.setProperty(key, object, OType.EMBEDDED);
|
||||||
|
@ -1215,9 +1218,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isUserAllowedToGetPrivacyMeta() {
|
public boolean isUserAllowedToGetPrivacyMeta() {
|
||||||
// TODO
|
boolean allowed = false;
|
||||||
return true;
|
SecretManager secretManager = SecretManagerProvider.instance.get();
|
||||||
|
User user = secretManager.getUser();
|
||||||
|
Collection<String> roles = new HashSet<>(user.getRoles());
|
||||||
|
if(roles.contains(Environment.CONTEXT_MANAGER)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
roles.retainAll(Environment.getAllOperationsAllowedRoles());
|
||||||
|
if(roles.size()>0) {
|
||||||
|
allowed = true;
|
||||||
|
}
|
||||||
|
return allowed;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected JsonNode getPropertyForJson(String key, Object object) throws ResourceRegistryException {
|
protected JsonNode getPropertyForJson(String key, Object object) throws ResourceRegistryException {
|
||||||
|
@ -1243,11 +1256,11 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
|
||||||
// TODO check a solution for supertypes
|
// TODO check a solution for supertypes
|
||||||
TypesCache typesCache = TypesCache.getInstance();
|
TypesCache typesCache = TypesCache.getInstance();
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
CachedType<PropertyType<Property>> metadataType = (CachedType<PropertyType<Property>>) typesCache.getCachedType(Metadata.NAME);
|
CachedType<PropertyType> metadataType = (CachedType<PropertyType>) typesCache.getCachedType(Metadata.NAME);
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
Collection<String> superClasses = metadataType.getSuperTypes();
|
Collection<String> superClasses = metadataType.getSuperTypes();
|
||||||
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
|
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
|
||||||
metadataJson.replace(Element.SUPERTYPES_PROPERTY, arrayNode);
|
metadataJson.replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
|
||||||
|
|
||||||
return metadataJson;
|
return metadataJson;
|
||||||
}
|
}
|
|
@ -1,25 +1,29 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.instances.base;
|
package org.gcube.informationsystem.resourceregistry.base;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import javax.activation.UnsupportedDataTypeException;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Entity;
|
|
||||||
|
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.JsonNodeType;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Facet;
|
import org.gcube.informationsystem.model.reference.entities.Facet;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Resource;
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
||||||
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
|
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
|
||||||
import org.gcube.informationsystem.model.reference.relations.Relation;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.properties.PropertyElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.EntityManagement;
|
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.FacetManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
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.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -37,48 +41,6 @@ public class ElementManagementUtility {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ElementManagementUtility.class);
|
private static Logger logger = LoggerFactory.getLogger(ElementManagementUtility.class);
|
||||||
|
|
||||||
public static ElementManagement<?,?> getERManagement(String type) throws ResourceRegistryException {
|
|
||||||
|
|
||||||
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
|
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = null;
|
|
||||||
|
|
||||||
switch (accessType) {
|
|
||||||
case RESOURCE:
|
|
||||||
erManagement = new ResourceManagement();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case FACET:
|
|
||||||
erManagement = new FacetManagement();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case IS_RELATED_TO:
|
|
||||||
erManagement = new IsRelatedToManagement();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case CONSISTS_OF:
|
|
||||||
erManagement = new ConsistsOfManagement();
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new ResourceRegistryException(String.format("%s is not querable", type.toString()));
|
|
||||||
}
|
|
||||||
erManagement.setElementType(type);
|
|
||||||
|
|
||||||
return erManagement;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static ElementManagement<?,?> getERManagement(SecurityContext workingContext, ODatabaseDocument orientGraph,
|
|
||||||
OElement element) throws ResourceRegistryException {
|
|
||||||
if(element instanceof OVertex) {
|
|
||||||
return getEntityManagement(workingContext, orientGraph, (OVertex) element);
|
|
||||||
} else if(element instanceof OEdge) {
|
|
||||||
return getRelationManagement(workingContext, orientGraph, (OEdge) element);
|
|
||||||
}
|
|
||||||
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
|
|
||||||
Entity.NAME, Relation.NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
|
public static OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OVertex.class);
|
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OVertex.class);
|
||||||
|
@ -104,19 +66,9 @@ public class ElementManagementUtility {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ElementManagement<?, ?> getERManagementFromUUID(SecurityContext workingContext, ODatabaseDocument orientGraph,
|
|
||||||
UUID uuid) throws ResourceRegistryException {
|
|
||||||
OElement element;
|
|
||||||
try {
|
|
||||||
element = getAnyElementByUUID(orientGraph, uuid);
|
|
||||||
return getERManagement(workingContext, orientGraph, element);
|
|
||||||
} catch(Exception e) {
|
|
||||||
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
|
|
||||||
uuid.toString(), Entity.NAME, Relation.NAME));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static EntityManagement<?, ?> getEntityManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument,
|
|
||||||
|
public static EntityManagement<?, ?> getEntityManagement(Environment workingContext, ODatabaseDocument oDatabaseDocument,
|
||||||
OVertex vertex) throws ResourceRegistryException {
|
OVertex vertex) throws ResourceRegistryException {
|
||||||
|
|
||||||
if(oDatabaseDocument == null) {
|
if(oDatabaseDocument == null) {
|
||||||
|
@ -150,12 +102,12 @@ public class ElementManagementUtility {
|
||||||
throw new ResourceRegistryException(error);
|
throw new ResourceRegistryException(error);
|
||||||
}
|
}
|
||||||
entityManagement.setODatabaseDocument(oDatabaseDocument);
|
entityManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
entityManagement.setWorkingContext(workingContext);
|
entityManagement.setWorkingEnvironment(workingContext);
|
||||||
entityManagement.setElement(vertex);
|
entityManagement.setElement(vertex);
|
||||||
return entityManagement;
|
return entityManagement;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static RelationManagement<?,?> getRelationManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument,
|
public static RelationManagement<?,?> getRelationManagement(Environment workingContext, ODatabaseDocument oDatabaseDocument,
|
||||||
OEdge edge) throws ResourceRegistryException {
|
OEdge edge) throws ResourceRegistryException {
|
||||||
|
|
||||||
if(oDatabaseDocument == null) {
|
if(oDatabaseDocument == null) {
|
||||||
|
@ -183,7 +135,7 @@ public class ElementManagementUtility {
|
||||||
|
|
||||||
|
|
||||||
relationManagement.setODatabaseDocument(oDatabaseDocument);
|
relationManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
relationManagement.setWorkingContext(workingContext);
|
relationManagement.setWorkingEnvironment(workingContext);
|
||||||
|
|
||||||
relationManagement.setElement(edge);
|
relationManagement.setElement(edge);
|
||||||
return relationManagement;
|
return relationManagement;
|
||||||
|
@ -205,5 +157,63 @@ public class ElementManagementUtility {
|
||||||
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
|
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Object getObjectFromJsonNode(JsonNode value)
|
||||||
|
throws UnsupportedDataTypeException, ResourceRegistryException {
|
||||||
|
JsonNodeType jsonNodeType = value.getNodeType();
|
||||||
|
|
||||||
|
switch(jsonNodeType) {
|
||||||
|
case OBJECT:
|
||||||
|
return PropertyElementManagement.getPropertyDocument(value);
|
||||||
|
|
||||||
|
case ARRAY:
|
||||||
|
/*
|
||||||
|
* Due to bug https://github.com/orientechnologies/orientdb/issues/7354
|
||||||
|
* we should not support ArrayList
|
||||||
|
*/
|
||||||
|
List<Object> list = new ArrayList<>();
|
||||||
|
ArrayNode arrayNode = (ArrayNode) value;
|
||||||
|
for(JsonNode node : arrayNode) {
|
||||||
|
list.add(getObjectFromJsonNode(node));
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
|
||||||
|
case BINARY:
|
||||||
|
break;
|
||||||
|
|
||||||
|
case BOOLEAN:
|
||||||
|
return value.asBoolean();
|
||||||
|
|
||||||
|
case NULL:
|
||||||
|
break;
|
||||||
|
|
||||||
|
case NUMBER:
|
||||||
|
if(value.isDouble() || value.isFloat()) {
|
||||||
|
return value.asDouble();
|
||||||
|
}
|
||||||
|
if(value.isBigInteger() || value.isShort() || value.isInt()) {
|
||||||
|
return value.asInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(value.isLong()) {
|
||||||
|
return value.asLong();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case STRING:
|
||||||
|
return value.asText();
|
||||||
|
|
||||||
|
case MISSING:
|
||||||
|
break;
|
||||||
|
|
||||||
|
case POJO:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.instances.base.entities;
|
package org.gcube.informationsystem.resourceregistry.base.entities;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
@ -14,10 +14,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAn
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.EntityAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.EntityAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.base.relations.RelationElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
|
||||||
|
@ -52,10 +52,10 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected EntityElementManagement(AccessType accessType, SecurityContext workingContext, ODatabaseDocument oDatabaseDocument) {
|
protected EntityElementManagement(AccessType accessType, Environment workingContext, ODatabaseDocument oDatabaseDocument) {
|
||||||
this(accessType);
|
this(accessType);
|
||||||
this.oDatabaseDocument = oDatabaseDocument;
|
this.oDatabaseDocument = oDatabaseDocument;
|
||||||
setWorkingContext(workingContext);
|
setWorkingEnvironment(workingContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
@ -68,7 +68,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
|
||||||
String id = edge.getIdentity().toString();
|
String id = edge.getIdentity().toString();
|
||||||
RelationElementManagement<?,?,?,?> relationManagement = relationManagements.get(id);
|
RelationElementManagement<?,?,?,?> relationManagement = relationManagements.get(id);
|
||||||
if(relationManagement == null) {
|
if(relationManagement == null) {
|
||||||
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
|
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
}
|
}
|
||||||
return relationManagement;
|
return relationManagement;
|
|
@ -1,4 +1,4 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.instances.base.properties;
|
package org.gcube.informationsystem.resourceregistry.base.properties;
|
||||||
|
|
||||||
import java.security.Key;
|
import java.security.Key;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
@ -12,16 +12,15 @@ 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.ObjectNode;
|
||||||
import org.gcube.common.encryption.encrypter.StringEncrypter;
|
import org.gcube.common.encryption.encrypter.StringEncrypter;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Element;
|
import org.gcube.informationsystem.model.reference.ModelElement;
|
||||||
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
|
|
||||||
import org.gcube.informationsystem.model.reference.properties.Encrypted;
|
import org.gcube.informationsystem.model.reference.properties.Encrypted;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Property;
|
import org.gcube.informationsystem.model.reference.properties.Property;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient;
|
import org.gcube.informationsystem.resourceregistry.utils.EncryptedOrient;
|
||||||
|
@ -52,6 +51,7 @@ public class PropertyElementManagement {
|
||||||
PROPERTY_IGNORE_START_WITH_KEYS = new HashSet<String>();
|
PROPERTY_IGNORE_START_WITH_KEYS = new HashSet<String>();
|
||||||
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.AT);
|
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.AT);
|
||||||
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.UNDERSCORE);
|
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.UNDERSCORE);
|
||||||
|
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.DOLLAR);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -63,8 +63,12 @@ public class PropertyElementManagement {
|
||||||
|
|
||||||
JsonNode jsonNode = jsonNodeOrig.deepCopy();
|
JsonNode jsonNode = jsonNodeOrig.deepCopy();
|
||||||
|
|
||||||
if(jsonNode.has(Element.SUPERTYPES_PROPERTY)) {
|
if(jsonNode.has(ModelElement.SUPERTYPES_PROPERTY)) {
|
||||||
((ObjectNode) jsonNode).remove(Element.SUPERTYPES_PROPERTY);
|
((ObjectNode) jsonNode).remove(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(jsonNode.has(ModelElement.EXPECTED_TYPE_PROPERTY)) {
|
||||||
|
((ObjectNode) jsonNode).remove(ModelElement.EXPECTED_TYPE_PROPERTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
String type = TypeUtility.getTypeName(jsonNode);
|
String type = TypeUtility.getTypeName(jsonNode);
|
||||||
|
@ -75,7 +79,7 @@ public class PropertyElementManagement {
|
||||||
try {
|
try {
|
||||||
TypesCache typesCache = TypesCache.getInstance();
|
TypesCache typesCache = TypesCache.getInstance();
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
|
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(type);
|
||||||
oClass = cachedType.getOClass();
|
oClass = cachedType.getOClass();
|
||||||
AccessType gotAccessType = cachedType.getAccessType();
|
AccessType gotAccessType = cachedType.getAccessType();
|
||||||
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
|
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
|
||||||
|
@ -152,7 +156,7 @@ public class PropertyElementManagement {
|
||||||
|
|
||||||
TypesCache typesCache = TypesCache.getInstance();
|
TypesCache typesCache = TypesCache.getInstance();
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
|
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(type);
|
||||||
OClass oClass = cachedType.getOClass();
|
OClass oClass = cachedType.getOClass();
|
||||||
AccessType gotAccessType = cachedType.getAccessType();
|
AccessType gotAccessType = cachedType.getAccessType();
|
||||||
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
|
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
|
||||||
|
@ -161,7 +165,7 @@ public class PropertyElementManagement {
|
||||||
|
|
||||||
Collection<String> superClasses = cachedType.getSuperTypes();
|
Collection<String> superClasses = cachedType.getSuperTypes();
|
||||||
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
|
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
|
||||||
((ObjectNode) jsonNode).replace(Element.SUPERTYPES_PROPERTY, arrayNode);
|
((ObjectNode) jsonNode).replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* In case it is an Encrypted type the value is encrypted with the DB Key
|
* In case it is an Encrypted type the value is encrypted with the DB Key
|
|
@ -1,4 +1,4 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.instances.base.relations;
|
package org.gcube.informationsystem.resourceregistry.base.relations;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@ -13,9 +13,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
import org.gcube.informationsystem.types.reference.relations.RelationType;
|
import org.gcube.informationsystem.types.reference.relations.RelationType;
|
||||||
|
@ -73,10 +73,10 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
|
||||||
this.includeTarget = includeTarget;
|
this.includeTarget = includeTarget;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass, SecurityContext workingContext, ODatabaseDocument orientGraph) {
|
protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass, Environment workingContext, ODatabaseDocument orientGraph) {
|
||||||
this(accessType, sourceEntityClass, targetEntityClass);
|
this(accessType, sourceEntityClass, targetEntityClass);
|
||||||
this.oDatabaseDocument = orientGraph;
|
this.oDatabaseDocument = orientGraph;
|
||||||
setWorkingContext(workingContext);
|
setWorkingEnvironment(workingContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SEM getSourceEntityManagement() throws ResourceRegistryException {
|
public SEM getSourceEntityManagement() throws ResourceRegistryException {
|
|
@ -5,6 +5,7 @@ import java.util.Map;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.gcube.common.authorization.utils.manager.SecretManager;
|
||||||
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
||||||
import org.gcube.common.scope.impl.ScopeBean;
|
import org.gcube.common.scope.impl.ScopeBean;
|
||||||
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
|
@ -12,10 +13,10 @@ import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
@ -35,7 +36,7 @@ public class ContextUtility {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
|
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
|
||||||
|
|
||||||
private Map<UUID,SecurityContext> contexts;
|
private Map<UUID,InstanceEnvironment> contexts;
|
||||||
|
|
||||||
private static ContextUtility contextUtility;
|
private static ContextUtility contextUtility;
|
||||||
|
|
||||||
|
@ -54,56 +55,52 @@ public class ContextUtility {
|
||||||
return SecretManagerProvider.instance.get().getContext();
|
return SecretManagerProvider.instance.get().getContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
|
public static InstanceEnvironment getCurrentRequestEnvironment() throws ResourceRegistryException {
|
||||||
String fullName = getCurrentContextFullName();
|
String fullName = getCurrentContextFullName();
|
||||||
if(fullName == null) {
|
if(fullName == null) {
|
||||||
throw new ContextException("Null Token and Scope. Please set your token first.");
|
throw new ContextException("Null Token and Scope. Please set your token first.");
|
||||||
}
|
}
|
||||||
return ContextUtility.getInstance().getSecurityContextByFullName(fullName);
|
return ContextUtility.getInstance().getRequestEnvironmentByContextFullName(fullName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static AdminSecurityContext getAdminSecurityContext() throws ResourceRegistryException {
|
public static String getCurrentUserUsername() {
|
||||||
AdminSecurityContext adminSecurityContext = AdminSecurityContext.getInstance();
|
SecretManager sm = SecretManagerProvider.instance.get();
|
||||||
return adminSecurityContext;
|
return sm.getUser().getUsername();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void addSecurityContext(SecurityContext securityContext) {
|
public synchronized void addInstanceEnvironment(InstanceEnvironment instanceEnvironment) {
|
||||||
contexts.put(securityContext.getUUID(), securityContext);
|
contexts.put(instanceEnvironment.getUUID(), instanceEnvironment);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void addSecurityContext(String fullname, SecurityContext securityContext) {
|
public synchronized InstanceEnvironment getRequestEnvironmentByContextFullName(String fullName) throws ContextException {
|
||||||
contexts.put(securityContext.getUUID(), securityContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException {
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
SecurityContext securityContext = null;
|
InstanceEnvironment instanceEnvironment = null;
|
||||||
|
|
||||||
logger.trace("Trying to get {} for {}", SecurityContext.class.getSimpleName(), fullName);
|
logger.trace("Trying to get {} for {}", InstanceEnvironment.class.getSimpleName(), fullName);
|
||||||
UUID uuid = ServerContextCache.getInstance().getUUIDByFullName(fullName);
|
UUID uuid = ServerContextCache.getInstance().getUUIDByFullName(fullName);
|
||||||
|
|
||||||
if(uuid != null) {
|
if(uuid != null) {
|
||||||
securityContext = contexts.get(uuid);
|
instanceEnvironment = contexts.get(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(securityContext==null) {
|
if(instanceEnvironment==null) {
|
||||||
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
|
logger.trace("{} for {} is not in cache. Going to get it", InstanceEnvironment.class.getSimpleName(),
|
||||||
fullName);
|
fullName);
|
||||||
oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
OVertex contextVertex = getContextVertexByFullName(oDatabaseDocument, fullName);
|
OVertex contextVertex = getContextVertexByFullName(oDatabaseDocument, fullName);
|
||||||
|
|
||||||
uuid = UUIDUtility.getUUID(contextVertex);
|
uuid = UUIDUtility.getUUID(contextVertex);
|
||||||
|
|
||||||
securityContext = getSecurityContextByUUID(uuid, contextVertex);
|
instanceEnvironment = getEnvironmentByUUID(uuid, contextVertex);
|
||||||
|
|
||||||
addSecurityContext(fullName, securityContext);
|
addInstanceEnvironment(instanceEnvironment);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return securityContext;
|
return instanceEnvironment;
|
||||||
|
|
||||||
} catch(ContextException e) {
|
} catch(ContextException e) {
|
||||||
throw e;
|
throw e;
|
||||||
|
@ -120,8 +117,8 @@ public class ContextUtility {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException {
|
public InstanceEnvironment getEnvironmentByUUID(UUID uuid) throws ResourceRegistryException {
|
||||||
return getSecurityContextByUUID(uuid, null);
|
return getEnvironmentByUUID(uuid, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() {
|
public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() {
|
||||||
|
@ -134,50 +131,44 @@ public class ContextUtility {
|
||||||
return current;
|
return current;
|
||||||
}
|
}
|
||||||
|
|
||||||
private OVertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
|
private InstanceEnvironment getEnvironmentByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
InstanceEnvironment instanceEnvironment = contexts.get(uuid);
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
if(instanceEnvironment == null) {
|
||||||
try {
|
|
||||||
oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER);
|
|
||||||
OVertex oVertex = OrientDBUtility.getElementByUUID(oDatabaseDocument, Context.NAME, uuid,
|
|
||||||
OVertex.class);
|
|
||||||
return oVertex;
|
|
||||||
} finally {
|
|
||||||
if(oDatabaseDocument!=null) {
|
|
||||||
oDatabaseDocument.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(current!=null) {
|
instanceEnvironment = new InstanceEnvironment(uuid);
|
||||||
current.activateOnCurrentThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private SecurityContext getSecurityContextByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException {
|
|
||||||
SecurityContext securityContext = contexts.get(uuid);
|
|
||||||
if(securityContext == null) {
|
|
||||||
|
|
||||||
securityContext = new SecurityContext(uuid);
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if(contextVertex == null) {
|
if(contextVertex == null) {
|
||||||
contextVertex = getContextVertexByUUID(uuid);
|
oDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.READER);
|
||||||
|
contextVertex = OrientDBUtility.getElementByUUID(oDatabaseDocument, Context.NAME, uuid, OVertex.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
OVertex parentVertex = contextVertex.getVertices(ODirection.IN, IsParentOf.NAME).iterator().next();
|
OVertex parentVertex = contextVertex.getVertices(ODirection.IN, IsParentOf.NAME).iterator().next();
|
||||||
|
|
||||||
if(parentVertex != null) {
|
if(parentVertex != null) {
|
||||||
UUID parentUUID = UUIDUtility.getUUID(parentVertex);
|
UUID parentUUID = UUIDUtility.getUUID(parentVertex);
|
||||||
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
|
instanceEnvironment.setParentEnvironment(getEnvironmentByUUID(parentUUID, parentVertex));
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch(NoSuchElementException e) {
|
} catch(NoSuchElementException e) {
|
||||||
// No parent
|
// No parent
|
||||||
|
} finally {
|
||||||
|
if(oDatabaseDocument!=null) {
|
||||||
|
oDatabaseDocument.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(current!=null) {
|
||||||
|
current.activateOnCurrentThread();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
contexts.put(uuid, securityContext);
|
contexts.put(uuid, instanceEnvironment);
|
||||||
}
|
}
|
||||||
|
|
||||||
return securityContext;
|
return instanceEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|
|
@ -3,11 +3,16 @@ package org.gcube.informationsystem.resourceregistry.contexts;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.TreeSet;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import javax.ws.rs.InternalServerErrorException;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ObjectNode;
|
||||||
|
@ -21,26 +26,26 @@ import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
|
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* TODO find a distributed solution
|
||||||
*/
|
*/
|
||||||
public class ServerContextCache extends ContextCache {
|
public class ServerContextCache extends ContextCache {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ServerContextCache.class);
|
private static Logger logger = LoggerFactory.getLogger(ServerContextCache.class);
|
||||||
|
|
||||||
protected List<Context> contextsNoMeta;
|
|
||||||
protected Map<UUID, Context> uuidToContextNoMeta;
|
|
||||||
|
|
||||||
protected List<Context> contextsMetaPrivacy;
|
protected List<Context> contextsMetaPrivacy;
|
||||||
protected Map<UUID, Context> uuidToContextMetaPrivacy;
|
protected Map<UUID, Context> uuidToContextMetaPrivacy;
|
||||||
|
|
||||||
|
protected List<Context> contextsBasicInfo;
|
||||||
|
protected Map<UUID, Context> uuidToContextBasicInfo;
|
||||||
|
|
||||||
protected boolean includeMeta;
|
protected boolean includeMeta;
|
||||||
|
|
||||||
protected static ServerContextCache singleton;
|
protected static ServerContextCache singleton;
|
||||||
|
@ -60,15 +65,17 @@ public class ServerContextCache extends ContextCache {
|
||||||
@Override
|
@Override
|
||||||
protected void cleanCache(Calendar now) {
|
protected void cleanCache(Calendar now) {
|
||||||
super.cleanCache(now);
|
super.cleanCache(now);
|
||||||
contextsNoMeta = null;
|
|
||||||
uuidToContextNoMeta = new LinkedHashMap<>();
|
this.contextsMetaPrivacy = new ArrayList<>();
|
||||||
contextsMetaPrivacy = null;
|
this.uuidToContextMetaPrivacy = new LinkedHashMap<>();
|
||||||
uuidToContextMetaPrivacy = new LinkedHashMap<>();
|
|
||||||
|
this.contextsBasicInfo = new ArrayList<>();
|
||||||
|
this.uuidToContextBasicInfo = new LinkedHashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public ServerContextCache() {
|
public ServerContextCache() {
|
||||||
super();
|
Calendar now = Calendar.getInstance();
|
||||||
cleanCache();
|
cleanCache(now);
|
||||||
initContextCacheRenewal();
|
initContextCacheRenewal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -85,7 +92,9 @@ public class ServerContextCache extends ContextCache {
|
||||||
@Override
|
@Override
|
||||||
public List<Context> renew() throws ResourceRegistryException {
|
public List<Context> renew() throws ResourceRegistryException {
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
String contextsJsonString = contextManagement.allFromServer(false);
|
contextManagement.setForceOffset(0);
|
||||||
|
contextManagement.setForceLimit(-1);
|
||||||
|
String contextsJsonString = contextManagement.allFromDatabase(false);
|
||||||
List<Context> contexts = null;
|
List<Context> contexts = null;
|
||||||
try {
|
try {
|
||||||
contexts = ElementMapper.unmarshalList(contextsJsonString);
|
contexts = ElementMapper.unmarshalList(contextsJsonString);
|
||||||
|
@ -98,38 +107,56 @@ public class ServerContextCache extends ContextCache {
|
||||||
setContextCacheRenewal(contextCacheRenewal);
|
setContextCacheRenewal(contextCacheRenewal);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected boolean isUserAllowedToGetPrivacyMeta() {
|
|
||||||
return ElementManagement.isUserAllowedToGetPrivacyMeta();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized List<Context> getContexts() throws ResourceRegistryException {
|
public synchronized List<Context> getContexts() throws ResourceRegistryException {
|
||||||
refreshContextsIfNeeded();
|
refreshContextsIfNeeded();
|
||||||
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
||||||
if(requestInfo.getUriInfo()!=null && !requestInfo.includeMeta()){
|
if(requestInfo!=null && !requestInfo.includeMeta()){
|
||||||
return contextsNoMeta;
|
return contextsBasicInfo;
|
||||||
}
|
}
|
||||||
if(isUserAllowedToGetPrivacyMeta()) {
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
|
if(contextManagement.isUserAllowedToGetPrivacyMeta()) {
|
||||||
return contexts;
|
return contexts;
|
||||||
}else {
|
}else {
|
||||||
return contextsMetaPrivacy;
|
return contextsMetaPrivacy;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public synchronized List<Context> getFullInfoContexts() throws ResourceRegistryException {
|
||||||
|
refreshContextsIfNeeded();
|
||||||
|
return contexts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized Context getFullInfoContextByUUID(UUID uuid) throws ResourceRegistryException {
|
||||||
|
refreshContextsIfNeeded();
|
||||||
|
return uuidToContext.get(uuid);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized Context getContextByUUID(UUID uuid) throws ResourceRegistryException {
|
public synchronized Context getContextByUUID(UUID uuid) throws ResourceRegistryException {
|
||||||
refreshContextsIfNeeded();
|
refreshContextsIfNeeded();
|
||||||
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
||||||
if(requestInfo.getUriInfo()!=null && !requestInfo.includeMeta()){
|
if(requestInfo.getUriInfo()!=null && !requestInfo.includeMeta()){
|
||||||
return uuidToContextNoMeta.get(uuid);
|
return uuidToContextBasicInfo.get(uuid);
|
||||||
}
|
}
|
||||||
if(isUserAllowedToGetPrivacyMeta()) {
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
|
if(contextManagement.isUserAllowedToGetPrivacyMeta()) {
|
||||||
return uuidToContext.get(uuid);
|
return uuidToContext.get(uuid);
|
||||||
}else {
|
}else {
|
||||||
return uuidToContextMetaPrivacy.get(uuid);
|
return uuidToContextMetaPrivacy.get(uuid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* USer internally to the service to get info such as state
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
* @throws ResourceRegistryException
|
||||||
|
*/
|
||||||
|
public synchronized Context getContextByUUIDFullInfo(UUID uuid) throws ResourceRegistryException {
|
||||||
|
return uuidToContext.get(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
protected Metadata getMetadataForPrivacy(ObjectMapper objectMapper, Metadata metadata) {
|
protected Metadata getMetadataForPrivacy(ObjectMapper objectMapper, Metadata metadata) {
|
||||||
ObjectNode objectNode = objectMapper.valueToTree(metadata);
|
ObjectNode objectNode = objectMapper.valueToTree(metadata);
|
||||||
|
@ -144,69 +171,112 @@ public class ServerContextCache extends ContextCache {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void setContexts(List<Context> contexts) {
|
protected void setContexts(Calendar calendar, List<Context> contexts) {
|
||||||
this.contexts = new ArrayList<>();
|
cleanCache(calendar);
|
||||||
this.contextsNoMeta = new ArrayList<>();
|
|
||||||
this.contextsMetaPrivacy = new ArrayList<>();
|
|
||||||
|
|
||||||
ObjectMapper objectMapper = ElementMapper.getObjectMapper();
|
ObjectMapper objectMapper = ElementMapper.getObjectMapper();
|
||||||
|
|
||||||
for(Context c : contexts) {
|
for(Context c : contexts) {
|
||||||
UUID uuid = c.getID();
|
UUID uuid = c.getID();
|
||||||
|
|
||||||
Context contextWithMeta = new ContextImpl(c.getName());
|
try {
|
||||||
contextWithMeta.setMetadata(c.getMetadata());
|
/*
|
||||||
contextWithMeta.setID(uuid);
|
* The user entitled to get all meta is also
|
||||||
this.contexts.add(contextWithMeta);
|
* entitled to get state as well as
|
||||||
this.uuidToContext.put(uuid, contextWithMeta);
|
* additional properties
|
||||||
|
*/
|
||||||
Context contextMetaPrivacy = new ContextImpl(c.getName());
|
Context contextWithMeta = new ContextImpl(c.getName());
|
||||||
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, c.getMetadata());
|
contextWithMeta.setMetadata(c.getMetadata());
|
||||||
contextMetaPrivacy.setMetadata(metadataWithPrivacy);
|
contextWithMeta.setID(uuid);
|
||||||
contextMetaPrivacy.setID(uuid);
|
contextWithMeta.setState(c.getState());
|
||||||
this.contextsMetaPrivacy.add(contextMetaPrivacy);
|
contextWithMeta.setAdditionalProperties(c.getAdditionalProperties());
|
||||||
this.uuidToContextMetaPrivacy.put(uuid, contextMetaPrivacy);
|
this.contexts.add(contextWithMeta);
|
||||||
|
this.uuidToContext.put(uuid, contextWithMeta);
|
||||||
Context contextNoMeta = new ContextImpl(c.getName());
|
|
||||||
contextNoMeta.setMetadata(null);
|
|
||||||
contextWithMeta.setID(uuid);
|
Context contextMetaPrivacy = new ContextImpl(c.getName());
|
||||||
this.contextsNoMeta.add(contextNoMeta);
|
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, c.getMetadata());
|
||||||
this.uuidToContextNoMeta.put(uuid, contextNoMeta);
|
contextMetaPrivacy.setMetadata(metadataWithPrivacy);
|
||||||
|
contextMetaPrivacy.setID(uuid);
|
||||||
|
/*
|
||||||
|
* state and additional properties are not added because
|
||||||
|
* the user which get this classes are non entitled to get this info
|
||||||
|
*
|
||||||
|
* contextMetaPrivacy.setState(c.getState());
|
||||||
|
* contextMetaPrivacy.setAdditionalProperties(c.getAdditionalProperties());
|
||||||
|
*/
|
||||||
|
this.contextsMetaPrivacy.add(contextMetaPrivacy);
|
||||||
|
this.uuidToContextMetaPrivacy.put(uuid, contextMetaPrivacy);
|
||||||
|
|
||||||
|
|
||||||
|
Context contextNoMeta = new ContextImpl(c.getName());
|
||||||
|
contextNoMeta.setMetadata(null);
|
||||||
|
contextNoMeta.setID(uuid);
|
||||||
|
/*
|
||||||
|
* state and additional properties are not added because
|
||||||
|
* the user which get this classes are non entitled to get this info
|
||||||
|
*
|
||||||
|
* contextNoMeta.setState(c.getState());
|
||||||
|
* contextNoMeta.setAdditionalProperties(c.getAdditionalProperties());
|
||||||
|
*/
|
||||||
|
this.contextsBasicInfo.add(contextNoMeta);
|
||||||
|
this.uuidToContextBasicInfo.put(uuid, contextNoMeta);
|
||||||
|
|
||||||
|
}catch (Exception e) {
|
||||||
|
throw new InternalServerErrorException("Error while creating context Cache", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<UUID, IsParentOf> parentOfWithMetaMap = new HashMap<>();
|
||||||
|
Map<UUID, IsParentOf> parentOfMetaWithPrivacyMap = new HashMap<>();
|
||||||
|
Map<UUID, IsParentOf> parentOfNoMetaMap = new HashMap<>();
|
||||||
|
|
||||||
for(Context c : contexts) {
|
for(Context c : contexts) {
|
||||||
UUID uuid = c.getID();
|
UUID uuid = c.getID();
|
||||||
|
|
||||||
Context contextMeta = this.uuidToContext.get(uuid);
|
Context contextMeta = this.uuidToContext.get(uuid);
|
||||||
Context contextMetaPrivacy = this.uuidToContextMetaPrivacy.get(uuid);
|
Context contextMetaPrivacy = this.uuidToContextMetaPrivacy.get(uuid);
|
||||||
Context contextNoMeta = this.uuidToContextNoMeta.get(uuid);
|
Context contextNoMeta = this.uuidToContextBasicInfo.get(uuid);
|
||||||
|
|
||||||
|
|
||||||
if(c.getParent()!=null) {
|
if(c.getParent()!=null) {
|
||||||
IsParentOf ipo = c.getParent();
|
IsParentOf ipo = c.getParent();
|
||||||
UUID parentUUID = ipo.getSource().getID();
|
UUID isParentOfParentUUID = ipo.getID();
|
||||||
|
UUID contextParentUUID = ipo.getSource().getID();
|
||||||
|
|
||||||
Context parentWithMeta = this.uuidToContext.get(parentUUID);
|
Context parentWithMeta = this.uuidToContext.get(contextParentUUID);
|
||||||
IsParentOf isParentOf = new IsParentOfImpl(parentWithMeta, contextMeta);
|
IsParentOf isParentOfWithMeta = parentOfWithMetaMap.get(isParentOfParentUUID);
|
||||||
isParentOf.setID(parentUUID);
|
if(isParentOfWithMeta==null) {
|
||||||
isParentOf.setMetadata(ipo.getMetadata());
|
isParentOfWithMeta = new IsParentOfImpl(parentWithMeta, contextMeta);
|
||||||
parentWithMeta.addChild(isParentOf);
|
isParentOfWithMeta.setID(isParentOfParentUUID);
|
||||||
contextMeta.setParent(isParentOf);
|
isParentOfWithMeta.setMetadata(ipo.getMetadata());
|
||||||
|
parentOfWithMetaMap.put(isParentOfParentUUID, isParentOfWithMeta);
|
||||||
|
parentWithMeta.addChild(isParentOfWithMeta);
|
||||||
|
}
|
||||||
|
contextMeta.setParent(isParentOfWithMeta);
|
||||||
|
|
||||||
Context parentWithMetaPrivacy = this.uuidToContextMetaPrivacy.get(parentUUID);
|
|
||||||
IsParentOf isParentOfMetaPrivacy = new IsParentOfImpl(parentWithMetaPrivacy, contextMetaPrivacy);
|
Context parentWithMetaPrivacy = this.uuidToContextMetaPrivacy.get(contextParentUUID);
|
||||||
isParentOfMetaPrivacy.setID(parentUUID);
|
IsParentOf isParentOfMetaPrivacy = parentOfMetaWithPrivacyMap.get(isParentOfParentUUID);
|
||||||
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, ipo.getMetadata());
|
if(isParentOfMetaPrivacy==null) {
|
||||||
isParentOfMetaPrivacy.setMetadata(metadataWithPrivacy);
|
isParentOfMetaPrivacy = new IsParentOfImpl(parentWithMetaPrivacy, contextMetaPrivacy);
|
||||||
parentWithMetaPrivacy.addChild(isParentOfMetaPrivacy);
|
isParentOfMetaPrivacy.setID(isParentOfParentUUID);
|
||||||
|
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, ipo.getMetadata());
|
||||||
|
isParentOfMetaPrivacy.setMetadata(metadataWithPrivacy);
|
||||||
|
parentOfMetaWithPrivacyMap.put(isParentOfParentUUID, isParentOfMetaPrivacy);
|
||||||
|
parentWithMetaPrivacy.addChild(isParentOfMetaPrivacy);
|
||||||
|
}
|
||||||
contextMetaPrivacy.setParent(isParentOfMetaPrivacy);
|
contextMetaPrivacy.setParent(isParentOfMetaPrivacy);
|
||||||
|
|
||||||
|
|
||||||
Context parentNoMeta = this.uuidToContextNoMeta.get(parentUUID);
|
Context parentNoMeta = this.uuidToContextBasicInfo.get(contextParentUUID);
|
||||||
IsParentOf isParentOfNoMeta = new IsParentOfImpl(parentNoMeta, contextNoMeta);
|
IsParentOf isParentOfNoMeta = parentOfNoMetaMap.get(isParentOfParentUUID);
|
||||||
isParentOfNoMeta.setMetadata(null);
|
if(isParentOfNoMeta==null) {
|
||||||
isParentOfNoMeta.setID(parentUUID);
|
isParentOfNoMeta = new IsParentOfImpl(parentNoMeta, contextNoMeta);
|
||||||
parentNoMeta.addChild(isParentOfNoMeta);
|
isParentOfNoMeta.setMetadata(null);
|
||||||
|
isParentOfNoMeta.setID(isParentOfParentUUID);
|
||||||
|
parentOfNoMetaMap.put(isParentOfParentUUID, isParentOfNoMeta);
|
||||||
|
parentNoMeta.addChild(isParentOfNoMeta);
|
||||||
|
}
|
||||||
contextNoMeta.setParent(isParentOfNoMeta);
|
contextNoMeta.setParent(isParentOfNoMeta);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -220,5 +290,12 @@ public class ServerContextCache extends ContextCache {
|
||||||
this.contextFullNameToUUID.put(fullName, uuid);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,11 +1,17 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts.entities;
|
package org.gcube.informationsystem.resourceregistry.contexts.entities;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import javax.ws.rs.BadRequestException;
|
||||||
|
import javax.ws.rs.ForbiddenException;
|
||||||
|
import javax.ws.rs.NotAuthorizedException;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
@ -14,6 +20,7 @@ import org.gcube.com.fasterxml.jackson.databind.node.NullNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
||||||
|
import org.gcube.informationsystem.contexts.reference.ContextState;
|
||||||
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
|
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
|
||||||
import org.gcube.informationsystem.model.reference.relations.Relation;
|
import org.gcube.informationsystem.model.reference.relations.Relation;
|
||||||
|
@ -25,14 +32,17 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.relations.IsParentOfManagement;
|
import org.gcube.informationsystem.resourceregistry.contexts.relations.IsParentOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator;
|
import org.gcube.informationsystem.resourceregistry.queries.operators.ComparisonOperator;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
|
import org.gcube.informationsystem.resourceregistry.queries.operators.LogicalOperator;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
@ -50,19 +60,34 @@ import com.orientechnologies.orient.core.sql.executor.OResultSet;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*
|
||||||
|
* TODO the result returned to the client should be get from ServerContextCache
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
public class ContextManagement extends EntityElementManagement<Context, EntityType> {
|
public class ContextManagement extends EntityElementManagement<Context, EntityType> {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
|
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
|
||||||
|
|
||||||
protected String name;
|
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() {
|
private void init() {
|
||||||
this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY);
|
this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY);
|
||||||
this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY);
|
this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY);
|
||||||
this.typeName = Context.NAME;
|
this.typeName = Context.NAME;
|
||||||
this.forceIncludeMeta = true;
|
this.forceIncludeMeta = true;
|
||||||
this.forceIncludeAllMeta = true;
|
this.forceIncludeAllMeta = true;
|
||||||
|
this.forceOffset = null;
|
||||||
|
this.forceLimit = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ContextManagement() {
|
public ContextManagement() {
|
||||||
|
@ -73,7 +98,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
||||||
this();
|
this();
|
||||||
this.oDatabaseDocument = oDatabaseDocument;
|
this.oDatabaseDocument = oDatabaseDocument;
|
||||||
getWorkingContext();
|
getWorkingEnvironment();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -95,11 +120,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
if (workingContext == null) {
|
if (workingEnvironment == null) {
|
||||||
workingContext = ContextSecurityContext.getInstance();
|
workingEnvironment = ContextEnvironment.getInstance();
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -127,13 +152,13 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
select.append(parentId);
|
select.append(parentId);
|
||||||
select.append(" MAXDEPTH 1) WHERE ");
|
select.append(" MAXDEPTH 1) WHERE ");
|
||||||
select.append(Context.NAME_PROPERTY);
|
select.append(Context.NAME_PROPERTY);
|
||||||
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
|
select.append(ComparisonOperator.EQ.getDbOperator());
|
||||||
select.append("\"");
|
select.append("\"");
|
||||||
select.append(getName());
|
select.append(getName());
|
||||||
select.append("\"");
|
select.append("\"");
|
||||||
select.append(QueryLogicalOperator.AND.getLogicalOperator());
|
select.append(LogicalOperator.AND.getDbOperator());
|
||||||
select.append(IdentifiableElement.ID_PROPERTY);
|
select.append(IdentifiableElement.ID_PROPERTY);
|
||||||
select.append(QueryConditionalOperator.NE.getConditionalOperator());
|
select.append(ComparisonOperator.NE.getDbOperator());
|
||||||
select.append("\"");
|
select.append("\"");
|
||||||
select.append(parentContext.uuid);
|
select.append(parentContext.uuid);
|
||||||
select.append("\"");
|
select.append("\"");
|
||||||
|
@ -149,11 +174,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
select.append(Context.NAME);
|
select.append(Context.NAME);
|
||||||
select.append(" WHERE ");
|
select.append(" WHERE ");
|
||||||
select.append(Context.NAME_PROPERTY);
|
select.append(Context.NAME_PROPERTY);
|
||||||
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
|
select.append(ComparisonOperator.EQ.getDbOperator());
|
||||||
select.append("\"");
|
select.append("\"");
|
||||||
select.append(getName());
|
select.append(getName());
|
||||||
select.append("\"");
|
select.append("\"");
|
||||||
select.append(QueryLogicalOperator.AND.getLogicalOperator());
|
select.append(LogicalOperator.AND.getDbOperator());
|
||||||
select.append("in(\"");
|
select.append("in(\"");
|
||||||
select.append(IsParentOf.NAME);
|
select.append(IsParentOf.NAME);
|
||||||
select.append("\").size() = 0");
|
select.append("\").size() = 0");
|
||||||
|
@ -174,11 +199,18 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private JsonNode filterFieldsByRole(JsonNode context) {
|
||||||
|
// TODO return extra info only to authorized users
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected JsonNode createCompleteJsonNode() throws ResourceRegistryException {
|
protected JsonNode createCompleteJsonNode() throws ResourceRegistryException {
|
||||||
|
|
||||||
JsonNode context = serializeSelfAsJsonNode();
|
JsonNode context = serializeSelfAsJsonNode();
|
||||||
|
|
||||||
|
context = filterFieldsByRole(context);
|
||||||
|
|
||||||
int count = 0;
|
int count = 0;
|
||||||
Iterable<OEdge> parents = getElement().getEdges(ODirection.IN);
|
Iterable<OEdge> parents = getElement().getEdges(ODirection.IN);
|
||||||
for (OEdge edge : parents) {
|
for (OEdge edge : parents) {
|
||||||
|
@ -220,29 +252,63 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The Context-Manager is allowed to delete a context
|
||||||
|
* only if he is the Context-Manager of the parent context
|
||||||
|
* (so the request must arrive from the parent context).
|
||||||
|
*/
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
|
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
|
||||||
SecurityContext securityContext = null;
|
InstanceEnvironment newInstanceEnvironment = null;
|
||||||
SecurityContext parentSecurityContext = null;
|
InstanceEnvironment parentInstanceEnvironment = null;
|
||||||
|
|
||||||
|
if (uuid == null) {
|
||||||
|
uuid = UUIDManager.getInstance().generateValidUUID();
|
||||||
|
}
|
||||||
|
newInstanceEnvironment = new InstanceEnvironment(uuid);
|
||||||
|
boolean vertexCreated = false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
|
||||||
|
|
||||||
if (isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
|
if (isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
|
||||||
|
|
||||||
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
|
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
|
||||||
ContextManagement parentContextManagement = new ContextManagement(oDatabaseDocument);
|
ContextManagement parentContextManagement = new ContextManagement(oDatabaseDocument);
|
||||||
parentContextManagement.setJsonNode(parentJsonNode);
|
parentContextManagement.setJsonNode(parentJsonNode);
|
||||||
UUID parentUUID = parentContextManagement.uuid;
|
UUID parentUUID = parentContextManagement.getUUID();
|
||||||
parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID);
|
parentInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(parentUUID);
|
||||||
|
|
||||||
checkContext(parentContextManagement);
|
InstanceEnvironment requestEnvironment = null;
|
||||||
if (uuid == null) {
|
try {
|
||||||
uuid = UUIDManager.getInstance().generateValidUUID();
|
requestEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
|
}catch (Exception e) {
|
||||||
|
/*
|
||||||
|
* The request arrives from a non existing context.
|
||||||
|
* This is possible when we are trying to create/delete
|
||||||
|
* the root context or another root for testing/migration purpose
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(requestEnvironment!=null && requestEnvironment.getUUID().compareTo(parentContextManagement.getUUID())==0) {
|
||||||
|
Set<String> allowedRoles = requestEnvironment.getAllowedRoles();
|
||||||
|
if(!parentInstanceEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new NotAuthorizedException("Only user with one of the following roles " + allowedRoles + " can create a child Context.");
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
|
||||||
|
if(!newInstanceEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new NotAuthorizedException("Only user with one of the following roles " + allowedRoles + " can create a child Context requesting the operation from a Context which is not the parent.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkContext(parentContextManagement);
|
||||||
|
|
||||||
|
logFullPath();
|
||||||
createVertex();
|
createVertex();
|
||||||
|
vertexCreated = true;
|
||||||
|
|
||||||
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
|
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
|
||||||
isParentOfManagement.setJsonNode(isParentOfJsonNode);
|
isParentOfManagement.setJsonNode(isParentOfJsonNode);
|
||||||
isParentOfManagement.setSourceEntityManagement(parentContextManagement);
|
isParentOfManagement.setSourceEntityManagement(parentContextManagement);
|
||||||
|
@ -251,35 +317,73 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
isParentOfManagement.internalCreate();
|
isParentOfManagement.internalCreate();
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
// We are creating the rootnewInstanceEnvironment = new InstanceEnvironment(uuid);
|
||||||
|
Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
|
||||||
|
if(!newInstanceEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new NotAuthorizedException("Only user with one of the following roles " + allowedRoles + " can create a root Context.");
|
||||||
|
}
|
||||||
checkContext(null);
|
checkContext(null);
|
||||||
|
logFullPath();
|
||||||
createVertex();
|
createVertex();
|
||||||
|
vertexCreated = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
securityContext = new SecurityContext(uuid);
|
this.element.setProperty(Context.STATE, ContextState.CREATED.getState());
|
||||||
securityContext.setParentSecurityContext(parentSecurityContext);
|
|
||||||
securityContext.create(oDatabaseDocument);
|
newInstanceEnvironment.setParentEnvironment(parentInstanceEnvironment);
|
||||||
|
newInstanceEnvironment.create(oDatabaseDocument);
|
||||||
|
|
||||||
ContextUtility.getInstance().addSecurityContext(securityContext);
|
ContextUtility.getInstance().addInstanceEnvironment(newInstanceEnvironment);
|
||||||
|
|
||||||
return getElement();
|
return getElement();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
oDatabaseDocument.rollback();
|
oDatabaseDocument.rollback();
|
||||||
if (securityContext != null) {
|
if (vertexCreated) {
|
||||||
securityContext.delete(oDatabaseDocument);
|
newInstanceEnvironment.delete(oDatabaseDocument);
|
||||||
if (parentSecurityContext != null && securityContext != null) {
|
if (parentInstanceEnvironment != null && newInstanceEnvironment != null) {
|
||||||
parentSecurityContext.getChildren().remove(securityContext);
|
parentInstanceEnvironment.getChildren().remove(newInstanceEnvironment);
|
||||||
}
|
}
|
||||||
ServerContextCache.getInstance().cleanCache();
|
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
|
} finally {
|
||||||
|
ServerContextCache.getInstance().cleanCache();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO
|
||||||
|
* The full path of the context is added for every non safe action
|
||||||
|
* - At creation time
|
||||||
|
* - At rename time (see #25139)
|
||||||
|
* - At parent change time (see #26544)
|
||||||
|
*
|
||||||
|
* In this way we are sure to track context fullpath changes.
|
||||||
|
* Furthermore when a context is deleted is moved to the cemetery
|
||||||
|
* i.e. ShadowContextEnvironment (see #19428)
|
||||||
|
* we do not have to do nothing with the fullpath just
|
||||||
|
* move the vertex representing the Context in the cemetery
|
||||||
|
*/
|
||||||
|
protected void logFullPath() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void checkStateChange(ContextState newContextstate) {
|
||||||
|
if(newContextstate == ContextState.DELETED || newContextstate == ContextState.CREATED) {
|
||||||
|
throw new BadRequestException("A " + Context.NAME + " cannot be set to " + newContextstate.getState());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
|
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
|
||||||
|
|
||||||
|
Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
|
||||||
|
if(!workingEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new ForbiddenException("You are not allowed to update a " + Context.NAME +". Allowed roles are " + allowedRoles);
|
||||||
|
}
|
||||||
|
|
||||||
boolean parentChanged = false;
|
boolean parentChanged = false;
|
||||||
boolean nameChanged = false;
|
boolean nameChanged = false;
|
||||||
|
boolean stateChanged = false;
|
||||||
|
|
||||||
OVertex parent = null;
|
OVertex parent = null;
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
|
@ -331,21 +435,40 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String oldName = getElement().getProperty(Context.NAME_PROPERTY);
|
String oldName = element.getProperty(Context.NAME_PROPERTY);
|
||||||
String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
|
String newName = jsonNode.get(Context.NAME_PROPERTY).asText();
|
||||||
if (oldName.compareTo(newName) != 0) {
|
if (oldName.compareTo(newName) != 0) {
|
||||||
nameChanged = true;
|
|
||||||
name = newName;
|
name = newName;
|
||||||
|
nameChanged = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String oldStateString = element.getProperty(Context.STATE);
|
||||||
|
ContextState state = ContextState.fromString(oldStateString);
|
||||||
|
JsonNode stateNode = jsonNode.get(Context.STATE);
|
||||||
|
String newStateString = stateNode.asText();
|
||||||
|
if(newStateString.compareTo(oldStateString)!=0) {
|
||||||
|
state = ContextState.fromString(newStateString);
|
||||||
|
stateChanged = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(stateChanged) {
|
||||||
|
checkStateChange(state);
|
||||||
|
}
|
||||||
|
|
||||||
if (parentChanged || nameChanged) {
|
if (parentChanged || nameChanged) {
|
||||||
checkContext(newParentContextManagement);
|
checkContext(newParentContextManagement);
|
||||||
|
// TODO uncomment if we want temporary suspend the Context
|
||||||
|
// state = ContextState.SUSPENDED;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parentChanged) {
|
if (parentChanged) {
|
||||||
move(newParentContextManagement, false);
|
move(newParentContextManagement, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (parentChanged || nameChanged) {
|
||||||
|
logFullPath();
|
||||||
|
}
|
||||||
|
|
||||||
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
|
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
|
||||||
|
|
||||||
ServerContextCache.getInstance().cleanCache();
|
ServerContextCache.getInstance().cleanCache();
|
||||||
|
@ -359,21 +482,21 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
checkContext(newParentContextManagement);
|
checkContext(newParentContextManagement);
|
||||||
}
|
}
|
||||||
|
|
||||||
SecurityContext newParentSecurityContext = null;
|
InstanceEnvironment newParentInstanceEnvironment = null;
|
||||||
|
|
||||||
// Removing the old parent relationship if any
|
// Removing the old parent relationship if any
|
||||||
Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME);
|
Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME);
|
||||||
if (edges != null && edges.iterator().hasNext()) {
|
if (edges != null && edges.iterator().hasNext()) {
|
||||||
Iterator<OEdge> edgeIterator = edges.iterator();
|
Iterator<OEdge> edgeIterator = edges.iterator();
|
||||||
OEdge edge = edgeIterator.next();
|
OEdge edge = edgeIterator.next();
|
||||||
IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
|
|
||||||
isParentOfManagement.setElement(edge);
|
|
||||||
isParentOfManagement.internalDelete();
|
|
||||||
|
|
||||||
if (edgeIterator.hasNext()) {
|
if (edgeIterator.hasNext()) {
|
||||||
throw new ContextException(
|
throw new ContextException(
|
||||||
"Seems that the Context has more than one Parent. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
"Seems that the Context has more than one Parent. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
|
||||||
|
isParentOfManagement.setElement(edge);
|
||||||
|
isParentOfManagement.internalDelete();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newParentContextManagement != null) {
|
if (newParentContextManagement != null) {
|
||||||
|
@ -383,27 +506,67 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
isParentOfManagement.setSourceEntityManagement(newParentContextManagement);
|
isParentOfManagement.setSourceEntityManagement(newParentContextManagement);
|
||||||
isParentOfManagement.setTargetEntityManagement(this);
|
isParentOfManagement.setTargetEntityManagement(this);
|
||||||
isParentOfManagement.internalCreate();
|
isParentOfManagement.internalCreate();
|
||||||
newParentSecurityContext = ContextUtility.getInstance()
|
newParentInstanceEnvironment = ContextUtility.getInstance()
|
||||||
.getSecurityContextByUUID(newParentContextManagement.uuid);
|
.getEnvironmentByUUID(newParentContextManagement.uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
|
InstanceEnvironment thisInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
|
||||||
thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, oDatabaseDocument);
|
thisInstanceEnvironment.changeParentEnvironment(newParentInstanceEnvironment, oDatabaseDocument);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
|
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
|
||||||
|
|
||||||
|
ContextUtility contextUtility = ContextUtility.getInstance();
|
||||||
|
InstanceEnvironment instanceEnvironment = contextUtility.getEnvironmentByUUID(uuid);
|
||||||
|
InstanceEnvironment parentInstanceEnvironment = (InstanceEnvironment) instanceEnvironment.getParentEnvironment();
|
||||||
|
|
||||||
|
if(parentInstanceEnvironment==null) {
|
||||||
|
// We are trying to delete the root
|
||||||
|
Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
|
||||||
|
if(!instanceEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new ForbiddenException("Only user with one of the following roles " + allowedRoles + " can delete the root Context.");
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
InstanceEnvironment requestInstanceEnvironment = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
requestInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
|
}catch (Exception e) {
|
||||||
|
/*
|
||||||
|
* The request arrives from a non existing context.
|
||||||
|
* This is possible when we are trying to create/delete
|
||||||
|
* the root context or another root for testing/migration purpose
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
if(requestInstanceEnvironment!=null && requestInstanceEnvironment.getUUID().compareTo(parentInstanceEnvironment.getUUID())==0) {
|
||||||
|
Set<String> allowedRoles = requestInstanceEnvironment.getAllowedRoles();
|
||||||
|
if(!parentInstanceEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new NotAuthorizedException("Only user with one of the following roles " + allowedRoles + " can delete a child Context.");
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
|
||||||
|
if(!instanceEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new NotAuthorizedException("Only user with one of the following roles " + allowedRoles + " can delete a Context requesting the operation from a Context which is not the parent.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Iterable<OEdge> iterable = getElement().getEdges(ODirection.OUT);
|
Iterable<OEdge> iterable = getElement().getEdges(ODirection.OUT);
|
||||||
Iterator<OEdge> iterator = iterable.iterator();
|
Iterator<OEdge> iterator = iterable.iterator();
|
||||||
while (iterator.hasNext()) {
|
while (iterator.hasNext()) {
|
||||||
throw new ContextException("Cannot remove a " + Context.NAME + " having children");
|
throw new ContextException("Cannot remove a " + Context.NAME + " having children");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* TODO Move the vertex to the ShadowContextEnvironment (i.e the cemetery)
|
||||||
|
* We do NOT have to create the parent in ShadowContextEnvironment
|
||||||
|
* Infact, the context itself it enough to identify the full path
|
||||||
|
* of the context when deleted because the full path is logged.
|
||||||
|
*/
|
||||||
element.delete();
|
element.delete();
|
||||||
|
|
||||||
ContextUtility contextUtility = ContextUtility.getInstance();
|
instanceEnvironment.delete(oDatabaseDocument);
|
||||||
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
|
|
||||||
securityContext.delete(oDatabaseDocument);
|
|
||||||
|
|
||||||
ServerContextCache.getInstance().cleanCache();
|
ServerContextCache.getInstance().cleanCache();
|
||||||
}
|
}
|
||||||
|
@ -412,8 +575,35 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
ArrayNode arrayNode = objectMapper.createArrayNode();
|
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);
|
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
|
||||||
for (ODocument vertex : iterable) {
|
for (ODocument vertex : iterable) {
|
||||||
|
if(++position < offset) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setForceIncludeMeta(forceIncludeMeta);
|
contextManagement.setForceIncludeMeta(forceIncludeMeta);
|
||||||
contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta);
|
contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta);
|
||||||
|
@ -421,6 +611,9 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
try {
|
try {
|
||||||
JsonNode jsonObject = contextManagement.serializeAsJsonNode();
|
JsonNode jsonObject = contextManagement.serializeAsJsonNode();
|
||||||
arrayNode.add(jsonObject);
|
arrayNode.add(jsonObject);
|
||||||
|
if(limit > 0 && ++count >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
} catch (ResourceRegistryException e) {
|
} catch (ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
||||||
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
|
@ -433,7 +626,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String allFromServer(boolean polymorphic) throws ResourceRegistryException {
|
public String allFromDatabase(boolean polymorphic) throws ResourceRegistryException {
|
||||||
return super.all(polymorphic);
|
return super.all(polymorphic);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -442,9 +635,45 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
try {
|
try {
|
||||||
ServerContextCache contextCache = ServerContextCache.getInstance();
|
ServerContextCache contextCache = ServerContextCache.getInstance();
|
||||||
List<Context> contexts = contextCache.getContexts();
|
List<Context> contexts = contextCache.getContexts();
|
||||||
return ElementMapper.marshal(contexts);
|
|
||||||
|
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
||||||
|
Integer limit = requestInfo.getLimit();
|
||||||
|
if(forceLimit!=null) {
|
||||||
|
limit = forceLimit;
|
||||||
|
}else if(limit == null) {
|
||||||
|
limit = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer offset = requestInfo.getOffset();
|
||||||
|
if(forceOffset!=null) {
|
||||||
|
offset = forceOffset;
|
||||||
|
}else if(offset == null) {
|
||||||
|
offset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int position = -1;
|
||||||
|
int count = 0;
|
||||||
|
|
||||||
|
if(offset==0 && limit<=0) {
|
||||||
|
return ElementMapper.marshal(contexts);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Context> requestedContexts = new ArrayList<>();
|
||||||
|
for (Context c : contexts) {
|
||||||
|
if(++position < offset) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
requestedContexts.add(c);
|
||||||
|
|
||||||
|
if(limit > 0 && ++count >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ElementMapper.marshal(requestedContexts);
|
||||||
} catch (JsonProcessingException | ResourceRegistryException e) {
|
} catch (JsonProcessingException | ResourceRegistryException e) {
|
||||||
return allFromServer(polymorphic);
|
return allFromDatabase(polymorphic);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -467,4 +696,73 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
|
||||||
public void sanityCheck() throws SchemaViolationException, ResourceRegistryException {
|
public void sanityCheck() throws SchemaViolationException, ResourceRegistryException {
|
||||||
// Nothing to do
|
// Nothing to do
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// public String changeState() throws ResourceRegistryException {
|
||||||
|
// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
//
|
||||||
|
// try {
|
||||||
|
// Environment environment = getWorkingEnvironment();
|
||||||
|
// Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
|
||||||
|
// if(!workingEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
// throw new ForbiddenException("You are not allowed to change the state of a " + Context.NAME +". Allowed roles are " + allowedRoles);
|
||||||
|
// }
|
||||||
|
// oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
// oDatabaseDocument.begin();
|
||||||
|
// getElement();
|
||||||
|
// setAsEntryPoint();
|
||||||
|
// setOperation(Operation.UPDATE);
|
||||||
|
//
|
||||||
|
// String stateString = jsonNode.get(Context.STATE).asText();
|
||||||
|
// ContextState state = ContextState.fromString(stateString);
|
||||||
|
// if(state == ContextState.DELETED || state == ContextState.CREATED) {
|
||||||
|
// throw new BadRequestException("A Context cannot be set to " + state.getState());
|
||||||
|
// }
|
||||||
|
// element.setProperty(Context.STATE, state.getState());
|
||||||
|
// element.save();
|
||||||
|
//
|
||||||
|
// oDatabaseDocument.commit();
|
||||||
|
//
|
||||||
|
// // TODO Notify to subscriptionNotification
|
||||||
|
//
|
||||||
|
// ServerContextCache cache = ServerContextCache.getInstance();
|
||||||
|
// cache.cleanCache();
|
||||||
|
//
|
||||||
|
// return readAsString();
|
||||||
|
//
|
||||||
|
// } catch(ResourceRegistryException e) {
|
||||||
|
// logger.error("Unable to change the state to {} with UUID {}", Context.NAME, uuid, e);
|
||||||
|
// if(oDatabaseDocument != null) {
|
||||||
|
// oDatabaseDocument.rollback();
|
||||||
|
// }
|
||||||
|
// throw e;
|
||||||
|
// } catch(BadRequestException e) {
|
||||||
|
// logger.error("Unable to change the state to {} with UUID {}. Reason \"{}\"", Context.NAME, uuid, e.getMessage());
|
||||||
|
// if(oDatabaseDocument != null) {
|
||||||
|
// oDatabaseDocument.rollback();
|
||||||
|
// }
|
||||||
|
// throw e;
|
||||||
|
// } catch(WebApplicationException e) {
|
||||||
|
// logger.error("Unable to change the state to {} with UUID {}", Context.NAME, uuid, e);
|
||||||
|
// if(oDatabaseDocument != null) {
|
||||||
|
// oDatabaseDocument.rollback();
|
||||||
|
// }
|
||||||
|
// throw e;
|
||||||
|
// } catch(Exception e) {
|
||||||
|
// logger.error("Unable to change the state to {} with UUID {}", Context.NAME, uuid, e);
|
||||||
|
// if(oDatabaseDocument != null) {
|
||||||
|
// oDatabaseDocument.rollback();
|
||||||
|
// }
|
||||||
|
// throw new ResourceRegistryException(e);
|
||||||
|
// } finally {
|
||||||
|
// if(oDatabaseDocument != null) {
|
||||||
|
// oDatabaseDocument.close();
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if(current!=null) {
|
||||||
|
// current.activateOnCurrentThread();
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,10 +14,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isparentof.IsParentOfAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isparentof.IsParentOfAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isparentof.IsParentOfNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isparentof.IsParentOfNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.relations.RelationElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
|
||||||
|
@ -37,7 +37,7 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
|
||||||
public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
||||||
this();
|
this();
|
||||||
this.oDatabaseDocument = oDatabaseDocument;
|
this.oDatabaseDocument = oDatabaseDocument;
|
||||||
getWorkingContext();
|
getWorkingEnvironment();
|
||||||
this.includeSource = false;
|
this.includeSource = false;
|
||||||
this.includeTarget = true;
|
this.includeTarget = true;
|
||||||
this.forceIncludeMeta = true;
|
this.forceIncludeMeta = true;
|
||||||
|
@ -50,11 +50,11 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
if (workingContext == null) {
|
if (workingEnvironment == null) {
|
||||||
workingContext = ContextSecurityContext.getInstance();
|
workingEnvironment = ContextEnvironment.getInstance();
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -1,672 +0,0 @@
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts.security;
|
|
||||||
|
|
||||||
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 java.util.concurrent.Callable;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.Future;
|
|
||||||
|
|
||||||
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
|
||||||
import org.gcube.informationsystem.utils.UUIDManager;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.orientechnologies.orient.core.db.ODatabasePool;
|
|
||||||
import com.orientechnologies.orient.core.db.ODatabaseSession;
|
|
||||||
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
|
|
||||||
import com.orientechnologies.orient.core.db.record.OIdentifiable;
|
|
||||||
import com.orientechnologies.orient.core.db.record.ORecordLazySet;
|
|
||||||
import com.orientechnologies.orient.core.id.ORID;
|
|
||||||
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
|
|
||||||
import com.orientechnologies.orient.core.metadata.security.ORole;
|
|
||||||
import com.orientechnologies.orient.core.metadata.security.OSecurity;
|
|
||||||
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
|
|
||||||
import com.orientechnologies.orient.core.metadata.security.OUser;
|
|
||||||
import com.orientechnologies.orient.core.record.OElement;
|
|
||||||
import com.orientechnologies.orient.core.record.ORecord;
|
|
||||||
import com.orientechnologies.orient.core.record.impl.ODocument;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
|
||||||
*/
|
|
||||||
public class SecurityContext {
|
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
|
|
||||||
|
|
||||||
protected static final String DEFAULT_WRITER_ROLE = "writer";
|
|
||||||
protected static final String DEFAULT_READER_ROLE = "reader";
|
|
||||||
|
|
||||||
/*
|
|
||||||
* H stand for Hierarchical
|
|
||||||
*/
|
|
||||||
public static final String H = "H";
|
|
||||||
|
|
||||||
protected final boolean hierarchical;
|
|
||||||
|
|
||||||
public enum SecurityType {
|
|
||||||
ROLE("Role"), USER("User");
|
|
||||||
|
|
||||||
private final String name;
|
|
||||||
|
|
||||||
private SecurityType(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String toString() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum PermissionMode {
|
|
||||||
READER("Reader"), WRITER("Writer");
|
|
||||||
|
|
||||||
private final String name;
|
|
||||||
|
|
||||||
private PermissionMode(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String toString() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected final UUID context;
|
|
||||||
|
|
||||||
protected final Map<Boolean,Map<PermissionMode,ODatabasePool>> poolMap;
|
|
||||||
|
|
||||||
protected SecurityContext parentSecurityContext;
|
|
||||||
|
|
||||||
protected Set<SecurityContext> children;
|
|
||||||
|
|
||||||
protected boolean isHierarchicalMode() {
|
|
||||||
return hierarchical && RequestUtility.getRequestInfo().get().isHierarchicalMode();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setParentSecurityContext(SecurityContext parentSecurityContext) {
|
|
||||||
if(this.parentSecurityContext!=null) {
|
|
||||||
this.parentSecurityContext.getChildren().remove(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.parentSecurityContext = parentSecurityContext;
|
|
||||||
if(parentSecurityContext!=null) {
|
|
||||||
this.parentSecurityContext.addChild(this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public SecurityContext getParentSecurityContext() {
|
|
||||||
return parentSecurityContext;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addChild(SecurityContext child) {
|
|
||||||
this.children.add(child);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<SecurityContext> getChildren(){
|
|
||||||
return this.children;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected ODatabaseDocument getAdminDatabaseDocument() throws ResourceRegistryException {
|
|
||||||
return ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return a set containing all children and recursively
|
|
||||||
* all children.
|
|
||||||
*/
|
|
||||||
private Set<SecurityContext> getAllChildren(){
|
|
||||||
Set<SecurityContext> allChildren = new HashSet<>();
|
|
||||||
allChildren.add(this);
|
|
||||||
for(SecurityContext securityContext : getChildren()) {
|
|
||||||
allChildren.addAll(securityContext.getAllChildren());
|
|
||||||
}
|
|
||||||
return allChildren;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
private Set<SecurityContext> getAllParents(){
|
|
||||||
Set<SecurityContext> allParents = new HashSet<>();
|
|
||||||
SecurityContext parent = getParentSecurityContext();
|
|
||||||
while(parent!=null) {
|
|
||||||
allParents.add(parent);
|
|
||||||
parent = parent.getParentSecurityContext();
|
|
||||||
}
|
|
||||||
return allParents;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use to change the parent not to set the first time
|
|
||||||
*
|
|
||||||
* @param newParentSecurityContext
|
|
||||||
* @param orientGraph
|
|
||||||
* @throws ResourceRegistryException
|
|
||||||
*/
|
|
||||||
public void changeParentSecurityContext(SecurityContext newParentSecurityContext, ODatabaseDocument orientGraph) throws ResourceRegistryException {
|
|
||||||
if(!hierarchical) {
|
|
||||||
StringBuilder errorMessage = new StringBuilder();
|
|
||||||
errorMessage.append("Cannot change parent ");
|
|
||||||
errorMessage.append(SecurityContext.class.getSimpleName());
|
|
||||||
errorMessage.append(" to non hierarchic ");
|
|
||||||
errorMessage.append(SecurityContext.class.getSimpleName());
|
|
||||||
errorMessage.append(". ");
|
|
||||||
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
final String error = errorMessage.toString();
|
|
||||||
logger.error(error);
|
|
||||||
throw new RuntimeException(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
OSecurity oSecurity = getOSecurity(orientGraph);
|
|
||||||
|
|
||||||
Set<SecurityContext> allChildren = getAllChildren();
|
|
||||||
|
|
||||||
Set<SecurityContext> oldParents = getAllParents();
|
|
||||||
|
|
||||||
Set<SecurityContext> newParents = new HashSet<>();
|
|
||||||
if(newParentSecurityContext!=null) {
|
|
||||||
newParents = newParentSecurityContext.getAllParents();
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* From old parents I remove the new parents so that oldParents
|
|
||||||
* contains only the parents where I have to remove all
|
|
||||||
* HReaderRole-UUID e HWriterRole-UUID of allChildren by using
|
|
||||||
* removeHierarchicRoleFromParent() function
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
oldParents.removeAll(newParents);
|
|
||||||
removeChildrenHRolesFromParents(oSecurity, oldParents, allChildren);
|
|
||||||
|
|
||||||
setParentSecurityContext(newParentSecurityContext);
|
|
||||||
|
|
||||||
if(newParentSecurityContext!=null){
|
|
||||||
for(PermissionMode permissionMode : PermissionMode.values()) {
|
|
||||||
List<ORole> roles = new ArrayList<>();
|
|
||||||
for(SecurityContext child : allChildren) {
|
|
||||||
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
|
|
||||||
ORole role = oSecurity.getRole(roleName);
|
|
||||||
roles.add(role);
|
|
||||||
}
|
|
||||||
newParentSecurityContext.addHierarchicalRoleToParent(oSecurity, permissionMode, roles.toArray(new ORole[allChildren.size()]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
protected SecurityContext(UUID context, boolean hierarchical) throws ResourceRegistryException {
|
|
||||||
this.context = context;
|
|
||||||
this.poolMap = new HashMap<>();
|
|
||||||
this.hierarchical = hierarchical;
|
|
||||||
this.children = new HashSet<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public SecurityContext(UUID context) throws ResourceRegistryException {
|
|
||||||
this(context, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized ODatabasePool getPool(PermissionMode permissionMode, boolean recreate) {
|
|
||||||
ODatabasePool pool = null;
|
|
||||||
|
|
||||||
Boolean h = isHierarchicalMode();
|
|
||||||
|
|
||||||
Map<PermissionMode,ODatabasePool> pools = poolMap.get(h);
|
|
||||||
if(pools == null) {
|
|
||||||
pools = new HashMap<>();
|
|
||||||
poolMap.put(h, pools);
|
|
||||||
} else {
|
|
||||||
if(recreate) {
|
|
||||||
pool = pools.get(permissionMode);
|
|
||||||
if(pool!=null) {
|
|
||||||
pool.close();
|
|
||||||
pools.remove(permissionMode);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pool = pools.get(permissionMode);
|
|
||||||
|
|
||||||
if(pool == null) {
|
|
||||||
|
|
||||||
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h);
|
|
||||||
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
|
|
||||||
|
|
||||||
pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password);
|
|
||||||
|
|
||||||
pools.put(permissionMode, pool);
|
|
||||||
}
|
|
||||||
|
|
||||||
return pool;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UUID getUUID() {
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String getRoleOrUserName(PermissionMode permissionMode, SecurityType securityType) {
|
|
||||||
return getRoleOrUserName(permissionMode, securityType, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String getRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
|
|
||||||
boolean hierarchic) {
|
|
||||||
StringBuilder stringBuilder = new StringBuilder();
|
|
||||||
if(hierarchic) {
|
|
||||||
stringBuilder.append(H);
|
|
||||||
}
|
|
||||||
stringBuilder.append(permissionMode);
|
|
||||||
stringBuilder.append(securityType);
|
|
||||||
return stringBuilder.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public String getSecurityRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
|
|
||||||
boolean hierarchic) {
|
|
||||||
StringBuilder stringBuilder = new StringBuilder();
|
|
||||||
stringBuilder.append(getRoleOrUserName(permissionMode, securityType, hierarchic));
|
|
||||||
stringBuilder.append("_");
|
|
||||||
stringBuilder.append(context.toString());
|
|
||||||
return stringBuilder.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private OSecurity getOSecurity(ODatabaseDocument oDatabaseDocument) {
|
|
||||||
return oDatabaseDocument.getMetadata().getSecurity();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Set<String> getContexts(OElement element) {
|
|
||||||
Set<String> contexts = new HashSet<>();
|
|
||||||
ORecordLazySet oRecordLazySet = element.getProperty(OSecurity.ALLOW_ALL_FIELD);
|
|
||||||
for (OIdentifiable oIdentifiable : oRecordLazySet) {
|
|
||||||
ODocument oDocument = (ODocument) oIdentifiable;
|
|
||||||
String name = oDocument.getProperty("name");
|
|
||||||
if (name.startsWith(getRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE))
|
|
||||||
|| name.startsWith(getRoleOrUserName(PermissionMode.READER, SecurityType.ROLE))) {
|
|
||||||
String[] list = name.split("_");
|
|
||||||
if (list.length == 2) {
|
|
||||||
String contextUUID = list[1];
|
|
||||||
if (!UUIDManager.getInstance().isReservedUUID(contextUUID)) {
|
|
||||||
contexts.add(contextUUID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return contexts;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public void addElement(OElement element) throws ResourceRegistryException {
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
|
||||||
ODatabaseDocument adminDatabaseDocument = null;
|
|
||||||
try {
|
|
||||||
adminDatabaseDocument = getAdminDatabaseDocument();
|
|
||||||
addElement(element, adminDatabaseDocument);
|
|
||||||
}finally {
|
|
||||||
if(adminDatabaseDocument!=null) {
|
|
||||||
adminDatabaseDocument.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(current!=null) {
|
|
||||||
current.activateOnCurrentThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) {
|
|
||||||
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic);
|
|
||||||
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
|
|
||||||
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic);
|
|
||||||
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isElementInContext(final OElement element) throws ResourceRegistryException {
|
|
||||||
ORID orid = element.getIdentity();
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
|
||||||
ODatabaseDocument contextODatabaseDocument = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
contextODatabaseDocument = getDatabaseDocument(PermissionMode.READER);
|
|
||||||
|
|
||||||
ORecord oRecord = contextODatabaseDocument.getRecord(orid);
|
|
||||||
if(oRecord==null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
|
|
||||||
} finally {
|
|
||||||
if(contextODatabaseDocument!=null) {
|
|
||||||
contextODatabaseDocument.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(current!=null) {
|
|
||||||
current.activateOnCurrentThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addElement(OElement element, ODatabaseDocument oDatabaseDocument) {
|
|
||||||
ODocument oDocument = element.getRecord();
|
|
||||||
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
|
||||||
allow(oSecurity, oDocument, false);
|
|
||||||
if(hierarchical) {
|
|
||||||
allow(oSecurity, oDocument, true);
|
|
||||||
}
|
|
||||||
oDocument.save();
|
|
||||||
element.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void removeElement(OElement element) throws ResourceRegistryException {
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
|
||||||
ODatabaseDocument adminDatabaseDocument = null;
|
|
||||||
try {
|
|
||||||
adminDatabaseDocument = getAdminDatabaseDocument();
|
|
||||||
removeElement(element, adminDatabaseDocument);
|
|
||||||
}finally {
|
|
||||||
if(adminDatabaseDocument!=null) {
|
|
||||||
adminDatabaseDocument.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(current!=null) {
|
|
||||||
current.activateOnCurrentThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchical) {
|
|
||||||
// The element could be created in such a context so the writerUser for the
|
|
||||||
// context is allowed by default because it was the creator
|
|
||||||
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
|
|
||||||
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_ALL, writerUserName);
|
|
||||||
String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
|
|
||||||
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName);
|
|
||||||
|
|
||||||
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchical);
|
|
||||||
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
|
|
||||||
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchical);
|
|
||||||
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void removeElement(OElement element, ODatabaseDocument oDatabaseDocument) {
|
|
||||||
ODocument oDocument = element.getRecord();
|
|
||||||
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
|
||||||
deny(oSecurity, oDocument, false);
|
|
||||||
if(hierarchical) {
|
|
||||||
deny(oSecurity, oDocument, true);
|
|
||||||
}
|
|
||||||
oDocument.save();
|
|
||||||
element.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
RequestUtility.getRequestInfo().get().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);
|
|
||||||
try {
|
|
||||||
return result.get();
|
|
||||||
} catch(Exception e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void create() throws ResourceRegistryException {
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
|
||||||
ODatabaseDocument adminDatabaseDocument = null;
|
|
||||||
try {
|
|
||||||
adminDatabaseDocument = getAdminDatabaseDocument();
|
|
||||||
|
|
||||||
create(adminDatabaseDocument);
|
|
||||||
|
|
||||||
adminDatabaseDocument.commit();
|
|
||||||
} finally {
|
|
||||||
if(adminDatabaseDocument!=null) {
|
|
||||||
adminDatabaseDocument.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(current!=null) {
|
|
||||||
current.activateOnCurrentThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
|
|
||||||
return role;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) {
|
|
||||||
String superRoleName = permissionMode.name().toLowerCase();
|
|
||||||
return oSecurity.getRole(superRoleName);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void addHierarchicalRoleToParent(OSecurity oSecurity, PermissionMode permissionMode, ORole... roles) {
|
|
||||||
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
|
|
||||||
OUser user = oSecurity.getUser(userName);
|
|
||||||
for(ORole role : roles) {
|
|
||||||
user.addRole(role);
|
|
||||||
}
|
|
||||||
user.save();
|
|
||||||
|
|
||||||
if(getParentSecurityContext() != null) {
|
|
||||||
getParentSecurityContext().addHierarchicalRoleToParent(oSecurity, permissionMode, roles);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void createRolesAndUsers(OSecurity oSecurity) {
|
|
||||||
boolean[] booleanArray;
|
|
||||||
if(hierarchical) {
|
|
||||||
booleanArray = new boolean[] {false, true};
|
|
||||||
} else {
|
|
||||||
booleanArray = new boolean[] {false};
|
|
||||||
}
|
|
||||||
|
|
||||||
for(boolean hierarchical : booleanArray) {
|
|
||||||
for(PermissionMode permissionMode : PermissionMode.values()) {
|
|
||||||
ORole superRole = getSuperRole(oSecurity, permissionMode);
|
|
||||||
|
|
||||||
String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchical);
|
|
||||||
ORole role = oSecurity.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT);
|
|
||||||
addExtraRules(role, permissionMode);
|
|
||||||
role.save();
|
|
||||||
logger.trace("{} created", role);
|
|
||||||
|
|
||||||
if(hierarchical && getParentSecurityContext() != null) {
|
|
||||||
getParentSecurityContext().addHierarchicalRoleToParent(oSecurity, permissionMode, role);
|
|
||||||
}
|
|
||||||
|
|
||||||
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchical);
|
|
||||||
OUser user = oSecurity.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode),
|
|
||||||
role);
|
|
||||||
user.save();
|
|
||||||
logger.trace("{} created", user);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void create(ODatabaseDocument oDatabaseDocument) {
|
|
||||||
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
|
||||||
createRolesAndUsers(oSecurity);
|
|
||||||
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void drop(OSecurity oSecurity, String name, SecurityType securityType) {
|
|
||||||
boolean dropped = false;
|
|
||||||
switch(securityType) {
|
|
||||||
case ROLE:
|
|
||||||
dropped = oSecurity.dropRole(name);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case USER:
|
|
||||||
dropped = oSecurity.dropUser(name);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if(dropped) {
|
|
||||||
logger.trace("{} successfully dropped", name);
|
|
||||||
} else {
|
|
||||||
logger.error("{} was not dropped successfully", name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void delete() throws ResourceRegistryException {
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
|
||||||
ODatabaseDocument adminDatabaseDocument = null;
|
|
||||||
try {
|
|
||||||
adminDatabaseDocument = getAdminDatabaseDocument();
|
|
||||||
|
|
||||||
delete(adminDatabaseDocument);
|
|
||||||
|
|
||||||
adminDatabaseDocument.commit();
|
|
||||||
} finally {
|
|
||||||
if(adminDatabaseDocument!=null) {
|
|
||||||
adminDatabaseDocument.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(current!=null) {
|
|
||||||
current.activateOnCurrentThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void removeChildrenHRolesFromParents(OSecurity oSecurity) {
|
|
||||||
Set<SecurityContext> parents = getAllParents();
|
|
||||||
Set<SecurityContext> allChildren = getAllChildren();
|
|
||||||
removeChildrenHRolesFromParents(oSecurity, parents, allChildren);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void removeChildrenHRolesFromParents(OSecurity oSecurity, Set<SecurityContext> parents, Set<SecurityContext> children) {
|
|
||||||
for(SecurityContext parent : parents) {
|
|
||||||
parent.removeChildrenHRolesFromMyHUsers(oSecurity, children);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void removeChildrenHRolesFromMyHUsers(OSecurity oSecurity, Set<SecurityContext> children) {
|
|
||||||
for(PermissionMode permissionMode : PermissionMode.values()) {
|
|
||||||
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
|
|
||||||
OUser user = oSecurity.getUser(userName);
|
|
||||||
for(SecurityContext child : children) {
|
|
||||||
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
|
|
||||||
logger.debug("Going to remove {} from {}", roleName, userName);
|
|
||||||
boolean removed = user.removeRole(roleName);
|
|
||||||
logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName);
|
|
||||||
}
|
|
||||||
user.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void removeHierarchicRoleFromMyHUser(OSecurity oSecurity, PermissionMode permissionMode, String roleName) {
|
|
||||||
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
|
|
||||||
OUser user = oSecurity.getUser(userName);
|
|
||||||
logger.debug("Going to remove {} from {}", roleName, userName);
|
|
||||||
boolean removed = user.removeRole(roleName);
|
|
||||||
logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName);
|
|
||||||
user.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void deleteRolesAndUsers(OSecurity oSecurity) {
|
|
||||||
boolean[] booleanArray;
|
|
||||||
if(hierarchical) {
|
|
||||||
booleanArray = new boolean[] {false, true};
|
|
||||||
} else {
|
|
||||||
booleanArray = new boolean[] {false};
|
|
||||||
}
|
|
||||||
for(boolean hierarchic : booleanArray) {
|
|
||||||
if(hierarchic) {
|
|
||||||
removeChildrenHRolesFromParents(oSecurity);
|
|
||||||
}
|
|
||||||
for(PermissionMode permissionMode : PermissionMode.values()) {
|
|
||||||
for(SecurityType securityType : SecurityType.values()) {
|
|
||||||
String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic);
|
|
||||||
drop(oSecurity, name, securityType);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void delete(ODatabaseDocument orientGraph) {
|
|
||||||
OSecurity oSecurity = getOSecurity(orientGraph);
|
|
||||||
delete(oSecurity);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void delete(OSecurity oSecurity) {
|
|
||||||
logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString());
|
|
||||||
deleteRolesAndUsers(oSecurity);
|
|
||||||
logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
public ODatabaseDocument getDatabaseDocument(PermissionMode permissionMode) throws ResourceRegistryException {
|
|
||||||
try {
|
|
||||||
ODatabasePool oDatabasePool = getPool(permissionMode, false);
|
|
||||||
ODatabaseSession oDatabaseSession = null;
|
|
||||||
try {
|
|
||||||
oDatabaseSession = oDatabasePool.acquire();
|
|
||||||
if(oDatabaseSession.isClosed()) {
|
|
||||||
// Enforcing pool recreation
|
|
||||||
throw new Exception();
|
|
||||||
}
|
|
||||||
}catch (Exception e) {
|
|
||||||
oDatabasePool = getPool(permissionMode, true);
|
|
||||||
oDatabaseSession = oDatabasePool.acquire();
|
|
||||||
}
|
|
||||||
oDatabaseSession.activateOnCurrentThread();
|
|
||||||
return oDatabaseSession;
|
|
||||||
}catch (Exception e) {
|
|
||||||
throw new ResourceRegistryException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("%s %s", Context.NAME, getUUID().toString());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -22,13 +22,13 @@ import org.gcube.informationsystem.discovery.RegistrationProvider;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Property;
|
import org.gcube.informationsystem.model.reference.properties.Property;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.queries.templates.QueryTemplateEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
|
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.types.TypeMapper;
|
import org.gcube.informationsystem.types.TypeMapper;
|
||||||
|
@ -178,14 +178,14 @@ public class DatabaseEnvironment {
|
||||||
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME,
|
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME,
|
||||||
CHANGED_ADMIN_PASSWORD);
|
CHANGED_ADMIN_PASSWORD);
|
||||||
ODatabaseDocument oDatabaseDocument = pool.acquire();
|
ODatabaseDocument oDatabaseDocument = pool.acquire();
|
||||||
AdminSecurityContext.getInstance().create(oDatabaseDocument);
|
AdminEnvironment.getInstance().create(oDatabaseDocument);
|
||||||
oDatabaseDocument.commit();
|
oDatabaseDocument.commit();
|
||||||
oDatabaseDocument.close();
|
oDatabaseDocument.close();
|
||||||
pool.close();
|
pool.close();
|
||||||
|
|
||||||
QueryTemplatesSecurityContext.getInstance().create();
|
QueryTemplateEnvironment.getInstance().create();
|
||||||
TypeSecurityContext.getInstance().create();
|
TypeEnvironment.getInstance().create();
|
||||||
ContextSecurityContext.getInstance().create();
|
ContextEnvironment.getInstance().create();
|
||||||
|
|
||||||
/* We must create only OrientDB types */
|
/* We must create only OrientDB types */
|
||||||
List<Class<? extends Element>> definitionToBeCreated = new ArrayList<>();
|
List<Class<? extends Element>> definitionToBeCreated = new ArrayList<>();
|
||||||
|
@ -209,7 +209,7 @@ public class DatabaseEnvironment {
|
||||||
TypeManagement typeManagement = new TypeManagement();
|
TypeManagement typeManagement = new TypeManagement();
|
||||||
typeManagement.setTypeAndTypeName(clz);
|
typeManagement.setTypeAndTypeName(clz);
|
||||||
if(clz.equals(Property.class) || clz.equals(Metadata.class) ) {
|
if(clz.equals(Property.class) || clz.equals(Metadata.class) ) {
|
||||||
((TypeManagement) typeManagement).setSkipTypeDefinitionCreation(true);
|
typeManagement.setSkipTypeDefinitionCreation(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
@ -224,12 +224,12 @@ public class DatabaseEnvironment {
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* We have already created Property and Metadata
|
* We have already created Property and Metadata
|
||||||
* because Metadata is needed to create
|
* because Metadata is needed to create
|
||||||
* types for internal use (i.e. Context, EntityType).
|
* types for internal use (i.e. Context, EntityType).
|
||||||
*
|
*
|
||||||
* For Property and Metadata we also need
|
* For Property and Metadata we also need
|
||||||
* to create the instance in TypeSecurityContext
|
* to create the instance in TypeEnvironment
|
||||||
* as we will do for any other Property specialization.
|
* as we will do for any other Property specialization.
|
||||||
*/
|
*/
|
||||||
List<Class<? extends Element>> schemaToBeCreated = new ArrayList<>();
|
List<Class<? extends Element>> schemaToBeCreated = new ArrayList<>();
|
||||||
|
|
|
@ -0,0 +1,480 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
package org.gcube.informationsystem.resourceregistry.environments;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.gcube.common.authorization.utils.manager.SecretManager;
|
||||||
|
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
||||||
|
import org.gcube.common.authorization.utils.user.User;
|
||||||
|
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.environments.administration.AdminEnvironment;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.orientechnologies.orient.core.db.ODatabasePool;
|
||||||
|
import com.orientechnologies.orient.core.db.ODatabaseSession;
|
||||||
|
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
|
||||||
|
import com.orientechnologies.orient.core.id.ORID;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.ORole;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.OSecurity;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.OUser;
|
||||||
|
import com.orientechnologies.orient.core.record.OElement;
|
||||||
|
import com.orientechnologies.orient.core.record.ORecord;
|
||||||
|
import com.orientechnologies.orient.core.record.impl.ODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* Base class for any environment.
|
||||||
|
* In the current implementation it represents a
|
||||||
|
* portion of a graph which in OrientDB
|
||||||
|
* is implemented via security.
|
||||||
|
*/
|
||||||
|
public abstract class Environment {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(Environment.class);
|
||||||
|
|
||||||
|
protected static final String DEFAULT_WRITER_ROLE = "writer";
|
||||||
|
protected static final String DEFAULT_READER_ROLE = "reader";
|
||||||
|
|
||||||
|
public enum SecurityType {
|
||||||
|
ROLE("Role"), USER("User");
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
private SecurityType(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum PermissionMode {
|
||||||
|
READER("Reader"), WRITER("Writer");
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
private PermissionMode(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected final UUID environmentUUID;
|
||||||
|
|
||||||
|
protected final Map<PermissionMode,ODatabasePool> poolMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Roles allowed to operate on the security context
|
||||||
|
*/
|
||||||
|
protected static Set<String> allOperationAllowedRoles;
|
||||||
|
protected Set<String> allowedRoles;
|
||||||
|
|
||||||
|
public final static String INFRASTRUCTURE_MANAGER = "Infrastructure-Manager";
|
||||||
|
public final static String IS_MANAGER = "IS-Manager";
|
||||||
|
|
||||||
|
public final static String CONTEXT_MANAGER = "Context-Manager";
|
||||||
|
|
||||||
|
static {
|
||||||
|
Environment.allOperationAllowedRoles = new HashSet<>();
|
||||||
|
Environment.allOperationAllowedRoles.add(INFRASTRUCTURE_MANAGER);
|
||||||
|
Environment.allOperationAllowedRoles.add(IS_MANAGER);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<String> getAllOperationsAllowedRoles() {
|
||||||
|
return new HashSet<>(allOperationAllowedRoles);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> getAllowedRoles() {
|
||||||
|
return new HashSet<>(allowedRoles);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Environment(UUID context) throws ResourceRegistryException {
|
||||||
|
this.environmentUUID = context;
|
||||||
|
this.poolMap = new HashMap<>();
|
||||||
|
|
||||||
|
this.allowedRoles = new HashSet<>(Environment.allOperationAllowedRoles);
|
||||||
|
this.allowedRoles.add(CONTEXT_MANAGER);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected synchronized ODatabasePool getPool(PermissionMode permissionMode, boolean recreate) {
|
||||||
|
ODatabasePool pool = null;
|
||||||
|
|
||||||
|
if(recreate) {
|
||||||
|
pool = poolMap.get(permissionMode);
|
||||||
|
if(pool!=null) {
|
||||||
|
pool.close();
|
||||||
|
poolMap.remove(permissionMode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pool = poolMap.get(permissionMode);
|
||||||
|
|
||||||
|
if(pool == null) {
|
||||||
|
|
||||||
|
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER);
|
||||||
|
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
|
||||||
|
|
||||||
|
pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password);
|
||||||
|
|
||||||
|
poolMap.put(permissionMode, pool);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID getUUID() {
|
||||||
|
return environmentUUID;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getRoleOrUserName(PermissionMode permissionMode, SecurityType securityType) {
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
stringBuilder.append(permissionMode);
|
||||||
|
stringBuilder.append(securityType);
|
||||||
|
return stringBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSecurityRoleOrUserName(PermissionMode permissionMode, SecurityType securityType) {
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
stringBuilder.append(getRoleOrUserName(permissionMode, securityType));
|
||||||
|
stringBuilder.append("_");
|
||||||
|
stringBuilder.append(environmentUUID.toString());
|
||||||
|
return stringBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private OSecurity getOSecurity(ODatabaseDocument oDatabaseDocument) {
|
||||||
|
return oDatabaseDocument.getMetadata().getSecurity();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addElement(OElement element) throws ResourceRegistryException {
|
||||||
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument adminDatabaseDocument = null;
|
||||||
|
try {
|
||||||
|
adminDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
addElement(element, adminDatabaseDocument);
|
||||||
|
}finally {
|
||||||
|
if(adminDatabaseDocument!=null) {
|
||||||
|
adminDatabaseDocument.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(current!=null) {
|
||||||
|
current.activateOnCurrentThread();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void allow(OSecurity oSecurity, ODocument oDocument) {
|
||||||
|
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE);
|
||||||
|
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
|
||||||
|
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE);
|
||||||
|
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isElementInContext(final OElement element) throws ResourceRegistryException {
|
||||||
|
ORID orid = element.getIdentity();
|
||||||
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument contextODatabaseDocument = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
contextODatabaseDocument = getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
|
ORecord oRecord = contextODatabaseDocument.getRecord(orid);
|
||||||
|
if(oRecord==null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if(contextODatabaseDocument!=null) {
|
||||||
|
contextODatabaseDocument.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(current!=null) {
|
||||||
|
current.activateOnCurrentThread();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addElement(OElement element, ODatabaseDocument oDatabaseDocument) {
|
||||||
|
ODocument oDocument = element.getRecord();
|
||||||
|
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
||||||
|
allow(oSecurity, oDocument);
|
||||||
|
oDocument.save();
|
||||||
|
element.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeElement(OElement element) throws ResourceRegistryException {
|
||||||
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument adminDatabaseDocument = null;
|
||||||
|
try {
|
||||||
|
adminDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
removeElement(element, adminDatabaseDocument);
|
||||||
|
}finally {
|
||||||
|
if(adminDatabaseDocument!=null) {
|
||||||
|
adminDatabaseDocument.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(current!=null) {
|
||||||
|
current.activateOnCurrentThread();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void deny(OSecurity oSecurity, ODocument oDocument) {
|
||||||
|
// The element could be created in such a context so the writerUser for the
|
||||||
|
// context is allowed by default because it was the creator
|
||||||
|
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER);
|
||||||
|
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_ALL, writerUserName);
|
||||||
|
String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER);
|
||||||
|
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName);
|
||||||
|
|
||||||
|
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE);
|
||||||
|
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
|
||||||
|
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE);
|
||||||
|
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeElement(OElement element, ODatabaseDocument oDatabaseDocument) {
|
||||||
|
ODocument oDocument = element.getRecord();
|
||||||
|
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
||||||
|
deny(oSecurity, oDocument);
|
||||||
|
oDocument.save();
|
||||||
|
element.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean allowed(final ORole role, final ODocument oDocument) {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUserAllowed(Collection<String> allowedRoles) {
|
||||||
|
boolean allowed = false;
|
||||||
|
SecretManager secretManager = SecretManagerProvider.instance.get();
|
||||||
|
User user = secretManager.getUser();
|
||||||
|
Collection<String> roles = new HashSet<>(user.getRoles());
|
||||||
|
roles.retainAll(allowedRoles);
|
||||||
|
if(roles.size()>0) {
|
||||||
|
allowed = true;
|
||||||
|
}
|
||||||
|
return allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// public boolean isUserAllowed(Operation operation) {
|
||||||
|
// switch (operation) {
|
||||||
|
// case CREATE:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case READ:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case EXISTS:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case UPDATE:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case DELETE:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case ADD_TO_CONTEXT:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case REMOVE_FROM_CONTEXT:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case QUERY:
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case GET_METADATA:
|
||||||
|
// return isUserAllowed(allOperationAllowedRoles);
|
||||||
|
//
|
||||||
|
// default:
|
||||||
|
// break;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return true;
|
||||||
|
// }
|
||||||
|
|
||||||
|
public void create() throws ResourceRegistryException {
|
||||||
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument adminDatabaseDocument = null;
|
||||||
|
try {
|
||||||
|
adminDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
|
||||||
|
create(adminDatabaseDocument);
|
||||||
|
|
||||||
|
adminDatabaseDocument.commit();
|
||||||
|
} finally {
|
||||||
|
if(adminDatabaseDocument!=null) {
|
||||||
|
adminDatabaseDocument.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(current!=null) {
|
||||||
|
current.activateOnCurrentThread();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) {
|
||||||
|
String superRoleName = permissionMode.name().toLowerCase();
|
||||||
|
return oSecurity.getRole(superRoleName);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void createRolesAndUsers(OSecurity oSecurity) {
|
||||||
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
ORole superRole = getSuperRole(oSecurity, permissionMode);
|
||||||
|
|
||||||
|
String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE);
|
||||||
|
ORole role = oSecurity.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT);
|
||||||
|
addExtraRules(role, permissionMode);
|
||||||
|
role.save();
|
||||||
|
logger.trace("{} created", role);
|
||||||
|
|
||||||
|
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER);
|
||||||
|
OUser user = oSecurity.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode),
|
||||||
|
role);
|
||||||
|
user.save();
|
||||||
|
logger.trace("{} created", user);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void create(ODatabaseDocument oDatabaseDocument) {
|
||||||
|
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
||||||
|
createRolesAndUsers(oSecurity);
|
||||||
|
logger.trace("Security Context (roles and users) with UUID {} successfully created", environmentUUID.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void drop(OSecurity oSecurity, String name, SecurityType securityType) {
|
||||||
|
boolean dropped = false;
|
||||||
|
switch(securityType) {
|
||||||
|
case ROLE:
|
||||||
|
dropped = oSecurity.dropRole(name);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case USER:
|
||||||
|
dropped = oSecurity.dropUser(name);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if(dropped) {
|
||||||
|
logger.trace("{} successfully dropped", name);
|
||||||
|
} else {
|
||||||
|
logger.error("{} was not dropped successfully", name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete() throws ResourceRegistryException {
|
||||||
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
ODatabaseDocument adminDatabaseDocument = null;
|
||||||
|
try {
|
||||||
|
adminDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
|
||||||
|
delete(adminDatabaseDocument);
|
||||||
|
|
||||||
|
adminDatabaseDocument.commit();
|
||||||
|
} finally {
|
||||||
|
if(adminDatabaseDocument!=null) {
|
||||||
|
adminDatabaseDocument.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(current!=null) {
|
||||||
|
current.activateOnCurrentThread();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void deleteRolesAndUsers(OSecurity oSecurity) {
|
||||||
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
for(SecurityType securityType : SecurityType.values()) {
|
||||||
|
String name = getSecurityRoleOrUserName(permissionMode, securityType);
|
||||||
|
drop(oSecurity, name, securityType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(ODatabaseDocument orientGraph) {
|
||||||
|
OSecurity oSecurity = getOSecurity(orientGraph);
|
||||||
|
delete(oSecurity);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void delete(OSecurity oSecurity) {
|
||||||
|
logger.trace("Going to remove Security Context (roles and users) with UUID {}", environmentUUID.toString());
|
||||||
|
deleteRolesAndUsers(oSecurity);
|
||||||
|
logger.trace("Security Context (roles and users) with UUID {} successfully removed", environmentUUID.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public ODatabaseDocument getDatabaseDocument(PermissionMode permissionMode) throws ResourceRegistryException {
|
||||||
|
try {
|
||||||
|
ODatabasePool oDatabasePool = getPool(permissionMode, false);
|
||||||
|
ODatabaseSession oDatabaseSession = null;
|
||||||
|
try {
|
||||||
|
oDatabaseSession = oDatabasePool.acquire();
|
||||||
|
if(oDatabaseSession.isClosed()) {
|
||||||
|
// Enforcing pool recreation
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
}catch (Exception e) {
|
||||||
|
oDatabasePool = getPool(permissionMode, true);
|
||||||
|
oDatabaseSession = oDatabasePool.acquire();
|
||||||
|
}
|
||||||
|
oDatabaseSession.activateOnCurrentThread();
|
||||||
|
return oDatabaseSession;
|
||||||
|
}catch (Exception e) {
|
||||||
|
throw new ResourceRegistryException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return String.format("%s %s", this.getClass().getSimpleName(), getUUID().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,415 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
package org.gcube.informationsystem.resourceregistry.environments;
|
||||||
|
|
||||||
|
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.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
|
import org.gcube.informationsystem.utils.UUIDManager;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.orientechnologies.orient.core.db.ODatabasePool;
|
||||||
|
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
|
||||||
|
import com.orientechnologies.orient.core.db.record.OIdentifiable;
|
||||||
|
import com.orientechnologies.orient.core.db.record.ORecordLazySet;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.ORestrictedOperation;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.ORole;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.OSecurity;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.OSecurityRole.ALLOW_MODES;
|
||||||
|
import com.orientechnologies.orient.core.metadata.security.OUser;
|
||||||
|
import com.orientechnologies.orient.core.record.OElement;
|
||||||
|
import com.orientechnologies.orient.core.record.impl.ODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* Base class for all environments which have an hierarchy.
|
||||||
|
* An example is InstanceEnviroment where the instances
|
||||||
|
* belonging to a context must be visible from parent
|
||||||
|
* context if the requesting client has enough privileges
|
||||||
|
*/
|
||||||
|
public abstract class HierarchicalEnvironment extends Environment {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(HierarchicalEnvironment.class);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* H stand for Hierarchical
|
||||||
|
*/
|
||||||
|
public static final String H = "H";
|
||||||
|
|
||||||
|
protected final boolean hierarchicalMode;
|
||||||
|
|
||||||
|
protected final Map<PermissionMode,ODatabasePool> hierarchicPoolMap;
|
||||||
|
|
||||||
|
protected HierarchicalEnvironment parentEnvironment;
|
||||||
|
|
||||||
|
protected Set<HierarchicalEnvironment> children;
|
||||||
|
|
||||||
|
public HierarchicalEnvironment(UUID uuid) throws ResourceRegistryException {
|
||||||
|
super(uuid);
|
||||||
|
|
||||||
|
this.hierarchicPoolMap = new HashMap<>();
|
||||||
|
|
||||||
|
boolean hierarchicalModeRequested = RequestUtility.getRequestInfo().get().isHierarchicalMode();
|
||||||
|
logger.trace("HierarchicalMode {}requested", hierarchicalModeRequested ? "" : "not ");
|
||||||
|
|
||||||
|
boolean hierarchicalAllowed = isUserAllowed(Environment.getAllOperationsAllowedRoles());
|
||||||
|
logger.trace("{} is {}allowed to request the HierarchicalMode", ContextUtility.getCurrentUserUsername(), hierarchicalAllowed ? "" : "not ");
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Only the Infrastructure Manager and IS Manager are entitled to use hierarchical mode.
|
||||||
|
* I decided not to complain if the user does not have such roles and assumed the hierarchical mode was not requested.
|
||||||
|
*/
|
||||||
|
if(hierarchicalModeRequested && !hierarchicalAllowed) {
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append("The user ");
|
||||||
|
sb.append(ContextUtility.getCurrentUserUsername());
|
||||||
|
sb.append(" requested hierarchical mode but he/she does not have one of the following roles ");
|
||||||
|
sb.append(allOperationAllowedRoles.toString());
|
||||||
|
sb.append(". Instead of complaining, the request will be elaborated not in hierarchical mode.");
|
||||||
|
logger.warn(sb.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
this.hierarchicalMode = hierarchicalAllowed && hierarchicalModeRequested;
|
||||||
|
|
||||||
|
this.children = new HashSet<>();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean isHierarchicalMode() {
|
||||||
|
return hierarchicalMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setParentEnvironment(HierarchicalEnvironment parentEnvironment) {
|
||||||
|
if(this.parentEnvironment!=null) {
|
||||||
|
this.parentEnvironment.getChildren().remove(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.parentEnvironment = parentEnvironment;
|
||||||
|
if(parentEnvironment!=null) {
|
||||||
|
this.parentEnvironment.addChild(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public HierarchicalEnvironment getParentEnvironment() {
|
||||||
|
return parentEnvironment;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addChild(HierarchicalEnvironment child) {
|
||||||
|
this.children.add(child);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<HierarchicalEnvironment> getChildren(){
|
||||||
|
return this.children;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return a set containing all children and recursively
|
||||||
|
* all children.
|
||||||
|
*/
|
||||||
|
private Set<HierarchicalEnvironment> getAllChildren(){
|
||||||
|
Set<HierarchicalEnvironment> allChildren = new HashSet<>();
|
||||||
|
allChildren.add(this);
|
||||||
|
for(HierarchicalEnvironment hierarchicalEnvironment : getChildren()) {
|
||||||
|
allChildren.addAll(hierarchicalEnvironment.getAllChildren());
|
||||||
|
}
|
||||||
|
return allChildren;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private Set<HierarchicalEnvironment> getAllParents(){
|
||||||
|
Set<HierarchicalEnvironment> allParents = new HashSet<>();
|
||||||
|
HierarchicalEnvironment parent = getParentEnvironment();
|
||||||
|
while(parent!=null) {
|
||||||
|
allParents.add(parent);
|
||||||
|
parent = parent.getParentEnvironment();
|
||||||
|
}
|
||||||
|
return allParents;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use to change the parent not to set the first time
|
||||||
|
*
|
||||||
|
* @param newParentEnvironment
|
||||||
|
* @param orientGraph
|
||||||
|
* @throws ResourceRegistryException
|
||||||
|
*/
|
||||||
|
public void changeParentEnvironment(HierarchicalEnvironment newParentEnvironment, ODatabaseDocument orientGraph) throws ResourceRegistryException {
|
||||||
|
OSecurity oSecurity = getOSecurity(orientGraph);
|
||||||
|
|
||||||
|
Set<HierarchicalEnvironment> allChildren = getAllChildren();
|
||||||
|
|
||||||
|
Set<HierarchicalEnvironment> oldParents = getAllParents();
|
||||||
|
|
||||||
|
Set<HierarchicalEnvironment> newParents = new HashSet<>();
|
||||||
|
if(newParentEnvironment!=null) {
|
||||||
|
newParents = newParentEnvironment.getAllParents();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* From old parents I remove the new parents so that oldParents
|
||||||
|
* contains only the parents where I have to remove all
|
||||||
|
* HReaderRole-UUID e HWriterRole-UUID of allChildren by using
|
||||||
|
* removeHierarchicRoleFromParent() function
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
oldParents.removeAll(newParents);
|
||||||
|
removeChildrenHRolesFromParents(oSecurity, oldParents, allChildren);
|
||||||
|
|
||||||
|
setParentEnvironment(newParentEnvironment);
|
||||||
|
|
||||||
|
if(newParentEnvironment!=null){
|
||||||
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
List<ORole> roles = new ArrayList<>();
|
||||||
|
for(HierarchicalEnvironment child : allChildren) {
|
||||||
|
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
|
||||||
|
ORole role = oSecurity.getRole(roleName);
|
||||||
|
roles.add(role);
|
||||||
|
}
|
||||||
|
newParentEnvironment.addHierarchicalRoleToParent(oSecurity, permissionMode, roles.toArray(new ORole[allChildren.size()]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected synchronized ODatabasePool getPool(PermissionMode permissionMode, boolean recreate) {
|
||||||
|
ODatabasePool pool = null;
|
||||||
|
|
||||||
|
Boolean h = hierarchicalMode || RequestUtility.getRequestInfo().get().isHierarchicalMode();
|
||||||
|
|
||||||
|
Map<PermissionMode,ODatabasePool> pools = h ? hierarchicPoolMap : poolMap;
|
||||||
|
|
||||||
|
if(recreate) {
|
||||||
|
pool = pools.get(permissionMode);
|
||||||
|
if(pool!=null) {
|
||||||
|
pool.close();
|
||||||
|
pools.remove(permissionMode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pool = pools.get(permissionMode);
|
||||||
|
|
||||||
|
if(pool == null) {
|
||||||
|
|
||||||
|
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h);
|
||||||
|
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
|
||||||
|
|
||||||
|
pool = new ODatabasePool(DatabaseEnvironment.DB_URI, username, password);
|
||||||
|
|
||||||
|
pools.put(permissionMode, pool);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getRoleOrUserName(PermissionMode permissionMode, SecurityType securityType) {
|
||||||
|
return getRoleOrUserName(permissionMode, securityType, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
|
||||||
|
boolean hierarchic) {
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
if(hierarchic) {
|
||||||
|
stringBuilder.append(H);
|
||||||
|
}
|
||||||
|
stringBuilder.append(permissionMode);
|
||||||
|
stringBuilder.append(securityType);
|
||||||
|
return stringBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSecurityRoleOrUserName(PermissionMode permissionMode, SecurityType securityType,
|
||||||
|
boolean hierarchic) {
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
stringBuilder.append(getRoleOrUserName(permissionMode, securityType, hierarchic));
|
||||||
|
stringBuilder.append("_");
|
||||||
|
stringBuilder.append(environmentUUID.toString());
|
||||||
|
return stringBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private OSecurity getOSecurity(ODatabaseDocument oDatabaseDocument) {
|
||||||
|
return oDatabaseDocument.getMetadata().getSecurity();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<String> getContexts(OElement element) {
|
||||||
|
Set<String> contexts = new HashSet<>();
|
||||||
|
ORecordLazySet oRecordLazySet = element.getProperty(OSecurity.ALLOW_ALL_FIELD);
|
||||||
|
for (OIdentifiable oIdentifiable : oRecordLazySet) {
|
||||||
|
ODocument oDocument = (ODocument) oIdentifiable;
|
||||||
|
String name = oDocument.getProperty("name");
|
||||||
|
if (name.startsWith(getRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE))
|
||||||
|
|| name.startsWith(getRoleOrUserName(PermissionMode.READER, SecurityType.ROLE))) {
|
||||||
|
String[] list = name.split("_");
|
||||||
|
if (list.length == 2) {
|
||||||
|
String contextUUID = list[1];
|
||||||
|
if (!UUIDManager.getInstance().isReservedUUID(contextUUID)) {
|
||||||
|
contexts.add(contextUUID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return contexts;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void allow(OSecurity oSecurity, ODocument oDocument, boolean hierarchic) {
|
||||||
|
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic);
|
||||||
|
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
|
||||||
|
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic);
|
||||||
|
oSecurity.allowRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addElement(OElement element, ODatabaseDocument oDatabaseDocument) {
|
||||||
|
ODocument oDocument = element.getRecord();
|
||||||
|
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
||||||
|
allow(oSecurity, oDocument, false);
|
||||||
|
allow(oSecurity, oDocument, true);
|
||||||
|
oDocument.save();
|
||||||
|
element.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void deny(OSecurity oSecurity, ODocument oDocument, boolean hierarchical) {
|
||||||
|
// The element could be created in such a context so the writerUser for the
|
||||||
|
// context is allowed by default because it was the creator
|
||||||
|
String writerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
|
||||||
|
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_ALL, writerUserName);
|
||||||
|
String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
|
||||||
|
oSecurity.denyUser(oDocument, ORestrictedOperation.ALLOW_READ, readerUserName);
|
||||||
|
|
||||||
|
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchical);
|
||||||
|
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_ALL, writerRoleName);
|
||||||
|
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchical);
|
||||||
|
oSecurity.denyRole(oDocument, ORestrictedOperation.ALLOW_READ, readerRoleName);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void removeElement(OElement element, ODatabaseDocument oDatabaseDocument) {
|
||||||
|
ODocument oDocument = element.getRecord();
|
||||||
|
OSecurity oSecurity = getOSecurity(oDatabaseDocument);
|
||||||
|
deny(oSecurity, oDocument, false);
|
||||||
|
deny(oSecurity, oDocument, true);
|
||||||
|
oDocument.save();
|
||||||
|
element.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean allowed(final ORole role, final ODocument oDocument) {
|
||||||
|
ServerRequestInfo sri = RequestUtility.getRequestInfo().get();
|
||||||
|
Boolean hm = sri.isHierarchicalMode();
|
||||||
|
sri.setHierarchicalMode(false);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return super.allowed(role, oDocument);
|
||||||
|
}finally {
|
||||||
|
sri.setHierarchicalMode(hm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void addHierarchicalRoleToParent(OSecurity oSecurity, PermissionMode permissionMode, ORole... roles) {
|
||||||
|
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
|
||||||
|
OUser user = oSecurity.getUser(userName);
|
||||||
|
for(ORole role : roles) {
|
||||||
|
user.addRole(role);
|
||||||
|
}
|
||||||
|
user.save();
|
||||||
|
|
||||||
|
if(getParentEnvironment() != null) {
|
||||||
|
getParentEnvironment().addHierarchicalRoleToParent(oSecurity, permissionMode, roles);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void createRolesAndUsers(OSecurity oSecurity) {
|
||||||
|
boolean[] booleanArray = new boolean[] {false, true};
|
||||||
|
|
||||||
|
for(boolean hierarchical : booleanArray) {
|
||||||
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
ORole superRole = getSuperRole(oSecurity, permissionMode);
|
||||||
|
|
||||||
|
String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchical);
|
||||||
|
ORole role = oSecurity.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT);
|
||||||
|
addExtraRules(role, permissionMode);
|
||||||
|
role.save();
|
||||||
|
logger.trace("{} created", role);
|
||||||
|
|
||||||
|
if(hierarchical && getParentEnvironment() != null) {
|
||||||
|
getParentEnvironment().addHierarchicalRoleToParent(oSecurity, permissionMode, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchical);
|
||||||
|
OUser user = oSecurity.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode),
|
||||||
|
role);
|
||||||
|
user.save();
|
||||||
|
logger.trace("{} created", user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void removeChildrenHRolesFromParents(OSecurity oSecurity) {
|
||||||
|
Set<HierarchicalEnvironment> parents = getAllParents();
|
||||||
|
Set<HierarchicalEnvironment> allChildren = getAllChildren();
|
||||||
|
removeChildrenHRolesFromParents(oSecurity, parents, allChildren);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void removeChildrenHRolesFromParents(OSecurity oSecurity, Set<HierarchicalEnvironment> parents, Set<HierarchicalEnvironment> children) {
|
||||||
|
for(HierarchicalEnvironment parent : parents) {
|
||||||
|
parent.removeChildrenHRolesFromMyHUsers(oSecurity, children);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void removeChildrenHRolesFromMyHUsers(OSecurity oSecurity, Set<HierarchicalEnvironment> children) {
|
||||||
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
|
||||||
|
OUser user = oSecurity.getUser(userName);
|
||||||
|
for(HierarchicalEnvironment child : children) {
|
||||||
|
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
|
||||||
|
logger.debug("Going to remove {} from {}", roleName, userName);
|
||||||
|
boolean removed = user.removeRole(roleName);
|
||||||
|
logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName);
|
||||||
|
}
|
||||||
|
user.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void removeHierarchicRoleFromMyHUser(OSecurity oSecurity, PermissionMode permissionMode, String roleName) {
|
||||||
|
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
|
||||||
|
OUser user = oSecurity.getUser(userName);
|
||||||
|
logger.debug("Going to remove {} from {}", roleName, userName);
|
||||||
|
boolean removed = user.removeRole(roleName);
|
||||||
|
logger.trace("{} {} removed from {}", roleName, removed ? "successfully" : "NOT", userName);
|
||||||
|
user.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void deleteRolesAndUsers(OSecurity oSecurity) {
|
||||||
|
boolean[] booleanArray = new boolean[] {false, true};
|
||||||
|
for(boolean hierarchic : booleanArray) {
|
||||||
|
if(hierarchic) {
|
||||||
|
removeChildrenHRolesFromParents(oSecurity);
|
||||||
|
}
|
||||||
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
|
for(SecurityType securityType : SecurityType.values()) {
|
||||||
|
String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic);
|
||||||
|
drop(oSecurity, name, securityType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.environments;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
|
public abstract class SystemEnvironment extends Environment {
|
||||||
|
|
||||||
|
protected SystemEnvironment(UUID context) throws ResourceRegistryException {
|
||||||
|
super(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,10 +1,11 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts.security;
|
package org.gcube.informationsystem.resourceregistry.environments.administration;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.dbinitialization.DatabaseEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.SystemEnvironment;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -14,10 +15,12 @@ import com.orientechnologies.orient.core.metadata.security.OSecurity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* This SystemEnvironment is used in all the case the
|
||||||
|
* operation must be done by an administrator
|
||||||
*/
|
*/
|
||||||
public class AdminSecurityContext extends SecurityContext {
|
public class AdminEnvironment extends SystemEnvironment {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
|
private static Logger logger = LoggerFactory.getLogger(Environment.class);
|
||||||
|
|
||||||
private static final String ADMIN_SECURITY_CONTEXT;
|
private static final String ADMIN_SECURITY_CONTEXT;
|
||||||
private static final UUID ADMIN_SECURITY_CONTEXT_UUID;
|
private static final UUID ADMIN_SECURITY_CONTEXT_UUID;
|
||||||
|
@ -27,19 +30,17 @@ public class AdminSecurityContext extends SecurityContext {
|
||||||
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
|
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static AdminSecurityContext instance;
|
private static AdminEnvironment instance;
|
||||||
|
|
||||||
public static AdminSecurityContext getInstance() throws ResourceRegistryException {
|
public static AdminEnvironment getInstance() throws ResourceRegistryException {
|
||||||
if(instance==null) {
|
if(instance==null) {
|
||||||
instance = new AdminSecurityContext();
|
instance = new AdminEnvironment();
|
||||||
ContextUtility contextUtility = ContextUtility.getInstance();
|
|
||||||
contextUtility.addSecurityContext(ADMIN_SECURITY_CONTEXT, instance);
|
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
private AdminSecurityContext() throws ResourceRegistryException {
|
private AdminEnvironment() throws ResourceRegistryException {
|
||||||
super(ADMIN_SECURITY_CONTEXT_UUID, false);
|
super(ADMIN_SECURITY_CONTEXT_UUID);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
|
@ -1,9 +1,10 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts.security;
|
package org.gcube.informationsystem.resourceregistry.environments.contexts;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.SystemEnvironment;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -12,10 +13,13 @@ import com.orientechnologies.orient.core.metadata.security.ORule;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* This SystemEnvironment is used to pesists
|
||||||
|
* Contexts information and their relations among
|
||||||
|
* others, e.g. a Context is parent of another.
|
||||||
*/
|
*/
|
||||||
public class ContextSecurityContext extends SecurityContext {
|
public class ContextEnvironment extends SystemEnvironment {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
|
private static Logger logger = LoggerFactory.getLogger(Environment.class);
|
||||||
|
|
||||||
private static final String CONTEXT_SECURITY_CONTEXT;
|
private static final String CONTEXT_SECURITY_CONTEXT;
|
||||||
private static final UUID CONTEXT_SECURITY_CONTEXT_UUID;
|
private static final UUID CONTEXT_SECURITY_CONTEXT_UUID;
|
||||||
|
@ -25,21 +29,20 @@ public class ContextSecurityContext extends SecurityContext {
|
||||||
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
|
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ContextSecurityContext instance;
|
private static ContextEnvironment instance;
|
||||||
|
|
||||||
public static ContextSecurityContext getInstance() throws ResourceRegistryException {
|
public static ContextEnvironment getInstance() throws ResourceRegistryException {
|
||||||
if(instance==null) {
|
if(instance==null) {
|
||||||
instance = new ContextSecurityContext();
|
instance = new ContextEnvironment();
|
||||||
ContextUtility contextUtility = ContextUtility.getInstance();
|
|
||||||
contextUtility.addSecurityContext(CONTEXT_SECURITY_CONTEXT, instance);
|
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ContextSecurityContext() throws ResourceRegistryException {
|
private ContextEnvironment() throws ResourceRegistryException {
|
||||||
super(CONTEXT_SECURITY_CONTEXT_UUID, false);
|
super(CONTEXT_SECURITY_CONTEXT_UUID);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
|
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
|
||||||
logger.trace("Adding extra rules for {}", role.getName());
|
logger.trace("Adding extra rules for {}", role.getName());
|
|
@ -0,0 +1,72 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.environments.contexts;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.SystemEnvironment;
|
||||||
|
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)
|
||||||
|
* Added for feature #19428
|
||||||
|
* It is used as a sort of cemetery for deleted Contexts.
|
||||||
|
* e.g the information regarding a deleted context are not
|
||||||
|
* really deleted instead are moved in this partition to
|
||||||
|
* ah historical information and to provide a minimal support for
|
||||||
|
* Context reborn.
|
||||||
|
*/
|
||||||
|
public class ShadowContextEnvironment extends SystemEnvironment {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(Environment.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 ShadowContextEnvironment instance;
|
||||||
|
|
||||||
|
public static ShadowContextEnvironment getInstance() throws ResourceRegistryException {
|
||||||
|
if(instance==null) {
|
||||||
|
instance = new ShadowContextEnvironment();
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ShadowContextEnvironment() throws ResourceRegistryException {
|
||||||
|
super(SHADOW_CONTEXT_SECURITY_CONTEXT_UUID);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.environments.instances;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.HierarchicalEnvironment;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* Contains all the instances belonging to a context.
|
||||||
|
*/
|
||||||
|
public class InstanceEnvironment extends HierarchicalEnvironment {
|
||||||
|
|
||||||
|
public InstanceEnvironment(UUID uuid) throws ResourceRegistryException {
|
||||||
|
super(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,9 +1,10 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts.security;
|
package org.gcube.informationsystem.resourceregistry.environments.queries.templates;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.SystemEnvironment;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -12,10 +13,11 @@ import com.orientechnologies.orient.core.metadata.security.ORule;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* Contains all the query templates
|
||||||
*/
|
*/
|
||||||
public class QueryTemplatesSecurityContext extends SecurityContext {
|
public class QueryTemplateEnvironment extends SystemEnvironment {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
|
private static Logger logger = LoggerFactory.getLogger(Environment.class);
|
||||||
|
|
||||||
private static final String QUERY_TEMPLATES_SECURITY_CONTEXT;
|
private static final String QUERY_TEMPLATES_SECURITY_CONTEXT;
|
||||||
private static final UUID QUERY_TEMPLATES_SECURITY_CONTEXT_UUID;
|
private static final UUID QUERY_TEMPLATES_SECURITY_CONTEXT_UUID;
|
||||||
|
@ -25,19 +27,17 @@ public class QueryTemplatesSecurityContext extends SecurityContext {
|
||||||
QUERY_TEMPLATES_SECURITY_CONTEXT_UUID = UUID.fromString(QUERY_TEMPLATES_SECURITY_CONTEXT);
|
QUERY_TEMPLATES_SECURITY_CONTEXT_UUID = UUID.fromString(QUERY_TEMPLATES_SECURITY_CONTEXT);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static QueryTemplatesSecurityContext instance;
|
private static QueryTemplateEnvironment instance;
|
||||||
|
|
||||||
public static QueryTemplatesSecurityContext getInstance() throws ResourceRegistryException {
|
public static QueryTemplateEnvironment getInstance() throws ResourceRegistryException {
|
||||||
if(instance==null) {
|
if(instance==null) {
|
||||||
instance = new QueryTemplatesSecurityContext();
|
instance = new QueryTemplateEnvironment();
|
||||||
ContextUtility contextUtility = ContextUtility.getInstance();
|
|
||||||
contextUtility.addSecurityContext(QUERY_TEMPLATES_SECURITY_CONTEXT, instance);
|
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
private QueryTemplatesSecurityContext() throws ResourceRegistryException {
|
private QueryTemplateEnvironment() throws ResourceRegistryException {
|
||||||
super(QUERY_TEMPLATES_SECURITY_CONTEXT_UUID, false);
|
super(QUERY_TEMPLATES_SECURITY_CONTEXT_UUID);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
|
@ -1,9 +1,10 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts.security;
|
package org.gcube.informationsystem.resourceregistry.environments.types;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.SystemEnvironment;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -12,10 +13,13 @@ import com.orientechnologies.orient.core.metadata.security.ORule;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
* Contains all the information-system-model types
|
||||||
|
* plus all the types defined on top of the
|
||||||
|
* information-system-model (e.g the gcube-model)
|
||||||
*/
|
*/
|
||||||
public class TypeSecurityContext extends SecurityContext {
|
public class TypeEnvironment extends SystemEnvironment {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
|
private static Logger logger = LoggerFactory.getLogger(Environment.class);
|
||||||
|
|
||||||
private static final String SCHEMA_SECURITY_CONTEXT;
|
private static final String SCHEMA_SECURITY_CONTEXT;
|
||||||
private static final UUID SCHEMA_SECURITY_CONTEXT_UUID;
|
private static final UUID SCHEMA_SECURITY_CONTEXT_UUID;
|
||||||
|
@ -25,19 +29,17 @@ public class TypeSecurityContext extends SecurityContext {
|
||||||
SCHEMA_SECURITY_CONTEXT_UUID = UUID.fromString(SCHEMA_SECURITY_CONTEXT);
|
SCHEMA_SECURITY_CONTEXT_UUID = UUID.fromString(SCHEMA_SECURITY_CONTEXT);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static TypeSecurityContext instance;
|
private static TypeEnvironment instance;
|
||||||
|
|
||||||
public static TypeSecurityContext getInstance() throws ResourceRegistryException {
|
public static TypeEnvironment getInstance() throws ResourceRegistryException {
|
||||||
if(instance==null) {
|
if(instance==null) {
|
||||||
instance = new TypeSecurityContext();
|
instance = new TypeEnvironment();
|
||||||
ContextUtility contextUtility = ContextUtility.getInstance();
|
|
||||||
contextUtility.addSecurityContext(SCHEMA_SECURITY_CONTEXT, instance);
|
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
private TypeSecurityContext() throws ResourceRegistryException {
|
private TypeEnvironment() throws ResourceRegistryException {
|
||||||
super(SCHEMA_SECURITY_CONTEXT_UUID, false);
|
super(SCHEMA_SECURITY_CONTEXT_UUID);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
|
@ -9,8 +9,11 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundExcep
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public interface ERManagement {
|
public interface ERManagement {
|
||||||
|
|
||||||
public boolean isHonourPropagationConstraintsInContextSharing();
|
public boolean isHonourPropagationConstraintsInContextSharing();
|
||||||
|
@ -20,12 +23,12 @@ public interface ERManagement {
|
||||||
public Map<UUID,JsonNode> getAffectedInstances();
|
public Map<UUID,JsonNode> getAffectedInstances();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set source security context to evaluate addToContext
|
* Set source InstanceEnvironment to evaluate addToContext
|
||||||
* @param sourceSecurityContext the source security context
|
* @param source the source security context
|
||||||
*/
|
*/
|
||||||
public void setSourceSecurityContext(SecurityContext sourceSecurityContext);
|
public void setSourceInstanceEnvironment(InstanceEnvironment source);
|
||||||
|
|
||||||
public SecurityContext getSourceSecurityContext();
|
public InstanceEnvironment getSourceInstanceEnvironment();
|
||||||
|
|
||||||
public void internalAddToContext()
|
public void internalAddToContext()
|
||||||
throws ContextException, ResourceRegistryException;
|
throws ContextException, ResourceRegistryException;
|
||||||
|
@ -35,11 +38,11 @@ public interface ERManagement {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set target security context of addToContext/removeFromContext
|
* Set target security context of addToContext/removeFromContext
|
||||||
* @param targetSecurityContext
|
* @param target
|
||||||
*/
|
*/
|
||||||
public void setTargetSecurityContext(SecurityContext targetSecurityContext);
|
public void setTargetInstanceEnvironment(InstanceEnvironment target);
|
||||||
|
|
||||||
public SecurityContext getTargetSecurityContext();
|
public InstanceEnvironment getTargetInstanceEnvironment();
|
||||||
|
|
||||||
public void internalRemoveFromContext()
|
public void internalRemoveFromContext()
|
||||||
throws ContextException, ResourceRegistryException;
|
throws ContextException, ResourceRegistryException;
|
||||||
|
|
|
@ -6,25 +6,94 @@ import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
|
import org.gcube.informationsystem.model.reference.entities.Entity;
|
||||||
|
import org.gcube.informationsystem.model.reference.relations.Relation;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.ContextException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
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.types.TypesCache;
|
||||||
import org.gcube.informationsystem.utils.TypeUtility;
|
import org.gcube.informationsystem.utils.TypeUtility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
|
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
|
||||||
|
import com.orientechnologies.orient.core.record.OEdge;
|
||||||
|
import com.orientechnologies.orient.core.record.OElement;
|
||||||
|
import com.orientechnologies.orient.core.record.OVertex;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class ERManagementUtility {
|
public class ERManagementUtility {
|
||||||
|
|
||||||
private static Logger staticLogger = LoggerFactory.getLogger(ERManagementUtility.class);
|
private static Logger staticLogger = LoggerFactory.getLogger(ERManagementUtility.class);
|
||||||
|
|
||||||
|
public static ElementManagement<?,?> getERManagement(String type) throws ResourceRegistryException {
|
||||||
|
|
||||||
|
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
|
||||||
|
|
||||||
|
ElementManagement<?,?> erManagement = null;
|
||||||
|
|
||||||
|
switch (accessType) {
|
||||||
|
case RESOURCE:
|
||||||
|
erManagement = new ResourceManagement();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case FACET:
|
||||||
|
erManagement = new FacetManagement();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case IS_RELATED_TO:
|
||||||
|
erManagement = new IsRelatedToManagement();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CONSISTS_OF:
|
||||||
|
erManagement = new ConsistsOfManagement();
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new ResourceRegistryException(String.format("%s is not querable", type.toString()));
|
||||||
|
}
|
||||||
|
erManagement.setElementType(type);
|
||||||
|
|
||||||
|
return erManagement;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ElementManagement<?, ?> getERManagementFromUUID(Environment workingContext, ODatabaseDocument orientGraph,
|
||||||
|
UUID uuid) throws ResourceRegistryException {
|
||||||
|
OElement element;
|
||||||
|
try {
|
||||||
|
element = ElementManagementUtility.getAnyElementByUUID(orientGraph, uuid);
|
||||||
|
return getERManagement(workingContext, orientGraph, element);
|
||||||
|
} catch(Exception e) {
|
||||||
|
throw new ResourceRegistryException(String.format("%s does not belong to an %s nor to a %s",
|
||||||
|
uuid.toString(), Entity.NAME, Relation.NAME));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ElementManagement<?,?> getERManagement(Environment workingContext, ODatabaseDocument orientGraph,
|
||||||
|
OElement element) throws ResourceRegistryException {
|
||||||
|
if(element instanceof OVertex) {
|
||||||
|
return ElementManagementUtility.getEntityManagement(workingContext, orientGraph, (OVertex) element);
|
||||||
|
} else if(element instanceof OEdge) {
|
||||||
|
return ElementManagementUtility.getRelationManagement(workingContext, orientGraph, (OEdge) element);
|
||||||
|
}
|
||||||
|
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
|
||||||
|
Entity.NAME, Relation.NAME));
|
||||||
|
}
|
||||||
|
|
||||||
public static Map<UUID,JsonNode> addToContextNoPropagationConstraint(Map<UUID, JsonNode> expectedInstances, UUID contextUUID, boolean dryRun)
|
public static Map<UUID,JsonNode> addToContextNoPropagationConstraint(Map<UUID, JsonNode> expectedInstances, UUID contextUUID, boolean dryRun)
|
||||||
throws NotFoundException, ContextException, ResourceRegistryException {
|
throws NotFoundException, ContextException, ResourceRegistryException {
|
||||||
Set<UUID> instances = expectedInstances.keySet();
|
Set<UUID> instances = expectedInstances.keySet();
|
||||||
|
@ -32,11 +101,11 @@ public class ERManagementUtility {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
|
|
||||||
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
|
InstanceEnvironment targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
|
||||||
|
|
||||||
// Map<UUID, JsonNode> enforcedInstances = new HashMap<>();
|
// Map<UUID, JsonNode> enforcedInstances = new HashMap<>();
|
||||||
|
|
||||||
|
@ -44,16 +113,16 @@ public class ERManagementUtility {
|
||||||
Set<UUID> uuids = expectedInstances.keySet();
|
Set<UUID> uuids = expectedInstances.keySet();
|
||||||
for(UUID uuid : uuids) {
|
for(UUID uuid : uuids) {
|
||||||
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
|
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
|
||||||
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> elementManagement = ERManagementUtility.getERManagement(type);
|
||||||
elementManagement.setWorkingContext(adminSecurityContext);
|
elementManagement.setWorkingEnvironment(adminEnvironment);
|
||||||
elementManagement.setODatabaseDocument(oDatabaseDocument);
|
elementManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
elementManagement.setUUID(uuid);
|
elementManagement.setUUID(uuid);
|
||||||
elementManagement.setElementType(type);
|
elementManagement.setElementType(type);
|
||||||
elementManagement.setDryRun(dryRun);
|
elementManagement.setDryRun(dryRun);
|
||||||
|
|
||||||
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
|
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
|
||||||
// enforcedInstances.putAll(((ERManagement) elementManagement).internalAddToContext(targetSecurityContext));
|
// enforcedInstances.putAll(((ERManagement) elementManagement).internalAddToContext(targetInstanceEnvironment));
|
||||||
((ERManagement) elementManagement).setTargetSecurityContext(targetSecurityContext);
|
((ERManagement) elementManagement).setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
((ERManagement) elementManagement).internalAddToContext();
|
((ERManagement) elementManagement).internalAddToContext();
|
||||||
instancesManagement.put(uuid, elementManagement);
|
instancesManagement.put(uuid, elementManagement);
|
||||||
}
|
}
|
||||||
|
@ -61,7 +130,7 @@ public class ERManagementUtility {
|
||||||
/*
|
/*
|
||||||
for(UUID uuid : uuids) {
|
for(UUID uuid : uuids) {
|
||||||
ElementManagement<?,?> elementManagement = instancesManagement.get(uuid);
|
ElementManagement<?,?> elementManagement = instancesManagement.get(uuid);
|
||||||
((ERManagement) elementManagement).contextSanityCheck(targetSecurityContext, expectedInstances);
|
((ERManagement) elementManagement).contextSanityCheck(targetInstanceEnvironment, expectedInstances);
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@ -113,25 +182,25 @@ public class ERManagementUtility {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
|
|
||||||
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
|
InstanceEnvironment targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
|
||||||
|
|
||||||
//Map<UUID, JsonNode> enforcedInstances = new HashMap<>();
|
//Map<UUID, JsonNode> enforcedInstances = new HashMap<>();
|
||||||
|
|
||||||
Map<UUID, ElementManagement<?,?>> instancesManagement = new HashMap<>();
|
Map<UUID, ElementManagement<?,?>> instancesManagement = new HashMap<>();
|
||||||
for(UUID uuid : expectedInstances.keySet()) {
|
for(UUID uuid : expectedInstances.keySet()) {
|
||||||
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
|
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
|
||||||
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> elementManagement = ERManagementUtility.getERManagement(type);
|
||||||
elementManagement.setWorkingContext(adminSecurityContext);
|
elementManagement.setWorkingEnvironment(adminEnvironment);
|
||||||
elementManagement.setODatabaseDocument(oDatabaseDocument);
|
elementManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
elementManagement.setUUID(uuid);
|
elementManagement.setUUID(uuid);
|
||||||
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
|
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
|
||||||
elementManagement.setDryRun(dryRun);
|
elementManagement.setDryRun(dryRun);
|
||||||
//enforcedInstances.putAll(((ERManagement) elementManagement).internalRemoveFromContext(targetSecurityContext));
|
//enforcedInstances.putAll(((ERManagement) elementManagement).internalRemoveFromContext(targetInstanceEnvironment));
|
||||||
((ERManagement) elementManagement).setTargetSecurityContext(targetSecurityContext);
|
((ERManagement) elementManagement).setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
((ERManagement) elementManagement).internalRemoveFromContext();
|
((ERManagement) elementManagement).internalRemoveFromContext();
|
||||||
instancesManagement.put(uuid, elementManagement);
|
instancesManagement.put(uuid, elementManagement);
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,7 +13,7 @@ public enum Operation {
|
||||||
ADD_TO_CONTEXT,
|
ADD_TO_CONTEXT,
|
||||||
REMOVE_FROM_CONTEXT,
|
REMOVE_FROM_CONTEXT,
|
||||||
QUERY(true),
|
QUERY(true),
|
||||||
// GET_METADATA e.g. getinstanceContexts
|
// GET_METADATA e.g. getInstanceContexts
|
||||||
GET_METADATA(true);
|
GET_METADATA(true);
|
||||||
|
|
||||||
private final boolean safe;
|
private final boolean safe;
|
||||||
|
|
|
@ -12,6 +12,9 @@ import org.gcube.informationsystem.utils.TypeUtility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class SharingOperationValidator implements OperationValidator {
|
public class SharingOperationValidator implements OperationValidator {
|
||||||
|
|
||||||
protected static Logger logger = LoggerFactory.getLogger(SharingOperationValidator.class);
|
protected static Logger logger = LoggerFactory.getLogger(SharingOperationValidator.class);
|
||||||
|
|
|
@ -1,19 +1,19 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.instances.model.entities;
|
package org.gcube.informationsystem.resourceregistry.instances.model.entities;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import javax.ws.rs.ForbiddenException;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ArrayNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
|
import org.gcube.informationsystem.contexts.reference.ContextState;
|
||||||
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Entity;
|
import org.gcube.informationsystem.model.reference.entities.Entity;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Facet;
|
import org.gcube.informationsystem.model.reference.entities.Facet;
|
||||||
|
@ -26,26 +26,27 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
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.entities.EntityAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
|
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.api.exceptions.types.SchemaViolationException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
|
||||||
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
|
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.ODirection;
|
||||||
import com.orientechnologies.orient.core.record.OEdge;
|
import com.orientechnologies.orient.core.record.OEdge;
|
||||||
import com.orientechnologies.orient.core.record.OElement;
|
import com.orientechnologies.orient.core.record.OElement;
|
||||||
|
@ -62,18 +63,18 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
/**
|
/**
|
||||||
* The source context of an addToContex
|
* The source context of an addToContex
|
||||||
*/
|
*/
|
||||||
protected SecurityContext sourceSecurityContext;
|
protected InstanceEnvironment sourceInstanceEnvironment;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The target context of an addToContex/RemoveFromContext
|
* The target context of an addToContex/RemoveFromContext
|
||||||
*/
|
*/
|
||||||
protected SecurityContext targetSecurityContext;
|
protected InstanceEnvironment targetInstanceEnvironment;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* By the default the system honour the propagation constraints
|
* By default the system honour the propagation constraints
|
||||||
* so this variable is initialised as true.
|
* so this variable is initialised as true.
|
||||||
*
|
*
|
||||||
* To revert a previous operation or for particular a maintenance
|
* To revert a previous operation or for a particular maintenance
|
||||||
* we could request to the service do not honour the propagation
|
* we could request to the service do not honour the propagation
|
||||||
* constraints but under certain conditions and with some limitation
|
* constraints but under certain conditions and with some limitation
|
||||||
* only.
|
* only.
|
||||||
|
@ -102,23 +103,23 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
protected boolean honourPropagationConstraintsInContextSharing;
|
protected boolean honourPropagationConstraintsInContextSharing;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setSourceSecurityContext(SecurityContext sourceSecurityContext) {
|
public void setSourceInstanceEnvironment(InstanceEnvironment source) {
|
||||||
this.sourceSecurityContext = sourceSecurityContext;
|
this.sourceInstanceEnvironment = source;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SecurityContext getSourceSecurityContext() {
|
public InstanceEnvironment getSourceInstanceEnvironment() {
|
||||||
return sourceSecurityContext;
|
return sourceInstanceEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setTargetSecurityContext(SecurityContext targetSecurityContext) {
|
public void setTargetInstanceEnvironment(InstanceEnvironment target) {
|
||||||
this.targetSecurityContext = targetSecurityContext;
|
this.targetInstanceEnvironment = target;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SecurityContext getTargetSecurityContext() {
|
public InstanceEnvironment getTargetInstanceEnvironment() {
|
||||||
return sourceSecurityContext;
|
return sourceInstanceEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -154,14 +155,30 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
this.relationManagements = new HashMap<>();
|
this.relationManagements = new HashMap<>();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* By the default the system honour the propagation constraints
|
* By default the system honor the propagation constraints
|
||||||
* so this variable is initialised as true.
|
* so this variable is initialized as true.
|
||||||
*/
|
*/
|
||||||
this.honourPropagationConstraintsInContextSharing = true;
|
this.honourPropagationConstraintsInContextSharing = true;
|
||||||
|
|
||||||
this.skipped = false;
|
this.skipped = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
|
if(workingEnvironment == null) {
|
||||||
|
workingEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
|
Context context = ServerContextCache.getInstance().getFullInfoContextByUUID(workingEnvironment.getUUID());
|
||||||
|
String state = context.getState();
|
||||||
|
if(state.compareTo(ContextState.ACTIVE.getState())!=0) {
|
||||||
|
Set<String> allowedRoles = workingEnvironment.getAllowedRoles();
|
||||||
|
if(!workingEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new ForbiddenException("You are not allowed to operate in non " + ContextState.ACTIVE.getState() + " Contexts. Allowed roles are " + allowedRoles);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return workingEnvironment;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public OVertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
public OVertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
|
@ -195,7 +212,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
String id = edge.getIdentity().toString();
|
String id = edge.getIdentity().toString();
|
||||||
RelationManagement<?,?> relationManagement = relationManagements.get(id);
|
RelationManagement<?,?> relationManagement = relationManagements.get(id);
|
||||||
if(relationManagement == null) {
|
if(relationManagement == null) {
|
||||||
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
|
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
}
|
}
|
||||||
return relationManagement;
|
return relationManagement;
|
||||||
|
@ -298,14 +315,14 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
|
|
||||||
protected void reallyAddToContext()
|
protected void reallyAddToContext()
|
||||||
throws ContextException, ResourceRegistryException {
|
throws ContextException, ResourceRegistryException {
|
||||||
if(!forceAddToContext && !sourceSecurityContext.isElementInContext(getElement())) {
|
if(!forceAddToContext && !sourceInstanceEnvironment.isElementInContext(getElement())) {
|
||||||
// The element in not in the source security context. It will be skipped
|
// The element in not in the source security context. It will be skipped
|
||||||
skipped = true;
|
skipped = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* DO NOT UNCOMMENT
|
* DO NOT UNCOMMENT
|
||||||
|
@ -320,8 +337,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
|
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
|
||||||
relationManagement.setDryRun(dryRun);
|
relationManagement.setDryRun(dryRun);
|
||||||
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
relationManagement.setSourceSecurityContext(sourceSecurityContext);
|
relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
relationManagement.setTargetSecurityContext(targetSecurityContext);
|
relationManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
relationManagement.internalAddToContext();
|
relationManagement.internalAddToContext();
|
||||||
affectedInstances.putAll(relationManagement.getAffectedInstances());
|
affectedInstances.putAll(relationManagement.getAffectedInstances());
|
||||||
}
|
}
|
||||||
|
@ -344,7 +361,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
"Error Adding " + typeName + " to " + targetSecurityContext.toString(), e.getCause());
|
"Error Adding " + typeName + " to " + targetInstanceEnvironment.toString(), e.getCause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -354,13 +371,13 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName);
|
logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName);
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
workingContext = ContextUtility.getAdminSecurityContext();
|
workingEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
|
||||||
sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
|
sourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
|
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
|
||||||
|
|
||||||
internalAddToContext();
|
internalAddToContext();
|
||||||
|
|
||||||
|
@ -407,14 +424,14 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
"Error Removing " + typeName + " from " + targetSecurityContext.toString(), e.getCause());
|
"Error Removing " + typeName + " from " + targetInstanceEnvironment.toString(), e.getCause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void reallyRemoveFromContext()
|
protected void reallyRemoveFromContext()
|
||||||
throws ContextException, ResourceRegistryException {
|
throws ContextException, ResourceRegistryException {
|
||||||
|
|
||||||
if(!targetSecurityContext.isElementInContext(getElement())) {
|
if(!targetInstanceEnvironment.isElementInContext(getElement())) {
|
||||||
// The element in not in the source security context. It will be skipped
|
// The element in not in the source security context. It will be skipped
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -426,21 +443,21 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
|
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
|
||||||
relationManagement.setDryRun(dryRun);
|
relationManagement.setDryRun(dryRun);
|
||||||
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
// Not needed relationManagement.setSourceSecurityContext(sourceSecurityContext);
|
// Not needed relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
relationManagement.setTargetSecurityContext(targetSecurityContext);
|
relationManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
relationManagement.internalRemoveFromContext();
|
relationManagement.internalRemoveFromContext();
|
||||||
addToRelationManagements(relationManagement);
|
addToRelationManagements(relationManagement);
|
||||||
affectedInstances.putAll(relationManagement.getAffectedInstances());
|
affectedInstances.putAll(relationManagement.getAffectedInstances());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.removeElement(getElement(), oDatabaseDocument);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* DO NOT UNCOMMENT
|
* DO NOT UNCOMMENT
|
||||||
* the instance is added internalAddToContext() function after
|
|
||||||
* the update of Metadata i.e. modifiedBy, lastUpdateTime
|
|
||||||
* affectedInstances.put(uuid, serializeSelfOnly());
|
* affectedInstances.put(uuid, serializeSelfOnly());
|
||||||
|
* the instance is added in internalAddToContext() function after
|
||||||
|
* the update of Metadata i.e. modifiedBy, lastUpdateTime
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -451,13 +468,13 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
|
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
workingContext = ContextUtility.getAdminSecurityContext();
|
workingEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
|
||||||
// Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
|
// Not needed sourcesourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
|
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
|
||||||
|
|
||||||
internalRemoveFromContext();
|
internalRemoveFromContext();
|
||||||
|
|
||||||
|
@ -495,212 +512,34 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
ArrayNode arrayNode = objectMapper.createArrayNode();
|
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);
|
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
|
||||||
for(ODocument vertex : iterable) {
|
for(ODocument vertex : iterable) {
|
||||||
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
|
if(++position < offset) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
|
||||||
oDatabaseDocument, (OVertex) vertex);
|
oDatabaseDocument, (OVertex) vertex);
|
||||||
try {
|
try {
|
||||||
entityManagement.setAsEntryPoint();
|
entityManagement.setAsEntryPoint();
|
||||||
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
|
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
|
||||||
arrayNode.add(jsonNode);
|
arrayNode.add(jsonNode);
|
||||||
|
if(limit > 0 && ++count >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
||||||
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
return objectMapper.writeValueAsString(arrayNode);
|
|
||||||
} catch(JsonProcessingException e) {
|
|
||||||
throw new ResourceRegistryException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean propertyMatchRequestedValue(OVertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
|
|
||||||
return requestedValue.compareTo(instanceValue.toString())==0;
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
OClass oClass = ElementManagement.getOClass(v);
|
|
||||||
OProperty oProperty = oClass.getProperty(key);
|
|
||||||
if(oProperty==null){
|
|
||||||
// It is an additional property
|
|
||||||
return requestedValue.compareTo(instanceValue.toString())==0;
|
|
||||||
}
|
|
||||||
OType oType = oProperty.getType();
|
|
||||||
switch (oType) {
|
|
||||||
case BOOLEAN:
|
|
||||||
Boolean requested = Boolean.valueOf(requestedValue.toLowerCase());
|
|
||||||
return requested == (Boolean) instanceValue;
|
|
||||||
|
|
||||||
case STRING:
|
|
||||||
return requestedValue.compareTo((String) instanceValue)==0;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
|
|
||||||
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
|
|
||||||
*/
|
|
||||||
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
|
|
||||||
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
ArrayNode arrayNode = objectMapper.createArrayNode();
|
|
||||||
|
|
||||||
Iterable<?> references = null;
|
|
||||||
|
|
||||||
if(referenceUUID != null) {
|
|
||||||
OElement element = null;
|
|
||||||
try {
|
|
||||||
element = ElementManagementUtility.getAnyElementByUUID(oDatabaseDocument, referenceUUID);
|
|
||||||
}catch (ResourceRegistryException e) {
|
|
||||||
String error = String.format("No instace with UUID %s exists", referenceUUID.toString());
|
|
||||||
throw new InvalidQueryException(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(element instanceof OVertex) {
|
|
||||||
EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
|
|
||||||
oDatabaseDocument, (OVertex) element);
|
|
||||||
|
|
||||||
String elementType = entityManagement.getTypeName();
|
|
||||||
if(elementType.compareTo(referenceType) != 0) {
|
|
||||||
if(polymorphic && getOClass().isSubClassOf(referenceType)) {
|
|
||||||
// OK
|
|
||||||
} else {
|
|
||||||
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
|
|
||||||
throw new InvalidQueryException(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
List<OVertex> vertexes = new ArrayList<>();
|
|
||||||
vertexes.add((OVertex) element);
|
|
||||||
references = vertexes;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
|
|
||||||
throw new InvalidQueryException(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
references = oDatabaseDocument.browseClass(referenceType, polymorphic);
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<ORID> analysed = new HashSet<>();
|
|
||||||
|
|
||||||
for(Object r : references) {
|
|
||||||
OVertex v = (OVertex) r;
|
|
||||||
|
|
||||||
boolean skip = false;
|
|
||||||
// checking if the constraints are satisfied
|
|
||||||
for(String key : constraint.keySet()) {
|
|
||||||
String value = constraint.get(key);
|
|
||||||
Object o = v.getProperty(key);
|
|
||||||
if(value==null) {
|
|
||||||
if(o==null) {
|
|
||||||
//ok
|
|
||||||
}else {
|
|
||||||
skip = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}else {
|
|
||||||
if(o==null) {
|
|
||||||
// The vertex has not a required property to be tested
|
|
||||||
// or the property is null
|
|
||||||
skip = true;
|
|
||||||
break;
|
|
||||||
}else {
|
|
||||||
skip = !propertyMatchRequestedValue(v, key, value, o);
|
|
||||||
if(skip) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if(skip) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
List<ODirection> directions = new ArrayList<>();
|
|
||||||
if(direction==ODirection.BOTH) {
|
|
||||||
directions.add(ODirection.IN);
|
|
||||||
directions.add(ODirection.OUT);
|
|
||||||
}else {
|
|
||||||
directions.add(direction);
|
|
||||||
}
|
|
||||||
|
|
||||||
for(ODirection d : directions) {
|
|
||||||
|
|
||||||
Iterable<OEdge> edges = v.getEdges(d.opposite(), relationType);
|
|
||||||
for(OEdge edge : edges) {
|
|
||||||
OVertex vertex = edge.getVertex(d);
|
|
||||||
|
|
||||||
ORID vertexORID = vertex.getIdentity();
|
|
||||||
|
|
||||||
if(analysed.contains(vertexORID)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
analysed.add(vertexORID);
|
|
||||||
|
|
||||||
if(v.getIdentity().compareTo(vertexORID) == 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
OClass oClass = ElementManagementUtility.getOClass(vertex);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* If the requested type (i.e. elementType)
|
|
||||||
* differs form the resulting type (i.e. oClass.getName())
|
|
||||||
* we need to evaluate if polymorphism is requested and
|
|
||||||
* if the resulting type is a subclass of the requested type
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
if(oClass.getName().compareTo(typeName)!=0) {
|
|
||||||
if(polymorphic && oClass.isSubClassOf(typeName)) {
|
|
||||||
// OK
|
|
||||||
} else {
|
|
||||||
// excluding from results
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
|
|
||||||
oDatabaseDocument, vertex);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
JsonNode jsonNode;
|
|
||||||
if(includeRelationInResult) {
|
|
||||||
RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
|
|
||||||
oDatabaseDocument, edge);
|
|
||||||
jsonNode = relationManagement.serializeAsJsonNode();
|
|
||||||
}else {
|
|
||||||
jsonNode = entityManagement.serializeAsJsonNode();
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
entityManagement.setAsEntryPoint();
|
|
||||||
JsonNode node = entityManagement.serializeAsJsonNode();
|
|
||||||
|
|
||||||
arrayNode.add(node);
|
|
||||||
} catch(ResourceRegistryException e) {
|
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
|
||||||
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return objectMapper.writeValueAsString(arrayNode);
|
return objectMapper.writeValueAsString(arrayNode);
|
||||||
|
@ -709,7 +548,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
|
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID,
|
||||||
ODirection direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
ODirection direction, boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
ArrayNode arrayNode = objectMapper.createArrayNode();
|
ArrayNode arrayNode = objectMapper.createArrayNode();
|
||||||
|
@ -718,80 +557,92 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
constraint.put(Entity.ID_PROPERTY, referenceUUID.toString());
|
constraint.put(Entity.ID_PROPERTY, referenceUUID.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO check types
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
|
* SELECT FROM (
|
||||||
* FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
|
* TRAVERSE outV('EService'), inE('isIdentifiedBy') FROM (
|
||||||
|
* SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'
|
||||||
|
* )
|
||||||
|
* )
|
||||||
*
|
*
|
||||||
* WHERE type='EService' // Only is not polymorphic
|
* WHERE @class INSTANCEOF 'EService' // if polymorphic is true
|
||||||
|
*
|
||||||
|
* WHERE @class='EService' // if polymorphic is false
|
||||||
*/
|
*/
|
||||||
|
|
||||||
StringBuilder selectStringBuilder = new StringBuilder("SELECT FROM (TRAVERSE ");
|
StringBuffer selectStringBuffer = new StringBuffer();
|
||||||
selectStringBuilder.append(direction.name().toLowerCase());
|
selectStringBuffer.append("SELECT FROM (TRAVERSE ");
|
||||||
selectStringBuilder.append("E('");
|
selectStringBuffer.append(direction.name().toLowerCase());
|
||||||
selectStringBuilder.append(relationType);
|
selectStringBuffer.append("V('");
|
||||||
selectStringBuilder.append("'), ");
|
selectStringBuffer.append(typeName);
|
||||||
selectStringBuilder.append(direction.opposite().name().toLowerCase());
|
selectStringBuffer.append("')");
|
||||||
selectStringBuilder.append("V('");
|
|
||||||
selectStringBuilder.append(typeName);
|
selectStringBuffer.append(", ");
|
||||||
selectStringBuilder.append("') FROM (SELECT FROM ");
|
|
||||||
selectStringBuilder.append(referenceType);
|
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;
|
boolean first = true;
|
||||||
for(String key : constraint.keySet()) {
|
for(String key : constraint.keySet()) {
|
||||||
if(first) {
|
if(first) {
|
||||||
selectStringBuilder.append(" WHERE ");
|
selectStringBuffer.append(" WHERE ");
|
||||||
first = false;
|
first = false;
|
||||||
} else {
|
} else {
|
||||||
selectStringBuilder.append(" AND ");
|
selectStringBuffer.append(" AND ");
|
||||||
}
|
}
|
||||||
selectStringBuilder.append(key);
|
selectStringBuffer.append(key);
|
||||||
selectStringBuilder.append("=");
|
selectStringBuffer.append("=");
|
||||||
String value = constraint.get(key).trim();
|
String value = constraint.get(key).trim();
|
||||||
selectStringBuilder.append("'");
|
selectStringBuffer.append("'");
|
||||||
selectStringBuilder.append(value);
|
selectStringBuffer.append(value);
|
||||||
selectStringBuilder.append("'");
|
selectStringBuffer.append("'");
|
||||||
}
|
}
|
||||||
selectStringBuilder.append(" ))");
|
selectStringBuffer.append(" ))");
|
||||||
|
|
||||||
if(!polymorphic) {
|
|
||||||
selectStringBuilder.append(" WHERE type='");
|
selectStringBuffer.append(" WHERE @class");
|
||||||
selectStringBuilder.append(typeName);
|
if(polymorphic) {
|
||||||
selectStringBuilder.append("'");
|
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);
|
logger.trace(select);
|
||||||
|
|
||||||
OResultSet resultSet = oDatabaseDocument.command(select,new HashMap<>());
|
OResultSet resultSet = oDatabaseDocument.command(select, map);
|
||||||
|
|
||||||
while(resultSet.hasNext()) {
|
while(resultSet.hasNext()) {
|
||||||
OResult oResult = resultSet.next();
|
OResult oResult = resultSet.next();
|
||||||
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
|
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
|
||||||
|
|
||||||
if(polymorphic) {
|
|
||||||
OClass oClass = null;
|
|
||||||
try {
|
|
||||||
if(element instanceof OEdge) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
oClass = ElementManagementUtility.getOClass(element);
|
|
||||||
} catch(Exception e) {
|
|
||||||
String error = String.format("Unable to detect type of %s. %s", element.toString(),
|
|
||||||
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
|
||||||
logger.error(error, e);
|
|
||||||
throw new ResourceRegistryException(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(oClass.isSubClassOf(typeName)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
OVertex vertex = (OVertex) element;
|
OVertex vertex = (OVertex) element;
|
||||||
|
|
||||||
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
|
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
|
||||||
oDatabaseDocument, vertex);
|
oDatabaseDocument, vertex);
|
||||||
try {
|
try {
|
||||||
if(constraint.containsKey(Entity.ID_PROPERTY)) {
|
if(constraint.containsKey(Entity.ID_PROPERTY)) {
|
||||||
|
@ -816,17 +667,13 @@ 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,
|
public String query(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
|
||||||
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
|
||||||
|
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
workingContext = ContextUtility.getAdminSecurityContext();
|
workingEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
setOperation(Operation.QUERY);
|
setOperation(Operation.QUERY);
|
||||||
|
@ -882,7 +729,6 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// return reallyQuery(relationType, referenceType, referenceUUID, direction, polymorphic, constraint, includeRelationInResult);
|
|
||||||
return reallyQuery(relationType, referenceType, referenceUUID, direction, polymorphic, constraint);
|
return reallyQuery(relationType, referenceType, referenceUUID, direction, polymorphic, constraint);
|
||||||
|
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
|
|
|
@ -11,7 +11,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.face
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.facet.FacetAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.facet.FacetAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.facet.FacetNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.facet.FacetNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.types.reference.entities.FacetType;
|
import org.gcube.informationsystem.types.reference.entities.FacetType;
|
||||||
|
@ -74,8 +74,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
|
||||||
consistsOfManagement = new ConsistsOfManagement();
|
consistsOfManagement = new ConsistsOfManagement();
|
||||||
consistsOfManagement.setElement(oEdge);
|
consistsOfManagement.setElement(oEdge);
|
||||||
consistsOfManagement.setTargetEntityManagement(this);
|
consistsOfManagement.setTargetEntityManagement(this);
|
||||||
// Not needed consistsOfManagement.setSourceSecurityContext(sourceSecurityContext);
|
// Not needed consistsOfManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
consistsOfManagement.setTargetSecurityContext(targetSecurityContext);
|
consistsOfManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
|
|
||||||
|
|
||||||
affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance());
|
affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance());
|
||||||
|
@ -83,8 +83,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
|
||||||
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
|
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
|
||||||
resourceManagement = new ResourceManagement();
|
resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setElement(oVertex);
|
resourceManagement.setElement(oVertex);
|
||||||
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
|
// Not needed resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
resourceManagement.setTargetSecurityContext(targetSecurityContext);
|
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
resourceManagement.addToRelationManagements(consistsOfManagement);
|
resourceManagement.addToRelationManagements(consistsOfManagement);
|
||||||
}
|
}
|
||||||
super.reallyRemoveFromContext();
|
super.reallyRemoveFromContext();
|
||||||
|
@ -125,7 +125,7 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
|
||||||
// an update to the Facet only modify the Facet properties, no need to check the source resource
|
// an update to the Facet only modify the Facet properties, no need to check the source resource
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ODatabaseDocument targetSecurityContextODatabaseDocument = null;
|
ODatabaseDocument targetInstanceEnvironmentODatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
if(resourceManagement==null) {
|
if(resourceManagement==null) {
|
||||||
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
|
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
|
||||||
|
@ -134,24 +134,24 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
|
||||||
}
|
}
|
||||||
switch (operation) {
|
switch (operation) {
|
||||||
case CREATE: case DELETE:
|
case CREATE: case DELETE:
|
||||||
resourceManagement.setWorkingContext(getWorkingContext());
|
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
resourceManagement.setODatabaseDocument(oDatabaseDocument);
|
resourceManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case ADD_TO_CONTEXT:
|
case ADD_TO_CONTEXT:
|
||||||
resourceManagement.setSourceSecurityContext(sourceSecurityContext);
|
resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
resourceManagement.setTargetSecurityContext(targetSecurityContext);
|
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
resourceManagement.setWorkingContext(targetSecurityContext);
|
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
|
||||||
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument);
|
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case REMOVE_FROM_CONTEXT:
|
case REMOVE_FROM_CONTEXT:
|
||||||
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
|
// Not needed resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
resourceManagement.setTargetSecurityContext(targetSecurityContext);
|
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
resourceManagement.setWorkingContext(targetSecurityContext);
|
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
|
||||||
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument);
|
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
@ -168,8 +168,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
|
||||||
}catch (Exception e) {
|
}catch (Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}finally {
|
}finally {
|
||||||
if(targetSecurityContextODatabaseDocument!=null) {
|
if(targetInstanceEnvironmentODatabaseDocument!=null) {
|
||||||
targetSecurityContextODatabaseDocument.close();
|
targetInstanceEnvironmentODatabaseDocument.close();
|
||||||
oDatabaseDocument.activateOnCurrentThread();
|
oDatabaseDocument.activateOnCurrentThread();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -187,7 +187,7 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
|
||||||
}
|
}
|
||||||
|
|
||||||
public OVertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
|
public OVertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
|
||||||
if(entryPoint && operation == Operation.CREATE) {
|
if(entryPoint) {
|
||||||
throw new SchemaViolationException("You cannot create a stand alone Facet");
|
throw new SchemaViolationException("You cannot create a stand alone Facet");
|
||||||
}
|
}
|
||||||
return super.internalCreate();
|
return super.internalCreate();
|
||||||
|
|
|
@ -23,9 +23,9 @@ 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.entities.resource.ResourceNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
||||||
|
@ -155,7 +155,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for(JsonNode consistOfJsonNode : jsonNodeArray) {
|
for(JsonNode consistOfJsonNode : jsonNodeArray) {
|
||||||
ConsistsOfManagement com = new ConsistsOfManagement();
|
ConsistsOfManagement com = new ConsistsOfManagement();
|
||||||
com.setWorkingContext(getWorkingContext());
|
com.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
com.setODatabaseDocument(oDatabaseDocument);
|
com.setODatabaseDocument(oDatabaseDocument);
|
||||||
com.setJsonNode(consistOfJsonNode);
|
com.setJsonNode(consistOfJsonNode);
|
||||||
com.setSourceEntityManagement(this);
|
com.setSourceEntityManagement(this);
|
||||||
|
@ -169,7 +169,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for(JsonNode relationJsonNode : jsonNodeArray) {
|
for(JsonNode relationJsonNode : jsonNodeArray) {
|
||||||
IsRelatedToManagement irtm = new IsRelatedToManagement();
|
IsRelatedToManagement irtm = new IsRelatedToManagement();
|
||||||
irtm.setWorkingContext(getWorkingContext());
|
irtm.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
irtm.setODatabaseDocument(oDatabaseDocument);
|
irtm.setODatabaseDocument(oDatabaseDocument);
|
||||||
irtm.setJsonNode(relationJsonNode);
|
irtm.setJsonNode(relationJsonNode);
|
||||||
irtm.setSourceEntityManagement(this);
|
irtm.setSourceEntityManagement(this);
|
||||||
|
@ -191,7 +191,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for(JsonNode relationJsonNode : jsonNodeArray) {
|
for(JsonNode relationJsonNode : jsonNodeArray) {
|
||||||
ConsistsOfManagement com = new ConsistsOfManagement();
|
ConsistsOfManagement com = new ConsistsOfManagement();
|
||||||
com.setWorkingContext(getWorkingContext());
|
com.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
com.setODatabaseDocument(oDatabaseDocument);
|
com.setODatabaseDocument(oDatabaseDocument);
|
||||||
com.setJsonNode(relationJsonNode);
|
com.setJsonNode(relationJsonNode);
|
||||||
com.internalCreateOrUdate();
|
com.internalCreateOrUdate();
|
||||||
|
@ -204,7 +204,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
JsonNode jsonNodeArray = jsonNode.get(property);
|
JsonNode jsonNodeArray = jsonNode.get(property);
|
||||||
for(JsonNode relationJsonNode : jsonNodeArray) {
|
for(JsonNode relationJsonNode : jsonNodeArray) {
|
||||||
IsRelatedToManagement irtm = new IsRelatedToManagement();
|
IsRelatedToManagement irtm = new IsRelatedToManagement();
|
||||||
irtm.setWorkingContext(getWorkingContext());
|
irtm.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
irtm.setODatabaseDocument(oDatabaseDocument);
|
irtm.setODatabaseDocument(oDatabaseDocument);
|
||||||
irtm.setJsonNode(relationJsonNode);
|
irtm.setJsonNode(relationJsonNode);
|
||||||
irtm.internalUpdate();
|
irtm.internalUpdate();
|
||||||
|
@ -238,7 +238,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
}
|
}
|
||||||
if(relationManagement != null) {
|
if(relationManagement != null) {
|
||||||
relationManagement.setWorkingContext(getWorkingContext());
|
relationManagement.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
relationManagement.setODatabaseDocument(oDatabaseDocument);
|
relationManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
relationManagement.setElement(edge);
|
relationManagement.setElement(edge);
|
||||||
relationManagement.internalDelete();
|
relationManagement.internalDelete();
|
||||||
|
@ -262,13 +262,13 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
protected void reallyAddToContext()
|
protected void reallyAddToContext()
|
||||||
throws ContextException, ResourceRegistryException {
|
throws ContextException, ResourceRegistryException {
|
||||||
|
|
||||||
if(!forceAddToContext && !sourceSecurityContext.isElementInContext(getElement())) {
|
if(!forceAddToContext && !sourceInstanceEnvironment.isElementInContext(getElement())) {
|
||||||
// The element in not in the source security context. It will be skipped
|
// The element in not in the source security context. It will be skipped
|
||||||
skipped = true;
|
skipped = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* DO NOT UNCOMMENT
|
* DO NOT UNCOMMENT
|
||||||
|
@ -286,8 +286,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
|
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
|
||||||
relationManagement.setDryRun(dryRun);
|
relationManagement.setDryRun(dryRun);
|
||||||
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
relationManagement.setSourceSecurityContext(sourceSecurityContext);
|
relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
relationManagement.setTargetSecurityContext(targetSecurityContext);
|
relationManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
relationManagement.internalAddToContext();
|
relationManagement.internalAddToContext();
|
||||||
affectedInstances.putAll(relationManagement.getAffectedInstances());
|
affectedInstances.putAll(relationManagement.getAffectedInstances());
|
||||||
if(relationManagement instanceof ConsistsOfManagement) {
|
if(relationManagement instanceof ConsistsOfManagement) {
|
||||||
|
@ -317,7 +317,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
public String all(boolean polymorphic) throws ResourceRegistryException {
|
public String all(boolean polymorphic) throws ResourceRegistryException {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
|
||||||
return reallyGetAll(polymorphic);
|
return reallyGetAll(polymorphic);
|
||||||
} catch(ResourceRegistryException e) {
|
} catch(ResourceRegistryException e) {
|
||||||
throw e;
|
throw e;
|
||||||
|
@ -452,17 +452,19 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
case ADD_TO_CONTEXT:
|
case ADD_TO_CONTEXT:
|
||||||
if(relationManagement == null) {
|
if(relationManagement == null) {
|
||||||
try {
|
try {
|
||||||
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge);
|
relationManagement = ElementManagementUtility.getRelationManagement(targetInstanceEnvironment, oDatabaseDocument, edge);
|
||||||
relationManagement.setSourceSecurityContext(sourceSecurityContext);
|
relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
}catch (AvailableInAnotherContextException e) {
|
}catch (AvailableInAnotherContextException e) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}else {
|
}else {
|
||||||
/*
|
/*
|
||||||
* The relation has been already managed in add to context so it has been added to the targetSecurityContext.
|
* The relation has been already managed in add to context
|
||||||
* The transaction is not yet committed so we need to consider as part of context without trying to load from
|
* so it has been added to the targetInstanceEnvironment.
|
||||||
* DB with dedicated security connection.
|
* The transaction is not yet committed so we need
|
||||||
|
* to consider as part of context without trying
|
||||||
|
* to load from DB with dedicated security connection.
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
@ -470,12 +472,13 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
case REMOVE_FROM_CONTEXT:
|
case REMOVE_FROM_CONTEXT:
|
||||||
if(relationManagement != null) {
|
if(relationManagement != null) {
|
||||||
/*
|
/*
|
||||||
* The relation has been removed from the targetContext but it has not been committed.
|
* The relation has been removed from the targetContext
|
||||||
* We must consider as not available in targetSecurityContext
|
* but it has not been committed.
|
||||||
|
* We must consider as not available in targetInstanceEnvironment
|
||||||
*/
|
*/
|
||||||
continue;
|
continue;
|
||||||
}else {
|
}else {
|
||||||
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge);
|
relationManagement = ElementManagementUtility.getRelationManagement(targetInstanceEnvironment, oDatabaseDocument, edge);
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
@ -483,7 +486,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
case CREATE: case UPDATE:
|
case CREATE: case UPDATE:
|
||||||
|
|
||||||
if(relationManagement == null) {
|
if(relationManagement == null) {
|
||||||
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
|
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
|
||||||
relationManagements.put(id, relationManagement);
|
relationManagements.put(id, relationManagement);
|
||||||
/*
|
/*
|
||||||
* Here the AvailableInAnotherContextException should not occur because the connection to the DB is with the
|
* Here the AvailableInAnotherContextException should not occur because the connection to the DB is with the
|
||||||
|
@ -504,8 +507,9 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
|
||||||
}else {
|
}else {
|
||||||
if(operation == Operation.REMOVE_FROM_CONTEXT && relationManagement!=null) {
|
if(operation == Operation.REMOVE_FROM_CONTEXT && relationManagement!=null) {
|
||||||
/*
|
/*
|
||||||
* The relation has been removed from the targetContext but it has not been committed.
|
* The relation has been removed from the targetContext
|
||||||
* We must consider as not available in targetSecurityContext
|
* but it has not been committed.
|
||||||
|
* We must consider as not available in targetInstanceEnvironment
|
||||||
*/
|
*/
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,7 +16,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.con
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.consistsof.ConsistsOfAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.consistsof.ConsistsOfAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.consistsof.ConsistsOfNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.consistsof.ConsistsOfNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
|
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.entities.ResourceManagement;
|
||||||
|
@ -65,7 +65,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
|
||||||
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
|
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
facetManagement.setODatabaseDocument(oDatabaseDocument);
|
facetManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
facetManagement.setWorkingContext(getWorkingContext());
|
facetManagement.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
return facetManagement;
|
return facetManagement;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -107,7 +107,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ODatabaseDocument targetSecurityContextODatabaseDocument = null;
|
ODatabaseDocument targetInstanceEnvironmentODatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
ResourceManagement resourceManagement = getSourceEntityManagement();
|
ResourceManagement resourceManagement = getSourceEntityManagement();
|
||||||
|
|
||||||
|
@ -120,12 +120,12 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
|
||||||
resourceManagement.setElementType(sourceEntityManagement.getTypeName());
|
resourceManagement.setElementType(sourceEntityManagement.getTypeName());
|
||||||
resourceManagement.setUUID(sourceEntityManagement.getUUID());
|
resourceManagement.setUUID(sourceEntityManagement.getUUID());
|
||||||
if(operation == Operation.ADD_TO_CONTEXT) {
|
if(operation == Operation.ADD_TO_CONTEXT) {
|
||||||
resourceManagement.setSourceSecurityContext(sourceSecurityContext);
|
resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
}
|
}
|
||||||
resourceManagement.setTargetSecurityContext(targetSecurityContext);
|
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
resourceManagement.setWorkingContext(targetSecurityContext);
|
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
|
||||||
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument);
|
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
@ -140,8 +140,8 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
|
||||||
}catch (Exception e) {
|
}catch (Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}finally {
|
}finally {
|
||||||
if(targetSecurityContextODatabaseDocument!=null) {
|
if(targetInstanceEnvironmentODatabaseDocument!=null) {
|
||||||
targetSecurityContextODatabaseDocument.close();
|
targetInstanceEnvironmentODatabaseDocument.close();
|
||||||
oDatabaseDocument.activateOnCurrentThread();
|
oDatabaseDocument.activateOnCurrentThread();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isr
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
|
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
@ -60,7 +60,7 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
|
||||||
@Override
|
@Override
|
||||||
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
|
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setWorkingContext(getWorkingContext());
|
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
resourceManagement.setODatabaseDocument(oDatabaseDocument);
|
resourceManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
return resourceManagement;
|
return resourceManagement;
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,13 +5,17 @@ import java.util.Collection;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import javax.ws.rs.ForbiddenException;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ArrayNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.relations.RelationElement;
|
import org.gcube.informationsystem.base.reference.relations.RelationElement;
|
||||||
|
import org.gcube.informationsystem.contexts.reference.ContextState;
|
||||||
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Entity;
|
import org.gcube.informationsystem.model.reference.entities.Entity;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Resource;
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
|
@ -27,18 +31,22 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.relations.RelationElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
import org.gcube.informationsystem.resourceregistry.contexts.ServerContextCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
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.EntityManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
|
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.entities.ResourceManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
|
@ -64,12 +72,12 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
/**
|
/**
|
||||||
* The source context of an addToContex
|
* The source context of an addToContex
|
||||||
*/
|
*/
|
||||||
protected SecurityContext sourceSecurityContext;
|
protected InstanceEnvironment sourceInstanceEnvironment;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The target context of an addToContex/RemoveFromContext
|
* The target context of an addToContex/RemoveFromContext
|
||||||
*/
|
*/
|
||||||
protected SecurityContext targetSecurityContext;
|
protected InstanceEnvironment targetInstanceEnvironment;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* By the default the system honour the propagation constraints
|
* By the default the system honour the propagation constraints
|
||||||
|
@ -104,23 +112,23 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
protected boolean honourPropagationConstraintsInContextSharing;
|
protected boolean honourPropagationConstraintsInContextSharing;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setSourceSecurityContext(SecurityContext sourceSecurityContext) {
|
public void setSourceInstanceEnvironment(InstanceEnvironment source) {
|
||||||
this.sourceSecurityContext = sourceSecurityContext;
|
this.sourceInstanceEnvironment = source;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SecurityContext getSourceSecurityContext() {
|
public InstanceEnvironment getSourceInstanceEnvironment() {
|
||||||
return sourceSecurityContext;
|
return sourceInstanceEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setTargetSecurityContext(SecurityContext targetSecurityContext) {
|
public void setTargetInstanceEnvironment(InstanceEnvironment target) {
|
||||||
this.targetSecurityContext = targetSecurityContext;
|
this.targetInstanceEnvironment = target;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SecurityContext getTargetSecurityContext() {
|
public InstanceEnvironment getTargetInstanceEnvironment() {
|
||||||
return sourceSecurityContext;
|
return targetInstanceEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -135,9 +143,9 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
|
|
||||||
public final PropagationConstraint defaultPropagationConstraint;
|
public final PropagationConstraint defaultPropagationConstraint;
|
||||||
|
|
||||||
public boolean isAvailableOnContext(SecurityContext securityContext) {
|
public boolean isAvailableOnContext(InstanceEnvironment instanceEnvironment) {
|
||||||
try {
|
try {
|
||||||
return securityContext.isElementInContext(element);
|
return instanceEnvironment.isElementInContext(element);
|
||||||
} catch (ResourceRegistryException e) {
|
} catch (ResourceRegistryException e) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -157,6 +165,22 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
|
if(workingEnvironment == null) {
|
||||||
|
workingEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
|
Context context = ServerContextCache.getInstance().getFullInfoContextByUUID(workingEnvironment.getUUID());
|
||||||
|
String state = context.getState();
|
||||||
|
if(state.compareTo(ContextState.ACTIVE.getState())!=0) {
|
||||||
|
Set<String> allowedRoles = workingEnvironment.getAllowedRoles();
|
||||||
|
if(!workingEnvironment.isUserAllowed(allowedRoles)) {
|
||||||
|
throw new ForbiddenException("You are not allowed to operate in non " + ContextState.ACTIVE.getState() + " Contexts. Allowed roles are " + allowedRoles);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return workingEnvironment;
|
||||||
|
}
|
||||||
|
|
||||||
protected PropagationConstraint propagationConstraint;
|
protected PropagationConstraint propagationConstraint;
|
||||||
|
|
||||||
/* The instance is added to the context even is not in source context */
|
/* The instance is added to the context even is not in source context */
|
||||||
|
@ -208,7 +232,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
ResourceManagement resourceManagement = null;
|
ResourceManagement resourceManagement = null;
|
||||||
|
|
||||||
if(sourceResource == null) {
|
if(sourceResource == null) {
|
||||||
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingContext(),
|
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
|
||||||
oDatabaseDocument, source);
|
oDatabaseDocument, source);
|
||||||
if(this instanceof IsRelatedToManagement) {
|
if(this instanceof IsRelatedToManagement) {
|
||||||
sourceResource = resourceManagement.createCompleteJsonNode();
|
sourceResource = resourceManagement.createCompleteJsonNode();
|
||||||
|
@ -322,7 +346,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
@Override
|
@Override
|
||||||
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
|
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setWorkingContext(getWorkingContext());
|
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
resourceManagement.setODatabaseDocument(oDatabaseDocument);
|
resourceManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
return resourceManagement;
|
return resourceManagement;
|
||||||
}
|
}
|
||||||
|
@ -380,7 +404,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
|
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
|
||||||
if(target != null) {
|
if(target != null) {
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
facetManagement.setWorkingContext(getWorkingContext());
|
facetManagement.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
facetManagement.setODatabaseDocument(oDatabaseDocument);
|
facetManagement.setODatabaseDocument(oDatabaseDocument);
|
||||||
facetManagement.setJsonNode(target);
|
facetManagement.setJsonNode(target);
|
||||||
facetManagement.internalUpdate();
|
facetManagement.internalUpdate();
|
||||||
|
@ -396,7 +420,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
|
|
||||||
protected void reallyAddToContext()
|
protected void reallyAddToContext()
|
||||||
throws ContextException, ResourceRegistryException {
|
throws ContextException, ResourceRegistryException {
|
||||||
if(!forceAddToContext && !sourceSecurityContext.isElementInContext(getElement())) {
|
if(!forceAddToContext && !sourceInstanceEnvironment.isElementInContext(getElement())) {
|
||||||
// The element in not in the source security context. It will be skipped
|
// The element in not in the source security context. It will be skipped
|
||||||
skipped = true;
|
skipped = true;
|
||||||
return;
|
return;
|
||||||
|
@ -433,12 +457,12 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
*/
|
*/
|
||||||
getTargetEntityManagement().setDryRun(dryRun);
|
getTargetEntityManagement().setDryRun(dryRun);
|
||||||
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
targetEntityManagement.setSourceSecurityContext(sourceSecurityContext);
|
targetEntityManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
targetEntityManagement.setTargetSecurityContext(targetSecurityContext);
|
targetEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
targetEntityManagement.internalAddToContext();
|
targetEntityManagement.internalAddToContext();
|
||||||
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
|
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
|
||||||
|
|
||||||
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* DO NOT UNCOMMENT
|
* DO NOT UNCOMMENT
|
||||||
|
@ -456,7 +480,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}else {
|
}else {
|
||||||
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
|
||||||
/*
|
/*
|
||||||
* DO NOT UNCOMMENT
|
* DO NOT UNCOMMENT
|
||||||
* // affectedInstances.put(uuid, serializeSelfOnly());
|
* // affectedInstances.put(uuid, serializeSelfOnly());
|
||||||
|
@ -481,7 +505,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
"Error Adding " + typeName + " to " + targetSecurityContext.toString(), e.getCause());
|
"Error Adding " + typeName + " to " + targetInstanceEnvironment.toString(), e.getCause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -492,18 +516,18 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
/* Adding source to Context */
|
/* Adding source to Context */
|
||||||
getSourceEntityManagement().setDryRun(dryRun);
|
getSourceEntityManagement().setDryRun(dryRun);
|
||||||
sourceEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
sourceEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
sourceEntityManagement.setTargetSecurityContext(targetSecurityContext);
|
sourceEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
sourceEntityManagement.internalAddToContext();
|
sourceEntityManagement.internalAddToContext();
|
||||||
affectedInstances.putAll(sourceEntityManagement.getAffectedInstances());
|
affectedInstances.putAll(sourceEntityManagement.getAffectedInstances());
|
||||||
|
|
||||||
/* Adding target to Context */
|
/* Adding target to Context */
|
||||||
getTargetEntityManagement().setDryRun(dryRun);
|
getTargetEntityManagement().setDryRun(dryRun);
|
||||||
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
targetEntityManagement.setTargetSecurityContext(targetSecurityContext);
|
targetEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
targetEntityManagement.internalAddToContext();
|
targetEntityManagement.internalAddToContext();
|
||||||
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
|
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
|
||||||
|
|
||||||
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
|
||||||
|
|
||||||
affectedInstances.put(uuid, serializeAsAffectedInstance());
|
affectedInstances.put(uuid, serializeAsAffectedInstance());
|
||||||
}
|
}
|
||||||
|
@ -514,12 +538,12 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
|
logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
workingContext = ContextUtility.getAdminSecurityContext();
|
workingEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
|
||||||
sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
|
sourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
|
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
|
||||||
|
|
||||||
forcedAddToContext();
|
forcedAddToContext();
|
||||||
|
|
||||||
|
@ -551,7 +575,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
|
|
||||||
protected Map<UUID,JsonNode> reallyRemoveFromContext()
|
protected Map<UUID,JsonNode> reallyRemoveFromContext()
|
||||||
throws ContextException, ResourceRegistryException {
|
throws ContextException, ResourceRegistryException {
|
||||||
if(!targetSecurityContext.isElementInContext(getElement())) {
|
if(!targetInstanceEnvironment.isElementInContext(getElement())) {
|
||||||
// The element in not in the source security context. It will be skipped
|
// The element in not in the source security context. It will be skipped
|
||||||
return affectedInstances;
|
return affectedInstances;
|
||||||
}
|
}
|
||||||
|
@ -585,15 +609,15 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
* In any removeConstraint value the relation MUST be removed from context to
|
* In any removeConstraint value the relation MUST be removed from context to
|
||||||
* avoid to have edge having a source outside of the context.
|
* avoid to have edge having a source outside of the context.
|
||||||
*/
|
*/
|
||||||
targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
|
targetInstanceEnvironment.removeElement(getElement(), oDatabaseDocument);
|
||||||
|
|
||||||
affectedInstances.put(uuid, serializeAsAffectedInstance());
|
affectedInstances.put(uuid, serializeAsAffectedInstance());
|
||||||
|
|
||||||
T targetEntityManagement = getTargetEntityManagement();
|
T targetEntityManagement = getTargetEntityManagement();
|
||||||
targetEntityManagement.setDryRun(dryRun);
|
targetEntityManagement.setDryRun(dryRun);
|
||||||
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
|
||||||
// Not needed targetEntityManagement.setSourceSecurityContext(sourceSecurityContext);
|
// Not needed targetEntityManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
|
||||||
targetEntityManagement.setTargetSecurityContext(targetSecurityContext);
|
targetEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
|
||||||
if(targetEntityManagement instanceof ResourceManagement) {
|
if(targetEntityManagement instanceof ResourceManagement) {
|
||||||
((ResourceManagement) targetEntityManagement).setSanityCheckNotRequired();
|
((ResourceManagement) targetEntityManagement).setSanityCheckNotRequired();
|
||||||
}
|
}
|
||||||
|
@ -627,7 +651,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
if(count > 0) {
|
if(count > 0) {
|
||||||
logger.trace(
|
logger.trace(
|
||||||
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from {}.",
|
"{} point to {} which is not orphan ({} exists). Giving {} directive, it will be not remove from {}.",
|
||||||
element, target, edge, removeConstraint, targetSecurityContext);
|
element, target, edge, removeConstraint, targetInstanceEnvironment);
|
||||||
} else {
|
} else {
|
||||||
targetEntityManagement.internalRemoveFromContext();
|
targetEntityManagement.internalRemoveFromContext();
|
||||||
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
|
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
|
||||||
|
@ -657,7 +681,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
throw e;
|
throw e;
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
throw new ResourceRegistryException(
|
throw new ResourceRegistryException(
|
||||||
"Error Removing " + typeName + " from " + targetSecurityContext.toString(), e.getCause());
|
"Error Removing " + typeName + " from " + targetInstanceEnvironment.toString(), e.getCause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -667,14 +691,14 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
|
||||||
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
|
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
workingContext = ContextUtility.getAdminSecurityContext();
|
workingEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
setAsEntryPoint();
|
setAsEntryPoint();
|
||||||
|
|
||||||
|
|
||||||
// Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
|
// Not needed sourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
|
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
|
||||||
|
|
||||||
internalRemoveFromContext();
|
internalRemoveFromContext();
|
||||||
|
|
||||||
|
@ -777,21 +801,36 @@ 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 {
|
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<>();
|
// Map<String,JsonNode> visitedSourceResources = new HashMap<>();
|
||||||
List<JsonNode> serilizedEdges = new ArrayList<>();
|
List<JsonNode> serilizedEdges = new ArrayList<>();
|
||||||
for(ODocument d : edges) {
|
for(ODocument d : edges) {
|
||||||
|
if(++position < offset) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
OEdge edge = (OEdge) d;
|
OEdge edge = (OEdge) d;
|
||||||
|
|
||||||
if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) {
|
if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
|
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(),
|
||||||
oDatabaseDocument, edge);
|
oDatabaseDocument, edge);
|
||||||
// visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
|
// visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
|
||||||
serilizedEdges.add(relationManagement.serializeAsJsonNode());
|
serilizedEdges.add(relationManagement.serializeAsJsonNode());
|
||||||
|
if(limit > 0 && ++count >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return serilizedEdges;
|
return serilizedEdges;
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,11 +5,12 @@ 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.ArrayNode;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.InvalidQueryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -32,12 +33,12 @@ public class QueryImpl implements Query {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
|
InstanceEnvironment instanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
|
|
||||||
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = instanceEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
oDatabaseDocument.begin();
|
oDatabaseDocument.begin();
|
||||||
|
|
||||||
logger.debug("Going to execute query '{} limit {}'", query);
|
logger.debug("Going to execute query '{}'", query);
|
||||||
|
|
||||||
OResultSet resultSet = oDatabaseDocument.query(query);
|
OResultSet resultSet = oDatabaseDocument.query(query);
|
||||||
|
|
||||||
|
@ -59,7 +60,7 @@ public class QueryImpl implements Query {
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
|
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(instanceEnvironment, oDatabaseDocument,
|
||||||
element);
|
element);
|
||||||
erManagement.setAsEntryPoint();
|
erManagement.setAsEntryPoint();
|
||||||
jsonNode = erManagement.serializeAsJsonNode();
|
jsonNode = erManagement.serializeAsJsonNode();
|
||||||
|
|
|
@ -2,28 +2,33 @@ package org.gcube.informationsystem.resourceregistry.queries.json;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ArrayNode;
|
||||||
|
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Direction;
|
import org.gcube.informationsystem.base.reference.Direction;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.InvalidQueryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.base.JsonQueryERElement;
|
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.JsonQueryFacet;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryResource;
|
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.JsonQueryConsistsOf;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
|
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.utils.TypeUtility;
|
import org.gcube.informationsystem.utils.TypeUtility;
|
||||||
|
@ -42,8 +47,6 @@ public class JsonQuery {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(JsonQuery.class);
|
private static Logger logger = LoggerFactory.getLogger(JsonQuery.class);
|
||||||
|
|
||||||
private static final Integer UNBOUNDED_LIMIT = -1;
|
|
||||||
|
|
||||||
protected ObjectMapper objectMapper;
|
protected ObjectMapper objectMapper;
|
||||||
protected JsonNode jsonQuery;
|
protected JsonNode jsonQuery;
|
||||||
protected JsonQueryERElement entryPoint;
|
protected JsonQueryERElement entryPoint;
|
||||||
|
@ -98,27 +101,46 @@ public class JsonQuery {
|
||||||
return jsonQueryERElement;
|
return jsonQueryERElement;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public StringBuffer createQuery() throws SchemaException, InvalidQueryException, ResourceRegistryException {
|
public StringBuffer createQuery() throws SchemaException, InvalidQueryException, ResourceRegistryException {
|
||||||
entryPoint = getJsonQueryERElement(jsonQuery);
|
entryPoint = getJsonQueryERElement(jsonQuery);
|
||||||
entryPoint.setEntryPoint(true);
|
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 {
|
public String query() throws InvalidQueryException, ResourceRegistryException {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
oDatabaseDocument = null;
|
oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
|
InstanceEnvironment instanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
|
||||||
|
|
||||||
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = instanceEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
oDatabaseDocument.begin();
|
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 stringBuffer = createQuery();
|
||||||
stringBuffer.append(" limit :limit");
|
stringBuffer.append(" SKIP :offset");
|
||||||
|
stringBuffer.append(" LIMIT :limit");
|
||||||
|
|
||||||
Map<String, Object> map = new HashMap<>();
|
Map<String, Object> map = new HashMap<>();
|
||||||
map.put("limit", JsonQuery.UNBOUNDED_LIMIT);
|
map.put("offset", offset);
|
||||||
|
map.put("limit", limit);
|
||||||
|
|
||||||
|
|
||||||
String query = stringBuffer.toString();
|
String query = stringBuffer.toString();
|
||||||
logger.trace("Going to execute the following query:\n{} \n from the JSONQuery\n{}", query, objectMapper.writeValueAsString(jsonQuery));
|
logger.trace("Going to execute the following query:\n{} \n from the JSONQuery\n{}", query, objectMapper.writeValueAsString(jsonQuery));
|
||||||
|
@ -127,39 +149,52 @@ public class JsonQuery {
|
||||||
|
|
||||||
ArrayNode arrayNode = objectMapper.createArrayNode();
|
ArrayNode arrayNode = objectMapper.createArrayNode();
|
||||||
|
|
||||||
|
boolean projection = entryPoint.isProjection();
|
||||||
|
boolean first = true;
|
||||||
|
|
||||||
|
Set<String> keys = new HashSet<>();
|
||||||
|
|
||||||
while(resultSet.hasNext()) {
|
while(resultSet.hasNext()) {
|
||||||
OResult oResult = resultSet.next();
|
OResult oResult = resultSet.next();
|
||||||
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
|
|
||||||
|
|
||||||
try {
|
if(projection) {
|
||||||
JsonNode jsonNodeResult = null;
|
if(first) {
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
|
keys = oResult.getPropertyNames();
|
||||||
element);
|
first = false;
|
||||||
|
}
|
||||||
|
ObjectNode objectNode = objectMapper.createObjectNode();
|
||||||
|
|
||||||
// To support polymorphism we do not include ="TypeName" in query. So we need post processing filtering of results
|
for(String key : keys) {
|
||||||
|
Object value = oResult.getProperty(key);
|
||||||
String requestedType = entryPoint.getType();
|
|
||||||
String gotType = erManagement.getTypeName();
|
if(value == null) {
|
||||||
|
objectNode.put(key, "");
|
||||||
if(requestedType.compareTo(gotType)==0) {
|
}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 = ERManagementUtility.getERManagement(instanceEnvironment, oDatabaseDocument,
|
||||||
|
element);
|
||||||
erManagement.setAsEntryPoint();
|
erManagement.setAsEntryPoint();
|
||||||
jsonNodeResult = erManagement.serializeAsJsonNode();
|
jsonNodeResult = erManagement.serializeAsJsonNode();
|
||||||
arrayNode.add(jsonNodeResult);
|
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)) {
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,9 +1,13 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.queries.json.base;
|
package org.gcube.informationsystem.resourceregistry.queries.json.base;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
import javax.ws.rs.InternalServerErrorException;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ArrayNode;
|
||||||
|
@ -11,18 +15,26 @@ import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Direction;
|
import org.gcube.informationsystem.base.reference.Direction;
|
||||||
import org.gcube.informationsystem.base.reference.Element;
|
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.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
|
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.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator;
|
import org.gcube.informationsystem.resourceregistry.queries.operators.ComparisonOperator;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
|
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.resourceregistry.types.TypesCache;
|
||||||
import org.gcube.informationsystem.utils.TypeUtility;
|
import org.gcube.informationsystem.utils.TypeUtility;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public abstract class JsonQueryERElement {
|
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 {
|
public static void validateType(String type, AccessType requiredAccessType) throws SchemaException, ResourceRegistryException {
|
||||||
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
|
AccessType accessType = TypesCache.getInstance().getCachedType(type).getAccessType();
|
||||||
|
@ -41,16 +53,74 @@ public abstract class JsonQueryERElement {
|
||||||
protected Direction direction;
|
protected Direction direction;
|
||||||
protected boolean entryPoint;
|
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 {
|
public JsonQueryERElement(JsonNode jsonQuery, AccessType accessType) throws SchemaException, ResourceRegistryException {
|
||||||
this.objectMapper = new ObjectMapper();
|
this.objectMapper = new ObjectMapper();
|
||||||
this.type = TypeUtility.getTypeName(jsonQuery);
|
this.type = TypeUtility.getTypeName(jsonQuery);
|
||||||
this.jsonNode = jsonQuery;
|
this.jsonNode = jsonQuery;
|
||||||
|
this.size = jsonNode.size();
|
||||||
this.accessType = accessType;
|
this.accessType = accessType;
|
||||||
this.entryPoint = false;
|
this.entryPoint = false;
|
||||||
|
this.traverseBack = true;
|
||||||
|
|
||||||
|
this.projection = false;
|
||||||
|
this.breadcrumb = new ArrayList<>();
|
||||||
|
this.position = 0;
|
||||||
|
this.alias = null;
|
||||||
|
this.fieldsToEmit = new ArrayList<>();
|
||||||
|
|
||||||
|
|
||||||
this.fieldNamesToRemove = new HashSet<>();
|
this.fieldNamesToRemove = new HashSet<>();
|
||||||
this.fieldNamesToRemove.add(Element.TYPE_PROPERTY);
|
this.fieldNamesToRemove.add(Element.TYPE_PROPERTY);
|
||||||
this.fieldNamesToRemove.add(Element.SUPERTYPES_PROPERTY);
|
this.fieldNamesToRemove.add(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
|
this.fieldNamesToRemove.add(ModelElement.EXPECTED_TYPE_PROPERTY);
|
||||||
|
|
||||||
validateType(this.type, this.accessType);
|
validateType(this.type, this.accessType);
|
||||||
}
|
}
|
||||||
|
@ -73,16 +143,93 @@ public abstract class JsonQueryERElement {
|
||||||
|
|
||||||
public void setEntryPoint(boolean entryPoint) {
|
public void setEntryPoint(boolean entryPoint) {
|
||||||
this.entryPoint = 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();
|
StringBuffer stringBuffer = new StringBuffer();
|
||||||
|
|
||||||
if(queryLogicalOperator==null) {
|
if(queryLogicalOperator==null) {
|
||||||
queryLogicalOperator = QueryLogicalOperator.AND;
|
queryLogicalOperator = LogicalOperator.AND;
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonNode copiedJsonNode = jsonNode.deepCopy();
|
JsonNode copiedJsonNode = jsonNode.deepCopy();
|
||||||
|
@ -97,13 +244,17 @@ public abstract class JsonQueryERElement {
|
||||||
|
|
||||||
while(iterator.hasNext()) {
|
while(iterator.hasNext()) {
|
||||||
String fieldName = iterator.next();
|
String fieldName = iterator.next();
|
||||||
if(first) {
|
|
||||||
first = false;
|
|
||||||
}else {
|
|
||||||
stringBuffer.append(queryLogicalOperator.getLogicalOperator());
|
|
||||||
}
|
|
||||||
JsonNode node = objectNode.get(fieldName);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -112,13 +263,19 @@ public abstract class JsonQueryERElement {
|
||||||
Iterator<JsonNode> iterator = arrayNode.iterator();
|
Iterator<JsonNode> iterator = arrayNode.iterator();
|
||||||
boolean first = true;
|
boolean first = true;
|
||||||
while(iterator.hasNext()) {
|
while(iterator.hasNext()) {
|
||||||
if(first) {
|
|
||||||
first = false;
|
|
||||||
}else {
|
|
||||||
stringBuffer.append(queryLogicalOperator.getLogicalOperator());
|
|
||||||
}
|
|
||||||
JsonNode node = iterator.next();
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -126,26 +283,56 @@ public abstract class JsonQueryERElement {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected StringBuffer evaluateNode(JsonNode jsonNode, String fieldName, String fieldNamePrefix) throws InvalidQueryException {
|
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();
|
StringBuffer stringBuffer = new StringBuffer();
|
||||||
|
|
||||||
if(QueryLogicalOperator.getOperators().contains(fieldName)) {
|
if(LogicalOperator.getOperators().contains(fieldName)) {
|
||||||
QueryLogicalOperator queryLogicalOperator = QueryLogicalOperator.getQueryLogicalOperator(fieldName);
|
LogicalOperator queryLogicalOperator = LogicalOperator.getOperator(fieldName);
|
||||||
stringBuffer.append("(");
|
stringBuffer.append("(");
|
||||||
stringBuffer.append(addConstraints(jsonNode, queryLogicalOperator, fieldNamePrefix));
|
stringBuffer.append(addConstraints(jsonNode, queryLogicalOperator, fieldNamePrefix));
|
||||||
stringBuffer.append(")");
|
stringBuffer.append(")");
|
||||||
return stringBuffer;
|
return stringBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(QueryConditionalOperator.getOperators().contains(fieldName)) {
|
if(ComparisonOperator.getOperators().contains(fieldName)) {
|
||||||
QueryConditionalOperator queryConditionalOperator = QueryConditionalOperator.getQueryComparisonOperator(fieldName);
|
ComparisonOperator comparisonOperator = ComparisonOperator.getOperator(fieldName);
|
||||||
|
|
||||||
if(queryConditionalOperator == QueryConditionalOperator.IN) {
|
String key = getKey(null, fieldNamePrefix);
|
||||||
throw new UnsupportedOperationException();
|
String value = getValue(jsonNode);
|
||||||
}
|
stringBuffer.append(comparisonOperator.addCondition(key, value));
|
||||||
|
|
||||||
StringBuffer key = getKey(null, fieldNamePrefix);
|
|
||||||
StringBuffer value = getValue(jsonNode);
|
|
||||||
stringBuffer.append(addCondition(queryConditionalOperator, key, value));
|
|
||||||
return stringBuffer;
|
return stringBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -167,38 +354,34 @@ public abstract class JsonQueryERElement {
|
||||||
}
|
}
|
||||||
|
|
||||||
if(jsonNode.isTextual() || jsonNode.isNumber()) {
|
if(jsonNode.isTextual() || jsonNode.isNumber()) {
|
||||||
StringBuffer key = getKey(fieldName, fieldNamePrefix);
|
String key = getKey(fieldName, fieldNamePrefix);
|
||||||
StringBuffer value = getValue(jsonNode);
|
String value = getValue(jsonNode);
|
||||||
stringBuffer.append(addCondition(QueryConditionalOperator.EQ, key, value));
|
stringBuffer.append(ComparisonOperator.EQ.addCondition(key, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
if(jsonNode.isNull()) {
|
||||||
|
String key = getKey(fieldName, null);
|
||||||
|
stringBuffer.append(ComparisonOperator.IS.addCondition(key, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
return stringBuffer;
|
return stringBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected StringBuffer addCondition(QueryConditionalOperator queryConditionalOperator, StringBuffer key, StringBuffer value) {
|
protected String getKey(String fieldName, String fieldNamePrefix) {
|
||||||
StringBuffer stringBuffer = new StringBuffer();
|
|
||||||
stringBuffer.append(key);
|
|
||||||
stringBuffer.append(queryConditionalOperator.getConditionalOperator());
|
|
||||||
stringBuffer.append(value);
|
|
||||||
return stringBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
protected StringBuffer getKey(String fieldName, String fieldNamePrefix) {
|
|
||||||
StringBuffer stringBuffer = new StringBuffer();
|
StringBuffer stringBuffer = new StringBuffer();
|
||||||
if(fieldNamePrefix!=null) {
|
if(fieldNamePrefix!=null) {
|
||||||
stringBuffer.append(fieldNamePrefix);
|
stringBuffer.append(fieldNamePrefix.trim());
|
||||||
if(fieldName!=null && fieldName.compareTo("")!=0) {
|
if(fieldName!=null && fieldName.trim().length()!=0) {
|
||||||
stringBuffer.append(".");
|
stringBuffer.append(".");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(fieldName!=null) {
|
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();
|
StringBuffer stringBuffer = new StringBuffer();
|
||||||
|
|
||||||
String value = jsonNode.asText();
|
String value = jsonNode.asText();
|
||||||
|
@ -209,6 +392,92 @@ public abstract class JsonQueryERElement {
|
||||||
stringBuffer.append(value);
|
stringBuffer.append(value);
|
||||||
stringBuffer.append("\"");
|
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;
|
return stringBuffer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,42 +1,46 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.queries.json.base.entities;
|
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.JsonNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Direction;
|
import org.gcube.informationsystem.base.reference.Direction;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.InvalidQueryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
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.JsonQueryConsistsOf;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
public class JsonQueryFacet extends JsonQueryEntity {
|
public class JsonQueryFacet extends JsonQueryEntity {
|
||||||
|
|
||||||
public final static String _IN = "_in";
|
public final static String _SOURCE = "_source";
|
||||||
|
|
||||||
public JsonQueryFacet(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
|
public JsonQueryFacet(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
|
||||||
super(jsonQuery, AccessType.FACET);
|
super(jsonQuery, AccessType.FACET);
|
||||||
fieldNamesToRemove.add(JsonQueryFacet._IN);
|
fieldNamesToRemove.add(JsonQueryFacet._SOURCE);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
||||||
StringBuffer newBuffer = new StringBuffer();
|
StringBuffer newBuffer = new StringBuffer();
|
||||||
|
|
||||||
int size = jsonNode.size();
|
int size = jsonNode.size();
|
||||||
|
|
||||||
boolean entry = entryPoint;
|
boolean traverseBackLocal = traverseBack;
|
||||||
if(jsonNode.has(_IN)) {
|
if(jsonNode.has(_SOURCE)) {
|
||||||
if(!entryPoint) {
|
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 jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfNode);
|
||||||
jsonQueryConsistsOf.setEntryPoint(entryPoint);
|
jsonQueryConsistsOf.setTraverseBack(traverseBackLocal);
|
||||||
jsonQueryConsistsOf.setDirection(Direction.OUT);
|
jsonQueryConsistsOf.setDirection(Direction.OUT);
|
||||||
stringBuffer = jsonQueryConsistsOf.analize(stringBuffer);
|
stringBuffer = jsonQueryConsistsOf.createTraversalQuery(stringBuffer);
|
||||||
entry = false;
|
traverseBackLocal = true;
|
||||||
|
|
||||||
/* Need to substract 1 from size otherwise
|
/* Need to substract 1 from size otherwise
|
||||||
* it add WHERE at the end because _in
|
* it add WHERE at the end because _in
|
||||||
|
@ -47,28 +51,134 @@ public class JsonQueryFacet extends JsonQueryEntity {
|
||||||
|
|
||||||
newBuffer.append("SELECT FROM ");
|
newBuffer.append("SELECT FROM ");
|
||||||
|
|
||||||
if(!entry) {
|
if(traverseBackLocal) {
|
||||||
newBuffer.append("( ");
|
newBuffer.append("( ");
|
||||||
newBuffer.append("TRAVERSE inV(\"");
|
newBuffer.append("TRAVERSE inV(\"");
|
||||||
}
|
}
|
||||||
|
|
||||||
newBuffer.append(type);
|
newBuffer.append(type);
|
||||||
|
|
||||||
if(!entry) {
|
if(traverseBackLocal) {
|
||||||
newBuffer.append("\") FROM ( ");
|
newBuffer.append("\") FROM ( ");
|
||||||
newBuffer.append(stringBuffer);
|
newBuffer.append(stringBuffer);
|
||||||
newBuffer.append(")");
|
newBuffer.append(")");
|
||||||
newBuffer.append(")");
|
newBuffer.append(")");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* If size >1 I have to add constraints.
|
||||||
|
* If is an entry point I have to add the INSTANCEOF to properly support polymorphism
|
||||||
|
*/
|
||||||
|
if(size > 1 || entryPoint) {
|
||||||
|
newBuffer.append(" WHERE ");
|
||||||
|
}
|
||||||
|
|
||||||
// Size 1 means that only 'type' property is present
|
// Size 1 means that only 'type' property is present
|
||||||
if(size > 1) {
|
if(size > 1) {
|
||||||
newBuffer.append(" WHERE ");
|
|
||||||
newBuffer.append(addConstraints(jsonNode, null, null));
|
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;
|
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;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.queries.json.base.entities;
|
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.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
|
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
|
@ -7,8 +9,10 @@ import org.gcube.informationsystem.base.reference.Direction;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Resource;
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.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.JsonQueryConsistsOf;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
|
import org.gcube.informationsystem.resourceregistry.queries.json.base.relations.JsonQueryIsRelatedTo;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
@ -17,42 +21,74 @@ public class JsonQueryResource extends JsonQueryEntity {
|
||||||
|
|
||||||
public JsonQueryResource(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
|
public JsonQueryResource(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
|
||||||
super(jsonQuery, AccessType.RESOURCE);
|
super(jsonQuery, AccessType.RESOURCE);
|
||||||
fieldNamesToRemove.add(Resource.CONSISTS_OF_PROPERTY);
|
this.fieldNamesToRemove.add(Resource.CONSISTS_OF_PROPERTY);
|
||||||
fieldNamesToRemove.add(Resource.IS_RELATED_TO_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
|
@Override
|
||||||
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
||||||
boolean initFound = false;
|
|
||||||
|
|
||||||
int size = jsonNode.size();
|
boolean wrapInnerQuery = false;
|
||||||
|
|
||||||
if(!entryPoint) {
|
if(traverseBack) {
|
||||||
StringBuffer newBuffer = new StringBuffer();
|
StringBuffer buffer = new StringBuffer();
|
||||||
newBuffer.append("TRAVERSE ");
|
buffer.append("TRAVERSE ");
|
||||||
newBuffer.append(direction.name().toLowerCase());
|
buffer.append(direction.name().toLowerCase());
|
||||||
newBuffer.append("V(\"");
|
buffer.append("V(\"");
|
||||||
newBuffer.append(type);
|
buffer.append(type);
|
||||||
newBuffer.append("\") FROM ( ");
|
buffer.append("\") FROM ( ");
|
||||||
newBuffer.append(stringBuffer);
|
buffer.append(stringBuffer);
|
||||||
newBuffer.append(")");
|
buffer.append(")");
|
||||||
stringBuffer = newBuffer;
|
stringBuffer = buffer;
|
||||||
|
|
||||||
initFound = true;
|
wrapInnerQuery = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
ArrayNode isRelatedToArray = (ArrayNode) jsonNode.get(Resource.IS_RELATED_TO_PROPERTY);
|
ArrayNode isRelatedToArray = (ArrayNode) jsonNode.get(Resource.IS_RELATED_TO_PROPERTY);
|
||||||
if(isRelatedToArray!=null && isRelatedToArray.size()>0) {
|
if(isRelatedToArray!=null && isRelatedToArray.size()>0) {
|
||||||
--size;
|
--size;
|
||||||
initFound = true;
|
|
||||||
for(int i=0; i<isRelatedToArray.size(); i++) {
|
for(int i=0; i<isRelatedToArray.size(); i++) {
|
||||||
JsonNode isRelatedToJsonNode = isRelatedToArray.get(i);
|
JsonNode isRelatedToJsonNode = isRelatedToArray.get(i);
|
||||||
JsonQueryIsRelatedTo jsonQueryIsRelatedTo = new JsonQueryIsRelatedTo(isRelatedToJsonNode);
|
JsonQueryIsRelatedTo jsonQueryIsRelatedTo = new JsonQueryIsRelatedTo(isRelatedToJsonNode);
|
||||||
jsonQueryIsRelatedTo.setRequestedResourceType(type);
|
jsonQueryIsRelatedTo.setRequestedResourceType(type);
|
||||||
jsonQueryIsRelatedTo.setEntryPoint(entryPoint && i==0);
|
jsonQueryIsRelatedTo.setDirectionByJson();
|
||||||
stringBuffer = jsonQueryIsRelatedTo.analize(stringBuffer);
|
jsonQueryIsRelatedTo.setTraverseBack( (!(!traverseBack) && i==0) );
|
||||||
|
stringBuffer = jsonQueryIsRelatedTo.createTraversalQuery(stringBuffer);
|
||||||
}
|
}
|
||||||
|
wrapInnerQuery = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
ArrayNode consistsOfArray = (ArrayNode) jsonNode.get(Resource.CONSISTS_OF_PROPERTY);
|
ArrayNode consistsOfArray = (ArrayNode) jsonNode.get(Resource.CONSISTS_OF_PROPERTY);
|
||||||
|
@ -63,45 +99,154 @@ public class JsonQueryResource extends JsonQueryEntity {
|
||||||
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfJsonNode);
|
JsonQueryConsistsOf jsonQueryConsistsOf = new JsonQueryConsistsOf(consistsOfJsonNode);
|
||||||
jsonQueryConsistsOf.setRequestedResourceType(type);
|
jsonQueryConsistsOf.setRequestedResourceType(type);
|
||||||
jsonQueryConsistsOf.setDirection(Direction.IN);
|
jsonQueryConsistsOf.setDirection(Direction.IN);
|
||||||
jsonQueryConsistsOf.setEntryPoint(entryPoint && !initFound && i==0);
|
jsonQueryConsistsOf.setTraverseBack(!((!traverseBack) && !wrapInnerQuery && i==0));
|
||||||
stringBuffer = jsonQueryConsistsOf.analize(stringBuffer);
|
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(entryPoint) {
|
// The Resource has no other referenced ER inside
|
||||||
if(!initFound) {
|
if(!wrapInnerQuery) {
|
||||||
stringBuffer = new StringBuffer();
|
return createSelect(stringBuffer, wrapInnerQuery);
|
||||||
stringBuffer.append("SELECT FROM ");
|
}
|
||||||
stringBuffer.append(type);
|
|
||||||
if(size > 1) {
|
if(entryPoint || size>1) {
|
||||||
stringBuffer.append(" WHERE ");
|
return createSelect(stringBuffer, wrapInnerQuery);
|
||||||
stringBuffer.append(addConstraints(jsonNode, null, null));
|
|
||||||
}
|
|
||||||
}else {
|
|
||||||
if(size > 1) {
|
|
||||||
StringBuffer newBuffer = new StringBuffer();
|
|
||||||
newBuffer.append("SELECT FROM ( ");
|
|
||||||
newBuffer.append(stringBuffer);
|
|
||||||
newBuffer.append(")");
|
|
||||||
newBuffer.append(" WHERE ");
|
|
||||||
newBuffer.append(addConstraints(jsonNode, null, null));
|
|
||||||
stringBuffer = newBuffer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}else {
|
|
||||||
if(initFound && size > 1) {
|
|
||||||
StringBuffer newBuffer = new StringBuffer();
|
|
||||||
newBuffer.append("SELECT FROM ( ");
|
|
||||||
newBuffer.append(stringBuffer);
|
|
||||||
newBuffer.append(")");
|
|
||||||
newBuffer.append(" WHERE ");
|
|
||||||
newBuffer.append(addConstraints(jsonNode, null, null));
|
|
||||||
stringBuffer = newBuffer;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return stringBuffer;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,17 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.queries.json.base.relations;
|
package org.gcube.informationsystem.resourceregistry.queries.json.base.relations;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Direction;
|
import org.gcube.informationsystem.base.reference.Direction;
|
||||||
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.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.JsonQueryFacet;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryResource;
|
import org.gcube.informationsystem.resourceregistry.queries.json.base.entities.JsonQueryResource;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
@ -29,30 +33,58 @@ public class JsonQueryConsistsOf extends JsonQueryRelation {
|
||||||
this.requestedResourceType = requestedResourceType;
|
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
|
@Override
|
||||||
public StringBuffer analize(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
||||||
StringBuffer consistsOfBuffer = new StringBuffer();
|
|
||||||
|
|
||||||
if(!jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
|
boolean wrapInnerQuery = false;
|
||||||
consistsOfBuffer.append("TRAVERSE ");
|
|
||||||
consistsOfBuffer.append(direction.opposite().name().toLowerCase());
|
|
||||||
consistsOfBuffer.append("V(\"");
|
|
||||||
consistsOfBuffer.append(requestedResourceType);
|
|
||||||
consistsOfBuffer.append("\") FROM ( "); // Open ( 1
|
|
||||||
}
|
|
||||||
|
|
||||||
int size = jsonNode.size();
|
if(traverseBack) {
|
||||||
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) {
|
|
||||||
StringBuffer buffer = new StringBuffer();
|
StringBuffer buffer = new StringBuffer();
|
||||||
buffer.append("TRAVERSE ");
|
buffer.append("TRAVERSE ");
|
||||||
buffer.append(direction.opposite().name().toLowerCase());
|
buffer.append(direction.opposite().name().toLowerCase());
|
||||||
|
@ -62,34 +94,162 @@ public class JsonQueryConsistsOf extends JsonQueryRelation {
|
||||||
buffer.append(stringBuffer);
|
buffer.append(stringBuffer);
|
||||||
buffer.append(")");
|
buffer.append(")");
|
||||||
stringBuffer = buffer;
|
stringBuffer = buffer;
|
||||||
|
wrapInnerQuery = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
|
if(jsonNode.has(ConsistsOf.TARGET_PROPERTY)) {
|
||||||
|
--size;
|
||||||
JsonNode facetJsonNode = jsonNode.get(ConsistsOf.TARGET_PROPERTY);
|
JsonNode facetJsonNode = jsonNode.get(ConsistsOf.TARGET_PROPERTY);
|
||||||
JsonQueryFacet jsonQueryFacet = new JsonQueryFacet(facetJsonNode);
|
JsonQueryFacet jsonQueryFacet = new JsonQueryFacet(facetJsonNode);
|
||||||
jsonQueryFacet.setEntryPoint(entryPoint);
|
jsonQueryFacet.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
|
||||||
stringBuffer = jsonQueryFacet.analize(stringBuffer);
|
stringBuffer = jsonQueryFacet.createTraversalQuery(stringBuffer);
|
||||||
} else if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
|
wrapInnerQuery = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
|
||||||
|
--size;
|
||||||
JsonNode resourceJsonNode = jsonNode.get(ConsistsOf.SOURCE_PROPERTY);
|
JsonNode resourceJsonNode = jsonNode.get(ConsistsOf.SOURCE_PROPERTY);
|
||||||
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
|
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
|
||||||
jsonQueryResource.setEntryPoint(entryPoint);
|
jsonQueryResource.setTraverseBack(!((!traverseBack) && !wrapInnerQuery));
|
||||||
stringBuffer = jsonQueryResource.analize(stringBuffer);
|
stringBuffer = jsonQueryResource.createTraversalQuery(stringBuffer);
|
||||||
|
wrapInnerQuery = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
consistsOfBuffer.append(stringBuffer);
|
if(wrapInnerQuery) {
|
||||||
consistsOfBuffer.append(")"); // Close ) 2
|
StringBuffer buffer = new StringBuffer();
|
||||||
|
buffer.append("TRAVERSE ");
|
||||||
// Size 2 means that only 'type' and 'target' properties are present
|
buffer.append(direction.name().toLowerCase());
|
||||||
if(size > 2) {
|
buffer.append("E(\"");
|
||||||
consistsOfBuffer.append(") WHERE "); // Close ) SELECT
|
buffer.append(type);
|
||||||
consistsOfBuffer.append(addConstraints(jsonNode, null, null));
|
buffer.append("\") FROM ( ");
|
||||||
|
buffer.append(stringBuffer);
|
||||||
|
buffer.append(")");
|
||||||
|
stringBuffer = buffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!jsonNode.has(ConsistsOf.SOURCE_PROPERTY)) {
|
if(entryPoint || size>1) {
|
||||||
consistsOfBuffer.append(")"); // Close ) 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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,20 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.queries.json.base.relations;
|
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.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.informationsystem.base.reference.AccessType;
|
import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.base.reference.Direction;
|
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.model.reference.relations.IsRelatedTo;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.InvalidQueryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
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.queries.json.base.entities.JsonQueryResource;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
@ -18,6 +25,7 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
|
||||||
|
|
||||||
public JsonQueryIsRelatedTo(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
|
public JsonQueryIsRelatedTo(JsonNode jsonQuery) throws SchemaException, ResourceRegistryException {
|
||||||
super(jsonQuery, AccessType.IS_RELATED_TO);
|
super(jsonQuery, AccessType.IS_RELATED_TO);
|
||||||
|
direction = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getRequestedResourceType() {
|
public String getRequestedResourceType() {
|
||||||
|
@ -27,39 +35,106 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
|
||||||
public void setRequestedResourceType(String requestedResourceType) {
|
public void setRequestedResourceType(String requestedResourceType) {
|
||||||
this.requestedResourceType = requestedResourceType;
|
this.requestedResourceType = requestedResourceType;
|
||||||
}
|
}
|
||||||
|
|
||||||
private StringBuffer traverseThisEdge(StringBuffer stringBuffer) throws InvalidQueryException {
|
protected StringBuffer traverseBackToCallerResource(StringBuffer stringBuffer) {
|
||||||
StringBuffer buffer = new StringBuffer();
|
StringBuffer buffer = new StringBuffer();
|
||||||
|
buffer.append("TRAVERSE ");
|
||||||
|
buffer.append(direction.opposite().name().toLowerCase());
|
||||||
|
buffer.append("V(\"");
|
||||||
|
buffer.append(requestedResourceType);
|
||||||
|
buffer.append("\") FROM ( "); // Open (
|
||||||
|
buffer.append(stringBuffer);
|
||||||
|
buffer.append(")"); // Close )
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StringBuffer createSelect(StringBuffer stringBuffer, boolean wrapInnerQuery) throws SchemaException, ResourceRegistryException {
|
||||||
|
StringBuffer buffer = new StringBuffer();
|
||||||
|
buffer.append("SELECT FROM ");
|
||||||
|
|
||||||
int size = jsonNode.size();
|
if(wrapInnerQuery) {
|
||||||
|
buffer.append("( ");
|
||||||
|
buffer.append(stringBuffer);
|
||||||
|
buffer.append(")");
|
||||||
|
}else {
|
||||||
|
buffer.append(type);
|
||||||
|
}
|
||||||
|
|
||||||
// Remove type from size
|
if(entryPoint || size>1) {
|
||||||
--size;
|
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)) {
|
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)) {
|
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) {
|
if(matchQuery) {
|
||||||
buffer.append("SELECT FROM ");
|
direction = direction.opposite();
|
||||||
if(entryPoint) {
|
}
|
||||||
buffer.append(type);
|
}
|
||||||
}else {
|
|
||||||
buffer.append(" ( "); // Open ( SELECT
|
@Override
|
||||||
}
|
public StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaException, ResourceRegistryException {
|
||||||
|
|
||||||
}else {
|
if(!entryPoint && direction==null) {
|
||||||
if(entryPoint) {
|
throw new InternalServerErrorException("Caller Resource must invoke setDirectionByJson() first. This is a server bug. Please contact the administator. ");
|
||||||
buffer.append("SELECT FROM ");
|
|
||||||
buffer.append(type);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!entryPoint) {
|
boolean wrapInnerQuery = false;
|
||||||
|
|
||||||
|
if(traverseBack) {
|
||||||
|
StringBuffer buffer = new StringBuffer();
|
||||||
buffer.append("TRAVERSE ");
|
buffer.append("TRAVERSE ");
|
||||||
buffer.append(direction.opposite().name().toLowerCase());
|
buffer.append(direction.opposite().name().toLowerCase());
|
||||||
buffer.append("E(\"");
|
buffer.append("E(\"");
|
||||||
|
@ -67,84 +142,188 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
|
||||||
buffer.append("\") FROM ( ");
|
buffer.append("\") FROM ( ");
|
||||||
buffer.append(stringBuffer);
|
buffer.append(stringBuffer);
|
||||||
buffer.append(")");
|
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 'type' and 'target'/'source' properties are present
|
if(jsonNode.has(IsRelatedTo.TARGET_PROPERTY)) {
|
||||||
if(size > 0) {
|
if(jsonNode.has(IsRelatedTo.SOURCE_PROPERTY)) {
|
||||||
if(!entryPoint) {
|
StringBuffer buffer = new StringBuffer();
|
||||||
stringBuffer.append(" )"); // Close ) SELECT
|
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;
|
return stringBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@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);
|
if(!entryPoint && direction==null) {
|
||||||
JsonNode targetJsonNode = jsonNode.get(IsRelatedTo.TARGET_PROPERTY);
|
throw new InternalServerErrorException("Caller Resource must invoke setDirectionByJson() first. This is a server bug. Please contact the administator. ");
|
||||||
|
|
||||||
JsonNode resourceJsonNode = null;
|
|
||||||
|
|
||||||
if(sourceJsonNode!=null) {
|
|
||||||
resourceJsonNode = sourceJsonNode;
|
|
||||||
direction = Direction.OUT;
|
|
||||||
} else if(targetJsonNode!=null) {
|
|
||||||
resourceJsonNode = targetJsonNode;
|
|
||||||
direction = Direction.IN;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stringBuffer = traverseThisEdge(stringBuffer);
|
int childrenPosition = 0;
|
||||||
|
|
||||||
JsonQueryResource jsonQueryResource = new JsonQueryResource(resourceJsonNode);
|
boolean traverseBack = this.traverseBack;
|
||||||
jsonQueryResource.setDirection(direction);
|
|
||||||
jsonQueryResource.setEntryPoint(false);
|
StringBuffer newBuffer = new StringBuffer();
|
||||||
stringBuffer = jsonQueryResource.analize(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();
|
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) {
|
if(!entryPoint) {
|
||||||
// Target has still to be analised
|
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;
|
alias = getAlias(true);
|
||||||
// It is no more and entry point for the function traverseThisEdge
|
StringBuffer sb = null;
|
||||||
entryPoint = false;
|
if(size > 0) {
|
||||||
stringBuffer = traverseThisEdge(stringBuffer);
|
sb = addConstraints(jsonNode, null, null);
|
||||||
// Restoring entryPoint indication
|
}
|
||||||
entryPoint = entryPointOldValue;
|
|
||||||
|
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;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -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 {
|
||||||
|
|
||||||
|
}
|
|
@ -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 {
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,24 +1,35 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.queries.templates;
|
package org.gcube.informationsystem.resourceregistry.queries.templates;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ArrayNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
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.AccessType;
|
||||||
|
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
||||||
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
|
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
|
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.NotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.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.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.queries.templates.QueryTemplateEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
|
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
@ -49,7 +60,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
public QueryTemplateManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
public QueryTemplateManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
||||||
this();
|
this();
|
||||||
this.oDatabaseDocument = oDatabaseDocument;
|
this.oDatabaseDocument = oDatabaseDocument;
|
||||||
getWorkingContext();
|
getWorkingEnvironment();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void checkERMatch() throws ResourceRegistryException {
|
protected void checkERMatch() throws ResourceRegistryException {
|
||||||
|
@ -92,11 +103,11 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
if (workingContext == null) {
|
if (workingEnvironment == null) {
|
||||||
workingContext = QueryTemplatesSecurityContext.getInstance();
|
workingEnvironment = QueryTemplateEnvironment.getInstance();
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -129,7 +140,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
return select;
|
return select;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void checkIfNameAlreadyExists() throws AlreadyPresentException {
|
protected void checkIfNameAlreadyExists() throws QueryTemplateAlreadyPresentException {
|
||||||
StringBuffer select = getSelectQuery();
|
StringBuffer select = getSelectQuery();
|
||||||
|
|
||||||
StringBuffer errorMessage = new StringBuffer();
|
StringBuffer errorMessage = new StringBuffer();
|
||||||
|
@ -146,7 +157,13 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
if (resultSet != null) {
|
if (resultSet != null) {
|
||||||
try {
|
try {
|
||||||
if(resultSet.hasNext()) {
|
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 {
|
}finally {
|
||||||
resultSet.close();
|
resultSet.close();
|
||||||
|
@ -179,7 +196,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
if(resultSet!=null) {
|
if(resultSet!=null) {
|
||||||
resultSet.close();
|
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();
|
OResult oResult = resultSet.next();
|
||||||
|
@ -203,6 +220,80 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String createOrUpdate()
|
||||||
|
throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
|
||||||
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
|
try {
|
||||||
|
oDatabaseDocument = getWorkingEnvironment().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
|
@Override
|
||||||
protected OVertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException {
|
protected OVertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
|
@ -218,7 +309,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
|
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
|
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
|
||||||
try {
|
try {
|
||||||
|
@ -238,7 +329,9 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
@Override
|
@Override
|
||||||
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
|
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
|
||||||
logger.debug("Going to delete {} with name {}", accessType.getName(), name);
|
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
|
@Override
|
||||||
|
@ -255,13 +348,28 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
|
||||||
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
ArrayNode arrayNode = objectMapper.createArrayNode();
|
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);
|
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
|
||||||
for (ODocument vertex : iterable) {
|
for (ODocument vertex : iterable) {
|
||||||
|
if(++position < offset) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
queryTemplateManagement.setElement((OVertex) vertex);
|
queryTemplateManagement.setElement((OVertex) vertex);
|
||||||
try {
|
try {
|
||||||
JsonNode jsonObject = queryTemplateManagement.serializeAsJsonNode();
|
JsonNode jsonObject = queryTemplateManagement.serializeAsJsonNode();
|
||||||
arrayNode.add(jsonObject);
|
arrayNode.add(jsonObject);
|
||||||
|
if(limit > 0 && ++count >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
} catch (ResourceRegistryException e) {
|
} catch (ResourceRegistryException e) {
|
||||||
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
|
||||||
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
|
||||||
|
|
|
@ -1,193 +0,0 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.requests;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import javax.ws.rs.core.UriInfo;
|
|
||||||
|
|
||||||
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
|
||||||
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.request.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 implements RequestInfo {
|
|
||||||
|
|
||||||
protected static Logger logger = LoggerFactory.getLogger(ServerRequestInfo.class);
|
|
||||||
|
|
||||||
protected UriInfo uriInfo;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Track if the request requested to include {@link Metadata}
|
|
||||||
*/
|
|
||||||
protected boolean includeMeta;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Track if the request requested to include {@link Metadata} in all
|
|
||||||
* {@link IdentifiableElement} or just in the root instance
|
|
||||||
*/
|
|
||||||
protected boolean allMeta;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Track if hierarchicalMode has been requested
|
|
||||||
*/
|
|
||||||
protected boolean hierarchicalMode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Track if the request requested to include contexts
|
|
||||||
*/
|
|
||||||
protected boolean includeContexts;
|
|
||||||
|
|
||||||
public ServerRequestInfo() {
|
|
||||||
this.includeMeta = false;
|
|
||||||
this.allMeta = false;
|
|
||||||
this.hierarchicalMode = false;
|
|
||||||
this.includeContexts = false;
|
|
||||||
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;
|
|
||||||
|
|
||||||
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
|
|
||||||
* @return the value of variable corresponding the request parameter independetly if
|
|
||||||
* the value has been set.
|
|
||||||
*/
|
|
||||||
public boolean setIfAllowed(String queryParameterKey, boolean bool) {
|
|
||||||
boolean toBeSet = bool && isAllowed(queryParameterKey);
|
|
||||||
|
|
||||||
switch (queryParameterKey) {
|
|
||||||
case InstancePath.INCLUDE_META_QUERY_PARAMETER:
|
|
||||||
includeMeta = toBeSet;
|
|
||||||
return includeMeta;
|
|
||||||
|
|
||||||
case InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER:
|
|
||||||
allMeta = toBeSet;
|
|
||||||
return allMeta;
|
|
||||||
|
|
||||||
case InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER:
|
|
||||||
includeContexts = toBeSet;
|
|
||||||
return includeContexts;
|
|
||||||
|
|
||||||
case InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER:
|
|
||||||
hierarchicalMode = toBeSet;
|
|
||||||
return hierarchicalMode;
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void checkQueryParameter(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 the Hierarchical Mode is set", t.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUriInfo(UriInfo uriInfo) {
|
|
||||||
this.uriInfo = uriInfo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void checkAllQueryParameters() {
|
|
||||||
checkIncludeQueryParameters();
|
|
||||||
checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void checkIncludeQueryParameters() {
|
|
||||||
checkIncludeAllMetaQueryParameters();
|
|
||||||
checkQueryParameter(InstancePath.INCLUDE_CONTEXTS_QUERY_PARAMETER);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void checkIncludeAllMetaQueryParameters() {
|
|
||||||
checkQueryParameter(InstancePath.INCLUDE_META_QUERY_PARAMETER);
|
|
||||||
checkQueryParameter(InstancePath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean includeMeta() {
|
|
||||||
return includeMeta;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setIncludeMeta(boolean includeMeta) {
|
|
||||||
this.includeMeta = includeMeta;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean allMeta() {
|
|
||||||
return allMeta;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setAllMeta(boolean allMeta) {
|
|
||||||
this.allMeta = allMeta;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isHierarchicalMode() {
|
|
||||||
return hierarchicalMode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setHierarchicalMode(boolean hierarchicalMode) {
|
|
||||||
this.hierarchicalMode = hierarchicalMode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean includeContexts() {
|
|
||||||
return includeContexts;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setIncludeContexts(boolean includeContexts) {
|
|
||||||
this.includeContexts = includeContexts;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -5,6 +5,7 @@ import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.DefaultValue;
|
import javax.ws.rs.DefaultValue;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
import javax.ws.rs.HEAD;
|
import javax.ws.rs.HEAD;
|
||||||
|
@ -14,13 +15,14 @@ import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
import javax.ws.rs.QueryParam;
|
import javax.ws.rs.QueryParam;
|
||||||
import javax.ws.rs.core.Context;
|
import javax.ws.rs.core.Context;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.MultivaluedMap;
|
import javax.ws.rs.core.MultivaluedMap;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import javax.ws.rs.core.Response.Status;
|
import javax.ws.rs.core.Response.Status;
|
||||||
import javax.ws.rs.core.UriInfo;
|
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.model.reference.entities.Resource;
|
||||||
|
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
|
||||||
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
|
@ -28,19 +30,21 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
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.queries.InvalidQueryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
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.AccessPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.TypePath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.TypePath;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.Query;
|
import org.gcube.informationsystem.resourceregistry.queries.Query;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.QueryImpl;
|
import org.gcube.informationsystem.resourceregistry.queries.QueryImpl;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
|
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
|
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
|
||||||
import org.gcube.informationsystem.types.TypeMapper;
|
import org.gcube.informationsystem.types.TypeMapper;
|
||||||
import org.gcube.informationsystem.types.reference.Type;
|
import org.gcube.informationsystem.types.reference.Type;
|
||||||
|
@ -57,6 +61,11 @@ public class Access extends BaseRest {
|
||||||
public static final String RELATION_TYPE_PATH_PARAMETER = "RELATION_TYPE_NAME";
|
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 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() {
|
public Access() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
@ -69,10 +78,22 @@ public class Access extends BaseRest {
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String getAllContexts() throws ResourceRegistryException {
|
public String getAllContexts() throws ResourceRegistryException {
|
||||||
logger.info("Requested to read all {}s", org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
|
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();
|
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
/*
|
||||||
|
* We never provide meta information
|
||||||
|
* for context via this REST API.
|
||||||
|
* Contexts collection should be used instead.
|
||||||
|
*/
|
||||||
|
serverRequestInfo.setIncludeMeta(false);
|
||||||
|
serverRequestInfo.setAllMeta(false);
|
||||||
|
/*
|
||||||
|
* serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
* serverRequestInfo.setAllMeta(true);
|
||||||
|
*/
|
||||||
|
|
||||||
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
return contextManagement.all(false);
|
return contextManagement.all(false);
|
||||||
|
@ -88,19 +109,26 @@ public class Access extends BaseRest {
|
||||||
public String getContext(@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid)
|
public String getContext(@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid)
|
||||||
throws ContextNotFoundException, ResourceRegistryException {
|
throws ContextNotFoundException, ResourceRegistryException {
|
||||||
if(uuid.compareTo(ContextPath.CURRENT_CONTEXT_PATH_PART)==0){
|
if(uuid.compareTo(ContextPath.CURRENT_CONTEXT_PATH_PART)==0){
|
||||||
uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString();
|
uuid = ContextUtility.getCurrentRequestEnvironment().getUUID().toString();
|
||||||
}
|
}
|
||||||
logger.info("Requested to read {} with id {} ", org.gcube.informationsystem.contexts.reference.entities.Context.NAME, uuid);
|
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 serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
/*
|
||||||
|
* We have to think if never provide meta information
|
||||||
|
* for context via this REST API.
|
||||||
|
* Contexts collection should be used instead.
|
||||||
|
*/
|
||||||
|
serverRequestInfo.setAllMeta(true);
|
||||||
|
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setUUID(UUID.fromString(uuid));
|
contextManagement.setUUID(UUID.fromString(uuid));
|
||||||
return contextManagement.readAsString();
|
return contextManagement.readAsString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* GET /access/types/{TYPE_NAME}[?polymorphic=false]
|
* GET /access/types/{TYPE_NAME}[?polymorphic=false]
|
||||||
* e.g. GET /access/types/ContactFacet?polymorphic=true
|
* e.g. GET /access/types/ContactFacet?polymorphic=true
|
||||||
|
@ -112,10 +140,11 @@ public class Access extends BaseRest {
|
||||||
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
|
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
|
||||||
throws SchemaNotFoundException, ResourceRegistryException {
|
throws SchemaNotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested Schema for type {}", type);
|
logger.info("Requested Schema for type {}", type);
|
||||||
CalledMethodProvider.instance.set("readType");
|
setAccountingMethod(Method.READ, Type.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
serverRequestInfo.setAllMeta(true);
|
||||||
|
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
|
||||||
TypeManagement typeManagement = new TypeManagement();
|
TypeManagement typeManagement = new TypeManagement();
|
||||||
typeManagement.setTypeName(type);
|
typeManagement.setTypeName(type);
|
||||||
|
@ -126,6 +155,72 @@ public class Access extends BaseRest {
|
||||||
throw new ResourceRegistryException(e);
|
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]
|
* GET /access/instances/{TYPE_NAME}[?polymorphic=true]
|
||||||
|
@ -139,12 +234,13 @@ public class Access extends BaseRest {
|
||||||
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
|
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
|
||||||
throws NotFoundException, ResourceRegistryException {
|
throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
|
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
|
||||||
CalledMethodProvider.instance.set("listInstances");
|
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
return erManagement.all(polymorphic);
|
return erManagement.all(polymorphic);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -159,12 +255,12 @@ public class Access extends BaseRest {
|
||||||
public Response instanceExists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
public Response instanceExists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to check if {} with id {} exists", type, uuid);
|
logger.info("Requested to check if {} with id {} exists", type, uuid);
|
||||||
CalledMethodProvider.instance.set("existInstance");
|
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
erManagement.setUUID(UUID.fromString(uuid));
|
erManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
@ -196,21 +292,19 @@ public class Access extends BaseRest {
|
||||||
public String getInstance(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
public String getInstance(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to read {} with id {}", type, uuid);
|
logger.info("Requested to read {} with id {}", type, uuid);
|
||||||
CalledMethodProvider.instance.set("readInstance");
|
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
|
|
||||||
erManagement.setElementType(type);
|
erManagement.setElementType(type);
|
||||||
erManagement.setUUID(UUID.fromString(uuid));
|
erManagement.setUUID(UUID.fromString(uuid));
|
||||||
return erManagement.read().toString();
|
return erManagement.read().toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* GET /access/instances/{TYPE_NAME}/{UUID}/contexts
|
* GET /access/instances/{TYPE_NAME}/{UUID}/contexts
|
||||||
* e.g. GET /access/instances/ContactFacet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86/contexts
|
* e.g. GET /access/instances/ContactFacet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86/contexts
|
||||||
|
@ -222,13 +316,14 @@ public class Access extends BaseRest {
|
||||||
public String getInstanceContexts(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
public String getInstanceContexts(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String instanceId) throws NotFoundException, ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String instanceId) throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
|
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);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
erManagement.setUUID(UUID.fromString(instanceId));
|
erManagement.setUUID(UUID.fromString(instanceId));
|
||||||
return erManagement.getContexts();
|
return erManagement.getContexts();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It includeSubtypes to query Entities and Relations in the current Context.<br />
|
* It includeSubtypes to query Entities and Relations in the current Context.<br />
|
||||||
* It accepts idempotent query only.. <br />
|
* It accepts idempotent query only.. <br />
|
||||||
|
@ -241,6 +336,9 @@ public class Access extends BaseRest {
|
||||||
*
|
*
|
||||||
* e.g. GET /access/query?q=SELECT FROM V
|
* 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 query Defines the query to send to the backend.
|
||||||
* @param raw request a raw response (not a Element based response)
|
* @param raw request a raw response (not a Element based response)
|
||||||
* @return The JSON representation of the result
|
* @return The JSON representation of the result
|
||||||
|
@ -253,14 +351,18 @@ public class Access extends BaseRest {
|
||||||
@QueryParam(AccessPath.RAW_QUERY_PARAMETER) @DefaultValue(AccessPath.RAW_QUERY_PARAMETER_DEFAULT_VALUE) Boolean raw)
|
@QueryParam(AccessPath.RAW_QUERY_PARAMETER) @DefaultValue(AccessPath.RAW_QUERY_PARAMETER_DEFAULT_VALUE) Boolean raw)
|
||||||
throws InvalidQueryException {
|
throws InvalidQueryException {
|
||||||
logger.info("Requested query (Raw {}):\n{}", raw, query);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
if(raw) {
|
if(raw) {
|
||||||
// TODO Check if the role allow to request raw data
|
// TODO Check if the role allow to request raw data
|
||||||
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
||||||
}else {
|
}else {
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
}
|
}
|
||||||
|
|
||||||
Query queryManager = new QueryImpl();
|
Query queryManager = new QueryImpl();
|
||||||
|
@ -312,10 +414,11 @@ public class Access extends BaseRest {
|
||||||
@Path(AccessPath.QUERY_PATH_PART)
|
@Path(AccessPath.QUERY_PATH_PART)
|
||||||
public String jsonQuery(String jsonQuery) throws InvalidQueryException, ResourceRegistryException {
|
public String jsonQuery(String jsonQuery) throws InvalidQueryException, ResourceRegistryException {
|
||||||
logger.info("Requested json query \n{}", jsonQuery);
|
logger.info("Requested json query \n{}", jsonQuery);
|
||||||
CalledMethodProvider.instance.set("jsonQuery");
|
setAccountingMethod(Method.QUERY, JSON_QUERY_METHOD);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
JsonQuery jsonQueryManager = new JsonQuery();
|
JsonQuery jsonQueryManager = new JsonQuery();
|
||||||
jsonQueryManager.setJsonQuery(jsonQuery);
|
jsonQueryManager.setJsonQuery(jsonQuery);
|
||||||
|
@ -338,12 +441,12 @@ public class Access extends BaseRest {
|
||||||
* All the Resources with a ContactFacet :
|
* All the Resources with a ContactFacet :
|
||||||
* /access/query/Resource/ConsistsOf/ContactFacet?_polymorphic=true&_direction=out
|
* /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
|
* 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
|
* 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"})
|
@SuppressWarnings({"rawtypes"})
|
||||||
|
@ -363,12 +466,13 @@ public class Access extends BaseRest {
|
||||||
logger.info("Requested {} instances having a(n) {} ({}={}} with {} ({}={}). Request URI is {})", resourcetype, relationType,
|
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());
|
AccessPath._DIRECTION_QUERY_PARAMETER, direction, referenceType, AccessPath._POLYMORPHIC_QUERY_PARAMETER, polymorphic, uriInfo.getRequestUri());
|
||||||
|
|
||||||
CalledMethodProvider.instance.set("query");
|
setAccountingMethod(Method.QUERY, PREPARED_QUERY_METHOD);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
ElementManagement erManagement = ElementManagementUtility.getERManagement(resourcetype);
|
ElementManagement erManagement = ERManagementUtility.getERManagement(resourcetype);
|
||||||
|
|
||||||
if(erManagement instanceof ResourceManagement) {
|
if(erManagement instanceof ResourceManagement) {
|
||||||
UUID refereceUUID = null;
|
UUID refereceUUID = null;
|
||||||
|
|
|
@ -3,8 +3,9 @@ package org.gcube.informationsystem.resourceregistry.rest;
|
||||||
import javax.ws.rs.core.Context;
|
import javax.ws.rs.core.Context;
|
||||||
import javax.ws.rs.core.UriInfo;
|
import javax.ws.rs.core.UriInfo;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
|
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -21,14 +22,33 @@ public class BaseRest {
|
||||||
public BaseRest() {
|
public BaseRest() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected void setAccountingMethod(String method) {
|
||||||
|
CalledMethodProvider.instance.set(method);
|
||||||
|
}
|
||||||
|
|
||||||
protected ServerRequestInfo initRequestInfo() {
|
protected void setAccountingMethod(Method method, String type) {
|
||||||
ServerRequestInfo requestInfo = new ServerRequestInfo();
|
StringBuffer accountingMethod = new StringBuffer();
|
||||||
|
accountingMethod.append(method.getPrefix());
|
||||||
|
accountingMethod.append(type);
|
||||||
|
accountingMethod.append(method.getSuffix());
|
||||||
|
setAccountingMethod(accountingMethod.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ServerRequestInfo initRequestInfo(ServerRequestInfo requestInfo) {
|
||||||
requestInfo.setUriInfo(uriInfo);
|
requestInfo.setUriInfo(uriInfo);
|
||||||
|
|
||||||
RequestUtility.getRequestInfo().set(requestInfo);
|
RequestUtility.getRequestInfo().set(requestInfo);
|
||||||
|
|
||||||
return requestInfo;
|
return requestInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected ServerRequestInfo initRequestInfo(int offset, int limit) {
|
||||||
|
ServerRequestInfo requestInfo = new ServerRequestInfo(offset, limit);
|
||||||
|
return initRequestInfo(requestInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ServerRequestInfo initRequestInfo() {
|
||||||
|
ServerRequestInfo requestInfo = new ServerRequestInfo();
|
||||||
|
return initRequestInfo(requestInfo);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,10 +18,11 @@ import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
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.api.rest.ContextPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
@ -30,31 +31,51 @@ import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
||||||
public class ContextManager extends BaseRest {
|
public class ContextManager extends BaseRest {
|
||||||
|
|
||||||
public static final String CONTEXT_UUID_PATH_PARAMETER = "CONTEXT_UUID";
|
public static final String CONTEXT_UUID_PATH_PARAMETER = "CONTEXT_UUID";
|
||||||
|
|
||||||
public ContextManager() {
|
public ContextManager() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/**
|
||||||
|
*
|
||||||
* GET /contexts
|
* GET /contexts
|
||||||
*
|
*
|
||||||
|
* It returns the list of contexts as Json Array.
|
||||||
|
* Depending on the role and the requested parameter
|
||||||
|
* the json defining the context could contain
|
||||||
|
* minimal information.
|
||||||
|
*
|
||||||
|
* Only IS-Manager and Infrastructure-Manager are
|
||||||
|
* allowed to get all the information about contexts such as:
|
||||||
|
*
|
||||||
|
* - not obfuscated metadata (i.e. createdBy and lastUpdateBy)
|
||||||
|
* - context state
|
||||||
|
*
|
||||||
|
* IS-Manager and Infrastructure-Manager get the metadata by default
|
||||||
|
* even not requested.
|
||||||
|
*
|
||||||
|
* Other users requesting must explicitly request the metadata
|
||||||
|
* to get them but they will always receive obfuscated
|
||||||
|
* createdBy and lastUpdateBy properties.
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String all() throws ContextNotFoundException, ResourceRegistryException {
|
public String all() throws ContextNotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to read all {}s", Context.NAME);
|
logger.info("Requested to read all {}s", Context.NAME);
|
||||||
CalledMethodProvider.instance.set("listContexts");
|
setAccountingMethod(Method.LIST, Context.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
|
||||||
|
serverRequestInfo.setIncludeMeta(true);
|
||||||
serverRequestInfo.setAllMeta(true);
|
serverRequestInfo.setAllMeta(true);
|
||||||
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
return contextManagement.all(false);
|
return contextManagement.all(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/**
|
||||||
* GET /contexts/{UUID}
|
* GET /contexts/{UUID}
|
||||||
* e.g. GET /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
* e.g. GET /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
||||||
*
|
*
|
||||||
|
@ -66,21 +87,21 @@ public class ContextManager extends BaseRest {
|
||||||
public String read(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid)
|
public String read(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid)
|
||||||
throws ContextNotFoundException, ResourceRegistryException {
|
throws ContextNotFoundException, ResourceRegistryException {
|
||||||
if(uuid.compareTo(ContextPath.CURRENT_CONTEXT_PATH_PART)==0){
|
if(uuid.compareTo(ContextPath.CURRENT_CONTEXT_PATH_PART)==0){
|
||||||
uuid = ContextUtility.getCurrentSecurityContext().getUUID().toString();
|
uuid = ContextUtility.getCurrentRequestEnvironment().getUUID().toString();
|
||||||
}
|
}
|
||||||
logger.info("Requested to read {} with id {} ", Context.NAME, uuid);
|
logger.info("Requested to read {} with id {} ", Context.NAME, uuid);
|
||||||
CalledMethodProvider.instance.set("readContext");
|
setAccountingMethod(Method.READ, Context.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
|
serverRequestInfo.setIncludeMeta(true);
|
||||||
serverRequestInfo.setAllMeta(true);
|
serverRequestInfo.setAllMeta(true);
|
||||||
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
|
||||||
|
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setUUID(UUID.fromString(uuid));
|
contextManagement.setUUID(UUID.fromString(uuid));
|
||||||
return contextManagement.readAsString();
|
return contextManagement.readAsString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/**
|
||||||
* PUT /contexts/{UUID}
|
* PUT /contexts/{UUID}
|
||||||
* e.g. PUT /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
* e.g. PUT /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
||||||
*
|
*
|
||||||
|
@ -94,11 +115,11 @@ public class ContextManager extends BaseRest {
|
||||||
public String updateCreate(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid, String json)
|
public String updateCreate(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid, String json)
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
logger.info("Requested to update/create {} with json {} ", Context.NAME, json);
|
logger.info("Requested to update/create {} with json {} ", Context.NAME, json);
|
||||||
CalledMethodProvider.instance.set("updateContext");
|
setAccountingMethod(Method.UPDATE, Context.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
|
serverRequestInfo.setIncludeMeta(true);
|
||||||
serverRequestInfo.setAllMeta(true);
|
serverRequestInfo.setAllMeta(true);
|
||||||
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
|
||||||
|
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setUUID(UUID.fromString(uuid));
|
contextManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
@ -106,6 +127,35 @@ public class ContextManager extends BaseRest {
|
||||||
return contextManagement.createOrUpdate();
|
return contextManagement.createOrUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * POST /contexts/{UUID}
|
||||||
|
// * e.g. POST /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
||||||
|
// *
|
||||||
|
// * BODY: {...}
|
||||||
|
// *
|
||||||
|
// * The body contains the Contexts JSon representation
|
||||||
|
// * only the state property will be evaluated in this
|
||||||
|
// * method
|
||||||
|
// *
|
||||||
|
// */
|
||||||
|
// @POST
|
||||||
|
// @Path("{" + ContextManager.CONTEXT_UUID_PATH_PARAMETER + "}")
|
||||||
|
// @Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
|
// public String changeState(@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String uuid, String json)
|
||||||
|
// throws ResourceRegistryException {
|
||||||
|
// logger.info("Requested to activate {} with UUID {}", Context.NAME, uuid);
|
||||||
|
// setAccountingMethod(Method.UPDATE, Context.NAME);
|
||||||
|
//
|
||||||
|
// ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
|
// serverRequestInfo.setIncludeMeta(true);
|
||||||
|
// serverRequestInfo.setAllMeta(true);
|
||||||
|
//
|
||||||
|
// ContextManagement contextManagement = new ContextManagement();
|
||||||
|
// contextManagement.setJson(json);
|
||||||
|
// contextManagement.setUUID(UUID.fromString(uuid));
|
||||||
|
// return contextManagement.changeState();
|
||||||
|
// }
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* DELETE /contexts/{UUID}
|
* DELETE /contexts/{UUID}
|
||||||
* e.g. DELETE /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
* e.g. DELETE /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0
|
||||||
|
|
|
@ -16,7 +16,6 @@ import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import javax.ws.rs.core.Response.Status;
|
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.ResourceInitializer;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
|
@ -25,9 +24,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.resource.ResourceNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.resource.ResourceNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
@ -36,7 +35,10 @@ import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
||||||
public class InstancesManager extends BaseRest {
|
public class InstancesManager extends BaseRest {
|
||||||
|
|
||||||
public static final String UUID_PATH_PARAMETER = "UUID";
|
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() {
|
public InstancesManager() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
@ -54,12 +56,13 @@ public class InstancesManager extends BaseRest {
|
||||||
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
|
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
|
||||||
throws NotFoundException, ResourceRegistryException {
|
throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
|
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
|
||||||
CalledMethodProvider.instance.set("listInstances");
|
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
return erManagement.all(polymorphic);
|
return erManagement.all(polymorphic);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -75,13 +78,13 @@ public class InstancesManager extends BaseRest {
|
||||||
public Response exists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
public Response exists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to check if {} with id {} exists", type, uuid);
|
logger.info("Requested to check if {} with id {} exists", type, uuid);
|
||||||
CalledMethodProvider.instance.set("existInstance");
|
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
try {
|
try {
|
||||||
erManagement.setUUID(UUID.fromString(uuid));
|
erManagement.setUUID(UUID.fromString(uuid));
|
||||||
boolean found = erManagement.exists();
|
boolean found = erManagement.exists();
|
||||||
|
@ -113,12 +116,12 @@ public class InstancesManager extends BaseRest {
|
||||||
public String read(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
public String read(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to read {} with id {}", type, uuid);
|
logger.info("Requested to read {} with id {}", type, uuid);
|
||||||
CalledMethodProvider.instance.set("readInstance");
|
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkAllQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
erManagement.setElementType(type);
|
erManagement.setElementType(type);
|
||||||
erManagement.setUUID(UUID.fromString(uuid));
|
erManagement.setUUID(UUID.fromString(uuid));
|
||||||
return erManagement.read().toString();
|
return erManagement.read().toString();
|
||||||
|
@ -139,13 +142,13 @@ public class InstancesManager extends BaseRest {
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid, String json) throws ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid, String json) throws ResourceRegistryException {
|
||||||
logger.info("Requested to update/create {} with id {}", type, uuid);
|
logger.info("Requested to update/create {} with id {}", type, uuid);
|
||||||
logger.trace("Requested to update/create {} with id {} with json {}", type, uuid, json);
|
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 serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeQueryParameters();
|
serverRequestInfo.checkAllIncludeQueryParameters();
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
erManagement.setUUID(UUID.fromString(uuid));
|
erManagement.setUUID(UUID.fromString(uuid));
|
||||||
erManagement.setElementType(type);
|
erManagement.setElementType(type);
|
||||||
erManagement.setJson(json);
|
erManagement.setJson(json);
|
||||||
|
@ -162,9 +165,9 @@ public class InstancesManager extends BaseRest {
|
||||||
public Response delete(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
public Response delete(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
|
||||||
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws ResourceRegistryException {
|
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws ResourceRegistryException {
|
||||||
logger.info("Requested to delete {} with id {}", type, uuid);
|
logger.info("Requested to delete {} with id {}", type, uuid);
|
||||||
CalledMethodProvider.instance.set("deleteInstance");
|
setAccountingMethod(Method.DELETE, InstancesManager.INSTANCE);
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
erManagement.setUUID(UUID.fromString(uuid));
|
erManagement.setUUID(UUID.fromString(uuid));
|
||||||
erManagement.delete();
|
erManagement.delete();
|
||||||
|
|
||||||
|
@ -189,10 +192,10 @@ public class InstancesManager extends BaseRest {
|
||||||
@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String contextId)
|
@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String contextId)
|
||||||
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
|
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
|
||||||
CalledMethodProvider.instance.set("getInstanceContexts");
|
setAccountingMethod(InstancesManager.GET_INSTANCE_CONTEXTS_METHOD);
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
erManagement.setUUID(UUID.fromString(instanceId));
|
erManagement.setUUID(UUID.fromString(instanceId));
|
||||||
return erManagement.getContexts();
|
return erManagement.getContexts();
|
||||||
}
|
}
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -12,15 +12,15 @@ import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import javax.ws.rs.core.Response.Status;
|
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.queries.templates.reference.entities.QueryTemplate;
|
||||||
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.InvalidQueryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
|
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
@ -42,10 +42,12 @@ public class QueryTemplateManager extends BaseRest {
|
||||||
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
||||||
public String all() throws NotFoundException, ResourceRegistryException {
|
public String all() throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to read all {}s", QueryTemplate.NAME);
|
logger.info("Requested to read all {}s", QueryTemplate.NAME);
|
||||||
CalledMethodProvider.instance.set("listQueryTemplates");
|
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
serverRequestInfo.setAllMeta(true);
|
||||||
|
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
serverRequestInfo.checkLimitOffset();
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
return queryTemplateManagement.all(false);
|
return queryTemplateManagement.all(false);
|
||||||
|
@ -85,20 +87,19 @@ public class QueryTemplateManager extends BaseRest {
|
||||||
@Path("{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
|
@Path("{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
|
||||||
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
|
||||||
@Produces(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 {
|
throws InvalidQueryException, ResourceRegistryException {
|
||||||
logger.info("Requested {} creation with name {} and content {}", QueryTemplate.NAME, queryTemplateName, json);
|
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 serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
serverRequestInfo.setAllMeta(true);
|
||||||
|
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
queryTemplateManagement.setName(queryTemplateName);
|
queryTemplateManagement.setName(queryTemplateName);
|
||||||
queryTemplateManagement.setJson(json);
|
queryTemplateManagement.setJson(json);
|
||||||
String ret = queryTemplateManagement.createOrUpdate();
|
return queryTemplateManagement.createOrUpdate();
|
||||||
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
@ -111,10 +112,11 @@ public class QueryTemplateManager extends BaseRest {
|
||||||
public String read(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
|
public String read(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
|
||||||
throws NotFoundException, ResourceRegistryException {
|
throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
|
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
|
||||||
CalledMethodProvider.instance.set("readQueryTemplate");
|
setAccountingMethod(Method.READ, QueryTemplate.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
serverRequestInfo.setAllMeta(true);
|
||||||
|
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
queryTemplateManagement.setName(queryTemplateName);
|
queryTemplateManagement.setName(queryTemplateName);
|
||||||
|
@ -124,7 +126,7 @@ public class QueryTemplateManager extends BaseRest {
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* POST /query-templates/{QUERY_TEMPLATE_NAME}
|
* POST /query-templates/{QUERY_TEMPLATE_NAME}
|
||||||
* e.g. GET /query-templates/GetAllEServiceWithState
|
* e.g. POST /query-templates/GetAllEServiceWithState
|
||||||
*
|
*
|
||||||
* params = { "$state" : "ready" }
|
* params = { "$state" : "ready" }
|
||||||
*
|
*
|
||||||
|
@ -135,10 +137,10 @@ public class QueryTemplateManager extends BaseRest {
|
||||||
public String run(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
|
public String run(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
|
||||||
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
|
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
|
||||||
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
|
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
|
||||||
CalledMethodProvider.instance.set("readQueryTemplate");
|
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeAllMetaQueryParameters();
|
serverRequestInfo.checkAllBooleanQueryParameters();
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
queryTemplateManagement.setName(queryTemplateName);
|
queryTemplateManagement.setName(queryTemplateName);
|
||||||
|
@ -157,7 +159,7 @@ public class QueryTemplateManager extends BaseRest {
|
||||||
public Response delete(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
|
public Response delete(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
|
||||||
throws NotFoundException, ResourceRegistryException {
|
throws NotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested to delete {} with name {} ", QueryTemplate.NAME, queryTemplateName);
|
logger.info("Requested to delete {} with name {} ", QueryTemplate.NAME, queryTemplateName);
|
||||||
CalledMethodProvider.instance.set("deleteQueryTemplate");
|
setAccountingMethod(Method.DELETE, QueryTemplate.NAME);
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
queryTemplateManagement.setName(queryTemplateName);
|
queryTemplateManagement.setName(queryTemplateName);
|
||||||
|
|
|
@ -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.GCubeSecret;
|
||||||
import org.gcube.common.authorization.utils.secret.JWTSecret;
|
import org.gcube.common.authorization.utils.secret.JWTSecret;
|
||||||
import org.gcube.common.authorization.utils.secret.Secret;
|
import org.gcube.common.authorization.utils.secret.Secret;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -49,6 +50,7 @@ public class RequestFilter implements ContainerRequestFilter, ContainerResponseF
|
||||||
|
|
||||||
SecretManagerProvider.instance.set(secretManager);
|
SecretManagerProvider.instance.set(secretManager);
|
||||||
|
|
||||||
|
RequestUtility.getRequestInfo().remove();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -56,6 +58,7 @@ public class RequestFilter implements ContainerRequestFilter, ContainerResponseF
|
||||||
throws IOException {
|
throws IOException {
|
||||||
logger.trace("ResponseFilter");
|
logger.trace("ResponseFilter");
|
||||||
SecretManagerProvider.instance.remove();
|
SecretManagerProvider.instance.remove();
|
||||||
|
RequestUtility.getRequestInfo().remove();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,7 +15,6 @@ import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ArrayNode;
|
||||||
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
|
|
||||||
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
@ -24,10 +23,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.reso
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
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;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath.SharingOperation;
|
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath.SharingOperation;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
|
||||||
import org.gcube.informationsystem.utils.TypeUtility;
|
import org.gcube.informationsystem.utils.TypeUtility;
|
||||||
|
|
||||||
|
@ -90,7 +89,7 @@ public class SharingManager extends BaseRest {
|
||||||
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeQueryParameters();
|
serverRequestInfo.checkAllIncludeQueryParameters();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
StringBuffer calledMethod = new StringBuffer();
|
StringBuffer calledMethod = new StringBuffer();
|
||||||
|
@ -110,7 +109,7 @@ public class SharingManager extends BaseRest {
|
||||||
calledMethod.append("RemoveFromContext");
|
calledMethod.append("RemoveFromContext");
|
||||||
}
|
}
|
||||||
calledMethod.append("NoPropagationConstraint");
|
calledMethod.append("NoPropagationConstraint");
|
||||||
CalledMethodProvider.instance.set(calledMethod.toString());
|
setAccountingMethod(calledMethod.toString());
|
||||||
|
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(body);
|
ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(body);
|
||||||
|
@ -172,7 +171,7 @@ public class SharingManager extends BaseRest {
|
||||||
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.checkIncludeQueryParameters();
|
serverRequestInfo.checkAllIncludeQueryParameters();
|
||||||
|
|
||||||
StringBuffer calledMethod = new StringBuffer();
|
StringBuffer calledMethod = new StringBuffer();
|
||||||
if(dryRun==null) {
|
if(dryRun==null) {
|
||||||
|
@ -190,25 +189,25 @@ public class SharingManager extends BaseRest {
|
||||||
logger.info("Requested {} {} with UUID {} from {} with UUID {}", dryRun? "a dry run for removing": "to remove", type, instanceId, Context.NAME, contextId);
|
logger.info("Requested {} {} with UUID {} from {} with UUID {}", dryRun? "a dry run for removing": "to remove", type, instanceId, Context.NAME, contextId);
|
||||||
calledMethod.append("RemoveFromContext");
|
calledMethod.append("RemoveFromContext");
|
||||||
}
|
}
|
||||||
CalledMethodProvider.instance.set(calledMethod.toString());
|
setAccountingMethod(calledMethod.toString());
|
||||||
|
|
||||||
|
|
||||||
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
|
||||||
elementManagement.setUUID(UUID.fromString(instanceId));
|
erManagement.setUUID(UUID.fromString(instanceId));
|
||||||
elementManagement.setDryRun(dryRun);
|
erManagement.setDryRun(dryRun);
|
||||||
UUID contextUUID = UUID.fromString(contextId);
|
UUID contextUUID = UUID.fromString(contextId);
|
||||||
|
|
||||||
|
|
||||||
if(operation == SharingOperation.ADD) {
|
if(operation == SharingOperation.ADD) {
|
||||||
((ERManagement) elementManagement).setForceAddToContext(forceAddToContext);
|
((ERManagement) erManagement).setForceAddToContext(forceAddToContext);
|
||||||
((ERManagement) elementManagement).addToContext(contextUUID);
|
((ERManagement) erManagement).addToContext(contextUUID);
|
||||||
}else {
|
}else {
|
||||||
((ERManagement) elementManagement).removeFromContext(contextUUID);
|
((ERManagement) erManagement).removeFromContext(contextUUID);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
return serializeAffectedInstaces(objectMapper, elementManagement.getAffectedInstances());
|
return serializeAffectedInstaces(objectMapper, erManagement.getAffectedInstances());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new ResourceRegistryException(e);
|
throw new ResourceRegistryException(e);
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,22 +5,23 @@ import java.util.List;
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.DefaultValue;
|
import javax.ws.rs.DefaultValue;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.InternalServerErrorException;
|
||||||
import javax.ws.rs.PUT;
|
import javax.ws.rs.PUT;
|
||||||
import javax.ws.rs.Path;
|
import javax.ws.rs.Path;
|
||||||
import javax.ws.rs.PathParam;
|
import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
import javax.ws.rs.QueryParam;
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.WebApplicationException;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import javax.ws.rs.core.Response.Status;
|
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.ResourceInitializer;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.rest.TypePath;
|
import org.gcube.informationsystem.resourceregistry.api.rest.TypePath;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
|
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
|
||||||
import org.gcube.informationsystem.types.TypeMapper;
|
import org.gcube.informationsystem.types.TypeMapper;
|
||||||
import org.gcube.informationsystem.types.reference.Type;
|
import org.gcube.informationsystem.types.reference.Type;
|
||||||
|
@ -37,6 +38,23 @@ public class TypeManager extends BaseRest {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean the types cache
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
// @DELETE
|
||||||
|
public Response cleanCache() {
|
||||||
|
try {
|
||||||
|
// TODO
|
||||||
|
return Response.status(Status.NO_CONTENT).build();
|
||||||
|
}catch (WebApplicationException e) {
|
||||||
|
throw e;
|
||||||
|
}catch (Exception e) {
|
||||||
|
throw new InternalServerErrorException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* PUT /types/{TYPE_NAME}
|
* PUT /types/{TYPE_NAME}
|
||||||
* e.g. PUT /types/ContactFacet
|
* e.g. PUT /types/ContactFacet
|
||||||
|
@ -51,11 +69,11 @@ public class TypeManager extends BaseRest {
|
||||||
public Response create(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String typeName, String json)
|
public Response create(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String typeName, String json)
|
||||||
throws SchemaException, ResourceRegistryException {
|
throws SchemaException, ResourceRegistryException {
|
||||||
logger.info("Requested {} creation with schema {}", typeName, json);
|
logger.info("Requested {} creation with schema {}", typeName, json);
|
||||||
CalledMethodProvider.instance.set("createType");
|
setAccountingMethod(Method.CREATE, Type.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.setAllMeta(true);
|
serverRequestInfo.setAllMeta(true);
|
||||||
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
|
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
|
||||||
TypeManagement schemaManagement = new TypeManagement();
|
TypeManagement schemaManagement = new TypeManagement();
|
||||||
schemaManagement.setTypeName(typeName);
|
schemaManagement.setTypeName(typeName);
|
||||||
|
@ -77,11 +95,11 @@ public class TypeManager extends BaseRest {
|
||||||
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
|
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
|
||||||
throws SchemaNotFoundException, ResourceRegistryException {
|
throws SchemaNotFoundException, ResourceRegistryException {
|
||||||
logger.info("Requested Schema for type {}", type);
|
logger.info("Requested Schema for type {}", type);
|
||||||
CalledMethodProvider.instance.set("readType");
|
setAccountingMethod(Method.READ, Type.NAME);
|
||||||
|
|
||||||
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
ServerRequestInfo serverRequestInfo = initRequestInfo();
|
||||||
serverRequestInfo.setAllMeta(true);
|
serverRequestInfo.setAllMeta(true);
|
||||||
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
|
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
|
||||||
|
|
||||||
TypeManagement schemaManagement = new TypeManagement();
|
TypeManagement schemaManagement = new TypeManagement();
|
||||||
schemaManagement.setTypeName(type);
|
schemaManagement.setTypeName(type);
|
||||||
|
|
|
@ -7,6 +7,9 @@ import java.lang.annotation.Target;
|
||||||
|
|
||||||
import javax.ws.rs.HttpMethod;
|
import javax.ws.rs.HttpMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
@Target({ElementType.METHOD})
|
@Target({ElementType.METHOD})
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@HttpMethod("PATCH")
|
@HttpMethod("PATCH")
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.requests;
|
package org.gcube.informationsystem.resourceregistry.rest.requests;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
|
@ -0,0 +1,228 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.rest.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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -10,11 +10,11 @@ import org.gcube.informationsystem.base.reference.AccessType;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
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.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.types.TypeMapper;
|
import org.gcube.informationsystem.types.TypeMapper;
|
||||||
import org.gcube.informationsystem.types.reference.Type;
|
import org.gcube.informationsystem.types.reference.Type;
|
||||||
import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
|
import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
|
||||||
|
@ -67,8 +67,8 @@ public class CachedType<T extends Type> {
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
logger.debug("GettingType {} schema", typeName);
|
logger.debug("GettingType {} schema", typeName);
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
try {
|
try {
|
||||||
|
|
|
@ -24,6 +24,7 @@ public class OrientDBTypeMapping {
|
||||||
static {
|
static {
|
||||||
BASE_TYPE_TO_OTYPE = new HashMap<>();
|
BASE_TYPE_TO_OTYPE = new HashMap<>();
|
||||||
|
|
||||||
|
BASE_TYPE_TO_OTYPE.put(BaseType.ANY, OType.ANY);
|
||||||
BASE_TYPE_TO_OTYPE.put(BaseType.BOOLEAN, OType.BOOLEAN);
|
BASE_TYPE_TO_OTYPE.put(BaseType.BOOLEAN, OType.BOOLEAN);
|
||||||
BASE_TYPE_TO_OTYPE.put(BaseType.INTEGER, OType.INTEGER);
|
BASE_TYPE_TO_OTYPE.put(BaseType.INTEGER, OType.INTEGER);
|
||||||
BASE_TYPE_TO_OTYPE.put(BaseType.SHORT, OType.SHORT);
|
BASE_TYPE_TO_OTYPE.put(BaseType.SHORT, OType.SHORT);
|
||||||
|
|
|
@ -31,10 +31,9 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaA
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaCreationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaCreationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.types.entities.FacetTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.entities.FacetTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
|
||||||
|
@ -227,7 +226,7 @@ public class TypeManagement {
|
||||||
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
|
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
|
||||||
Type type, String baseType) throws SchemaException, SchemaNotFoundException {
|
Type type, String baseType) throws SchemaException, SchemaNotFoundException {
|
||||||
|
|
||||||
Set<String> superClasses = type.getTypeSuperTypes();
|
Set<String> superClasses = type.getExtendedTypes();
|
||||||
if(baseType != null) {
|
if(baseType != null) {
|
||||||
if(superClasses == null || superClasses.size() == 0) {
|
if(superClasses == null || superClasses.size() == 0) {
|
||||||
throw new RuntimeException(
|
throw new RuntimeException(
|
||||||
|
@ -292,8 +291,8 @@ public class TypeManagement {
|
||||||
throw new SchemaCreationException(error);
|
throw new SchemaCreationException(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
|
||||||
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
|
@ -360,18 +359,18 @@ public class TypeManagement {
|
||||||
* Excluding the check from types used for type definition
|
* Excluding the check from types used for type definition
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
if(!typeList.contains(type.getName())) {
|
// if(!typeList.contains(type.getName())) {
|
||||||
switch(propertyTypeName.getBaseType()) {
|
// switch(propertyTypeName.getBaseType()) {
|
||||||
case LIST:
|
// case LIST:
|
||||||
throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST
|
// throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST
|
||||||
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
// + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
||||||
case SET:
|
// case SET:
|
||||||
throw new UnsupportedDataTypeException(OType.EMBEDDEDSET
|
// throw new UnsupportedDataTypeException(OType.EMBEDDEDSET
|
||||||
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
// + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
|
||||||
default:
|
// default:
|
||||||
break;
|
// break;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
OType oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType());
|
OType oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType());
|
||||||
|
|
||||||
|
@ -442,8 +441,8 @@ public class TypeManagement {
|
||||||
|
|
||||||
private boolean superClassesMatch(Type actualTypeDefinition, Type newTypeDefinition) {
|
private boolean superClassesMatch(Type actualTypeDefinition, Type newTypeDefinition) {
|
||||||
// Checking superclasses. Must be the same. If differs the operation will be aborted.
|
// Checking superclasses. Must be the same. If differs the operation will be aborted.
|
||||||
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getTypeSuperTypes());
|
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
|
||||||
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getTypeSuperTypes());
|
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getExtendedTypes());
|
||||||
|
|
||||||
if(actualSuperClasses.size()!=newSuperClasses.size()) {
|
if(actualSuperClasses.size()!=newSuperClasses.size()) {
|
||||||
return false;
|
return false;
|
||||||
|
@ -454,7 +453,7 @@ public class TypeManagement {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
actualSuperClasses = new HashSet<>(actualTypeDefinition.getTypeSuperTypes());
|
actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
|
||||||
newSuperClasses.removeAll(actualSuperClasses);
|
newSuperClasses.removeAll(actualSuperClasses);
|
||||||
if(newSuperClasses.size()>0) {
|
if(newSuperClasses.size()>0) {
|
||||||
return false;
|
return false;
|
||||||
|
@ -469,8 +468,8 @@ public class TypeManagement {
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
|
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
|
||||||
|
|
||||||
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
|
@ -482,10 +481,10 @@ public class TypeManagement {
|
||||||
|
|
||||||
if(!superClassesMatch(actualTypeDefinition, newTypeDefinition)){
|
if(!superClassesMatch(actualTypeDefinition, newTypeDefinition)){
|
||||||
StringBuffer error = new StringBuffer();
|
StringBuffer error = new StringBuffer();
|
||||||
error.append("The new type definition has a different set of superclasses. Actual version superclasses are: ");
|
error.append("The new type definition has a different set of supertypes. Actual version supertypes are: ");
|
||||||
error.append(actualTypeDefinition.getTypeSuperTypes());
|
error.append(actualTypeDefinition.getExtendedTypes());
|
||||||
error.append(". New version superclasses are: ");
|
error.append(". New version supertypes are: ");
|
||||||
error.append(newTypeDefinition.getTypeSuperTypes());
|
error.append(newTypeDefinition.getExtendedTypes());
|
||||||
error.append(". This kind update is not supported for a type.");
|
error.append(". This kind update is not supported for a type.");
|
||||||
throw new SchemaException(error.toString());
|
throw new SchemaException(error.toString());
|
||||||
}
|
}
|
||||||
|
@ -648,8 +647,8 @@ public class TypeManagement {
|
||||||
protected List<Type> getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
|
protected List<Type> getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
|
@ -789,8 +788,8 @@ public class TypeManagement {
|
||||||
protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{
|
protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{
|
||||||
ODatabaseDocument oDatabaseDocument = null;
|
ODatabaseDocument oDatabaseDocument = null;
|
||||||
try {
|
try {
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
|
|
||||||
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
OMetadata oMetadata = oDatabaseDocument.getMetadata();
|
||||||
OSchema oSchema = oMetadata.getSchema();
|
OSchema oSchema = oMetadata.getSchema();
|
||||||
|
@ -798,7 +797,11 @@ public class TypeManagement {
|
||||||
oSchema.dropClass(typeName);
|
oSchema.dropClass(typeName);
|
||||||
|
|
||||||
ElementManagement<?,?> erManagement = getTypeManagement(accessType, typeName);
|
ElementManagement<?,?> erManagement = getTypeManagement(accessType, typeName);
|
||||||
erManagement.delete();
|
// If we need to delete an internal type for maintenance we this this check
|
||||||
|
// otherwise we have a null pointer exception
|
||||||
|
if(erManagement!=null) {
|
||||||
|
erManagement.delete();
|
||||||
|
}
|
||||||
|
|
||||||
oDatabaseDocument.commit();
|
oDatabaseDocument.commit();
|
||||||
|
|
||||||
|
|
|
@ -13,10 +13,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.Enti
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.TypeMapper;
|
import org.gcube.informationsystem.types.TypeMapper;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
|
@ -48,11 +48,11 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
if (workingContext == null) {
|
if (workingEnvironment == null) {
|
||||||
workingContext = TypeSecurityContext.getInstance();
|
workingEnvironment = TypeEnvironment.getInstance();
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
|
|
|
@ -12,10 +12,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
import org.gcube.informationsystem.types.reference.entities.EntityType;
|
||||||
import org.gcube.informationsystem.types.reference.properties.PropertyType;
|
import org.gcube.informationsystem.types.reference.properties.PropertyType;
|
||||||
|
@ -31,7 +31,7 @@ import com.orientechnologies.orient.core.sql.executor.OResultSet;
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
public class PropertyTypeDefinitionManagement extends ElementManagement<OElement, PropertyType<?>> {
|
public class PropertyTypeDefinitionManagement extends ElementManagement<OElement, PropertyType> {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
|
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
|
||||||
|
|
||||||
|
@ -42,10 +42,10 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
|
||||||
this.typeName = PropertyType.NAME;
|
this.typeName = PropertyType.NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PropertyTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
public PropertyTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
|
||||||
this();
|
this();
|
||||||
this.oDatabaseDocument = oDatabaseDocument;
|
this.oDatabaseDocument = oDatabaseDocument;
|
||||||
setWorkingContext(securityContext);
|
setWorkingEnvironment(typeEnvironment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -54,11 +54,11 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
if(workingContext == null) {
|
if(workingEnvironment == null) {
|
||||||
workingContext = TypeSecurityContext.getInstance();
|
workingEnvironment = TypeEnvironment.getInstance();
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
|
|
|
@ -2,7 +2,7 @@ package org.gcube.informationsystem.resourceregistry.types.relations;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.entities.FacetTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.entities.FacetTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.types.reference.entities.FacetType;
|
import org.gcube.informationsystem.types.reference.entities.FacetType;
|
||||||
import org.gcube.informationsystem.types.reference.relations.ConsistsOfType;
|
import org.gcube.informationsystem.types.reference.relations.ConsistsOfType;
|
||||||
|
@ -20,16 +20,16 @@ public class ConsistsOfTypeDefinitionManagement
|
||||||
this.typeName = ConsistsOfType.NAME;
|
this.typeName = ConsistsOfType.NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConsistsOfTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument)
|
public ConsistsOfTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument)
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
super(securityContext, oDatabaseDocument, FacetType.class);
|
super(typeEnvironment, oDatabaseDocument, FacetType.class);
|
||||||
this.typeName = ConsistsOfType.NAME;
|
this.typeName = ConsistsOfType.NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected FacetTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
|
protected FacetTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
|
||||||
FacetTypeDefinitionManagement ftdm = new FacetTypeDefinitionManagement();
|
FacetTypeDefinitionManagement ftdm = new FacetTypeDefinitionManagement();
|
||||||
ftdm.setWorkingContext(getWorkingContext());
|
ftdm.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
ftdm.setODatabaseDocument(oDatabaseDocument);
|
ftdm.setODatabaseDocument(oDatabaseDocument);
|
||||||
return ftdm;
|
return ftdm;
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,7 @@ package org.gcube.informationsystem.resourceregistry.types.relations;
|
||||||
|
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.types.reference.entities.ResourceType;
|
import org.gcube.informationsystem.types.reference.entities.ResourceType;
|
||||||
import org.gcube.informationsystem.types.reference.relations.IsRelatedToType;
|
import org.gcube.informationsystem.types.reference.relations.IsRelatedToType;
|
||||||
|
@ -20,16 +20,16 @@ public class IsRelatedToTypeDefinitionManagement
|
||||||
this.typeName = IsRelatedToType.NAME;
|
this.typeName = IsRelatedToType.NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IsRelatedToTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument)
|
public IsRelatedToTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument)
|
||||||
throws ResourceRegistryException {
|
throws ResourceRegistryException {
|
||||||
super(securityContext, oDatabaseDocument, ResourceType.class);
|
super(typeEnvironment, oDatabaseDocument, ResourceType.class);
|
||||||
this.typeName = IsRelatedToType.NAME;
|
this.typeName = IsRelatedToType.NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected ResourceTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
|
protected ResourceTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
|
||||||
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
|
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
|
||||||
rtdm.setWorkingContext(getWorkingContext());
|
rtdm.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
rtdm.setODatabaseDocument(oDatabaseDocument);
|
rtdm.setODatabaseDocument(oDatabaseDocument);
|
||||||
return rtdm;
|
return rtdm;
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,10 +15,10 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.Rel
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.base.relations.RelationElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.entities.EntityTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.entities.EntityTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
|
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
|
||||||
|
@ -46,11 +46,11 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
|
||||||
this.forceIncludeAllMeta = true;
|
this.forceIncludeAllMeta = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public RelationTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument,
|
public RelationTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument,
|
||||||
Class<TT> clz) throws ResourceRegistryException {
|
Class<TT> clz) throws ResourceRegistryException {
|
||||||
this(clz);
|
this(clz);
|
||||||
this.oDatabaseDocument = oDatabaseDocument;
|
this.oDatabaseDocument = oDatabaseDocument;
|
||||||
setWorkingContext(securityContext);
|
setWorkingEnvironment(typeEnvironment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -59,11 +59,11 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
|
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
|
||||||
if (workingContext == null) {
|
if (workingEnvironment == null) {
|
||||||
this.workingContext = TypeSecurityContext.getInstance();
|
this.workingEnvironment = TypeEnvironment.getInstance();
|
||||||
}
|
}
|
||||||
return workingContext;
|
return workingEnvironment;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
|
@ -212,7 +212,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
|
||||||
@Override
|
@Override
|
||||||
protected ResourceTypeDefinitionManagement newSourceEntityManagement() throws ResourceRegistryException {
|
protected ResourceTypeDefinitionManagement newSourceEntityManagement() throws ResourceRegistryException {
|
||||||
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
|
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
|
||||||
rtdm.setWorkingContext(getWorkingContext());
|
rtdm.setWorkingEnvironment(getWorkingEnvironment());
|
||||||
rtdm.setODatabaseDocument(oDatabaseDocument);
|
rtdm.setODatabaseDocument(oDatabaseDocument);
|
||||||
return rtdm;
|
return rtdm;
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,6 @@ import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.gcube.common.encryption.encrypter.StringEncrypter;
|
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.Encrypted;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Property;
|
import org.gcube.informationsystem.model.reference.properties.Property;
|
||||||
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
|
||||||
|
@ -46,7 +45,7 @@ public class EncryptedOrient extends ODocument implements Encrypted {
|
||||||
public List<String> getSupertypes() {
|
public List<String> getSupertypes() {
|
||||||
TypesCache typesCache = TypesCache.getInstance();
|
TypesCache typesCache = TypesCache.getInstance();
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
|
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(getTypeName());
|
||||||
try {
|
try {
|
||||||
return cachedType.getSuperTypes();
|
return cachedType.getSuperTypes();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
|
@ -5,7 +5,6 @@ import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
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.Metadata;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Property;
|
import org.gcube.informationsystem.model.reference.properties.Property;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
||||||
|
@ -37,7 +36,7 @@ public class MetadataOrient extends ODocument implements Metadata {
|
||||||
public List<String> getSupertypes() {
|
public List<String> getSupertypes() {
|
||||||
TypesCache typesCache = TypesCache.getInstance();
|
TypesCache typesCache = TypesCache.getInstance();
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
|
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(getTypeName());
|
||||||
try {
|
try {
|
||||||
return cachedType.getSuperTypes();
|
return cachedType.getSuperTypes();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
|
@ -10,6 +10,7 @@ import org.gcube.com.fasterxml.jackson.databind.JsonMappingException;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
||||||
|
import org.gcube.common.authorization.utils.user.User;
|
||||||
import org.gcube.informationsystem.base.reference.Element;
|
import org.gcube.informationsystem.base.reference.Element;
|
||||||
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
import org.gcube.informationsystem.base.reference.IdentifiableElement;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
||||||
|
@ -29,13 +30,14 @@ public class MetadataUtility {
|
||||||
private static final Logger logger = LoggerFactory.getLogger(MetadataUtility.class);
|
private static final Logger logger = LoggerFactory.getLogger(MetadataUtility.class);
|
||||||
|
|
||||||
public static String getUser() {
|
public static String getUser() {
|
||||||
String user = Metadata.UNKNOWN_USER;
|
String username = Metadata.UNKNOWN_USER;
|
||||||
try {
|
try {
|
||||||
user = SecretManagerProvider.instance.get().getUser().getUsername();
|
User user = SecretManagerProvider.instance.get().getUser();
|
||||||
|
username = user.getUsername();
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
logger.error("Unable to retrieve user. {} will be used", user);
|
logger.error("Unable to retrieve user. {} will be used", username, e);
|
||||||
}
|
}
|
||||||
return user;
|
return username;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Metadata createMetadata() {
|
public static Metadata createMetadata() {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.utils;
|
package org.gcube.informationsystem.resourceregistry.utils;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
@ -13,10 +13,10 @@ import org.gcube.informationsystem.model.reference.entities.Entity;
|
||||||
import org.gcube.informationsystem.model.reference.relations.Relation;
|
import org.gcube.informationsystem.model.reference.relations.Relation;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -93,8 +93,8 @@ public class OrientDBUtility {
|
||||||
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
try {
|
try {
|
||||||
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
|
||||||
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
|
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
|
||||||
adminDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
adminDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
|
return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
|
||||||
} finally {
|
} finally {
|
||||||
if(adminDatabaseDocument != null) {
|
if(adminDatabaseDocument != null) {
|
||||||
|
|
|
@ -4,7 +4,6 @@ import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
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.PropagationConstraint;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Property;
|
import org.gcube.informationsystem.model.reference.properties.Property;
|
||||||
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
import org.gcube.informationsystem.resourceregistry.types.CachedType;
|
||||||
|
@ -36,7 +35,7 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio
|
||||||
public List<String> getSupertypes() {
|
public List<String> getSupertypes() {
|
||||||
TypesCache typesCache = TypesCache.getInstance();
|
TypesCache typesCache = TypesCache.getInstance();
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
|
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(getTypeName());
|
||||||
try {
|
try {
|
||||||
return cachedType.getSuperTypes();
|
return cachedType.getSuperTypes();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
|
@ -12,9 +12,8 @@ import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
|
||||||
import org.gcube.common.authorization.utils.secret.JWTSecret;
|
import org.gcube.common.authorization.utils.secret.JWTSecret;
|
||||||
import org.gcube.common.authorization.utils.secret.Secret;
|
import org.gcube.common.authorization.utils.secret.Secret;
|
||||||
import org.gcube.common.authorization.utils.secret.SecretUtility;
|
import org.gcube.common.authorization.utils.secret.SecretUtility;
|
||||||
import org.gcube.common.keycloak.KeycloakClientFactory;
|
import org.gcube.common.iam.D4ScienceIAMClient;
|
||||||
import org.gcube.common.keycloak.model.TokenResponse;
|
import org.gcube.common.iam.D4ScienceIAMClientAuthn;
|
||||||
import org.gcube.common.scope.api.ScopeProvider;
|
|
||||||
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
||||||
import org.junit.AfterClass;
|
import org.junit.AfterClass;
|
||||||
import org.junit.BeforeClass;
|
import org.junit.BeforeClass;
|
||||||
|
@ -39,14 +38,15 @@ public class ContextTest {
|
||||||
public static final String NEXTNEXT;
|
public static final String NEXTNEXT;
|
||||||
public static final String DEVSEC;
|
public static final String DEVSEC;
|
||||||
public static final String DEVVRE;
|
public static final String DEVVRE;
|
||||||
|
|
||||||
protected static final Properties properties;
|
protected static final Properties properties;
|
||||||
|
|
||||||
protected static final String CLIENT_ID_PROPERTY_KEY = "client_id";
|
public static final String TYPE_PROPERTY_KEY = "type";
|
||||||
protected static final String CLIENT_SECRET_PROPERTY_KEY = "client_secret";
|
public static final String USERNAME_PROPERTY_KEY = "username";
|
||||||
|
public static final String PASSWORD_PROPERTY_KEY = "password";
|
||||||
|
public static final String CLIENT_ID_PROPERTY_KEY = "clientId";
|
||||||
|
|
||||||
protected static final String clientID;
|
public static final String RESOURCE_REGISTRY_URL_PROPERTY = "RESOURCE_REGISTRY_URL";
|
||||||
protected static final String clientSecret;
|
|
||||||
|
|
||||||
static {
|
static {
|
||||||
GCUBE = "/gcube";
|
GCUBE = "/gcube";
|
||||||
|
@ -55,7 +55,7 @@ public class ContextTest {
|
||||||
DEVSEC = GCUBE + "/devsec";
|
DEVSEC = GCUBE + "/devsec";
|
||||||
DEVVRE = DEVSEC + "/devVRE";
|
DEVVRE = DEVSEC + "/devVRE";
|
||||||
|
|
||||||
PARENT_DEFAULT_TEST_SCOPE = "/gcube";
|
PARENT_DEFAULT_TEST_SCOPE = GCUBE;
|
||||||
DEFAULT_TEST_SCOPE = DEVNEXT;
|
DEFAULT_TEST_SCOPE = DEVNEXT;
|
||||||
ALTERNATIVE_TEST_SCOPE = NEXTNEXT;
|
ALTERNATIVE_TEST_SCOPE = NEXTNEXT;
|
||||||
|
|
||||||
|
@ -64,16 +64,16 @@ public class ContextTest {
|
||||||
try {
|
try {
|
||||||
// load the properties file
|
// load the properties file
|
||||||
properties.load(input);
|
properties.load(input);
|
||||||
|
|
||||||
clientID = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
|
|
||||||
clientSecret = properties.getProperty(CLIENT_SECRET_PROPERTY_KEY);
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private enum Type{
|
||||||
|
USER, CLIENT_ID
|
||||||
|
};
|
||||||
|
|
||||||
public static void set(Secret secret) throws Exception {
|
public static void set(Secret secret) throws Exception {
|
||||||
SecretManagerProvider.instance.reset();
|
SecretManagerProvider.instance.reset();
|
||||||
SecretManager secretManager = new SecretManager();
|
SecretManager secretManager = new SecretManager();
|
||||||
|
@ -83,20 +83,49 @@ public class ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setContextByName(String fullContextName) throws Exception {
|
public static void setContextByName(String fullContextName) throws Exception {
|
||||||
|
logger.debug("Going to set credentials for context {}", fullContextName);
|
||||||
Secret secret = getSecretByContextName(fullContextName);
|
Secret secret = getSecretByContextName(fullContextName);
|
||||||
set(secret);
|
set(secret);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private static TokenResponse getJWTAccessToken(String context) throws Exception {
|
protected static String getJWTAccessToken(String context) throws Exception {
|
||||||
ScopeProvider.instance.set(context);
|
Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString());
|
||||||
TokenResponse tr = KeycloakClientFactory.newInstance().queryUMAToken(clientID, clientSecret, context, null);
|
|
||||||
return tr;
|
String accessToken = null;
|
||||||
|
|
||||||
|
int index = context.indexOf('/', 1);
|
||||||
|
String root = context.substring(0, index == -1 ? context.length() : index);
|
||||||
|
|
||||||
|
D4ScienceIAMClient iamClient = D4ScienceIAMClient.newInstance(root);
|
||||||
|
D4ScienceIAMClientAuthn d4ScienceIAMClientAuthn = null;
|
||||||
|
switch (type) {
|
||||||
|
case CLIENT_ID:
|
||||||
|
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
|
||||||
|
String clientSecret = properties.getProperty(root);
|
||||||
|
|
||||||
|
d4ScienceIAMClientAuthn = iamClient.authenticate(clientId, clientSecret, context);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case USER:
|
||||||
|
default:
|
||||||
|
String username = properties.getProperty(USERNAME_PROPERTY_KEY);
|
||||||
|
String password = properties.getProperty(PASSWORD_PROPERTY_KEY);
|
||||||
|
|
||||||
|
d4ScienceIAMClientAuthn = iamClient.authenticateUser(username, password, context);
|
||||||
|
break;
|
||||||
|
|
||||||
|
}
|
||||||
|
accessToken = d4ScienceIAMClientAuthn.getAccessTokenString();
|
||||||
|
|
||||||
|
logger.trace("Generated Access Token is {}", accessToken);
|
||||||
|
return accessToken;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Secret getSecretByContextName(String context) throws Exception {
|
public static Secret getSecretByContextName(String context) throws Exception {
|
||||||
TokenResponse tr = getJWTAccessToken(context);
|
String accessToken = getJWTAccessToken(context);
|
||||||
Secret secret = new JWTSecret(tr.getAccessToken());
|
Secret secret = new JWTSecret(accessToken);
|
||||||
return secret;
|
return secret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,40 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import org.gcube.common.iam.OIDCBearerAuth;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.Environment;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
|
public class TestTokenRoles extends ContextTest {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(ContextTest.class);
|
||||||
|
|
||||||
|
@Ignore
|
||||||
|
@Test
|
||||||
|
public void testRoles() throws Exception {
|
||||||
|
String[] contexts = new String[] {GCUBE, DEVSEC, DEVVRE, DEVNEXT, NEXTNEXT};
|
||||||
|
for(String context : contexts){
|
||||||
|
String accessToken = getJWTAccessToken(context);
|
||||||
|
OIDCBearerAuth auth = OIDCBearerAuth.fromAccessTokenString(accessToken);
|
||||||
|
Collection<String> roles = auth.getRoles();
|
||||||
|
logger.debug("{} All roles are {}", context, roles);
|
||||||
|
Assert.assertTrue(roles.contains(Environment.IS_MANAGER));
|
||||||
|
Collection<String> contextRoles = auth.getContextRoles();
|
||||||
|
logger.debug("{} Context roles are {}", context, contextRoles);
|
||||||
|
Collection<String> globalRoles = auth.getGlobalRoles();
|
||||||
|
logger.debug("{} Global roles are {}", context, globalRoles);
|
||||||
|
Assert.assertTrue(globalRoles.contains(Environment.IS_MANAGER));
|
||||||
|
Assert.assertTrue(roles.size()==(contextRoles.size() + globalRoles.size()));
|
||||||
|
Assert.assertTrue(roles.containsAll(contextRoles));
|
||||||
|
Assert.assertTrue(roles.containsAll(globalRoles));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,121 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.authorization;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.gcube.common.authorization.library.ClientType;
|
||||||
|
import org.gcube.common.authorization.library.exception.AuthorizationException;
|
||||||
|
import org.gcube.common.authorization.library.provider.ClientInfo;
|
||||||
|
import org.gcube.common.authorization.library.utils.Caller;
|
||||||
|
import org.gcube.common.authorization.utils.secret.Secret;
|
||||||
|
import org.gcube.common.authorization.utils.user.GCubeUser;
|
||||||
|
import org.gcube.common.authorization.utils.user.User;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
|
public class FakeSecret extends Secret {
|
||||||
|
|
||||||
|
protected ObjectMapper mapper;
|
||||||
|
protected String context;
|
||||||
|
protected GCubeUser user;
|
||||||
|
protected ClientInfo clientInfo;
|
||||||
|
|
||||||
|
public FakeSecret(String json, String context) {
|
||||||
|
this(json);
|
||||||
|
this.context = context;
|
||||||
|
user.setAdditionalProperty("context", context);
|
||||||
|
try {
|
||||||
|
token = mapper.writeValueAsString(user);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public FakeSecret(String json) {
|
||||||
|
super(100, json);
|
||||||
|
mapper = new ObjectMapper();
|
||||||
|
try {
|
||||||
|
user = mapper.readValue(json, GCubeUser.class);
|
||||||
|
context = (String) user.getAdditionalProperty("context");
|
||||||
|
clientInfo = new ClientInfo() {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = -7249742033510171100L;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ClientType getType() {
|
||||||
|
return ClientType.USER;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> getRoles() {
|
||||||
|
return (List<String>) user.getRoles();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return user.getUsername();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void check(String token) throws AuthorizationException {
|
||||||
|
super.check(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setToken() throws Exception {
|
||||||
|
// Nothing to do
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void resetToken() throws Exception {
|
||||||
|
// Nothing to do
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ClientInfo getClientInfo() throws Exception {
|
||||||
|
return clientInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Caller getCaller() throws Exception {
|
||||||
|
Caller caller = new Caller(clientInfo, "TOKEN");
|
||||||
|
return caller;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getContext() throws Exception {
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, String> getHTTPAuthorizationHeaders() {
|
||||||
|
Map<String, String> authorizationHeaders = new HashMap<>();
|
||||||
|
authorizationHeaders.put("x-fake-secret", token);
|
||||||
|
return authorizationHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isExpired() throws Exception {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isRefreshable() throws Exception {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public User getUser() {
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.authorization;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.gcube.common.authorization.utils.secret.Secret;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.queries.JsonQueryTest;
|
||||||
|
|
||||||
|
public class FakeSecretUtility {
|
||||||
|
|
||||||
|
public static File getFakeUsersDirectory() 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, "fake-users");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Secret getSecret(String filename, String context) throws Exception {
|
||||||
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
File file = new File(getFakeUsersDirectory(), filename);
|
||||||
|
JsonNode jsonNode = objectMapper.readTree(file);
|
||||||
|
String json = objectMapper.writeValueAsString(jsonNode);
|
||||||
|
FakeSecret secret = new FakeSecret(json, context);
|
||||||
|
return secret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setFakeSecret(String filename, String context) throws Exception {
|
||||||
|
Secret secret = getSecret(filename, context);
|
||||||
|
ContextTest.set(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,8 +1,10 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.contexts;
|
package org.gcube.informationsystem.resourceregistry.contexts;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
@ -16,13 +18,14 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.SecurityType;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.SecurityType;
|
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
@ -82,26 +85,26 @@ public class ContextManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void roleUserAssertions(UUID uuid, UUID oldParentUUID, boolean deleted) throws ResourceRegistryException {
|
protected void roleUserAssertions(UUID uuid, UUID oldParentUUID, boolean deleted) throws ResourceRegistryException {
|
||||||
ContextSecurityContext contextSecurityContext = ContextSecurityContext.getInstance();
|
ContextEnvironment contextEnvironment = ContextEnvironment.getInstance();
|
||||||
|
|
||||||
ODatabaseDocument oDatabaseDocument = contextSecurityContext.getDatabaseDocument(PermissionMode.READER);
|
ODatabaseDocument oDatabaseDocument = contextEnvironment.getDatabaseDocument(PermissionMode.READER);
|
||||||
OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity();
|
OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity();
|
||||||
|
|
||||||
SecurityContext securityContext = null;
|
InstanceEnvironment instanceEnvironment = null;
|
||||||
if(deleted) {
|
if(deleted) {
|
||||||
securityContext = new SecurityContext(uuid);
|
instanceEnvironment = new InstanceEnvironment(uuid);
|
||||||
} else {
|
} else {
|
||||||
securityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
|
instanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean[] booleanArray = new boolean[] {false, true};
|
boolean[] booleanArray = new boolean[] {false, true};
|
||||||
for(boolean hierarchic : booleanArray) {
|
for(boolean hierarchic : booleanArray) {
|
||||||
for(PermissionMode permissionMode : PermissionMode.values()) {
|
for(PermissionMode permissionMode : PermissionMode.values()) {
|
||||||
String role = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
|
String role = instanceEnvironment.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchic);
|
||||||
ORole oRole = oSecurity.getRole(role);
|
ORole oRole = oSecurity.getRole(role);
|
||||||
Assert.assertEquals(oRole == null, deleted);
|
Assert.assertEquals(oRole == null, deleted);
|
||||||
|
|
||||||
String user = securityContext.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
|
String user = instanceEnvironment.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
|
||||||
OUser oUser = oSecurity.getUser(user);
|
OUser oUser = oSecurity.getUser(user);
|
||||||
Assert.assertEquals(oUser == null, deleted);
|
Assert.assertEquals(oUser == null, deleted);
|
||||||
if(oUser != null) {
|
if(oUser != null) {
|
||||||
|
@ -109,20 +112,20 @@ public class ContextManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
if(hierarchic) {
|
if(hierarchic) {
|
||||||
SecurityContext parent = null;
|
InstanceEnvironment parent = null;
|
||||||
if(deleted) {
|
if(deleted) {
|
||||||
if(oldParentUUID != null) {
|
if(oldParentUUID != null) {
|
||||||
parent = ContextUtility.getInstance().getSecurityContextByUUID(oldParentUUID);
|
parent = ContextUtility.getInstance().getEnvironmentByUUID(oldParentUUID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
parent = securityContext.getParentSecurityContext();
|
parent = (InstanceEnvironment) instanceEnvironment.getParentEnvironment();
|
||||||
while(parent != null) {
|
while(parent != null) {
|
||||||
String parentUser = parent.getSecurityRoleOrUserName(permissionMode, SecurityType.USER,
|
String parentUser = parent.getSecurityRoleOrUserName(permissionMode, SecurityType.USER,
|
||||||
hierarchic);
|
hierarchic);
|
||||||
OUser parentOUser = oSecurity.getUser(parentUser);
|
OUser parentOUser = oSecurity.getUser(parentUser);
|
||||||
Assert.assertTrue(parentOUser != null);
|
Assert.assertTrue(parentOUser != null);
|
||||||
Assert.assertEquals(parentOUser.hasRole(oRole.getName(), false), !deleted);
|
Assert.assertEquals(parentOUser.hasRole(oRole.getName(), false), !deleted);
|
||||||
parent = parent.getParentSecurityContext();
|
parent = (InstanceEnvironment) parent.getParentEnvironment();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -165,11 +168,11 @@ public class ContextManagementTest extends ContextTest {
|
||||||
ContextManagement contextManagement = new ContextManagement();
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
contextManagement.setUUID(uuid);
|
contextManagement.setUUID(uuid);
|
||||||
|
|
||||||
SecurityContext securityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
|
InstanceEnvironment instanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
|
||||||
|
|
||||||
UUID oldParentUUID = null;
|
UUID oldParentUUID = null;
|
||||||
if(securityContext.getParentSecurityContext() != null) {
|
if(instanceEnvironment.getParentEnvironment() != null) {
|
||||||
oldParentUUID = securityContext.getParentSecurityContext().getUUID();
|
oldParentUUID = instanceEnvironment.getParentEnvironment().getUUID();
|
||||||
}
|
}
|
||||||
|
|
||||||
contextManagement.delete();
|
contextManagement.delete();
|
||||||
|
@ -441,7 +444,13 @@ public class ContextManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Context> getAll() throws Exception {
|
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 contextManagement = new ContextManagement();
|
||||||
|
contextManagement.setForceOffset(forceOffset);
|
||||||
|
contextManagement.setForceLimit(forcelimit);
|
||||||
String allString = contextManagement.all(false);
|
String allString = contextManagement.all(false);
|
||||||
logger.trace(allString);
|
logger.trace(allString);
|
||||||
List<Context> all = ElementMapper.unmarshalList(Context.class, allString);
|
List<Context> all = ElementMapper.unmarshalList(Context.class, allString);
|
||||||
|
@ -449,9 +458,10 @@ public class ContextManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
// @Test
|
@Ignore
|
||||||
|
@Test
|
||||||
public void deleteAll() throws Exception {
|
public void deleteAll() throws Exception {
|
||||||
ContextTest.setContextByName(PARENT_DEFAULT_TEST_SCOPE);
|
ContextTest.setContextByName(GCUBE);
|
||||||
List<Context> all = getAll();
|
List<Context> all = getAll();
|
||||||
while(all.size()>0) {
|
while(all.size()>0) {
|
||||||
for (Context context : all) {
|
for (Context context : all) {
|
||||||
|
@ -468,37 +478,45 @@ public class ContextManagementTest extends ContextTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetAll() throws Exception {
|
public void testGetAll() throws Exception {
|
||||||
List<Context> contexts = getAll();
|
// List<Context> contexts = getAll();
|
||||||
contexts = ServerContextCache.getInstance().getContexts();
|
// List<Context> contexts = ServerContextCache.getInstance().getContexts();
|
||||||
|
List<Context> contexts = ServerContextCache.getInstance().getFullInfoContexts();
|
||||||
for(Context context : contexts) {
|
for(Context context : contexts) {
|
||||||
logger.info(ElementMapper.marshal(context));
|
logger.info("{} {}", context.getName(), context.getID());
|
||||||
List<IsParentOf> children = context.getChildren();
|
List<IsParentOf> childrenIsParentOf = context.getChildren();
|
||||||
for(IsParentOf child : children) {
|
for(IsParentOf childIsParentOf : childrenIsParentOf) {
|
||||||
Assert.assertTrue(child.getSource() == context);
|
Assert.assertTrue(childIsParentOf.getSource() == context);
|
||||||
Context childContext = child.getTarget();
|
Context childContext = childIsParentOf.getTarget();
|
||||||
|
logger.info(" --- Child {}", childContext.getName());
|
||||||
|
Assert.assertTrue(childContext.getParent() == childIsParentOf);
|
||||||
Assert.assertTrue(childContext.getParent().getSource() == context);
|
Assert.assertTrue(childContext.getParent().getSource() == context);
|
||||||
}
|
}
|
||||||
roleUserAssertions(context.getID(), null, false);
|
roleUserAssertions(context.getID(), null, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Ignore
|
||||||
// @Test
|
// @Test
|
||||||
public void readContext() throws ResourceRegistryException, IOException {
|
public void readContext() throws ResourceRegistryException, IOException {
|
||||||
Context context = read(UUID.fromString(""));
|
Context context = read(UUID.fromString(""));
|
||||||
logger.debug("{}", context);
|
logger.debug("{}", context);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Ignore
|
||||||
// @Test
|
// @Test
|
||||||
public void deleteContext() throws ResourceRegistryException, IOException {
|
public void deleteContext() throws ResourceRegistryException, IOException {
|
||||||
Context context = read(UUID.fromString(""));
|
Context context = read(UUID.fromString(""));
|
||||||
delete(context);
|
delete(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testContextCache() throws Exception {
|
public void testContextCache() throws Exception {
|
||||||
List<Context> contexts = getAll();
|
List<Context> contexts = getAll();
|
||||||
logger.debug("{}", contexts);
|
logger.info("{}", contexts);
|
||||||
|
if(contexts==null || contexts.size()==0) {
|
||||||
|
logger.warn("No context found. The test cannot be executed.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ServerContextCache contextCache = ServerContextCache.getInstance();
|
ServerContextCache contextCache = ServerContextCache.getInstance();
|
||||||
Map<UUID, String> uuidToContextFullName = contextCache.getUUIDToContextFullNameAssociation();
|
Map<UUID, String> uuidToContextFullName = contextCache.getUUIDToContextFullNameAssociation();
|
||||||
|
@ -527,7 +545,7 @@ public class ContextManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Context currentContext = read(ContextUtility.getCurrentSecurityContext().getUUID());
|
Context currentContext = read(ContextUtility.getCurrentRequestEnvironment().getUUID());
|
||||||
logger.debug("Current context : {}", currentContext);
|
logger.debug("Current context : {}", currentContext);
|
||||||
|
|
||||||
for(Context c : contexts) {
|
for(Context c : contexts) {
|
||||||
|
@ -537,4 +555,94 @@ public class ContextManagementTest extends ContextTest {
|
||||||
logger.debug("{} - {} : {}", uuid, fullName, context);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,306 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.contexts;
|
||||||
|
|
||||||
|
import javax.ws.rs.BadRequestException;
|
||||||
|
import javax.ws.rs.ForbiddenException;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.contexts.impl.entities.ContextImpl;
|
||||||
|
import org.gcube.informationsystem.contexts.reference.ContextState;
|
||||||
|
import org.gcube.informationsystem.contexts.reference.entities.Context;
|
||||||
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.authorization.FakeSecretUtility;
|
||||||
|
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.serialization.ElementMapper;
|
||||||
|
import org.gcube.informationsystem.tree.Tree;
|
||||||
|
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class ContextStateTest extends ContextManagementTest {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(ContextManagementTest.class);
|
||||||
|
|
||||||
|
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
|
||||||
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
|
resourceManagement.setElementType(r.getTypeName());
|
||||||
|
resourceManagement.setJson(ElementMapper.marshal(r));
|
||||||
|
if (r.getID() != null) {
|
||||||
|
resourceManagement.setUUID(r.getID());
|
||||||
|
}
|
||||||
|
return resourceManagement;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test()
|
||||||
|
public void testNonActiveContext() throws Exception {
|
||||||
|
Tree<Context> tree = ServerContextCache.getInstance().getContextsTree();
|
||||||
|
Context root = tree.getRootNode().getNodeElement();
|
||||||
|
String rootContext = "/" + root.getName();
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("is-manager.json", rootContext);
|
||||||
|
|
||||||
|
Context contextA1 = new ContextImpl(CTX_NAME_A);
|
||||||
|
contextA1.setParent(root);
|
||||||
|
|
||||||
|
try {
|
||||||
|
contextA1 = create(contextA1);
|
||||||
|
}catch (Exception e) {
|
||||||
|
ContextTest.setContextByName(rootContext);
|
||||||
|
delete(contextA1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String newContext = rootContext+"/"+contextA1.getName();
|
||||||
|
|
||||||
|
boolean resourceCreated = false;
|
||||||
|
EService createdEservice = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
FakeSecretUtility.setFakeSecret("noroles.json", newContext);
|
||||||
|
|
||||||
|
EService eService = ERManagementTest.instantiateValidEService();
|
||||||
|
ResourceManagement resourceManagement = getResourceManagement(eService);
|
||||||
|
|
||||||
|
String json = null;
|
||||||
|
try {
|
||||||
|
json = resourceManagement.create();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
if(json!=null) {
|
||||||
|
resourceManagement.delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("infrastructure-manager.json", newContext);
|
||||||
|
|
||||||
|
try {
|
||||||
|
json = null;
|
||||||
|
resourceManagement = getResourceManagement(eService);
|
||||||
|
json = resourceManagement.create();
|
||||||
|
resourceCreated = true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
if(json != null) {
|
||||||
|
resourceManagement.delete();
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
createdEservice = ElementMapper.unmarshal(EService.class, json);
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.read();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.update();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("noroles.json", newContext);
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.read();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.update();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
resourceManagement.delete();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("is-manager.json", newContext);
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.read();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.update();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("noroles.json", newContext);
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.read();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
json = resourceManagement.update();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
resourceManagement.delete();
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("is-manager.json", newContext);
|
||||||
|
|
||||||
|
try {
|
||||||
|
resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
resourceManagement.delete();
|
||||||
|
resourceCreated = false;
|
||||||
|
} catch (ForbiddenException e) {
|
||||||
|
logger.info("As expected the no role user cannot operate in non active context", e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
FakeSecretUtility.setFakeSecret("is-manager.json", newContext);
|
||||||
|
|
||||||
|
if(resourceCreated) {
|
||||||
|
ResourceManagement resourceManagement = getResourceManagement(createdEservice);
|
||||||
|
try {
|
||||||
|
resourceManagement.delete();
|
||||||
|
}catch (Exception e) {
|
||||||
|
logger.error("Unable to delete resource {}", createdEservice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("is-manager.json", rootContext);
|
||||||
|
|
||||||
|
delete(contextA1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test()
|
||||||
|
public void testContextStates() throws Exception {
|
||||||
|
Tree<Context> tree = ServerContextCache.getInstance().getContextsTree();
|
||||||
|
Context root = tree.getRootNode().getNodeElement();
|
||||||
|
String rootContext = "/" + root.getName();
|
||||||
|
|
||||||
|
FakeSecretUtility.setFakeSecret("is-manager.json", rootContext);
|
||||||
|
|
||||||
|
Context contextA1 = new ContextImpl(CTX_NAME_A);
|
||||||
|
contextA1.setParent(root);
|
||||||
|
|
||||||
|
String newContext = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
contextA1 = create(contextA1);
|
||||||
|
ContextState state = ContextState.fromString(contextA1.getState());
|
||||||
|
newContext = rootContext + "/" + contextA1.getName();
|
||||||
|
Assert.assertTrue(state == ContextState.CREATED);
|
||||||
|
logger.info("Created contexts {} {} state is {}", newContext, contextA1.getID(), contextA1.getState());
|
||||||
|
}catch (Exception e) {
|
||||||
|
ContextTest.setContextByName(rootContext);
|
||||||
|
delete(contextA1);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
ContextManagement contextManagement = new ContextManagement();
|
||||||
|
ContextState contextState = ContextState.ACTIVE;
|
||||||
|
String state = contextState.getState();
|
||||||
|
contextA1.setState(state);
|
||||||
|
contextManagement.setJson(ElementMapper.marshal(contextA1));
|
||||||
|
String contextString = contextManagement.update();
|
||||||
|
contextA1 = ElementMapper.unmarshal(Context.class, contextString);
|
||||||
|
ContextState gotState = ContextState.fromString(contextA1.getState());
|
||||||
|
logger.info("Contexts {} {} expected state {} - got state {}", newContext, contextA1.getID(), contextState.getState(), gotState.getState());
|
||||||
|
Assert.assertTrue(contextState == gotState);
|
||||||
|
logger.info("Contexts {} {} successfully set as {}", newContext, contextA1.getID(), gotState.getState());
|
||||||
|
|
||||||
|
|
||||||
|
contextManagement = new ContextManagement();
|
||||||
|
contextState = ContextState.CREATED;
|
||||||
|
state = contextState.getState();
|
||||||
|
contextA1.setState(state);
|
||||||
|
contextManagement.setJson(ElementMapper.marshal(contextA1));
|
||||||
|
try {
|
||||||
|
contextString = contextManagement.update();
|
||||||
|
contextA1 = ElementMapper.unmarshal(Context.class, contextString);
|
||||||
|
gotState = ContextState.fromString(contextA1.getState());
|
||||||
|
throw new Exception("It should be possibile set explicitly the context " + newContext + " " + contextA1.getID() + " as " + gotState.getState());
|
||||||
|
}catch (BadRequestException e) {
|
||||||
|
logger.info("As expected a context cannot be explicitly se to {}", state, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
contextManagement = new ContextManagement();
|
||||||
|
contextState = ContextState.SUSPENDED;
|
||||||
|
state = contextState.getState();
|
||||||
|
contextA1.setState(state);
|
||||||
|
contextManagement.setJson(ElementMapper.marshal(contextA1));
|
||||||
|
contextString = contextManagement.update();
|
||||||
|
contextA1 = ElementMapper.unmarshal(Context.class, contextString);
|
||||||
|
gotState = ContextState.fromString(contextA1.getState());
|
||||||
|
logger.info("Contexts {} {} expected state {} - got state {}", newContext, contextA1.getID(), contextState.getState(), gotState.getState());
|
||||||
|
Assert.assertTrue(contextState == gotState);
|
||||||
|
logger.info("Contexts {} {} successfully set as {}", newContext, contextA1.getID(), gotState.getState());
|
||||||
|
|
||||||
|
|
||||||
|
contextManagement = new ContextManagement();
|
||||||
|
contextState = ContextState.DELETED;
|
||||||
|
state = contextState.getState();
|
||||||
|
contextA1.setState(state);
|
||||||
|
contextManagement.setJson(ElementMapper.marshal(contextA1));
|
||||||
|
try {
|
||||||
|
contextString = contextManagement.update();
|
||||||
|
contextA1 = ElementMapper.unmarshal(Context.class, contextString);
|
||||||
|
gotState = ContextState.fromString(contextA1.getState());
|
||||||
|
throw new Exception("It should be possibile set explicitly the context " + newContext + " " + contextA1.getID() + " as " + gotState.getState());
|
||||||
|
}catch (BadRequestException e) {
|
||||||
|
logger.info("As expected a context cannot be explicitly se to {}", state, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
delete(contextA1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,9 +1,9 @@
|
||||||
package org.gcube.informationsystem.resourceregistry.dbinitialization;
|
package org.gcube.informationsystem.resourceregistry.dbinitialization;
|
||||||
|
|
||||||
import org.gcube.informationsystem.base.reference.Element;
|
import org.gcube.informationsystem.base.reference.Element;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
|
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
|
||||||
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
@ -19,20 +19,21 @@ public class DatabaseEnvironmentTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironmentTest.class);
|
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironmentTest.class);
|
||||||
|
|
||||||
// @Test
|
@Test
|
||||||
public void createDB() throws Exception{
|
public void createDB() throws Exception {
|
||||||
|
ContextTest.setContextByName(ContextTest.GCUBE);
|
||||||
String db = DatabaseEnvironment.DB_URI;
|
String db = DatabaseEnvironment.DB_URI;
|
||||||
logger.trace("Created DB is {}", db);
|
logger.trace("Created DB is {}", db);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDateTimeFormat() throws ResourceRegistryException {
|
public void testDateTimeFormat() throws Exception {
|
||||||
ODatabaseDocument oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
|
ContextTest.setContextByName(ContextTest.GCUBE);
|
||||||
|
ODatabaseDocument oDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.WRITER);
|
||||||
String dateTime = oDatabaseDocument.get(ATTRIBUTES.DATETIMEFORMAT).toString();
|
String dateTime = oDatabaseDocument.get(ATTRIBUTES.DATETIMEFORMAT).toString();
|
||||||
Assert.assertTrue(dateTime.compareTo(Element.DATETIME_PATTERN)==0);
|
Assert.assertTrue(dateTime.compareTo(Element.DATETIME_PATTERN)==0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@Test
|
@Test
|
||||||
public void generateDBKey() throws Exception {
|
public void generateDBKey() throws Exception {
|
||||||
|
|
|
@ -0,0 +1,64 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.environments;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.contexts.ShadowContextEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.queries.templates.QueryTemplateEnvironment;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
|
||||||
|
import org.gcube.informationsystem.utils.ReflectionUtility;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
|
public class EnvironmentsTest {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(EnvironmentsTest.class);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExistingSystemEnvironments() throws ResourceRegistryException {
|
||||||
|
Map<UUID,SystemEnvironment> contexts = new HashMap<>();
|
||||||
|
try {
|
||||||
|
Class<?> clz = SystemEnvironment.class;
|
||||||
|
List<Class<?>> classes = ReflectionUtility.getClassesForPackage(clz.getPackage());
|
||||||
|
for(Class<?> c : classes) {
|
||||||
|
if(c!=clz && clz.isAssignableFrom(c)) {
|
||||||
|
Method m = c.getMethod("getInstance");
|
||||||
|
SystemEnvironment instance = (SystemEnvironment) m.invoke(null);
|
||||||
|
contexts.put(instance.getUUID(), instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}catch (Exception e) {
|
||||||
|
logger.error(":(",e);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.assertTrue(contexts.size()==5);
|
||||||
|
|
||||||
|
SystemEnvironment adminEnvironment = contexts.get(AdminEnvironment.getInstance().getUUID());
|
||||||
|
Assert.assertTrue(adminEnvironment instanceof AdminEnvironment);
|
||||||
|
|
||||||
|
SystemEnvironment contextEnvironment = contexts.get(ContextEnvironment.getInstance().getUUID());
|
||||||
|
Assert.assertTrue(contextEnvironment instanceof ContextEnvironment);
|
||||||
|
|
||||||
|
SystemEnvironment shadowContextEnvironment = contexts.get(ShadowContextEnvironment.getInstance().getUUID());
|
||||||
|
Assert.assertTrue(shadowContextEnvironment instanceof ShadowContextEnvironment);
|
||||||
|
|
||||||
|
SystemEnvironment queryTemplateEnvironment = contexts.get(QueryTemplateEnvironment.getInstance().getUUID());
|
||||||
|
Assert.assertTrue(queryTemplateEnvironment instanceof QueryTemplateEnvironment);
|
||||||
|
|
||||||
|
SystemEnvironment typeEnvironment = contexts.get(TypeEnvironment.getInstance().getUUID());
|
||||||
|
Assert.assertTrue(typeEnvironment instanceof TypeEnvironment);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -8,19 +8,24 @@ import java.net.URL;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.common.encryption.encrypter.StringEncrypter;
|
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.base.reference.IdentifiableElement;
|
||||||
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
|
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
|
||||||
|
import org.gcube.informationsystem.model.impl.properties.EventImpl;
|
||||||
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
|
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
|
||||||
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
|
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.Facet;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Resource;
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Encrypted;
|
import org.gcube.informationsystem.model.reference.properties.Encrypted;
|
||||||
|
import org.gcube.informationsystem.model.reference.properties.Event;
|
||||||
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
import org.gcube.informationsystem.model.reference.properties.Metadata;
|
||||||
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
|
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.AddConstraint;
|
||||||
|
@ -30,14 +35,17 @@ import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
||||||
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
|
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
|
||||||
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
|
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.entities.ResourceManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
|
||||||
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
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.AccessPointFacetImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
|
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.EventFacetImpl;
|
||||||
|
@ -86,12 +94,12 @@ import org.slf4j.LoggerFactory;
|
||||||
public class ERManagementTest extends ContextTest {
|
public class ERManagementTest extends ContextTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
|
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
|
||||||
|
|
||||||
public static final String GROUP = "InformationSystem";
|
public static final String GROUP = "InformationSystem";
|
||||||
public static final String NAME = "resource-registry";
|
public static final String NAME = "resource-registry";
|
||||||
public static final String VERSION = "1.0.0";
|
public static final String VERSION = "1.0.0";
|
||||||
public static final String NEW_VERSION = "2.0.0";
|
public static final String NEW_VERSION = "2.0.0";
|
||||||
|
|
||||||
// @Before
|
// @Before
|
||||||
// @After
|
// @After
|
||||||
// public void cleanInstances() throws Exception {
|
// public void cleanInstances() throws Exception {
|
||||||
|
@ -109,14 +117,16 @@ public class ERManagementTest extends ContextTest {
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void before() throws Exception {
|
public void before() throws Exception {
|
||||||
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
||||||
requestInfo.setIncludeMeta(true);
|
requestInfo.setIncludeMeta(true);
|
||||||
requestInfo.setAllMeta(true);
|
requestInfo.setAllMeta(true);
|
||||||
|
requestInfo.setLimit(1000);
|
||||||
|
requestInfo.setOffset(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static SoftwareFacet getSoftwareFacet() {
|
public static SoftwareFacet getSoftwareFacet() {
|
||||||
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
|
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
|
||||||
softwareFacet.setGroup(GROUP);
|
softwareFacet.setGroup(GROUP);
|
||||||
|
@ -124,13 +134,13 @@ public class ERManagementTest extends ContextTest {
|
||||||
softwareFacet.setVersion(VERSION);
|
softwareFacet.setVersion(VERSION);
|
||||||
return softwareFacet;
|
return softwareFacet;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, SoftwareFacet gotSoftwareFacet) {
|
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, SoftwareFacet gotSoftwareFacet) {
|
||||||
Assert.assertTrue(gotSoftwareFacet.getGroup().compareTo(softwareFacet.getGroup()) == 0);
|
Assert.assertTrue(gotSoftwareFacet.getGroup().compareTo(softwareFacet.getGroup()) == 0);
|
||||||
Assert.assertTrue(gotSoftwareFacet.getName().compareTo(softwareFacet.getName()) == 0);
|
Assert.assertTrue(gotSoftwareFacet.getName().compareTo(softwareFacet.getName()) == 0);
|
||||||
Assert.assertTrue(gotSoftwareFacet.getVersion().compareTo(softwareFacet.getVersion()) == 0);
|
Assert.assertTrue(gotSoftwareFacet.getVersion().compareTo(softwareFacet.getVersion()) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Configuration instantiateValidConfiguration() throws Exception {
|
public static Configuration instantiateValidConfiguration() throws Exception {
|
||||||
Configuration configuration = new ConfigurationImpl();
|
Configuration configuration = new ConfigurationImpl();
|
||||||
|
|
||||||
|
@ -142,10 +152,10 @@ public class ERManagementTest extends ContextTest {
|
||||||
IsIdentifiedBy<Configuration, IdentifierFacet> isIdentifiedBy = new IsIdentifiedByImpl<Configuration, IdentifierFacet>(
|
IsIdentifiedBy<Configuration, IdentifierFacet> isIdentifiedBy = new IsIdentifiedByImpl<Configuration, IdentifierFacet>(
|
||||||
configuration, identifierFacet);
|
configuration, identifierFacet);
|
||||||
configuration.addFacet(isIdentifiedBy);
|
configuration.addFacet(isIdentifiedBy);
|
||||||
|
|
||||||
return configuration;
|
return configuration;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static EService instantiateValidEService() throws Exception {
|
public static EService instantiateValidEService() throws Exception {
|
||||||
EService eService = new EServiceImpl();
|
EService eService = new EServiceImpl();
|
||||||
|
|
||||||
|
@ -161,8 +171,10 @@ public class ERManagementTest extends ContextTest {
|
||||||
eService.addFacet(accessPointFacet);
|
eService.addFacet(accessPointFacet);
|
||||||
|
|
||||||
EventFacet eventFacet = new EventFacetImpl();
|
EventFacet eventFacet = new EventFacetImpl();
|
||||||
eventFacet.setDate(Calendar.getInstance().getTime());
|
Event event = new EventImpl();
|
||||||
eventFacet.setEvent("Created");
|
event.setWhen(Calendar.getInstance().getTime());
|
||||||
|
event.setWhat("Created");
|
||||||
|
eventFacet.setEvent(event);
|
||||||
eService.addFacet(eventFacet);
|
eService.addFacet(eventFacet);
|
||||||
|
|
||||||
StateFacet stateFacet = new StateFacetImpl();
|
StateFacet stateFacet = new StateFacetImpl();
|
||||||
|
@ -171,8 +183,8 @@ public class ERManagementTest extends ContextTest {
|
||||||
|
|
||||||
LicenseFacet licenseFacet = new LicenseFacetImpl();
|
LicenseFacet licenseFacet = new LicenseFacetImpl();
|
||||||
licenseFacet.setName("EUPL");
|
licenseFacet.setName("EUPL");
|
||||||
licenseFacet.setTextURL(
|
licenseFacet.setTextURL(new URL(
|
||||||
new URL("https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
|
"https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
|
||||||
eService.addFacet(licenseFacet);
|
eService.addFacet(licenseFacet);
|
||||||
|
|
||||||
return eService;
|
return eService;
|
||||||
|
@ -219,82 +231,89 @@ public class ERManagementTest extends ContextTest {
|
||||||
hostingNode.addFacet(hnStateFacet);
|
hostingNode.addFacet(hnStateFacet);
|
||||||
|
|
||||||
EventFacet hnEventFacet = new EventFacetImpl();
|
EventFacet hnEventFacet = new EventFacetImpl();
|
||||||
hnEventFacet.setDate(Calendar.getInstance().getTime());
|
Event event = new EventImpl();
|
||||||
hnEventFacet.setEvent("Created");
|
event.setWhen(Calendar.getInstance().getTime());
|
||||||
|
event.setWhat("Created");
|
||||||
|
hnEventFacet.setEvent(event);
|
||||||
hostingNode.addFacet(hnEventFacet);
|
hostingNode.addFacet(hnEventFacet);
|
||||||
|
|
||||||
return hostingNode;
|
return hostingNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement, IdentifiableElement createdIdentifiableElement) {
|
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement,
|
||||||
|
IdentifiableElement createdIdentifiableElement) {
|
||||||
UUID createdUUID = createdIdentifiableElement.getID();
|
UUID createdUUID = createdIdentifiableElement.getID();
|
||||||
Assert.assertTrue(createdUUID!=null);
|
Assert.assertTrue(createdUUID != null);
|
||||||
|
|
||||||
if(identifiableElement.getID()!=null) {
|
if (identifiableElement.getID() != null) {
|
||||||
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID())==0);
|
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID()) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
|
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
|
||||||
Assert.assertTrue(createdMetadata!=null);
|
Assert.assertTrue(createdMetadata != null);
|
||||||
|
|
||||||
String createdBy = createdMetadata.getCreatedBy();
|
String createdBy = createdMetadata.getCreatedBy();
|
||||||
Assert.assertTrue(createdBy!=null);
|
Assert.assertTrue(createdBy != null);
|
||||||
|
|
||||||
String lastUpdateBy = createdMetadata.getLastUpdateBy();
|
String lastUpdateBy = createdMetadata.getLastUpdateBy();
|
||||||
Assert.assertTrue(lastUpdateBy!=null);
|
Assert.assertTrue(lastUpdateBy != null);
|
||||||
|
|
||||||
Date creationTime = createdMetadata.getCreationTime();
|
Date creationTime = createdMetadata.getCreationTime();
|
||||||
Assert.assertTrue(creationTime!=null);
|
Assert.assertTrue(creationTime != null);
|
||||||
|
|
||||||
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
|
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
|
||||||
Assert.assertTrue(lastUpdateTime!=null);
|
Assert.assertTrue(lastUpdateTime != null);
|
||||||
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
|
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
|
||||||
|
|
||||||
Metadata metadata = identifiableElement.getMetadata();
|
Metadata metadata = identifiableElement.getMetadata();
|
||||||
if(metadata!=null) {
|
if (metadata != null) {
|
||||||
|
|
||||||
if(metadata.getCreatedBy()!=null) {
|
if (metadata.getCreatedBy() != null) {
|
||||||
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy())==0);
|
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy()) == 0);
|
||||||
}else {
|
} else {
|
||||||
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser())==0);
|
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser()) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(metadata.getLastUpdateBy()!=null) {
|
if (metadata.getLastUpdateBy() != null) {
|
||||||
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy())==0);
|
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy()) == 0);
|
||||||
}else {
|
} else {
|
||||||
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser())==0);
|
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser()) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(metadata.getLastUpdateTime()!=null) {
|
if (metadata.getLastUpdateTime() != null) {
|
||||||
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime()) || lastUpdateTime.compareTo(metadata.getLastUpdateTime())==0);
|
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime())
|
||||||
|
|| lastUpdateTime.compareTo(metadata.getLastUpdateTime()) == 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint, PropagationConstraint gotPropagationConstraint) {
|
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint,
|
||||||
Assert.assertTrue(propagationConstraint.getAddConstraint()==gotPropagationConstraint.getAddConstraint());
|
PropagationConstraint gotPropagationConstraint) {
|
||||||
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==gotPropagationConstraint.getRemoveConstraint());
|
Assert.assertTrue(propagationConstraint.getAddConstraint() == gotPropagationConstraint.getAddConstraint());
|
||||||
|
Assert.assertTrue(
|
||||||
|
propagationConstraint.getRemoveConstraint() == gotPropagationConstraint.getRemoveConstraint());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf, ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
|
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf,
|
||||||
|
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
|
||||||
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
|
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
|
||||||
|
|
||||||
if(consistsOf.getPropagationConstraint()==null) {
|
if (consistsOf.getPropagationConstraint() == null) {
|
||||||
PropagationConstraint propagationConstraint = gotConsistsOf.getPropagationConstraint();
|
PropagationConstraint propagationConstraint = gotConsistsOf.getPropagationConstraint();
|
||||||
Assert.assertTrue(propagationConstraint.getAddConstraint()==AddConstraint.propagate);
|
Assert.assertTrue(propagationConstraint.getAddConstraint() == AddConstraint.propagate);
|
||||||
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==RemoveConstraint.cascade);
|
Assert.assertTrue(propagationConstraint.getRemoveConstraint() == RemoveConstraint.cascade);
|
||||||
checkPropagationConstraint(propagationConstraint, gotConsistsOf.getPropagationConstraint());
|
checkPropagationConstraint(propagationConstraint, gotConsistsOf.getPropagationConstraint());
|
||||||
}else {
|
} else {
|
||||||
checkPropagationConstraint(consistsOf.getPropagationConstraint(), gotConsistsOf.getPropagationConstraint());
|
checkPropagationConstraint(consistsOf.getPropagationConstraint(), gotConsistsOf.getPropagationConstraint());
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> additionalProperties = new HashMap<>(consistsOf.getAdditionalProperties());
|
Map<String, Object> additionalProperties = new HashMap<>(consistsOf.getAdditionalProperties());
|
||||||
additionalProperties.remove(Element.SUPERTYPES_PROPERTY);
|
additionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
|
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
|
||||||
gotAdditionalProperties.remove(Element.SUPERTYPES_PROPERTY);
|
gotAdditionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
|
||||||
Assert.assertTrue(additionalProperties.size()==gotAdditionalProperties.size());
|
Assert.assertTrue(additionalProperties.size() == gotAdditionalProperties.size());
|
||||||
for(String key : additionalProperties.keySet()) {
|
for (String key : additionalProperties.keySet()) {
|
||||||
Assert.assertTrue(gotAdditionalProperties.containsKey(key));
|
Assert.assertTrue(gotAdditionalProperties.containsKey(key));
|
||||||
Object additionalProperty = additionalProperties.get(key);
|
Object additionalProperty = additionalProperties.get(key);
|
||||||
Object gotAdditionalProperty = gotAdditionalProperties.get(key);
|
Object gotAdditionalProperty = gotAdditionalProperties.get(key);
|
||||||
|
@ -302,124 +321,123 @@ public class ERManagementTest extends ContextTest {
|
||||||
Assert.assertTrue(additionalProperty.equals(gotAdditionalProperty));
|
Assert.assertTrue(additionalProperty.equals(gotAdditionalProperty));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
|
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
|
||||||
checkUUIDAndMetadata(facet, gotFacet);
|
checkUUIDAndMetadata(facet, gotFacet);
|
||||||
Class<? extends Facet> clz = facet.getClass();
|
Class<? extends Facet> clz = facet.getClass();
|
||||||
Class<? extends Facet> gotClz = gotFacet.getClass();
|
Class<? extends Facet> gotClz = gotFacet.getClass();
|
||||||
Assert.assertTrue(clz==gotClz);
|
Assert.assertTrue(clz == gotClz);
|
||||||
|
|
||||||
if(clz == SoftwareFacet.class) {
|
if (clz == SoftwareFacet.class) {
|
||||||
checkSoftwareFacetAssertion((SoftwareFacet) facet, (SoftwareFacet) gotFacet);
|
checkSoftwareFacetAssertion((SoftwareFacet) facet, (SoftwareFacet) gotFacet);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static <R extends Resource> void checkResource(R resource, R gotResource) throws Exception {
|
protected static <R extends Resource> void checkResource(R resource, R gotResource) throws Exception {
|
||||||
Assert.assertTrue(resource.getClass() == gotResource.getClass());
|
Assert.assertTrue(resource.getClass() == gotResource.getClass());
|
||||||
checkUUIDAndMetadata(resource, gotResource);
|
checkUUIDAndMetadata(resource, gotResource);
|
||||||
|
|
||||||
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
|
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
|
||||||
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
|
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
|
||||||
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
|
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
|
||||||
|
|
||||||
for(ConsistsOf<? extends Resource, ? extends Facet> consistsOf : resourceConsistsOf) {
|
for (ConsistsOf<? extends Resource, ? extends Facet> consistsOf : resourceConsistsOf) {
|
||||||
@SuppressWarnings("unchecked")
|
@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);
|
checkConsistOf(consistsOf, gotConsistsOf);
|
||||||
|
|
||||||
Facet facet = consistsOf.getTarget();
|
Facet facet = consistsOf.getTarget();
|
||||||
Facet gotFacet = gotConsistsOf.getTarget();
|
Facet gotFacet = gotConsistsOf.getTarget();
|
||||||
checkFacet(facet, gotFacet);
|
checkFacet(facet, gotFacet);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
|
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
|
||||||
Assert.assertTrue(resource.getClass() == gotResource.getClass());
|
Assert.assertTrue(resource.getClass() == gotResource.getClass());
|
||||||
checkUUIDAndMetadata(resource, gotResource);
|
checkUUIDAndMetadata(resource, gotResource);
|
||||||
|
|
||||||
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
|
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
|
||||||
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
|
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
|
||||||
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
|
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
|
||||||
|
|
||||||
for(ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
|
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
|
||||||
Assert.assertNull(gotConsistsOf.getMetadata());
|
Assert.assertNull(gotConsistsOf.getMetadata());
|
||||||
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
|
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
protected static <R extends Resource> void checkResourceNoMeta(R resource, R gotResource) throws Exception {
|
protected static <R extends Resource> void checkResourceNoMeta(R resource, R gotResource) throws Exception {
|
||||||
Assert.assertTrue(resource.getClass() == gotResource.getClass());
|
Assert.assertTrue(resource.getClass() == gotResource.getClass());
|
||||||
Assert.assertNull(gotResource.getMetadata());
|
Assert.assertNull(gotResource.getMetadata());
|
||||||
|
|
||||||
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
|
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
|
||||||
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
|
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
|
||||||
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
|
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
|
||||||
|
|
||||||
for(ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
|
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
|
||||||
Assert.assertNull(gotConsistsOf.getMetadata());
|
Assert.assertNull(gotConsistsOf.getMetadata());
|
||||||
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
|
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
|
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setElementType(r.getTypeName());
|
resourceManagement.setElementType(r.getTypeName());
|
||||||
resourceManagement.setJson(ElementMapper.marshal(r));
|
resourceManagement.setJson(ElementMapper.marshal(r));
|
||||||
if(r.getID()!=null) {
|
if (r.getID() != null) {
|
||||||
resourceManagement.setUUID(r.getID());
|
resourceManagement.setUUID(r.getID());
|
||||||
}
|
}
|
||||||
return resourceManagement;
|
return resourceManagement;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
|
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(
|
||||||
|
IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
|
||||||
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
|
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
|
||||||
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
|
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
|
||||||
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
|
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
|
||||||
if(isRelatedTo.getID()!=null) {
|
if (isRelatedTo.getID() != null) {
|
||||||
isRelatedToManagement.setUUID(isRelatedTo.getID());
|
isRelatedToManagement.setUUID(isRelatedTo.getID());
|
||||||
}
|
}
|
||||||
return isRelatedToManagement;
|
return isRelatedToManagement;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public <R extends Resource> R createResource(R r) throws Exception {
|
public <R extends Resource> R createResource(R r) throws Exception {
|
||||||
ResourceManagement resourceManagement = getResourceManagement(r);
|
ResourceManagement resourceManagement = getResourceManagement(r);
|
||||||
String json = resourceManagement.create();
|
String json = resourceManagement.create();
|
||||||
|
|
||||||
logger.debug("Created resource {}", json);
|
logger.debug("Created resource {}", json);
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
R createdR = (R) ElementMapper.unmarshal(r.getClass(), json);
|
R createdR = (R) ElementMapper.unmarshal(r.getClass(), json);
|
||||||
|
|
||||||
logger.debug("Unmarshalled created resource {}", ElementMapper.marshal(createdR));
|
logger.debug("Unmarshalled created resource {}", ElementMapper.marshal(createdR));
|
||||||
|
|
||||||
checkResource(r, createdR);
|
checkResource(r, createdR);
|
||||||
|
|
||||||
return createdR;
|
return createdR;
|
||||||
}
|
}
|
||||||
|
|
||||||
public EService createEService() throws Exception {
|
public EService createEService() throws Exception {
|
||||||
EService eService = ERManagementTest.instantiateValidEService();
|
EService eService = ERManagementTest.instantiateValidEService();
|
||||||
return createResource(eService);
|
return createResource(eService);
|
||||||
}
|
}
|
||||||
|
|
||||||
public HostingNode createHostingNode() throws Exception {
|
public HostingNode createHostingNode() throws Exception {
|
||||||
return createHostingNode(null);
|
return createHostingNode(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public HostingNode createHostingNode(EService eService) throws Exception {
|
public HostingNode createHostingNode(EService eService) throws Exception {
|
||||||
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
|
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
|
||||||
}
|
}
|
||||||
|
|
||||||
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint, DeleteConstraint deleteConstraint) throws Exception {
|
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint,
|
||||||
|
DeleteConstraint deleteConstraint) throws Exception {
|
||||||
HostingNode hostingNode = ERManagementTest.instantiateValidHostingNode();
|
HostingNode hostingNode = ERManagementTest.instantiateValidHostingNode();
|
||||||
if(eService!=null) {
|
if (eService != null) {
|
||||||
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
|
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
|
||||||
propagationConstraint.setRemoveConstraint(removeConstraint);
|
propagationConstraint.setRemoveConstraint(removeConstraint);
|
||||||
propagationConstraint.setDeleteConstraint(deleteConstraint);
|
propagationConstraint.setDeleteConstraint(deleteConstraint);
|
||||||
|
@ -429,12 +447,12 @@ public class ERManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
return createResource(hostingNode);
|
return createResource(hostingNode);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Configuration createConfiguration() throws Exception {
|
public Configuration createConfiguration() throws Exception {
|
||||||
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
|
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
|
||||||
return createResource(configuration);
|
return createResource(configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
|
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
|
||||||
Map<String, Resource> map = new HashMap<>();
|
Map<String, Resource> map = new HashMap<>();
|
||||||
|
|
||||||
|
@ -446,24 +464,23 @@ public class ERManagementTest extends ContextTest {
|
||||||
|
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <R extends Resource> void deleteResource(R r) throws Exception {
|
public <R extends Resource> void deleteResource(R r) throws Exception {
|
||||||
if(r!=null) {
|
if (r != null) {
|
||||||
ResourceManagement resourceManagement = getResourceManagement(r);
|
ResourceManagement resourceManagement = getResourceManagement(r);
|
||||||
resourceManagement.delete();
|
resourceManagement.delete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateEService() throws Exception {
|
public void testCreateEService() throws Exception {
|
||||||
EService eService = null;
|
EService eService = null;
|
||||||
try {
|
try {
|
||||||
eService = createEService();
|
eService = createEService();
|
||||||
}finally {
|
} finally {
|
||||||
deleteResource(eService);
|
deleteResource(eService);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -472,28 +489,27 @@ public class ERManagementTest extends ContextTest {
|
||||||
try {
|
try {
|
||||||
eService = createEService();
|
eService = createEService();
|
||||||
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
|
||||||
|
|
||||||
requestInfo.setIncludeMeta(true);
|
requestInfo.setIncludeMeta(true);
|
||||||
requestInfo.setAllMeta(true);
|
requestInfo.setAllMeta(true);
|
||||||
EService readEService = (EService) readResource(eService.getID());
|
EService readEService = (EService) readResource(eService.getID());
|
||||||
checkResource(eService, readEService);
|
checkResource(eService, readEService);
|
||||||
|
|
||||||
requestInfo.setIncludeMeta(true);
|
requestInfo.setIncludeMeta(true);
|
||||||
requestInfo.setAllMeta(false);
|
requestInfo.setAllMeta(false);
|
||||||
readEService = (EService) readResource(eService.getID());
|
readEService = (EService) readResource(eService.getID());
|
||||||
checkResourceRootMetaOnly(eService, readEService);
|
checkResourceRootMetaOnly(eService, readEService);
|
||||||
|
|
||||||
requestInfo.setIncludeMeta(false);
|
requestInfo.setIncludeMeta(false);
|
||||||
readEService = (EService) readResource(eService.getID());
|
readEService = (EService) readResource(eService.getID());
|
||||||
checkResourceNoMeta(eService, readEService);
|
checkResourceNoMeta(eService, readEService);
|
||||||
|
|
||||||
}finally {
|
} finally {
|
||||||
deleteResource(eService);
|
deleteResource(eService);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
protected Resource readResource(UUID uuid) throws Exception {
|
protected Resource readResource(UUID uuid) throws Exception {
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
ResourceManagement resourceManagement = new ResourceManagement();
|
||||||
resourceManagement.setUUID(uuid);
|
resourceManagement.setUUID(uuid);
|
||||||
|
@ -501,73 +517,70 @@ public class ERManagementTest extends ContextTest {
|
||||||
logger.debug(json);
|
logger.debug(json);
|
||||||
return ElementMapper.unmarshal(Resource.class, json);
|
return ElementMapper.unmarshal(Resource.class, json);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@Test
|
* @Test public void testReadResource() throws Exception {
|
||||||
public void testReadResource() throws Exception {
|
* readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e")); }
|
||||||
readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e"));
|
*/
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@Test
|
* @Test public void testDeleteResource() throws Exception { ResourceManagement
|
||||||
public void testDeleteResource() throws Exception {
|
* resourceManagement = new ResourceManagement();
|
||||||
ResourceManagement resourceManagement = new ResourceManagement();
|
* resourceManagement.setUUID(UUID.fromString(
|
||||||
resourceManagement.setUUID(UUID.fromString("64635295-7ced-4931-a55f-40fc8199b280"));
|
* "64635295-7ced-4931-a55f-40fc8199b280")); boolean deleted =
|
||||||
boolean deleted = resourceManagement.delete();
|
* resourceManagement.delete(); Assert.assertTrue(deleted); }
|
||||||
Assert.assertTrue(deleted);
|
*/
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateHostingNode() throws Exception {
|
public void testCreateHostingNode() throws Exception {
|
||||||
HostingNode hostingNode = null;
|
HostingNode hostingNode = null;
|
||||||
try {
|
try {
|
||||||
hostingNode = createHostingNode();
|
hostingNode = createHostingNode();
|
||||||
}finally {
|
} finally {
|
||||||
deleteResource(hostingNode);
|
deleteResource(hostingNode);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateHostingNodeAndEService() throws Exception {
|
public void testCreateHostingNodeAndEService() throws Exception {
|
||||||
Map<String, Resource> map = createHostingNodeAndEService();
|
Map<String, Resource> map = createHostingNodeAndEService();
|
||||||
deleteResource(map.get(HostingNode.NAME));
|
deleteResource(map.get(HostingNode.NAME));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateReadUpdateDeleteFacet() throws Exception {
|
public void testCreateReadUpdateDeleteFacet() throws Exception {
|
||||||
EService eService = createEService();
|
EService eService = createEService();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
CPUFacet cpuFacet = new CPUFacetImpl();
|
CPUFacet cpuFacet = new CPUFacetImpl();
|
||||||
cpuFacet.setClockSpeed("1 GHz");
|
cpuFacet.setClockSpeed("1 GHz");
|
||||||
cpuFacet.setModel("Opteron");
|
cpuFacet.setModel("Opteron");
|
||||||
cpuFacet.setVendor("AMD");
|
cpuFacet.setVendor("AMD");
|
||||||
|
|
||||||
ConsistsOf<EService, CPUFacet> consistsOf = new ConsistsOfImpl<EService, CPUFacet>(eService, cpuFacet);
|
ConsistsOf<EService, CPUFacet> consistsOf = new ConsistsOfImpl<EService, CPUFacet>(eService, cpuFacet);
|
||||||
|
|
||||||
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
|
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
|
||||||
consistsOfManagement.setElementType(consistsOf.getTypeName());
|
consistsOfManagement.setElementType(consistsOf.getTypeName());
|
||||||
consistsOfManagement.setJson(ElementMapper.marshal(consistsOf));
|
consistsOfManagement.setJson(ElementMapper.marshal(consistsOf));
|
||||||
String createdConsistsOfString = consistsOfManagement.create();
|
String createdConsistsOfString = consistsOfManagement.create();
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class, createdConsistsOfString);
|
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class,
|
||||||
|
createdConsistsOfString);
|
||||||
|
|
||||||
CPUFacet createdCpuFacet = createdConsistsOf.getTarget();
|
CPUFacet createdCpuFacet = createdConsistsOf.getTarget();
|
||||||
|
|
||||||
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(createdCpuFacet.getClockSpeed()) == 0);
|
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(createdCpuFacet.getClockSpeed()) == 0);
|
||||||
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel()) == 0);
|
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel()) == 0);
|
||||||
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor()) == 0);
|
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor()) == 0);
|
||||||
|
|
||||||
UUID uuid = createdCpuFacet.getID();
|
UUID uuid = createdCpuFacet.getID();
|
||||||
|
|
||||||
FacetManagement facetManagement = new FacetManagement();
|
FacetManagement facetManagement = new FacetManagement();
|
||||||
facetManagement.setElementType(createdCpuFacet.getTypeName());
|
facetManagement.setElementType(createdCpuFacet.getTypeName());
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
|
|
||||||
String readJson = facetManagement.read().toString();
|
String readJson = facetManagement.read().toString();
|
||||||
CPUFacet readCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readJson);
|
CPUFacet readCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readJson);
|
||||||
logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet);
|
logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet);
|
||||||
|
@ -575,21 +588,21 @@ public class ERManagementTest extends ContextTest {
|
||||||
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
|
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
|
||||||
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
|
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
|
||||||
Assert.assertTrue(uuid.compareTo(readCpuFacet.getID()) == 0);
|
Assert.assertTrue(uuid.compareTo(readCpuFacet.getID()) == 0);
|
||||||
|
|
||||||
String newVendor = "Intel";
|
String newVendor = "Intel";
|
||||||
String newClockSpeed = "2 GHz";
|
String newClockSpeed = "2 GHz";
|
||||||
readCpuFacet.setVendor(newVendor);
|
readCpuFacet.setVendor(newVendor);
|
||||||
readCpuFacet.setClockSpeed(newClockSpeed);
|
readCpuFacet.setClockSpeed(newClockSpeed);
|
||||||
|
|
||||||
String additionPropertyKey = "My";
|
String additionPropertyKey = "My";
|
||||||
String additionPropertyValue = "Test";
|
String additionPropertyValue = "Test";
|
||||||
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
|
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
facetManagement = new FacetManagement();
|
||||||
facetManagement.setElementType(readCpuFacet.getTypeName());
|
facetManagement.setElementType(readCpuFacet.getTypeName());
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
facetManagement.setJson(ElementMapper.marshal(readCpuFacet));
|
facetManagement.setJson(ElementMapper.marshal(readCpuFacet));
|
||||||
|
|
||||||
String updatedJson = facetManagement.update();
|
String updatedJson = facetManagement.update();
|
||||||
CPUFacet updatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, updatedJson);
|
CPUFacet updatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, updatedJson);
|
||||||
logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, updatedCpuFacet);
|
logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, updatedCpuFacet);
|
||||||
|
@ -601,11 +614,11 @@ public class ERManagementTest extends ContextTest {
|
||||||
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
|
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
|
||||||
String user = ContextTest.getUser();
|
String user = ContextTest.getUser();
|
||||||
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
|
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
facetManagement = new FacetManagement();
|
||||||
facetManagement.setElementType(updatedCpuFacet.getTypeName());
|
facetManagement.setElementType(updatedCpuFacet.getTypeName());
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
|
|
||||||
String readUpdatedJson = facetManagement.read().toString();
|
String readUpdatedJson = facetManagement.read().toString();
|
||||||
CPUFacet readUpdatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readUpdatedJson);
|
CPUFacet readUpdatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readUpdatedJson);
|
||||||
logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet);
|
logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet);
|
||||||
|
@ -615,11 +628,11 @@ public class ERManagementTest extends ContextTest {
|
||||||
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
|
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
|
||||||
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
|
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
|
||||||
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
|
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
|
||||||
|
|
||||||
facetManagement = new FacetManagement();
|
facetManagement = new FacetManagement();
|
||||||
facetManagement.setElementType(readCpuFacet.getTypeName());
|
facetManagement.setElementType(readCpuFacet.getTypeName());
|
||||||
facetManagement.setUUID(uuid);
|
facetManagement.setUUID(uuid);
|
||||||
|
|
||||||
facetManagement.delete();
|
facetManagement.delete();
|
||||||
} finally {
|
} finally {
|
||||||
deleteResource(eService);
|
deleteResource(eService);
|
||||||
|
@ -633,7 +646,7 @@ public class ERManagementTest extends ContextTest {
|
||||||
* not impose any particular constraint except the IdentifierFact
|
* not impose any particular constraint except the IdentifierFact
|
||||||
*/
|
*/
|
||||||
Configuration configuration = instantiateValidConfiguration();
|
Configuration configuration = instantiateValidConfiguration();
|
||||||
|
|
||||||
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
|
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
|
||||||
accessPointFacet.setEndpoint(new URI("https://localhost"));
|
accessPointFacet.setEndpoint(new URI("https://localhost"));
|
||||||
accessPointFacet.setEntryName("port1");
|
accessPointFacet.setEntryName("port1");
|
||||||
|
@ -654,7 +667,7 @@ public class ERManagementTest extends ContextTest {
|
||||||
encrypted.setValue(encryptedValue);
|
encrypted.setValue(encryptedValue);
|
||||||
String encryptedKey = "Enc";
|
String encryptedKey = "Enc";
|
||||||
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
|
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
|
||||||
|
|
||||||
configuration.addFacet(accessPointFacet);
|
configuration.addFacet(accessPointFacet);
|
||||||
|
|
||||||
String marshalled = ElementMapper.marshal(configuration);
|
String marshalled = ElementMapper.marshal(configuration);
|
||||||
|
@ -663,7 +676,7 @@ public class ERManagementTest extends ContextTest {
|
||||||
Configuration createdConfiguration = createResource(configuration);
|
Configuration createdConfiguration = createResource(configuration);
|
||||||
|
|
||||||
AccessPointFacet apf = configuration.getFacets(AccessPointFacet.class).get(0);
|
AccessPointFacet apf = configuration.getFacets(AccessPointFacet.class).get(0);
|
||||||
|
|
||||||
Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema);
|
Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema);
|
||||||
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
|
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
|
||||||
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
|
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
|
||||||
|
@ -671,33 +684,33 @@ public class ERManagementTest extends ContextTest {
|
||||||
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
|
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
|
||||||
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
|
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
|
||||||
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
|
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
|
||||||
Assert.assertTrue(((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
|
Assert.assertTrue(
|
||||||
|
((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
|
||||||
|
|
||||||
deleteResource(createdConfiguration);
|
deleteResource(createdConfiguration);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testUpdateFacetValue() throws Exception {
|
public void testUpdateFacetValue() throws Exception {
|
||||||
EService eService =null;
|
EService eService = null;
|
||||||
try {
|
try {
|
||||||
eService = createEService();
|
eService = createEService();
|
||||||
|
|
||||||
final String newVersion = "1.2.0";
|
final String newVersion = "1.2.0";
|
||||||
eService.getFacets(SoftwareFacet.class).get(0).setVersion(newVersion);
|
eService.getFacets(SoftwareFacet.class).get(0).setVersion(newVersion);
|
||||||
|
|
||||||
ResourceManagement resourceManagement = getResourceManagement(eService);
|
ResourceManagement resourceManagement = getResourceManagement(eService);
|
||||||
|
|
||||||
String json = resourceManagement.update();
|
String json = resourceManagement.update();
|
||||||
EService updatedEService = ElementMapper.unmarshal(EService.class, json);
|
EService updatedEService = ElementMapper.unmarshal(EService.class, json);
|
||||||
|
|
||||||
checkResource(eService, updatedEService);
|
checkResource(eService, updatedEService);
|
||||||
|
|
||||||
SoftwareFacet softwareFacet = updatedEService.getFacets(SoftwareFacet.class).get(0);
|
SoftwareFacet softwareFacet = updatedEService.getFacets(SoftwareFacet.class).get(0);
|
||||||
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
|
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
throw e;
|
throw e;
|
||||||
}finally {
|
} finally {
|
||||||
deleteResource(eService);
|
deleteResource(eService);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -729,5 +742,126 @@ public class ERManagementTest extends ContextTest {
|
||||||
String ret = resourceManagement.all(true);
|
String ret = resourceManagement.all(true);
|
||||||
logger.debug("{}", ret);
|
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 = ERManagementUtility.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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,6 +37,9 @@ import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class InvalidOperationTest extends ERManagementTest {
|
public class InvalidOperationTest extends ERManagementTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(InvalidOperationTest.class);
|
private static Logger logger = LoggerFactory.getLogger(InvalidOperationTest.class);
|
||||||
|
|
|
@ -10,7 +10,6 @@ import java.io.IOException;
|
||||||
import java.lang.management.ManagementFactory;
|
import java.lang.management.ManagementFactory;
|
||||||
import java.lang.management.OperatingSystemMXBean;
|
import java.lang.management.OperatingSystemMXBean;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.nio.file.FileStore;
|
import java.nio.file.FileStore;
|
||||||
|
@ -33,10 +32,12 @@ import javax.management.MalformedObjectNameException;
|
||||||
import javax.management.ObjectName;
|
import javax.management.ObjectName;
|
||||||
import javax.management.ReflectionException;
|
import javax.management.ReflectionException;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.model.impl.properties.EventImpl;
|
||||||
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
|
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
|
||||||
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
|
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Facet;
|
import org.gcube.informationsystem.model.reference.entities.Facet;
|
||||||
import org.gcube.informationsystem.model.reference.entities.Resource;
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
|
import org.gcube.informationsystem.model.reference.properties.Event;
|
||||||
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
|
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
|
||||||
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
|
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
|
||||||
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
||||||
|
@ -52,7 +53,6 @@ import org.gcube.resourcemanagement.model.impl.entities.facets.SimplePropertyFac
|
||||||
import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl;
|
import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.entities.facets.StateFacetImpl;
|
import org.gcube.resourcemanagement.model.impl.entities.facets.StateFacetImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl;
|
import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.properties.ValueSchemaImpl;
|
|
||||||
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasPersistentMemoryImpl;
|
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasPersistentMemoryImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasVolatileMemoryImpl;
|
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasVolatileMemoryImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.relations.consistsof.IsIdentifiedByImpl;
|
import org.gcube.resourcemanagement.model.impl.relations.consistsof.IsIdentifiedByImpl;
|
||||||
|
@ -65,7 +65,6 @@ import org.gcube.resourcemanagement.model.reference.entities.facets.SimpleProper
|
||||||
import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet;
|
import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet;
|
||||||
import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet;
|
import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet;
|
||||||
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
|
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
|
||||||
import org.gcube.resourcemanagement.model.reference.properties.ValueSchema;
|
|
||||||
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPersistentMemory;
|
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPersistentMemory;
|
||||||
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory;
|
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory;
|
||||||
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
|
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
|
||||||
|
@ -159,10 +158,12 @@ public class SmartgearResourcesTest extends ERManagementTest {
|
||||||
hostingNode.addFacet(hasPersistentMemory);
|
hostingNode.addFacet(hasPersistentMemory);
|
||||||
|
|
||||||
EventFacet hnEventFacet = new EventFacetImpl();
|
EventFacet hnEventFacet = new EventFacetImpl();
|
||||||
hnEventFacet.setDate(Calendar.getInstance().getTime());
|
Event event = new EventImpl();
|
||||||
ValueSchema hnEvent = new ValueSchemaImpl();
|
event.setWhen(Calendar.getInstance().getTime());
|
||||||
hnEvent.setSchema(new URI("Schema"));
|
event.setWhat("Created");
|
||||||
hnEventFacet.setEvent("Created");
|
hnEventFacet.setEvent(event);
|
||||||
|
|
||||||
|
|
||||||
hostingNode.addFacet(hnEventFacet);
|
hostingNode.addFacet(hnEventFacet);
|
||||||
|
|
||||||
|
|
||||||
|
@ -445,6 +446,37 @@ public class SmartgearResourcesTest extends ERManagementTest {
|
||||||
public static final String CPU_MODEL_B = "model\b";
|
public static final String CPU_MODEL_B = "model\b";
|
||||||
public static final String CPU_MODEL_NUMBER = "modelNumber";
|
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() {
|
public static List<CPUFacet> getCPUFacets() {
|
||||||
|
|
||||||
List<CPUFacet> cpuFacets = new ArrayList<>();
|
List<CPUFacet> cpuFacets = new ArrayList<>();
|
||||||
|
@ -453,7 +485,7 @@ public class SmartgearResourcesTest extends ERManagementTest {
|
||||||
|
|
||||||
if (!file.exists()) {
|
if (!file.exists()) {
|
||||||
logger.warn("cannot acquire CPU info (no /proc/cpuinfo)");
|
logger.warn("cannot acquire CPU info (no /proc/cpuinfo)");
|
||||||
return cpuFacets;
|
return getFakeCPUFacets();
|
||||||
}
|
}
|
||||||
|
|
||||||
BufferedReader input = null;
|
BufferedReader input = null;
|
||||||
|
@ -531,6 +563,11 @@ public class SmartgearResourcesTest extends ERManagementTest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(cpuFacets.size()==0) {
|
||||||
|
return getFakeCPUFacets();
|
||||||
|
}
|
||||||
|
|
||||||
return cpuFacets;
|
return cpuFacets;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,7 +18,7 @@ import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextMan
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
|
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.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
|
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.gcube.resourcemanagement.model.impl.entities.facets.ContactFacetImpl;
|
import org.gcube.resourcemanagement.model.impl.entities.facets.ContactFacetImpl;
|
||||||
import org.gcube.resourcemanagement.model.impl.entities.facets.CoverageFacetImpl;
|
import org.gcube.resourcemanagement.model.impl.entities.facets.CoverageFacetImpl;
|
||||||
|
@ -46,6 +46,9 @@ import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class AddToContextTest extends MultiContextTest {
|
public class AddToContextTest extends MultiContextTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(AddToContextTest.class);
|
private static Logger logger = LoggerFactory.getLogger(AddToContextTest.class);
|
||||||
|
@ -61,7 +64,7 @@ public class AddToContextTest extends MultiContextTest {
|
||||||
consistsOfManagement.setUUID(isIdentifiedBy.getID());
|
consistsOfManagement.setUUID(isIdentifiedBy.getID());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
consistsOfManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
|
consistsOfManagement.removeFromContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
|
||||||
throw new Exception("You should not be able to delete a mandatory ConsistsOf");
|
throw new Exception("You should not be able to delete a mandatory ConsistsOf");
|
||||||
}catch (SchemaViolationException e) {
|
}catch (SchemaViolationException e) {
|
||||||
// As expected
|
// As expected
|
||||||
|
@ -76,7 +79,7 @@ public class AddToContextTest extends MultiContextTest {
|
||||||
facetManagement.setUUID(softwareFacet.getID());
|
facetManagement.setUUID(softwareFacet.getID());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
|
facetManagement.removeFromContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
|
||||||
throw new Exception("You should not be able to delete a mandatory Facet");
|
throw new Exception("You should not be able to delete a mandatory Facet");
|
||||||
}catch (SchemaViolationException e) {
|
}catch (SchemaViolationException e) {
|
||||||
// As expected
|
// As expected
|
||||||
|
@ -312,7 +315,7 @@ public class AddToContextTest extends MultiContextTest {
|
||||||
// hostingNode.setUUID(UUID.fromString("a87bb07e-5320-4fd8-a48d-bf3cc55756c4"));
|
// hostingNode.setUUID(UUID.fromString("a87bb07e-5320-4fd8-a48d-bf3cc55756c4"));
|
||||||
// ResourceManagement resourceManagement = getResourceManagement(hostingNode);
|
// ResourceManagement resourceManagement = getResourceManagement(hostingNode);
|
||||||
// resourceManagement.setDryRun(false);
|
// resourceManagement.setDryRun(false);
|
||||||
// UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName("/gcube/devsec").getUUID();
|
// UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName("/gcube/devsec").getUUID();
|
||||||
// resourceManagement.addToContext(contextUUID);
|
// resourceManagement.addToContext(contextUUID);
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
|
|
@ -18,7 +18,7 @@ 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.entities.resource.ResourceNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationAvailableInAnotherContextException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.RelationAvailableInAnotherContextException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToNotFoundException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.relations.isrelatedto.IsRelatedToNotFoundException;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
|
@ -171,7 +171,7 @@ public class BasicTest extends MultiContextTest {
|
||||||
|
|
||||||
String targetContextFullName = ALTERNATIVE_TEST_SCOPE;
|
String targetContextFullName = ALTERNATIVE_TEST_SCOPE;
|
||||||
|
|
||||||
ResourceManagement rm = (ResourceManagement) ElementManagementUtility.getERManagement(Resource.NAME);
|
ResourceManagement rm = (ResourceManagement) ERManagementUtility.getERManagement(Resource.NAME);
|
||||||
String all = rm.all(true);
|
String all = rm.all(true);
|
||||||
List<Resource> allResources = ElementMapper.unmarshalList(Resource.class, all);
|
List<Resource> allResources = ElementMapper.unmarshalList(Resource.class, all);
|
||||||
Assert.assertTrue(allResources.size()==2);
|
Assert.assertTrue(allResources.size()==2);
|
||||||
|
@ -180,7 +180,7 @@ public class BasicTest extends MultiContextTest {
|
||||||
|
|
||||||
deleteResource(hostingNode);
|
deleteResource(hostingNode);
|
||||||
|
|
||||||
rm = (ResourceManagement) ElementManagementUtility.getERManagement(Resource.NAME);
|
rm = (ResourceManagement) ERManagementUtility.getERManagement(Resource.NAME);
|
||||||
all = rm.all(true);
|
all = rm.all(true);
|
||||||
allResources = ElementMapper.unmarshalList(Resource.class, all);
|
allResources = ElementMapper.unmarshalList(Resource.class, all);
|
||||||
Assert.assertTrue(allResources.size()==0);
|
Assert.assertTrue(allResources.size()==0);
|
||||||
|
|
|
@ -26,6 +26,9 @@ import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class ComplexTest extends MultiContextTest {
|
public class ComplexTest extends MultiContextTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(ComplexTest.class);
|
private static Logger logger = LoggerFactory.getLogger(ComplexTest.class);
|
||||||
|
|
|
@ -32,6 +32,9 @@ import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.orientechnologies.orient.core.record.ODirection;
|
import com.orientechnologies.orient.core.record.ODirection;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class MultiContextTest extends ERManagementTest {
|
public class MultiContextTest extends ERManagementTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(MultiContextTest.class);
|
private static Logger logger = LoggerFactory.getLogger(MultiContextTest.class);
|
||||||
|
@ -81,7 +84,7 @@ public class MultiContextTest extends ERManagementTest {
|
||||||
|
|
||||||
ResourceManagement resourceManagement = getResourceManagement(r);
|
ResourceManagement resourceManagement = getResourceManagement(r);
|
||||||
resourceManagement.setDryRun(dryRun);
|
resourceManagement.setDryRun(dryRun);
|
||||||
UUID contextUUID = ContextUtility.getCurrentSecurityContext().getUUID();
|
UUID contextUUID = ContextUtility.getCurrentRequestEnvironment().getUUID();
|
||||||
resourceManagement.removeFromContext(contextUUID);
|
resourceManagement.removeFromContext(contextUUID);
|
||||||
// Map<UUID, JsonNode> affectedInstances = resourceManagement.getAffectedInstances();
|
// Map<UUID, JsonNode> affectedInstances = resourceManagement.getAffectedInstances();
|
||||||
|
|
||||||
|
@ -220,7 +223,7 @@ public class MultiContextTest extends ERManagementTest {
|
||||||
|
|
||||||
ResourceManagement resourceManagement = getResourceManagement(r);
|
ResourceManagement resourceManagement = getResourceManagement(r);
|
||||||
resourceManagement.setDryRun(dryRun);
|
resourceManagement.setDryRun(dryRun);
|
||||||
UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(targetContextFullName).getUUID();
|
UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName(targetContextFullName).getUUID();
|
||||||
resourceManagement.addToContext(contextUUID);
|
resourceManagement.addToContext(contextUUID);
|
||||||
// Map<UUID, JsonNode> affectedInstances = resourceManagement.getAffectedInstances();
|
// Map<UUID, JsonNode> affectedInstances = resourceManagement.getAffectedInstances();
|
||||||
//
|
//
|
||||||
|
@ -279,7 +282,7 @@ public class MultiContextTest extends ERManagementTest {
|
||||||
|
|
||||||
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(isRelatedTo);
|
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(isRelatedTo);
|
||||||
isRelatedToManagement.setDryRun(dryRun);
|
isRelatedToManagement.setDryRun(dryRun);
|
||||||
UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(targetContextFullName).getUUID();
|
UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName(targetContextFullName).getUUID();
|
||||||
isRelatedToManagement.addToContext(contextUUID);
|
isRelatedToManagement.addToContext(contextUUID);
|
||||||
// Map<UUID, JsonNode> affectedInstances = isRelatedToManagement.getAffectedInstances();
|
// Map<UUID, JsonNode> affectedInstances = isRelatedToManagement.getAffectedInstances();
|
||||||
|
|
||||||
|
|
|
@ -5,11 +5,17 @@ import java.io.File;
|
||||||
import java.io.FileReader;
|
import java.io.FileReader;
|
||||||
import java.io.FilenameFilter;
|
import java.io.FilenameFilter;
|
||||||
import java.net.URL;
|
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.JsonNode;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
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.ContextTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
|
import org.gcube.informationsystem.resourceregistry.queries.json.JsonQuery;
|
||||||
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
@ -29,8 +35,45 @@ public class JsonQueryTest extends ContextTest {
|
||||||
return new File(resourcesDirectory, "queries");
|
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
|
@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);
|
ContextTest.setContextByName(DEVVRE);
|
||||||
|
|
||||||
File queriesDirectory = getQueriesDirectory();
|
File queriesDirectory = getQueriesDirectory();
|
||||||
|
@ -43,7 +86,7 @@ public class JsonQueryTest extends ContextTest {
|
||||||
};
|
};
|
||||||
|
|
||||||
for(File jsonQueryFile : queriesDirectory.listFiles(filenameFilter)) {
|
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();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
|
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
|
||||||
|
@ -56,7 +99,7 @@ public class JsonQueryTest extends ContextTest {
|
||||||
logger.info("Created Query from JSON: {}", createdStringBuffer.toString());
|
logger.info("Created Query from JSON: {}", createdStringBuffer.toString());
|
||||||
|
|
||||||
StringBuffer expectedStringBuffer = new StringBuffer();
|
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))) {
|
try(BufferedReader br = new BufferedReader(new FileReader(expectedQueryFile))) {
|
||||||
for(String line; (line = br.readLine()) != null; ) {
|
for(String line; (line = br.readLine()) != null; ) {
|
||||||
expectedStringBuffer.append(line);
|
expectedStringBuffer.append(line);
|
||||||
|
@ -64,8 +107,7 @@ public class JsonQueryTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
|
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
|
||||||
|
Assert.assertTrue(compareQueries(createdStringBuffer, expectedStringBuffer));
|
||||||
Assert.assertTrue(createdStringBuffer.toString().compareTo(expectedStringBuffer.toString())==0);
|
|
||||||
|
|
||||||
String result = jsonQuery.query();
|
String result = jsonQuery.query();
|
||||||
logger.info("Result : {}", result);
|
logger.info("Result : {}", result);
|
||||||
|
@ -73,9 +115,9 @@ public class JsonQueryTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSingleCreateQuery() throws Exception {
|
public void testSingleQuery() throws Exception {
|
||||||
File queriesDirectory = getQueriesDirectory();
|
File queriesDirectory = getQueriesDirectory();
|
||||||
File jsonQueryFile = new File(queriesDirectory, "query6.json");
|
File jsonQueryFile = new File(queriesDirectory, "query10.json");
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
|
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
|
||||||
logger.info("Going to test the following JSON query {}", jsonNode.toString());
|
logger.info("Going to test the following JSON query {}", jsonNode.toString());
|
||||||
|
@ -87,7 +129,7 @@ public class JsonQueryTest extends ContextTest {
|
||||||
logger.info("Created Query from JSON: {}", createdStringBuffer.toString());
|
logger.info("Created Query from JSON: {}", createdStringBuffer.toString());
|
||||||
|
|
||||||
StringBuffer expectedStringBuffer = new StringBuffer();
|
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))) {
|
try(BufferedReader br = new BufferedReader(new FileReader(expectedQueryFile))) {
|
||||||
for(String line; (line = br.readLine()) != null; ) {
|
for(String line; (line = br.readLine()) != null; ) {
|
||||||
expectedStringBuffer.append(line);
|
expectedStringBuffer.append(line);
|
||||||
|
@ -95,18 +137,16 @@ public class JsonQueryTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
|
logger.info("Expected Query from JSON: {}", expectedStringBuffer.toString());
|
||||||
|
Assert.assertTrue(compareQueries(createdStringBuffer, expectedStringBuffer));
|
||||||
Assert.assertTrue(createdStringBuffer.toString().compareTo(expectedStringBuffer.toString())==0);
|
|
||||||
|
|
||||||
String result = jsonQuery.query();
|
String result = jsonQuery.query();
|
||||||
logger.info("Result : {}", result);
|
logger.info("Result : {}", result);
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Test
|
protected List<Entity> testSingleQuery(int offset, int limit) throws Exception {
|
||||||
public void testSingleQuery() throws Exception {
|
|
||||||
ContextTest.setContextByName(DEVVRE);
|
ContextTest.setContextByName(DEVVRE);
|
||||||
File queriesDirectory = getQueriesDirectory();
|
File queriesDirectory = getQueriesDirectory();
|
||||||
File jsonQueryFile = new File(queriesDirectory, "query3.json");
|
File jsonQueryFile = new File(queriesDirectory, "query1.json");
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
|
JsonNode jsonNode = objectMapper.readTree(jsonQueryFile);
|
||||||
logger.info("Going to test the following JSON query {}", jsonNode.toString());
|
logger.info("Going to test the following JSON query {}", jsonNode.toString());
|
||||||
|
@ -115,6 +155,140 @@ public class JsonQueryTest extends ContextTest {
|
||||||
jsonQuery.setJsonQuery(jsonNode);
|
jsonQuery.setJsonQuery(jsonNode);
|
||||||
String res = jsonQuery.query();
|
String res = jsonQuery.query();
|
||||||
logger.info(res);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,9 +14,9 @@ import org.gcube.informationsystem.model.reference.entities.Resource;
|
||||||
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
||||||
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
|
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
|
import org.gcube.informationsystem.resourceregistry.instances.ERManagementTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
|
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
|
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.ConsistsOfManagement;
|
||||||
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
|
||||||
|
@ -57,7 +57,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
public void testRawQuery() throws InvalidQueryException {
|
public void testRawQuery() throws InvalidQueryException {
|
||||||
QueryImpl queryImpl = new QueryImpl();
|
QueryImpl queryImpl = new QueryImpl();
|
||||||
|
|
||||||
String query = "select from SoftwareFacet";
|
String query = "SELECT FROM SoftwareFacet";
|
||||||
String ret = queryImpl.query(query, false);
|
String ret = queryImpl.query(query, false);
|
||||||
|
|
||||||
logger.debug(ret);
|
logger.debug(ret);
|
||||||
|
@ -90,7 +90,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
|
|
||||||
/* Getting all instances of created specific Resources */
|
/* Getting all instances of created specific Resources */
|
||||||
for (String key : resources.keySet()) {
|
for (String key : resources.keySet()) {
|
||||||
ResourceManagement resourceManagement = (ResourceManagement) ElementManagementUtility.getERManagement(key);
|
ResourceManagement resourceManagement = (ResourceManagement) ERManagementUtility.getERManagement(key);
|
||||||
String json = resourceManagement.all(false);
|
String json = resourceManagement.all(false);
|
||||||
|
|
||||||
List<Resource> list = ElementMapper.unmarshalList(Resource.class, json);
|
List<Resource> list = ElementMapper.unmarshalList(Resource.class, json);
|
||||||
|
@ -100,7 +100,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
|
|
||||||
/* Getting all Resources polymorphic and non polymorphic */
|
/* Getting all Resources polymorphic and non polymorphic */
|
||||||
|
|
||||||
ResourceManagement resourceManagement = (ResourceManagement) ElementManagementUtility
|
ResourceManagement resourceManagement = (ResourceManagement) ERManagementUtility
|
||||||
.getERManagement(Resource.NAME);
|
.getERManagement(Resource.NAME);
|
||||||
|
|
||||||
String json = resourceManagement.all(true);
|
String json = resourceManagement.all(true);
|
||||||
|
@ -114,7 +114,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
|
|
||||||
/* Getting all IsRelatedTo polymorphic and non polymorphic */
|
/* Getting all IsRelatedTo polymorphic and non polymorphic */
|
||||||
|
|
||||||
IsRelatedToManagement isRelatedToManagement = (IsRelatedToManagement) ElementManagementUtility
|
IsRelatedToManagement isRelatedToManagement = (IsRelatedToManagement) ERManagementUtility
|
||||||
.getERManagement(IsRelatedTo.NAME);
|
.getERManagement(IsRelatedTo.NAME);
|
||||||
|
|
||||||
json = isRelatedToManagement.all(true);
|
json = isRelatedToManagement.all(true);
|
||||||
|
@ -130,7 +130,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
|
|
||||||
/* Getting all ConsistsOf polymorphic and non polymorphic */
|
/* Getting all ConsistsOf polymorphic and non polymorphic */
|
||||||
|
|
||||||
ConsistsOfManagement consistsOfManagement = (ConsistsOfManagement) ElementManagementUtility
|
ConsistsOfManagement consistsOfManagement = (ConsistsOfManagement) ERManagementUtility
|
||||||
.getERManagement(ConsistsOf.NAME);
|
.getERManagement(ConsistsOf.NAME);
|
||||||
|
|
||||||
json = consistsOfManagement.all(true);
|
json = consistsOfManagement.all(true);
|
||||||
|
@ -298,7 +298,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
String type = Service.NAME;
|
String type = Service.NAME;
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
|
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
|
||||||
|
|
||||||
if (erManagement instanceof ResourceManagement) {
|
if (erManagement instanceof ResourceManagement) {
|
||||||
boolean[] booleans = new boolean[] {true, false};
|
boolean[] booleans = new boolean[] {true, false};
|
||||||
|
@ -337,7 +337,7 @@ public class QueryTest extends ERManagementTest {
|
||||||
@Test
|
@Test
|
||||||
public void getAllResourcesHavingFacet() throws ObjectNotFound, Exception {
|
public void getAllResourcesHavingFacet() throws ObjectNotFound, Exception {
|
||||||
String[] names = new String[]{"MyTest", "MyTest", "Aux", "MyID", "MyID"};
|
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<>();
|
List<Configuration> createdConfigurations = new ArrayList<>();
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,41 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -5,6 +5,7 @@ import java.io.IOException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JavaType;
|
import org.gcube.com.fasterxml.jackson.databind.JavaType;
|
||||||
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
@ -19,12 +20,16 @@ import org.gcube.informationsystem.queries.templates.reference.properties.Templa
|
||||||
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
|
||||||
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
||||||
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateAlreadyPresentException;
|
||||||
import org.gcube.informationsystem.serialization.ElementMapper;
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class QueryTemplateManagementTest extends ContextTest {
|
public class QueryTemplateManagementTest extends ContextTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(QueryTemplateManagementTest.class);
|
private static Logger logger = LoggerFactory.getLogger(QueryTemplateManagementTest.class);
|
||||||
|
@ -39,7 +44,9 @@ public class QueryTemplateManagementTest extends ContextTest {
|
||||||
|
|
||||||
public static void checkUUIDAndMetadata(IdentifiableElement previous, IdentifiableElement got) {
|
public static void checkUUIDAndMetadata(IdentifiableElement previous, IdentifiableElement got) {
|
||||||
Assert.assertTrue(got.getID()!= null);
|
Assert.assertTrue(got.getID()!= null);
|
||||||
Assert.assertTrue(got.getID().compareTo(previous.getID()) == 0);
|
if(previous.getID()!=null) {
|
||||||
|
Assert.assertTrue(got.getID().compareTo(previous.getID()) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
Metadata gotMetadata = got.getMetadata();
|
Metadata gotMetadata = got.getMetadata();
|
||||||
Metadata previousMetadata = previous.getMetadata();
|
Metadata previousMetadata = previous.getMetadata();
|
||||||
|
@ -68,10 +75,11 @@ public class QueryTemplateManagementTest extends ContextTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected QueryTemplate create(QueryTemplate queryTemplate) throws ResourceRegistryException, IOException {
|
protected QueryTemplate create(QueryTemplate queryTemplate) throws ResourceRegistryException, IOException {
|
||||||
list();
|
//list();
|
||||||
|
|
||||||
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
|
||||||
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
|
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
|
||||||
|
queryTemplateManagement.setForceIncludeMeta(true);
|
||||||
String json = ElementMapper.marshal(queryTemplate);
|
String json = ElementMapper.marshal(queryTemplate);
|
||||||
queryTemplateManagement.setJson(json);
|
queryTemplateManagement.setJson(json);
|
||||||
String created = queryTemplateManagement.create();
|
String created = queryTemplateManagement.create();
|
||||||
|
@ -79,7 +87,7 @@ public class QueryTemplateManagementTest extends ContextTest {
|
||||||
QueryTemplate createdQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, created);
|
QueryTemplate createdQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, created);
|
||||||
|
|
||||||
assertions(queryTemplate, createdQueryTemplate);
|
assertions(queryTemplate, createdQueryTemplate);
|
||||||
list(createdQueryTemplate);
|
// list(createdQueryTemplate);
|
||||||
return createdQueryTemplate;
|
return createdQueryTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -222,18 +230,21 @@ public class QueryTemplateManagementTest extends ContextTest {
|
||||||
stateTemplateVariable.setName(STATE_VARIABLE_NAME);
|
stateTemplateVariable.setName(STATE_VARIABLE_NAME);
|
||||||
stateTemplateVariable.setDescription("StateFacet value");
|
stateTemplateVariable.setDescription("StateFacet value");
|
||||||
stateTemplateVariable.setDefaultValue("running");
|
stateTemplateVariable.setDefaultValue("running");
|
||||||
|
stateTemplateVariable.setPropertyType("String");
|
||||||
queryTemplate.addTemplateVariable(stateTemplateVariable);
|
queryTemplate.addTemplateVariable(stateTemplateVariable);
|
||||||
|
|
||||||
TemplateVariable nameTemplateVariable = new TemplateVariableImpl();
|
TemplateVariable nameTemplateVariable = new TemplateVariableImpl();
|
||||||
nameTemplateVariable.setName(NAME_VARIABLE_NAME);
|
nameTemplateVariable.setName(NAME_VARIABLE_NAME);
|
||||||
nameTemplateVariable.setDescription("SoftwareFacet name");
|
nameTemplateVariable.setDescription("SoftwareFacet name");
|
||||||
nameTemplateVariable.setDefaultValue("resource-registry");
|
nameTemplateVariable.setDefaultValue("resource-registry");
|
||||||
|
nameTemplateVariable.setPropertyType("String");
|
||||||
queryTemplate.addTemplateVariable(nameTemplateVariable);
|
queryTemplate.addTemplateVariable(nameTemplateVariable);
|
||||||
|
|
||||||
TemplateVariable groupTemplateVariable = new TemplateVariableImpl();
|
TemplateVariable groupTemplateVariable = new TemplateVariableImpl();
|
||||||
groupTemplateVariable.setName(GROUP_VARIABLE_NAME);
|
groupTemplateVariable.setName(GROUP_VARIABLE_NAME);
|
||||||
groupTemplateVariable.setDescription("SoftwareFacet group");
|
groupTemplateVariable.setDescription("SoftwareFacet group");
|
||||||
groupTemplateVariable.setDefaultValue("information-system");
|
groupTemplateVariable.setDefaultValue("information-system");
|
||||||
|
groupTemplateVariable.setPropertyType("String");
|
||||||
queryTemplate.addTemplateVariable(groupTemplateVariable);
|
queryTemplate.addTemplateVariable(groupTemplateVariable);
|
||||||
|
|
||||||
return queryTemplate;
|
return queryTemplate;
|
||||||
|
@ -241,7 +252,7 @@ public class QueryTemplateManagementTest extends ContextTest {
|
||||||
|
|
||||||
protected JsonNode getTemplate() throws Exception {
|
protected JsonNode getTemplate() throws Exception {
|
||||||
File queryTemplatesDirectory = getQueryTemplatesDirectory();
|
File queryTemplatesDirectory = getQueryTemplatesDirectory();
|
||||||
File jsonQueryTemplateFile = new File(queryTemplatesDirectory, "queryTemplate" + 1 + ".json");
|
File jsonQueryTemplateFile = new File(queryTemplatesDirectory, "queryTemplate1.json");
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
JsonNode jsonNode = objectMapper.readTree(jsonQueryTemplateFile);
|
JsonNode jsonNode = objectMapper.readTree(jsonQueryTemplateFile);
|
||||||
return jsonNode;
|
return jsonNode;
|
||||||
|
@ -292,4 +303,102 @@ public class QueryTemplateManagementTest extends ContextTest {
|
||||||
logger.debug("The DB should be now clean");
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,7 +33,7 @@ public class AnotherEnhancedTest extends MultiContextTest {
|
||||||
// Map<UUID, JsonNode> expectedInstances = new HashMap<>();
|
// Map<UUID, JsonNode> expectedInstances = new HashMap<>();
|
||||||
// expectedInstances.put(eService.getUUID(), jsonNode);
|
// expectedInstances.put(eService.getUUID(), jsonNode);
|
||||||
//
|
//
|
||||||
// UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(ALTERNATIVE_TEST_SCOPE).getUUID();
|
// UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName(ALTERNATIVE_TEST_SCOPE).getUUID();
|
||||||
//
|
//
|
||||||
// try {
|
// try {
|
||||||
// ERManagementUtility.addToContextNoPropagationConstraint(expectedInstances, contextUUID, true);
|
// ERManagementUtility.addToContextNoPropagationConstraint(expectedInstances, contextUUID, true);
|
||||||
|
|
|
@ -13,10 +13,6 @@ import org.junit.Assert;
|
||||||
/**
|
/**
|
||||||
* @author Luca Frosini (ISTI - CNR)
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
*/
|
*/
|
||||||
/**
|
|
||||||
* @author lucafrosini
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class FacetManagementTest extends MultiContextTest {
|
public class FacetManagementTest extends MultiContextTest {
|
||||||
|
|
||||||
// private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
|
// private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
|
||||||
|
@ -139,7 +135,7 @@ public class FacetManagementTest extends MultiContextTest {
|
||||||
// facetManagement.setElementType(facetType);
|
// facetManagement.setElementType(facetType);
|
||||||
// facetManagement.setUUID(facet.getUUID());
|
// facetManagement.setUUID(facet.getUUID());
|
||||||
//
|
//
|
||||||
// facetManagement.addToContext(ContextUtility.getCurrentSecurityContext().getUUID());
|
// facetManagement.addToContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
|
||||||
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
|
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
|
||||||
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
|
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
|
||||||
// Assert.assertTrue(affectedInstances.size()==1);
|
// Assert.assertTrue(affectedInstances.size()==1);
|
||||||
|
@ -153,7 +149,7 @@ public class FacetManagementTest extends MultiContextTest {
|
||||||
// facetManagement.setElementType(facetType);
|
// facetManagement.setElementType(facetType);
|
||||||
// facetManagement.setUUID(facet.getUUID());
|
// facetManagement.setUUID(facet.getUUID());
|
||||||
//
|
//
|
||||||
// facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
|
// facetManagement.removeFromContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
|
||||||
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
|
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
|
||||||
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
|
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
|
||||||
// Assert.assertTrue(affectedInstances.size()==1);
|
// Assert.assertTrue(affectedInstances.size()==1);
|
||||||
|
|
|
@ -284,8 +284,8 @@ public class SchemaManagementImplTest extends ContextTest {
|
||||||
Assert.assertTrue(type.getDescription().compareTo(typeManaged.getDescription())==0);
|
Assert.assertTrue(type.getDescription().compareTo(typeManaged.getDescription())==0);
|
||||||
Assert.assertTrue(type.isAbstract() == typeManaged.isAbstract());
|
Assert.assertTrue(type.isAbstract() == typeManaged.isAbstract());
|
||||||
|
|
||||||
Assert.assertTrue(type.getTypeSuperTypes().containsAll(typeManaged.getTypeSuperTypes()));
|
Assert.assertTrue(type.getExtendedTypes().containsAll(typeManaged.getExtendedTypes()));
|
||||||
Assert.assertTrue(typeManaged.getTypeSuperTypes().containsAll(type.getTypeSuperTypes()));
|
Assert.assertTrue(typeManaged.getExtendedTypes().containsAll(type.getExtendedTypes()));
|
||||||
|
|
||||||
|
|
||||||
Map<Version, String> typeChangelog = type.getChangelog();
|
Map<Version, String> typeChangelog = type.getChangelog();
|
||||||
|
@ -400,4 +400,47 @@ public class SchemaManagementImplTest extends ContextTest {
|
||||||
compareTypes(type, typeManaged);
|
compareTypes(type, typeManaged);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void update_to_IS_Model_7_1_0_and_GCube_Model_5_1_0() throws Exception {
|
||||||
|
// TypeManagement typeManagement = new TypeManagement();
|
||||||
|
// String typeName = PropertyDefinition.NAME;
|
||||||
|
// typeManagement.setTypeName(typeName);
|
||||||
|
// logger.info("Going to delete {}", typeName);
|
||||||
|
// typeManagement.delete(AccessType.PROPERTY_ELEMENT);
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// Type type = TypeMapper.createTypeDefinition(PropertyDefinition.class);
|
||||||
|
// logger.info("Going to create {} : {}", type.getName(), TypeMapper.serializeTypeDefinition(type));
|
||||||
|
// String ret = create(PropertyDefinition.class);
|
||||||
|
// logger.info("Created {} : {}", type.getName(), ret);
|
||||||
|
// Type typeManaged = TypeMapper.deserializeTypeDefinition(ret);
|
||||||
|
// compareTypes(type, typeManaged);
|
||||||
|
|
||||||
|
|
||||||
|
// TypeManagement typeManagement = new TypeManagement();
|
||||||
|
// String typeName = TemplateVariable.NAME;
|
||||||
|
// typeManagement.setTypeName(typeName);
|
||||||
|
// logger.info("Going to delete {}", typeName);
|
||||||
|
// typeManagement.delete(AccessType.PROPERTY_ELEMENT);
|
||||||
|
|
||||||
|
|
||||||
|
// Type type = TypeMapper.createTypeDefinition(TemplateVariable.class);
|
||||||
|
// logger.info("Going to create {} : {}", type.getName(), TypeMapper.serializeTypeDefinition(type));
|
||||||
|
// String ret = create(TemplateVariable.class);
|
||||||
|
// logger.info("Created {} : {}", type.getName(), ret);
|
||||||
|
// Type typeManaged = TypeMapper.deserializeTypeDefinition(ret);
|
||||||
|
// compareTypes(type, typeManaged);
|
||||||
|
|
||||||
|
// create(AttributeProperty.class);
|
||||||
|
|
||||||
|
// create(TemplateFacet.class);
|
||||||
|
|
||||||
|
// update(ConfigurationTemplate.class, true);
|
||||||
|
|
||||||
|
// create(Event.class);
|
||||||
|
|
||||||
|
// update(EventFacet.class, true);
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,6 +13,9 @@ import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.orientechnologies.orient.core.metadata.schema.OClass;
|
import com.orientechnologies.orient.core.metadata.schema.OClass;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
public class TypesCacheTest {
|
public class TypesCacheTest {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(TypesCacheTest.class);
|
private static Logger logger = LoggerFactory.getLogger(TypesCacheTest.class);
|
||||||
|
@ -51,12 +54,4 @@ public class TypesCacheTest {
|
||||||
testCacheType(RunningPlugin.NAME);
|
testCacheType(RunningPlugin.NAME);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void test2() throws Exception {
|
|
||||||
logger.debug("------------------------------------------");
|
|
||||||
testCacheType(Service.NAME);
|
|
||||||
testCacheType(RunningPlugin.NAME);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,21 @@
|
||||||
|
package org.gcube.informationsystem.resourceregistry.utils;
|
||||||
|
|
||||||
|
import org.gcube.informationsystem.resourceregistry.ContextTest;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Luca Frosini (ISTI - CNR)
|
||||||
|
*/
|
||||||
|
public class MetadataUtilityTest extends ContextTest {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(MetadataUtilityTest.class);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetUsername() {
|
||||||
|
String username = MetadataUtility.getUser();
|
||||||
|
logger.info("Current User username is {}", username);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue