Compare commits

...

164 Commits

Author SHA1 Message Date
Luca Frosini aca1ffde5c Updated changelog 2024-11-13 17:12:32 +01:00
Luca Frosini ca1e91c6c4 Removed duplicated test 2024-11-13 14:18:46 +01:00
Luca Frosini b32188741c Fixed comment 2024-11-13 11:45:42 +01:00
Luca Frosini 70b9d23fa8 Moved code in the right implementation classes 2024-11-13 11:44:50 +01:00
Luca Frosini bcb55ea4e9 Fixed test issue 2024-11-13 11:40:25 +01:00
Luca Frosini 6160f73bc2 State change has been integrated in update. Keep the dedicated code as
comment
2024-11-12 16:55:55 +01:00
Luca Frosini 47ade46b63 Finalised implementation of context state change 2024-11-11 14:49:27 +01:00
Luca Frosini 24bdfca564 removed test try catch 2024-11-11 11:21:35 +01:00
Luca Frosini 95d6cdd699 Restored wrong commit 2024-11-11 11:13:09 +01:00
Luca Frosini 26aa96ae37 Fixed test for non active contexts 2024-11-11 11:12:51 +01:00
Luca Frosini 4a557031d6 Renamed method 2024-11-08 17:04:00 +01:00
Luca Frosini c2ed490fd9 Implementing the feature to change the state of a Context 2024-11-08 17:03:22 +01:00
Luca Frosini 244cec6854 Added test of context state 2024-11-08 15:32:30 +01:00
Luca Frosini f874c01d7a Fixed log 2024-11-08 15:31:43 +01:00
Luca Frosini 7cdd897f4e cleaned cache after create in any cases 2024-11-08 15:29:18 +01:00
Luca Frosini 8154011cc6 Improved exception management 2024-11-08 15:27:35 +01:00
Luca Frosini 84ebc54546 Added a way to simulate users and roles 2024-11-08 11:50:24 +01:00
Luca Frosini 40fa20a871 Improved test 2024-11-07 13:34:43 +01:00
Luca Frosini 2ff9841de2 fixed bug 2024-11-07 13:34:12 +01:00
Luca Frosini 39373982ed Added authorship 2024-11-06 15:05:27 +01:00
Luca Frosini 2790457fca Added authorship 2024-11-06 15:03:03 +01:00
Luca Frosini f6601cac8e Added authorship 2024-11-06 15:01:40 +01:00
Luca Frosini 833d2bd2cb Added authorship 2024-11-06 15:01:03 +01:00
Luca Frosini f205927545 Added authorship and formatted code 2024-11-06 15:00:37 +01:00
Luca Frosini 027da0216e Added authorship 2024-11-06 14:58:24 +01:00
Luca Frosini 9777ecc7b8 Added authorship 2024-11-06 14:58:16 +01:00
Luca Frosini bc511f48bf Removed old wrong and uneeded file 2024-11-06 14:57:56 +01:00
Luca Frosini 8110a24257 Added missing test file 2024-11-06 14:57:32 +01:00
Luca Frosini 0ead00f884 Fixing issues 2024-11-05 18:32:57 +01:00
Luca Frosini 4fe825cbfb Improved code readability 2024-11-05 17:13:43 +01:00
Luca Frosini cf3e5c9b98 Fixed tests 2024-11-04 16:13:05 +01:00
Luca Frosini 3b062d2774 Fixed corner cases 2024-11-04 16:11:17 +01:00
Luca Frosini ef6975a2b5 Fixing code 2024-11-04 14:44:32 +01:00
Luca Frosini 05299464ae improved test 2024-11-04 14:44:17 +01:00
Luca Frosini 292272a72e Added Test 2024-11-04 14:42:12 +01:00
Luca Frosini 84fbf0ea4e Splitter row for debugging 2024-11-04 14:41:56 +01:00
Luca Frosini d4201c68c6 Improved readability 2024-11-04 11:58:02 +01:00
Luca Frosini 8ca83520bd Renamed test function 2024-11-04 11:57:35 +01:00
Luca Frosini f65b6aee17 Moved and renamed test class 2024-11-04 11:56:49 +01:00
Luca Frosini b47a1b9ba7 Fixed comments 2024-11-04 11:38:03 +01:00
Luca Frosini 648fd0a8ae Added activate operation on contexts 2024-11-04 11:29:12 +01:00
Luca Frosini 64a2ced9ec Reorganizing code 2024-11-04 10:25:22 +01:00
Luca Frosini cd8627cf32 Fixing tests 2024-10-31 17:42:33 +01:00
Luca Frosini fb230cee94 Reorganizing code 2024-10-31 17:39:48 +01:00
Luca Frosini e29a78cd2d revising role operation checks 2024-10-31 17:26:34 +01:00
Luca Frosini 847edc72ef Added TODO as reminder 2024-10-31 16:14:02 +01:00
Luca Frosini e98a049ab4 Using new APIs in place of the deprecated ones 2024-10-31 15:00:34 +01:00
Luca Frosini 4fa38c24dd Variable instances renaming from securityContext to *Environment 2024-10-31 14:55:36 +01:00
Luca Frosini aeba8ba06a Fixed log 2024-10-30 15:07:35 +01:00
Luca Frosini 28ea920a05 Fixed log message 2024-10-30 14:38:46 +01:00
Luca Frosini 7dd3f13d7d Improving Environment hierarchy 2024-10-29 18:11:01 +01:00
Luca Frosini 8902f6b17b Reorganizing classes 2024-10-29 16:39:29 +01:00
Luca Frosini 281285761f fixed var name 2024-10-29 14:38:58 +01:00
Luca Frosini 3ec9670319 Added test 2024-10-28 15:46:00 +01:00
Luca Frosini 4766ad2f80 Added d4science-iam-client which is used for tests 2024-10-28 15:45:30 +01:00
Luca Frosini ec3a17b2d9 Migrated from keycloack-client to d4science-iam-client 2024-10-28 15:44:39 +01:00
Luca Frosini 66224d73f4 Reorganizing packages 2024-10-23 14:51:49 +02:00
Luca Frosini 5c195f8723 Reorganizing packages 2024-10-23 14:49:19 +02:00
Luca Frosini 0eb2cf9456 Reorganized packages 2024-10-23 14:48:07 +02:00
Luca Frosini 334a8aff37 Added classes description for future reference 2024-10-23 13:31:51 +02:00
Luca Frosini e1ef53f2ef Improved naming 2024-10-23 13:16:10 +02:00
Luca Frosini d9cc910fa9 Reorganized environments 2024-10-23 12:33:36 +02:00
Luca Frosini dafc4e5639 Fixing naming 2024-10-23 10:58:20 +02:00
Luca Frosini 924b370a81 Reorganizing naming 2024-10-23 10:50:38 +02:00
Luca Frosini ae2ec3ca5d Renaming SecurityContext in SystemEnvironment which is more clear 2024-10-23 10:30:34 +02:00
Luca Frosini 2360949ad3 temp commit 2024-10-08 14:31:30 +02:00
Luca Frosini 48f7b1a73b Adding the concept of allowed roles for some operations 2024-07-10 17:59:14 +02:00
Luca Frosini bf09efc8fd Fixed Changelog 2024-07-09 12:02:42 +02:00
Luca Frosini 99980cc20c PArent context must be get with the same current DB 2024-07-09 12:02:25 +02:00
Luca Frosini fb7ca52744 Fixed created value of Context state 2024-07-02 17:31:34 +02:00
Luca Frosini a3b66f300e Enabled support for List and Set 2024-07-02 17:30:52 +02:00
Luca Frosini 69ad3803eb Adding support for contexts extra info 2024-07-01 17:39:48 +02:00
Luca Frosini e42b2bde0a Removed wrong example 2024-06-26 17:11:24 +02:00
Luca Frosini 4ffaf4b082 upgraded procedure to upgrade models in the DB 2024-06-25 17:49:21 +02:00
Luca Frosini 984a1e5497 Added example to design feature #27707 2024-06-25 17:48:39 +02:00
Luca Frosini 47092cf13e improved comment 2024-06-14 09:45:25 +02:00
Luca Frosini 7b1631e8be Added method to clean cache which has to be exposed and implemented 2024-06-13 16:17:36 +02:00
Luca Frosini 8b49c4ffd2 Updated model upgrade procedure 2024-06-13 15:31:57 +02:00
Luca Frosini 8f701c10a5 enabled List and Set previously deactivated 2024-06-13 15:31:12 +02:00
Luca Frosini 8e4f173917 Added procedure to upgrade DB to IS model 7.1.0 2024-06-12 16:49:32 +02:00
Luca Frosini f85fb9948f Minor fixes 2024-06-12 16:49:02 +02:00
Luca Frosini b27a2695cf Fixed code to be aligned with removal of generic in IS Model class 2024-06-11 11:56:41 +02:00
Luca Frosini 1da984cac0 Fixed fullPath logging 2024-06-11 10:33:12 +02:00
Luca Frosini 6080c0ee41 Added ANY base type mapping 2024-06-11 10:22:16 +02:00
Luca Frosini 7865bd81cc Fixed comment whitespace and removed uneeded explicit cast 2024-06-11 10:21:52 +02:00
Luca Frosini c6049a122b Fixed context test base class 2024-04-16 15:11:33 +02:00
Luca Frosini 1e31a71fce starting to create the skeleton for changes 2024-01-25 17:18:39 +01:00
Luca Frosini 0917263f27 added test JSON query 2024-01-25 15:59:48 +01:00
luca.frosini 30e8c84258 Fixed projection 2023-11-29 14:26:02 +01:00
luca.frosini c324b3ab41 Fixed JSON queries 2023-11-29 13:19:48 +01:00
luca.frosini c5531d7c54 JSON queries has been switched to match queries 2023-11-28 16:57:54 +01:00
luca.frosini 8af757f3db Fixing tests and match queries 2023-11-27 17:44:15 +01:00
luca.frosini 0812a0c94c Improving code 2023-11-24 17:44:27 +01:00
luca.frosini 78ea9c2307 Improving code 2023-11-24 15:36:43 +01:00
luca.frosini 6657543a63 Improving code 2023-11-24 14:30:51 +01:00
luca.frosini 6a1e0e5838 Implementing projection 2023-11-24 14:03:06 +01:00
luca.frosini 5fe0e5771b Implementing projection match query 2023-11-23 17:10:17 +01:00
luca.frosini 9450134790 Implementing projection 2023-11-20 17:34:48 +01:00
luca.frosini f2cf0a4f17 Implementing projection 2023-11-20 16:27:57 +01:00
luca.frosini 24f2ec53c1 Implementing feature 2023-11-17 17:40:10 +01:00
luca.frosini d2b797c19a Implementing the new match query 2023-11-17 17:21:45 +01:00
luca.frosini 46cb4f0975 Added methods to create match query 2023-11-16 14:29:32 +01:00
luca.frosini 816c7693dc Fixed queries 2023-11-16 14:09:57 +01:00
luca.frosini ffd20403da Fixed test 2023-11-16 12:12:04 +01:00
luca.frosini 2dba63771b Renamed .query files in .oquery (o stand for OrientDB) 2023-11-16 12:11:03 +01:00
luca.frosini e0bfef4c49 Changing the generated query to support projection 2023-11-16 12:02:17 +01:00
luca.frosini 2d863b99fc Fixed ServerContextCache issue 2023-11-10 15:44:43 +01:00
luca.frosini 084e223669 Trying to fix Server Context Cache 2023-11-10 14:37:43 +01:00
luca.frosini e8a98dd54a Fixing REST API 2023-11-10 13:50:33 +01:00
luca.frosini 0878cdd7bd Merge remote-tracking branch 'origin/feature/24648' 2023-11-09 17:55:00 +01:00
luca.frosini dd7ad6840e Added pagination support 2023-11-09 17:38:51 +01:00
luca.frosini ca51189cab Cleaning commented code 2023-11-09 17:33:02 +01:00
luca.frosini dfccd87a62 Fixed queries and test 2023-11-09 17:21:21 +01:00
luca.frosini 00e0fc2a55 Improving queries 2023-11-09 12:53:35 +01:00
luca.frosini 996997804a Fixed changelog 2023-11-08 17:24:35 +01:00
luca.frosini 7ce298be17 Full refactor of JsonQuery management 2023-11-08 17:16:18 +01:00
luca.frosini b978185cd5 Added skip limit 2023-11-07 18:01:38 +01:00
luca.frosini 68c742eb09 Removed postfilter because polymorphism support has been added in query 2023-11-06 17:45:00 +01:00
luca.frosini 7409a8d278 Improving Json Queries 2023-11-03 17:56:55 +01:00
luca.frosini c611a839eb Improving offset limit management to properly support paginated result 2023-10-31 15:24:29 +01:00
luca.frosini 1eb1cf6773 Fixing whitespaces 2023-10-31 14:40:23 +01:00
luca.frosini d786ffff98 Fixing context pagination 2023-10-31 14:39:39 +01:00
luca.frosini 08fca98875 Changed the way to paginate results due to missing skip in TRAVERSE
command
2023-09-27 16:23:35 +02:00
luca.frosini e5106cd6c0 Fixed test to be able to be executed on OS different from linux 2023-09-27 16:16:23 +02:00
luca.frosini 849cc923f3 Added pagination support for QueryTemplates 2023-09-27 15:18:28 +02:00
luca.frosini 9851f83ecd Fixed log 2023-09-27 15:18:03 +02:00
luca.frosini 9b3ffcf5b4 Improved Query Readability 2023-09-27 15:17:54 +02:00
luca.frosini c34c5f9a59 Added pagination in JSONQuery 2023-09-27 15:16:58 +02:00
luca.frosini 22bedb9a75 Added complete test for ERElement pagination 2023-09-27 15:13:02 +02:00
luca.frosini 3f1a4f5795 Added pagination to prepared query 2023-09-27 15:12:36 +02:00
luca.frosini 5741f52072 fixed test 2023-09-27 15:11:41 +02:00
luca.frosini 290cb44221 Improved JUnit test to properly verify context pagination 2023-09-27 12:23:11 +02:00
luca.frosini 90e1ca1a28 Added pagination to context listing 2023-09-27 12:22:11 +02:00
luca.frosini af48246afa Added limit offset request check in query and listing methods 2023-09-25 18:01:47 +02:00
luca.frosini ee8bdefa8b Added pagination to contexts 2023-09-22 19:06:05 +02:00
luca.frosini 8c5dcd0341 improved test 2023-09-22 18:49:49 +02:00
luca.frosini 9d9ec44b90 Added the possibility to get unbounded instances using -1 2023-09-22 18:10:20 +02:00
luca.frosini 38668d8a21 Added pagination for instances listing 2023-09-22 16:58:23 +02:00
luca.frosini 31f0120c50 Added check of limit/offset query parameter 2023-09-21 22:13:41 +02:00
luca.frosini 01716b55cd Added libraries to comply with JDK 11 2023-09-21 10:28:01 +02:00
luca.frosini d650c16e29 Renamed functions to improve code 2023-09-21 10:27:28 +02:00
luca.frosini d2ca74cc72 Implementing limit offset 2023-09-18 18:09:00 +02:00
luca.frosini 95b86d8a40 Merged changes made to solve bug #25650 2023-09-18 16:30:43 +02:00
luca.frosini a3a2e3a0a9 Fixed bug #25650 2023-09-15 18:31:53 +02:00
luca.frosini 88c1ee60d8 Improved changelog 2023-09-14 15:10:26 +02:00
luca.frosini 71b780eb2a Extended BaseRequestInfo 2023-09-14 15:10:11 +02:00
luca.frosini 0cb336ded4 Enhanced version 2023-09-13 11:15:20 +02:00
luca.frosini 402ead3696 Removed -SNAPSHOT to release the component 2023-09-05 15:51:47 +02:00
luca.frosini d977e1ef8a Updated changelog 2023-08-28 13:47:50 +02:00
luca.frosini 1332261fc4 Cleaning RequestInfo refs #25211 2023-08-28 13:41:57 +02:00
luca.frosini cbe25a5832 Ignored MacOs File 2023-06-21 11:40:56 +02:00
Luca Frosini e3b6c8add5 Added shadow context class to allow to implements #19428 2023-05-19 16:05:28 +02:00
Luca Frosini dab30f5670 Fixing code 2023-05-17 14:03:59 +02:00
Luca Frosini 76438c6a90 Fixed path 2023-05-16 16:00:45 +02:00
Luca Frosini 46f0bea227 Fixed paths and called methods 2023-05-16 15:12:26 +02:00
Luca Frosini c7b9d21bba Rationalised accounting methods 2023-05-16 14:59:21 +02:00
Luca Frosini c79b579925 fixing query templates details 2023-05-16 14:07:12 +02:00
Luca Frosini f9e474d4cd Fixed code 2023-05-16 11:47:31 +02:00
Luca Frosini 804e2b2343 Fixing server context cache 2023-05-15 17:41:34 +02:00
Luca Frosini 20914f3f06 Fixed cache 2023-05-15 17:33:26 +02:00
Luca Frosini b32f282044 Fixed checked query parameters 2023-05-15 16:47:30 +02:00
Luca Frosini fe6e990605 Fixing get parameters 2023-05-15 16:33:47 +02:00
Luca Frosini 738b693697 Fixing bug 2023-05-15 13:00:59 +02:00
Luca Frosini 01a8480180 Applied changes made in IS Model 2023-05-12 17:55:53 +02:00
148 changed files with 7019 additions and 2695 deletions

4
.gitignore vendored
View File

@ -1,3 +1,7 @@
target
.classpath
.project
/.DS_Store
/bin/
/.apt_generated/
/.apt_generated_tests/

View File

@ -1,3 +1,4 @@
/org.eclipse.core.resources.prefs
/org.eclipse.jdt.core.prefs
/org.eclipse.m2e.core.prefs
/org.eclipse.jdt.apt.core.prefs

View File

@ -2,24 +2,36 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# 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]
- Metadata are added only if requested by the client [#25040]
- Restored Encrypted Property Type and removed Vault [#25041]
- Cleaned RequestInfo in RequestFilter class [#25211]
- Solved bug which allow to create two query template with the same name if a null id was provided [#25650]
## [v4.2.0]
- Fixed bug on JSONQuery for Facets which does not have any properties to match [#24237]
- Fixed bug on JSONQuery for IsRelatedTo relations indicating both source and target resources [#24264]
- Fixed bug on returned boolean values as string [#24240]
- Fixed bug on returned boolean values as string [#24240]
- Enabled array properties [#24225]
- Using delete in propagation contraint as action indication for delete operation [#24301]
- Fixed default value of propagation constraint of remove action for ConsistsOf to 'cascade' [#24223]
- Removed Encrypted Property Type and added Vault instead [#24655]
- Enhanced gcube-smartgears-bom version
## [v4.1.0]

26
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry</artifactId>
<version>4.3.0-SNAPSHOT</version>
<version>4.4.0-SNAPSHOT</version>
<name>Resource Registry Service</name>
<description>The Resource Registry is a web-service which represent the core component of the gCube Information System</description>
<packaging>war</packaging>
@ -31,7 +31,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-smartgears-bom</artifactId>
<version>2.5.0-SNAPSHOT</version>
<version>2.5.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -52,7 +52,7 @@
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-utils</artifactId>
<version>[2.1.0, 3.0.0-SNAPSHOT)</version>
<version>[2.2.0, 3.0.0-SNAPSHOT)</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
@ -101,12 +101,32 @@
<scope>provided</scope>
</dependency>
<!-- END Jersey -->
<!-- Added to support Java 11 JDK -->
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- END Added to support Java 11 JDK -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- 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>
<groupId>org.gcube.resource-management</groupId>
<artifactId>gcube-model</artifactId>

View File

@ -1,4 +1,4 @@
package org.gcube.informationsystem.resourceregistry.instances.base;
package org.gcube.informationsystem.resourceregistry.base;
import java.io.IOException;
import java.text.DateFormat;
@ -14,7 +14,7 @@ import java.util.Map.Entry;
import java.util.Set;
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.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.TextNode;
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.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
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.types.SchemaException;
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.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.properties.PropertyElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
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 UNDERSCORE = "_";
public final static String DOLLAR = "$";
protected final Set<String> ignoreKeys;
protected final Set<String> ignoreStartWithKeys;
@ -147,24 +152,27 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
protected Operation operation;
/**
* A Delete operation has a cascade impact we could want to know the impact
* Instances affected by a delete
* A Delete an addToContext and a RemoveFromContext operation has a cascade impact
* we want to know the impact, i.e. instances involved
*/
protected final Map<UUID,JsonNode> affectedInstances;
protected ElementManagement(AccessType accessType) {
this.accessType = accessType;
this.ignoreKeys = new HashSet<String>();
this.ignoreKeys.add(Element.TYPE_PROPERTY);
this.ignoreKeys.add(Element.SUPERTYPES_PROPERTY);
this.ignoreKeys.add(Element.EXPECTED_TYPE_PROPERTY);
this.ignoreKeys.add(ModelElement.SUPERTYPES_PROPERTY);
this.ignoreKeys.add(ModelElement.EXPECTED_TYPE_PROPERTY);
this.ignoreKeys.add(IdentifiableElement.ID_PROPERTY);
this.ignoreKeys.add(IdentifiableElement.METADATA_PROPERTY);
this.ignoreStartWithKeys = new HashSet<String>();
this.ignoreStartWithKeys.add(ElementManagement.AT);
this.ignoreStartWithKeys.add(ElementManagement.UNDERSCORE);
this.ignoreStartWithKeys.add(ElementManagement.DOLLAR);
this.reload = false;
@ -181,6 +189,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
this.forceIncludeMeta = false;
this.forceIncludeAllMeta = false;
}
public boolean isForceIncludeMeta() {
@ -243,17 +252,12 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
return accessType;
}
protected SecurityContext workingContext;
protected Environment workingEnvironment;
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = ContextUtility.getCurrentSecurityContext();
}
return workingContext;
}
protected abstract Environment getWorkingEnvironment() throws ResourceRegistryException;
public void setWorkingContext(SecurityContext workingContext) {
this.workingContext = workingContext;
public void setWorkingEnvironment(Environment workingContext) {
this.workingEnvironment = workingContext;
}
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<>();
keysToAddFirst.add(Element.TYPE_PROPERTY);
keysToAddFirst.add(Element.SUPERTYPES_PROPERTY);
keysToAddFirst.add(ModelElement.SUPERTYPES_PROPERTY);
keysToAddFirst.add(IdentifiableElement.ID_PROPERTY);
keysToAddFirst.add(IdentifiableElement.METADATA_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());
break;
case Element.SUPERTYPES_PROPERTY:
case ModelElement.SUPERTYPES_PROPERTY:
Collection<String> supertypes = getCachedType().getSuperTypes();
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;
case IdentifiableElement.METADATA_PROPERTY:
@ -543,7 +551,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
MetadataUtility.addMetadata(element);
getWorkingContext().addElement(element, oDatabaseDocument);
getWorkingEnvironment().addElement(element, oDatabaseDocument);
element.save();
@ -572,6 +580,8 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
sanityCheck();
return element;
} catch(WebApplicationException e) {
throw e;
} catch(ResourceRegistryException e) {
throw 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 {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
setAsEntryPoint();
setOperation(Operation.QUERY);
return reallyGetAll(polymorphic);
} catch (WebApplicationException e) {
throw e;
} catch(ResourceRegistryException e) {
throw 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 {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
setAsEntryPoint();
setOperation(Operation.EXISTS);
getElement();
return true;
} catch (WebApplicationException e) {
logger.error("Unable to find {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
throw 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;
} catch(Exception 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 {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
Environment environment = getWorkingEnvironment();
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
boolean update = false;
setAsEntryPoint();
setOperation(Operation.UPDATE);
try {
setAsEntryPoint();
getElement();
// TODO environment.isUserAllowed(operation);
update = true;
internalUpdate();
} catch(NotFoundException e) {
setAsEntryPoint();
setOperation(Operation.CREATE);
// TODO environment.isUserAllowed(operation);
String calledMethod = CalledMethodProvider.instance.get();
calledMethod = calledMethod.replace("update", "create");
CalledMethodProvider.instance.set(calledMethod);
@ -739,8 +758,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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) {
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) {
oDatabaseDocument.rollback();
}
@ -766,7 +791,9 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
Environment environment = getWorkingEnvironment();
// TODO environment.isUserAllowed(Operation.CREATE);
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
setAsEntryPoint();
@ -778,8 +805,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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) {
logger.error("Unable to create {}", accessType.getName());
logger.error("Unable to create {}. Reason {}", accessType.getName(), e.getMessage());
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
@ -805,16 +838,21 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
Environment environment = getWorkingEnvironment();
setOperation(Operation.READ);
// TODO environment.isUserAllowed(operation);
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.READER);
setAsEntryPoint();
setOperation(Operation.READ);
getElement();
return serializeAsJsonNode().toString();
} catch (WebApplicationException e) {
logger.error("Unable to read {} with UUID {}. Reason {}", accessType.getName(), uuid, e.getMessage());
throw 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;
} catch(Exception 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 {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
Environment environment = getWorkingEnvironment();
// TODO environment.isUserAllowed(Operation.UPDATE);
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
setAsEntryPoint();
@ -848,8 +887,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
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) {
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) {
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);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
// oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.WRITER);
Environment environment = getWorkingEnvironment();
setOperation(Operation.DELETE);
// TODO environment.isUserAllowed(operation);
oDatabaseDocument = environment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
setAsEntryPoint();
@ -888,8 +935,14 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}else {
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) {
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) {
oDatabaseDocument.rollback();
}
@ -911,21 +964,25 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
}
}
public Set<String> getContextsSet() throws NotFoundException, ContextException, ResourceRegistryException {
logger.trace("Going to get contexts for {} instance with UUID {}", typeName, uuid);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument instanceDB = this.oDatabaseDocument;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
setOperation(Operation.GET_METADATA);
// TODO adminEnvironment.isUserAllowed(operation);
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
setAsEntryPoint();
setOperation(Operation.GET_METADATA);
Set<String> contexts = SecurityContext.getContexts(getElement());
Set<String> contexts = InstanceEnvironment.getContexts(getElement());
return contexts;
} catch (WebApplicationException e) {
logger.error("Unable to get contexts for {} with UUID {}. Reason {}", typeName, uuid, e.getMessage());
throw 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;
} catch(Exception 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) {
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);
}
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,
Set<String> ignoreStartWith) throws JsonProcessingException, IOException {
@ -1087,7 +1090,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
Object object = null;
if(oProperty.getLinkedType()!=null) {
object = getObjectFromJsonNode(elementOfArray);
object = ElementManagementUtility.getObjectFromJsonNode(elementOfArray);
}else {
object = PropertyElementManagement.getPropertyDocument(elementOfArray);
}
@ -1104,7 +1107,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
Object object = null;
if(oProperty.getLinkedType()!=null) {
object = getObjectFromJsonNode(elementOfSet);
object = ElementManagementUtility.getObjectFromJsonNode(elementOfSet);
}else {
object = PropertyElementManagement.getPropertyDocument(elementOfSet);
}
@ -1120,7 +1123,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
String fieldKey = fieldNames.next();
Object object = null;
if(oProperty.getLinkedType()!=null) {
object = getObjectFromJsonNode(value.get(fieldKey));
object = ElementManagementUtility.getObjectFromJsonNode(value.get(fieldKey));
}else {
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) {
element.setProperty(key, value.toString());
}else {
element.setProperty(key, getObjectFromJsonNode(value));
element.setProperty(key, ElementManagementUtility.getObjectFromJsonNode(value));
}
break;
default:
Object obj = getObjectFromJsonNode(value);
Object obj = ElementManagementUtility.getObjectFromJsonNode(value);
if(obj != null) {
element.setProperty(key, obj);
}
@ -1170,7 +1173,7 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
OProperty oProperty = oClass.getProperty(key);
if(oProperty==null) {
Object object = getObjectFromJsonNode(value);
Object object = ElementManagementUtility.getObjectFromJsonNode(value);
if(object != null) {
if(object instanceof ODocument) {
element.setProperty(key, object, OType.EMBEDDED);
@ -1215,9 +1218,19 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
return element;
}
public static boolean isUserAllowedToGetPrivacyMeta() {
// TODO
return true;
public boolean isUserAllowedToGetPrivacyMeta() {
boolean allowed = false;
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 {
@ -1243,11 +1256,11 @@ public abstract class ElementManagement<El extends OElement, T extends Type> {
// TODO check a solution for supertypes
TypesCache typesCache = TypesCache.getInstance();
@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();
Collection<String> superClasses = metadataType.getSuperTypes();
ArrayNode arrayNode = objectMapper.valueToTree(superClasses);
metadataJson.replace(Element.SUPERTYPES_PROPERTY, arrayNode);
metadataJson.replace(ModelElement.SUPERTYPES_PROPERTY, arrayNode);
return metadataJson;
}

View File

@ -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.UUID;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.model.reference.entities.Entity;
import javax.activation.UnsupportedDataTypeException;
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.Resource;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
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.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.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,48 +41,6 @@ public class ElementManagementUtility {
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 {
try {
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 {
if(oDatabaseDocument == null) {
@ -150,12 +102,12 @@ public class ElementManagementUtility {
throw new ResourceRegistryException(error);
}
entityManagement.setODatabaseDocument(oDatabaseDocument);
entityManagement.setWorkingContext(workingContext);
entityManagement.setWorkingEnvironment(workingContext);
entityManagement.setElement(vertex);
return entityManagement;
}
public static RelationManagement<?,?> getRelationManagement(SecurityContext workingContext, ODatabaseDocument oDatabaseDocument,
public static RelationManagement<?,?> getRelationManagement(Environment workingContext, ODatabaseDocument oDatabaseDocument,
OEdge edge) throws ResourceRegistryException {
if(oDatabaseDocument == null) {
@ -183,7 +135,7 @@ public class ElementManagementUtility {
relationManagement.setODatabaseDocument(oDatabaseDocument);
relationManagement.setWorkingContext(workingContext);
relationManagement.setWorkingEnvironment(workingContext);
relationManagement.setElement(edge);
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.");
}
}
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;
}
}

View File

@ -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.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.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
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.environments.Environment;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
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.oDatabaseDocument = oDatabaseDocument;
setWorkingContext(workingContext);
setWorkingEnvironment(workingContext);
}
/*
@ -68,7 +68,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
String id = edge.getIdentity().toString();
RelationElementManagement<?,?,?,?> relationManagement = relationManagements.get(id);
if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement);
}
return relationManagement;

View File

@ -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.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.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
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.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
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.add(ElementManagement.AT);
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();
if(jsonNode.has(Element.SUPERTYPES_PROPERTY)) {
((ObjectNode) jsonNode).remove(Element.SUPERTYPES_PROPERTY);
if(jsonNode.has(ModelElement.SUPERTYPES_PROPERTY)) {
((ObjectNode) jsonNode).remove(ModelElement.SUPERTYPES_PROPERTY);
}
if(jsonNode.has(ModelElement.EXPECTED_TYPE_PROPERTY)) {
((ObjectNode) jsonNode).remove(ModelElement.EXPECTED_TYPE_PROPERTY);
}
String type = TypeUtility.getTypeName(jsonNode);
@ -75,7 +79,7 @@ public class PropertyElementManagement {
try {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(type);
oClass = cachedType.getOClass();
AccessType gotAccessType = cachedType.getAccessType();
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
@ -152,7 +156,7 @@ public class PropertyElementManagement {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(type);
OClass oClass = cachedType.getOClass();
AccessType gotAccessType = cachedType.getAccessType();
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
@ -161,7 +165,7 @@ public class PropertyElementManagement {
Collection<String> superClasses = cachedType.getSuperTypes();
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

View File

@ -1,4 +1,4 @@
package org.gcube.informationsystem.resourceregistry.instances.base.relations;
package org.gcube.informationsystem.resourceregistry.base.relations;
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.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
@ -73,10 +73,10 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
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.oDatabaseDocument = orientGraph;
setWorkingContext(workingContext);
setWorkingEnvironment(workingContext);
}
public SEM getSourceEntityManagement() throws ResourceRegistryException {

View File

@ -5,6 +5,7 @@ import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.impl.ScopeBean;
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.contexts.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.slf4j.Logger;
@ -35,7 +36,7 @@ public class ContextUtility {
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
private Map<UUID,SecurityContext> contexts;
private Map<UUID,InstanceEnvironment> contexts;
private static ContextUtility contextUtility;
@ -54,56 +55,52 @@ public class ContextUtility {
return SecretManagerProvider.instance.get().getContext();
}
public static SecurityContext getCurrentSecurityContext() throws ResourceRegistryException {
public static InstanceEnvironment getCurrentRequestEnvironment() throws ResourceRegistryException {
String fullName = getCurrentContextFullName();
if(fullName == null) {
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 {
AdminSecurityContext adminSecurityContext = AdminSecurityContext.getInstance();
return adminSecurityContext;
public static String getCurrentUserUsername() {
SecretManager sm = SecretManagerProvider.instance.get();
return sm.getUser().getUsername();
}
public synchronized void addSecurityContext(SecurityContext securityContext) {
contexts.put(securityContext.getUUID(), securityContext);
public synchronized void addInstanceEnvironment(InstanceEnvironment instanceEnvironment) {
contexts.put(instanceEnvironment.getUUID(), instanceEnvironment);
}
public synchronized void addSecurityContext(String fullname, SecurityContext securityContext) {
contexts.put(securityContext.getUUID(), securityContext);
}
public synchronized SecurityContext getSecurityContextByFullName(String fullName) throws ContextException {
public synchronized InstanceEnvironment getRequestEnvironmentByContextFullName(String fullName) throws ContextException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
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);
if(uuid != null) {
securityContext = contexts.get(uuid);
instanceEnvironment = contexts.get(uuid);
}
if(securityContext==null) {
logger.trace("{} for {} is not in cache. Going to get it", SecurityContext.class.getSimpleName(),
if(instanceEnvironment==null) {
logger.trace("{} for {} is not in cache. Going to get it", InstanceEnvironment.class.getSimpleName(),
fullName);
oDatabaseDocument = getAdminSecurityContext().getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.READER);
OVertex contextVertex = getContextVertexByFullName(oDatabaseDocument, fullName);
uuid = UUIDUtility.getUUID(contextVertex);
securityContext = getSecurityContextByUUID(uuid, contextVertex);
instanceEnvironment = getEnvironmentByUUID(uuid, contextVertex);
addSecurityContext(fullName, securityContext);
addInstanceEnvironment(instanceEnvironment);
}
return securityContext;
return instanceEnvironment;
} catch(ContextException e) {
throw e;
@ -120,8 +117,8 @@ public class ContextUtility {
}
}
public SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException {
return getSecurityContextByUUID(uuid, null);
public InstanceEnvironment getEnvironmentByUUID(UUID uuid) throws ResourceRegistryException {
return getEnvironmentByUUID(uuid, null);
}
public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() {
@ -134,50 +131,44 @@ public class ContextUtility {
return current;
}
private OVertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = 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();
}
private InstanceEnvironment getEnvironmentByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException {
InstanceEnvironment instanceEnvironment = contexts.get(uuid);
if(instanceEnvironment == null) {
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
private SecurityContext getSecurityContextByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid);
if(securityContext == null) {
instanceEnvironment = new InstanceEnvironment(uuid);
securityContext = new SecurityContext(uuid);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
try {
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();
if(parentVertex != null) {
UUID parentUUID = UUIDUtility.getUUID(parentVertex);
securityContext.setParentSecurityContext(getSecurityContextByUUID(parentUUID, parentVertex));
instanceEnvironment.setParentEnvironment(getEnvironmentByUUID(parentUUID, parentVertex));
}
} catch(NoSuchElementException e) {
// 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;
}
/*

View File

@ -3,11 +3,16 @@ package org.gcube.informationsystem.resourceregistry.contexts;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
@ -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.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
* TODO find a distributed solution
*/
public class ServerContextCache extends ContextCache {
private static Logger logger = LoggerFactory.getLogger(ServerContextCache.class);
protected List<Context> contextsNoMeta;
protected Map<UUID, Context> uuidToContextNoMeta;
protected List<Context> contextsMetaPrivacy;
protected Map<UUID, Context> uuidToContextMetaPrivacy;
protected List<Context> contextsBasicInfo;
protected Map<UUID, Context> uuidToContextBasicInfo;
protected boolean includeMeta;
protected static ServerContextCache singleton;
@ -60,15 +65,17 @@ public class ServerContextCache extends ContextCache {
@Override
protected void cleanCache(Calendar now) {
super.cleanCache(now);
contextsNoMeta = null;
uuidToContextNoMeta = new LinkedHashMap<>();
contextsMetaPrivacy = null;
uuidToContextMetaPrivacy = new LinkedHashMap<>();
this.contextsMetaPrivacy = new ArrayList<>();
this.uuidToContextMetaPrivacy = new LinkedHashMap<>();
this.contextsBasicInfo = new ArrayList<>();
this.uuidToContextBasicInfo = new LinkedHashMap<>();
}
public ServerContextCache() {
super();
cleanCache();
Calendar now = Calendar.getInstance();
cleanCache(now);
initContextCacheRenewal();
}
@ -85,7 +92,9 @@ public class ServerContextCache extends ContextCache {
@Override
public List<Context> renew() throws ResourceRegistryException {
ContextManagement contextManagement = new ContextManagement();
String contextsJsonString = contextManagement.allFromServer(false);
contextManagement.setForceOffset(0);
contextManagement.setForceLimit(-1);
String contextsJsonString = contextManagement.allFromDatabase(false);
List<Context> contexts = null;
try {
contexts = ElementMapper.unmarshalList(contextsJsonString);
@ -98,38 +107,56 @@ public class ServerContextCache extends ContextCache {
setContextCacheRenewal(contextCacheRenewal);
}
protected boolean isUserAllowedToGetPrivacyMeta() {
return ElementManagement.isUserAllowedToGetPrivacyMeta();
}
@Override
public synchronized List<Context> getContexts() throws ResourceRegistryException {
refreshContextsIfNeeded();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
if(requestInfo.getUriInfo()!=null && !requestInfo.includeMeta()){
return contextsNoMeta;
if(requestInfo!=null && !requestInfo.includeMeta()){
return contextsBasicInfo;
}
if(isUserAllowedToGetPrivacyMeta()) {
ContextManagement contextManagement = new ContextManagement();
if(contextManagement.isUserAllowedToGetPrivacyMeta()) {
return contexts;
}else {
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
public synchronized Context getContextByUUID(UUID uuid) throws ResourceRegistryException {
refreshContextsIfNeeded();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
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);
}else {
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) {
ObjectNode objectNode = objectMapper.valueToTree(metadata);
@ -144,69 +171,112 @@ public class ServerContextCache extends ContextCache {
}
@Override
protected void setContexts(List<Context> contexts) {
this.contexts = new ArrayList<>();
this.contextsNoMeta = new ArrayList<>();
this.contextsMetaPrivacy = new ArrayList<>();
protected void setContexts(Calendar calendar, List<Context> contexts) {
cleanCache(calendar);
ObjectMapper objectMapper = ElementMapper.getObjectMapper();
for(Context c : contexts) {
UUID uuid = c.getID();
Context contextWithMeta = new ContextImpl(c.getName());
contextWithMeta.setMetadata(c.getMetadata());
contextWithMeta.setID(uuid);
this.contexts.add(contextWithMeta);
this.uuidToContext.put(uuid, contextWithMeta);
Context contextMetaPrivacy = new ContextImpl(c.getName());
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, c.getMetadata());
contextMetaPrivacy.setMetadata(metadataWithPrivacy);
contextMetaPrivacy.setID(uuid);
this.contextsMetaPrivacy.add(contextMetaPrivacy);
this.uuidToContextMetaPrivacy.put(uuid, contextMetaPrivacy);
Context contextNoMeta = new ContextImpl(c.getName());
contextNoMeta.setMetadata(null);
contextWithMeta.setID(uuid);
this.contextsNoMeta.add(contextNoMeta);
this.uuidToContextNoMeta.put(uuid, contextNoMeta);
try {
/*
* The user entitled to get all meta is also
* entitled to get state as well as
* additional properties
*/
Context contextWithMeta = new ContextImpl(c.getName());
contextWithMeta.setMetadata(c.getMetadata());
contextWithMeta.setID(uuid);
contextWithMeta.setState(c.getState());
contextWithMeta.setAdditionalProperties(c.getAdditionalProperties());
this.contexts.add(contextWithMeta);
this.uuidToContext.put(uuid, contextWithMeta);
Context contextMetaPrivacy = new ContextImpl(c.getName());
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, c.getMetadata());
contextMetaPrivacy.setMetadata(metadataWithPrivacy);
contextMetaPrivacy.setID(uuid);
/*
* 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) {
UUID uuid = c.getID();
Context contextMeta = this.uuidToContext.get(uuid);
Context contextMetaPrivacy = this.uuidToContextMetaPrivacy.get(uuid);
Context contextNoMeta = this.uuidToContextNoMeta.get(uuid);
Context contextNoMeta = this.uuidToContextBasicInfo.get(uuid);
if(c.getParent()!=null) {
IsParentOf ipo = c.getParent();
UUID parentUUID = ipo.getSource().getID();
UUID isParentOfParentUUID = ipo.getID();
UUID contextParentUUID = ipo.getSource().getID();
Context parentWithMeta = this.uuidToContext.get(parentUUID);
IsParentOf isParentOf = new IsParentOfImpl(parentWithMeta, contextMeta);
isParentOf.setID(parentUUID);
isParentOf.setMetadata(ipo.getMetadata());
parentWithMeta.addChild(isParentOf);
contextMeta.setParent(isParentOf);
Context parentWithMeta = this.uuidToContext.get(contextParentUUID);
IsParentOf isParentOfWithMeta = parentOfWithMetaMap.get(isParentOfParentUUID);
if(isParentOfWithMeta==null) {
isParentOfWithMeta = new IsParentOfImpl(parentWithMeta, contextMeta);
isParentOfWithMeta.setID(isParentOfParentUUID);
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);
isParentOfMetaPrivacy.setID(parentUUID);
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, ipo.getMetadata());
isParentOfMetaPrivacy.setMetadata(metadataWithPrivacy);
parentWithMetaPrivacy.addChild(isParentOfMetaPrivacy);
Context parentWithMetaPrivacy = this.uuidToContextMetaPrivacy.get(contextParentUUID);
IsParentOf isParentOfMetaPrivacy = parentOfMetaWithPrivacyMap.get(isParentOfParentUUID);
if(isParentOfMetaPrivacy==null) {
isParentOfMetaPrivacy = new IsParentOfImpl(parentWithMetaPrivacy, contextMetaPrivacy);
isParentOfMetaPrivacy.setID(isParentOfParentUUID);
Metadata metadataWithPrivacy = getMetadataForPrivacy(objectMapper, ipo.getMetadata());
isParentOfMetaPrivacy.setMetadata(metadataWithPrivacy);
parentOfMetaWithPrivacyMap.put(isParentOfParentUUID, isParentOfMetaPrivacy);
parentWithMetaPrivacy.addChild(isParentOfMetaPrivacy);
}
contextMetaPrivacy.setParent(isParentOfMetaPrivacy);
Context parentNoMeta = this.uuidToContextNoMeta.get(parentUUID);
IsParentOf isParentOfNoMeta = new IsParentOfImpl(parentNoMeta, contextNoMeta);
isParentOfNoMeta.setMetadata(null);
isParentOfNoMeta.setID(parentUUID);
parentNoMeta.addChild(isParentOfNoMeta);
Context parentNoMeta = this.uuidToContextBasicInfo.get(contextParentUUID);
IsParentOf isParentOfNoMeta = parentOfNoMetaMap.get(isParentOfParentUUID);
if(isParentOfNoMeta==null) {
isParentOfNoMeta = new IsParentOfImpl(parentNoMeta, contextNoMeta);
isParentOfNoMeta.setMetadata(null);
isParentOfNoMeta.setID(isParentOfParentUUID);
parentOfNoMetaMap.put(isParentOfParentUUID, isParentOfNoMeta);
parentNoMeta.addChild(isParentOfNoMeta);
}
contextNoMeta.setParent(isParentOfNoMeta);
}
@ -220,5 +290,12 @@ public class ServerContextCache extends ContextCache {
this.contextFullNameToUUID.put(fullName, uuid);
}
SortedSet<String> contextFullNames = new TreeSet<String>(contextFullNameToUUID.keySet());
for(String contextFullName : contextFullNames) {
UUID uuid = contextFullNameToUUID.get(contextFullName);
Context context = uuidToContext.get(uuid);
contextsTree.addNode(context);
}
}
}

View File

@ -1,11 +1,17 @@
package org.gcube.informationsystem.resourceregistry.contexts.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.databind.JsonNode;
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.informationsystem.base.reference.AccessType;
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.relations.IsParentOf;
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.ContextNotFoundException;
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.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.relations.IsParentOfManagement;
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryConditionalOperator;
import org.gcube.informationsystem.resourceregistry.queries.operators.QueryLogicalOperator;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.queries.operators.ComparisonOperator;
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.serialization.ElementMapper;
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)
*
* TODO the result returned to the client should be get from ServerContextCache
*
*/
public class ContextManagement extends EntityElementManagement<Context, EntityType> {
private static Logger logger = LoggerFactory.getLogger(ContextManagement.class);
protected String name;
protected Integer forceOffset;
protected Integer forceLimit;
public void setForceOffset(Integer forceOffset) {
this.forceOffset = forceOffset;
}
public void setForceLimit(Integer forceLimit) {
this.forceLimit = forceLimit;
}
private void init() {
this.ignoreStartWithKeys.add(Context.PARENT_PROPERTY);
this.ignoreStartWithKeys.add(Context.CHILDREN_PROPERTY);
this.typeName = Context.NAME;
this.forceIncludeMeta = true;
this.forceIncludeAllMeta = true;
this.forceOffset = null;
this.forceLimit = null;
}
public ContextManagement() {
@ -73,7 +98,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext();
getWorkingEnvironment();
}
@Override
@ -95,11 +120,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if (workingContext == null) {
workingContext = ContextSecurityContext.getInstance();
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
if (workingEnvironment == null) {
workingEnvironment = ContextEnvironment.getInstance();
}
return workingContext;
return workingEnvironment;
}
@Override
@ -127,13 +152,13 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
select.append(parentId);
select.append(" MAXDEPTH 1) WHERE ");
select.append(Context.NAME_PROPERTY);
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
select.append(ComparisonOperator.EQ.getDbOperator());
select.append("\"");
select.append(getName());
select.append("\"");
select.append(QueryLogicalOperator.AND.getLogicalOperator());
select.append(LogicalOperator.AND.getDbOperator());
select.append(IdentifiableElement.ID_PROPERTY);
select.append(QueryConditionalOperator.NE.getConditionalOperator());
select.append(ComparisonOperator.NE.getDbOperator());
select.append("\"");
select.append(parentContext.uuid);
select.append("\"");
@ -149,11 +174,11 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
select.append(Context.NAME);
select.append(" WHERE ");
select.append(Context.NAME_PROPERTY);
select.append(QueryConditionalOperator.EQ.getConditionalOperator());
select.append(ComparisonOperator.EQ.getDbOperator());
select.append("\"");
select.append(getName());
select.append("\"");
select.append(QueryLogicalOperator.AND.getLogicalOperator());
select.append(LogicalOperator.AND.getDbOperator());
select.append("in(\"");
select.append(IsParentOf.NAME);
select.append("\").size() = 0");
@ -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
protected JsonNode createCompleteJsonNode() throws ResourceRegistryException {
JsonNode context = serializeSelfAsJsonNode();
context = filterFieldsByRole(context);
int count = 0;
Iterable<OEdge> parents = getElement().getEdges(ODirection.IN);
for (OEdge edge : parents) {
@ -220,29 +252,63 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
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
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null;
SecurityContext parentSecurityContext = null;
InstanceEnvironment newInstanceEnvironment = null;
InstanceEnvironment parentInstanceEnvironment = null;
if (uuid == null) {
uuid = UUIDManager.getInstance().generateValidUUID();
}
newInstanceEnvironment = new InstanceEnvironment(uuid);
boolean vertexCreated = false;
try {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
if (isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
ContextManagement parentContextManagement = new ContextManagement(oDatabaseDocument);
parentContextManagement.setJsonNode(parentJsonNode);
UUID parentUUID = parentContextManagement.uuid;
parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID);
checkContext(parentContextManagement);
if (uuid == null) {
uuid = UUIDManager.getInstance().generateValidUUID();
UUID parentUUID = parentContextManagement.getUUID();
parentInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(parentUUID);
InstanceEnvironment requestEnvironment = null;
try {
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();
vertexCreated = true;
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(parentContextManagement);
@ -251,35 +317,73 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
isParentOfManagement.internalCreate();
} 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);
logFullPath();
createVertex();
vertexCreated = true;
}
securityContext = new SecurityContext(uuid);
securityContext.setParentSecurityContext(parentSecurityContext);
securityContext.create(oDatabaseDocument);
this.element.setProperty(Context.STATE, ContextState.CREATED.getState());
newInstanceEnvironment.setParentEnvironment(parentInstanceEnvironment);
newInstanceEnvironment.create(oDatabaseDocument);
ContextUtility.getInstance().addSecurityContext(securityContext);
ContextUtility.getInstance().addInstanceEnvironment(newInstanceEnvironment);
return getElement();
} catch (Exception e) {
oDatabaseDocument.rollback();
if (securityContext != null) {
securityContext.delete(oDatabaseDocument);
if (parentSecurityContext != null && securityContext != null) {
parentSecurityContext.getChildren().remove(securityContext);
if (vertexCreated) {
newInstanceEnvironment.delete(oDatabaseDocument);
if (parentInstanceEnvironment != null && newInstanceEnvironment != null) {
parentInstanceEnvironment.getChildren().remove(newInstanceEnvironment);
}
ServerContextCache.getInstance().cleanCache();
}
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
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 nameChanged = false;
boolean stateChanged = false;
OVertex parent = null;
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();
if (oldName.compareTo(newName) != 0) {
nameChanged = true;
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) {
checkContext(newParentContextManagement);
// TODO uncomment if we want temporary suspend the Context
// state = ContextState.SUSPENDED;
}
if (parentChanged) {
move(newParentContextManagement, false);
}
if (parentChanged || nameChanged) {
logFullPath();
}
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ServerContextCache.getInstance().cleanCache();
@ -359,21 +482,21 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
checkContext(newParentContextManagement);
}
SecurityContext newParentSecurityContext = null;
InstanceEnvironment newParentInstanceEnvironment = null;
// Removing the old parent relationship if any
Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME);
if (edges != null && edges.iterator().hasNext()) {
Iterator<OEdge> edgeIterator = edges.iterator();
OEdge edge = edgeIterator.next();
IsParentOfManagement isParentOfManagement = new IsParentOfManagement();
isParentOfManagement.setElement(edge);
isParentOfManagement.internalDelete();
if (edgeIterator.hasNext()) {
throw new ContextException(
"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) {
@ -383,27 +506,67 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
isParentOfManagement.setSourceEntityManagement(newParentContextManagement);
isParentOfManagement.setTargetEntityManagement(this);
isParentOfManagement.internalCreate();
newParentSecurityContext = ContextUtility.getInstance()
.getSecurityContextByUUID(newParentContextManagement.uuid);
newParentInstanceEnvironment = ContextUtility.getInstance()
.getEnvironmentByUUID(newParentContextManagement.uuid);
}
SecurityContext thisSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
thisSecurityContext.changeParentSecurityContext(newParentSecurityContext, oDatabaseDocument);
InstanceEnvironment thisInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
thisInstanceEnvironment.changeParentEnvironment(newParentInstanceEnvironment, oDatabaseDocument);
}
@Override
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);
Iterator<OEdge> iterator = iterable.iterator();
while (iterator.hasNext()) {
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();
ContextUtility contextUtility = ContextUtility.getInstance();
SecurityContext securityContext = contextUtility.getSecurityContextByUUID(uuid);
securityContext.delete(oDatabaseDocument);
instanceEnvironment.delete(oDatabaseDocument);
ServerContextCache.getInstance().cleanCache();
}
@ -412,8 +575,35 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(forceLimit!=null) {
limit = forceLimit;
}
if(limit == null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(forceOffset!=null) {
offset = forceOffset;
}
if(offset == null) {
offset = 0;
}
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceIncludeMeta(forceIncludeMeta);
contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta);
@ -421,6 +611,9 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
try {
JsonNode jsonObject = contextManagement.serializeAsJsonNode();
arrayNode.add(jsonObject);
if(limit > 0 && ++count >= limit) {
break;
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
@ -433,7 +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);
}
@ -442,9 +635,45 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
try {
ServerContextCache contextCache = ServerContextCache.getInstance();
List<Context> contexts = contextCache.getContexts();
return ElementMapper.marshal(contexts);
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(forceLimit!=null) {
limit = forceLimit;
}else if(limit == null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(forceOffset!=null) {
offset = forceOffset;
}else if(offset == null) {
offset = 0;
}
int position = -1;
int count = 0;
if(offset==0 && limit<=0) {
return ElementMapper.marshal(contexts);
}
List<Context> requestedContexts = new ArrayList<>();
for (Context c : contexts) {
if(++position < offset) {
continue;
}
requestedContexts.add(c);
if(limit > 0 && ++count >= limit) {
break;
}
}
return ElementMapper.marshal(requestedContexts);
} catch (JsonProcessingException | ResourceRegistryException e) {
return allFromServer(polymorphic);
return allFromDatabase(polymorphic);
}
}
@ -467,4 +696,73 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
public void sanityCheck() throws SchemaViolationException, ResourceRegistryException {
// 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();
// }
//
// }
// }
}

View File

@ -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.IsParentOfNotFoundException;
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.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
@ -37,7 +37,7 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext();
getWorkingEnvironment();
this.includeSource = false;
this.includeTarget = true;
this.forceIncludeMeta = true;
@ -50,11 +50,11 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if (workingContext == null) {
workingContext = ContextSecurityContext.getInstance();
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
if (workingEnvironment == null) {
workingEnvironment = ContextEnvironment.getInstance();
}
return workingContext;
return workingEnvironment;
}
@Override

View File

@ -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());
}
}

View File

@ -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.Property;
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.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.queries.templates.QueryTemplateEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
import org.gcube.informationsystem.types.TypeMapper;
@ -178,14 +178,14 @@ public class DatabaseEnvironment {
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD);
ODatabaseDocument oDatabaseDocument = pool.acquire();
AdminSecurityContext.getInstance().create(oDatabaseDocument);
AdminEnvironment.getInstance().create(oDatabaseDocument);
oDatabaseDocument.commit();
oDatabaseDocument.close();
pool.close();
QueryTemplatesSecurityContext.getInstance().create();
TypeSecurityContext.getInstance().create();
ContextSecurityContext.getInstance().create();
QueryTemplateEnvironment.getInstance().create();
TypeEnvironment.getInstance().create();
ContextEnvironment.getInstance().create();
/* We must create only OrientDB types */
List<Class<? extends Element>> definitionToBeCreated = new ArrayList<>();
@ -209,7 +209,7 @@ public class DatabaseEnvironment {
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeAndTypeName(clz);
if(clz.equals(Property.class) || clz.equals(Metadata.class) ) {
((TypeManagement) typeManagement).setSkipTypeDefinitionCreation(true);
typeManagement.setSkipTypeDefinitionCreation(true);
}
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
* types for internal use (i.e. Context, EntityType).
*
* 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.
*/
List<Class<? extends Element>> schemaToBeCreated = new ArrayList<>();

View File

@ -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());
}
}

View File

@ -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);
}
}
}
}
}

View File

@ -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);
}
}

View File

@ -1,10 +1,11 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
package org.gcube.informationsystem.resourceregistry.environments.administration;
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.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.SystemEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -14,10 +15,12 @@ import com.orientechnologies.orient.core.metadata.security.OSecurity;
/**
* @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 UUID ADMIN_SECURITY_CONTEXT_UUID;
@ -27,19 +30,17 @@ public class AdminSecurityContext extends SecurityContext {
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) {
instance = new AdminSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(ADMIN_SECURITY_CONTEXT, instance);
instance = new AdminEnvironment();
}
return instance;
}
private AdminSecurityContext() throws ResourceRegistryException {
super(ADMIN_SECURITY_CONTEXT_UUID, false);
private AdminEnvironment() throws ResourceRegistryException {
super(ADMIN_SECURITY_CONTEXT_UUID);
}
@Override

View File

@ -1,9 +1,10 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
package org.gcube.informationsystem.resourceregistry.environments.contexts;
import java.util.UUID;
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.LoggerFactory;
@ -12,10 +13,13 @@ import com.orientechnologies.orient.core.metadata.security.ORule;
/**
* @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 UUID CONTEXT_SECURITY_CONTEXT_UUID;
@ -25,21 +29,20 @@ public class ContextSecurityContext extends SecurityContext {
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) {
instance = new ContextSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(CONTEXT_SECURITY_CONTEXT, instance);
instance = new ContextEnvironment();
}
return instance;
}
private ContextSecurityContext() throws ResourceRegistryException {
super(CONTEXT_SECURITY_CONTEXT_UUID, false);
private ContextEnvironment() throws ResourceRegistryException {
super(CONTEXT_SECURITY_CONTEXT_UUID);
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());

View File

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

View File

@ -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);
}
}

View File

@ -1,9 +1,10 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
package org.gcube.informationsystem.resourceregistry.environments.queries.templates;
import java.util.UUID;
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.LoggerFactory;
@ -12,10 +13,11 @@ import com.orientechnologies.orient.core.metadata.security.ORule;
/**
* @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 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);
}
private static QueryTemplatesSecurityContext instance;
private static QueryTemplateEnvironment instance;
public static QueryTemplatesSecurityContext getInstance() throws ResourceRegistryException {
public static QueryTemplateEnvironment getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new QueryTemplatesSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(QUERY_TEMPLATES_SECURITY_CONTEXT, instance);
instance = new QueryTemplateEnvironment();
}
return instance;
}
private QueryTemplatesSecurityContext() throws ResourceRegistryException {
super(QUERY_TEMPLATES_SECURITY_CONTEXT_UUID, false);
private QueryTemplateEnvironment() throws ResourceRegistryException {
super(QUERY_TEMPLATES_SECURITY_CONTEXT_UUID);
}
@Override

View File

@ -1,9 +1,10 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
package org.gcube.informationsystem.resourceregistry.environments.types;
import java.util.UUID;
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.LoggerFactory;
@ -12,10 +13,13 @@ import com.orientechnologies.orient.core.metadata.security.ORule;
/**
* @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 UUID SCHEMA_SECURITY_CONTEXT_UUID;
@ -25,19 +29,17 @@ public class TypeSecurityContext extends SecurityContext {
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) {
instance = new TypeSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(SCHEMA_SECURITY_CONTEXT, instance);
instance = new TypeEnvironment();
}
return instance;
}
private TypeSecurityContext() throws ResourceRegistryException {
super(SCHEMA_SECURITY_CONTEXT_UUID, false);
private TypeEnvironment() throws ResourceRegistryException {
super(SCHEMA_SECURITY_CONTEXT_UUID);
}
@Override

View File

@ -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.contexts.ContextException;
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 boolean isHonourPropagationConstraintsInContextSharing();
@ -20,12 +23,12 @@ public interface ERManagement {
public Map<UUID,JsonNode> getAffectedInstances();
/**
* Set source security context to evaluate addToContext
* @param sourceSecurityContext the source security context
* Set source InstanceEnvironment to evaluate addToContext
* @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()
throws ContextException, ResourceRegistryException;
@ -35,11 +38,11 @@ public interface ERManagement {
/**
* 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()
throws ContextException, ResourceRegistryException;

View File

@ -6,25 +6,94 @@ import java.util.Set;
import java.util.UUID;
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.ResourceRegistryException;
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.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ERManagementUtility {
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)
throws NotFoundException, ContextException, ResourceRegistryException {
Set<UUID> instances = expectedInstances.keySet();
@ -32,11 +101,11 @@ public class ERManagementUtility {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
InstanceEnvironment targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
// Map<UUID, JsonNode> enforcedInstances = new HashMap<>();
@ -44,16 +113,16 @@ public class ERManagementUtility {
Set<UUID> uuids = expectedInstances.keySet();
for(UUID uuid : uuids) {
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setWorkingContext(adminSecurityContext);
ElementManagement<?,?> elementManagement = ERManagementUtility.getERManagement(type);
elementManagement.setWorkingEnvironment(adminEnvironment);
elementManagement.setODatabaseDocument(oDatabaseDocument);
elementManagement.setUUID(uuid);
elementManagement.setElementType(type);
elementManagement.setDryRun(dryRun);
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
// enforcedInstances.putAll(((ERManagement) elementManagement).internalAddToContext(targetSecurityContext));
((ERManagement) elementManagement).setTargetSecurityContext(targetSecurityContext);
// enforcedInstances.putAll(((ERManagement) elementManagement).internalAddToContext(targetInstanceEnvironment));
((ERManagement) elementManagement).setTargetInstanceEnvironment(targetInstanceEnvironment);
((ERManagement) elementManagement).internalAddToContext();
instancesManagement.put(uuid, elementManagement);
}
@ -61,7 +130,7 @@ public class ERManagementUtility {
/*
for(UUID uuid : uuids) {
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 oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
SecurityContext targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
InstanceEnvironment targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
//Map<UUID, JsonNode> enforcedInstances = new HashMap<>();
Map<UUID, ElementManagement<?,?>> instancesManagement = new HashMap<>();
for(UUID uuid : expectedInstances.keySet()) {
String type = TypeUtility.getTypeName(expectedInstances.get(uuid));
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setWorkingContext(adminSecurityContext);
ElementManagement<?,?> elementManagement = ERManagementUtility.getERManagement(type);
elementManagement.setWorkingEnvironment(adminEnvironment);
elementManagement.setODatabaseDocument(oDatabaseDocument);
elementManagement.setUUID(uuid);
((ERManagement) elementManagement).setHonourPropagationConstraintsInContextSharing(false);
elementManagement.setDryRun(dryRun);
//enforcedInstances.putAll(((ERManagement) elementManagement).internalRemoveFromContext(targetSecurityContext));
((ERManagement) elementManagement).setTargetSecurityContext(targetSecurityContext);
//enforcedInstances.putAll(((ERManagement) elementManagement).internalRemoveFromContext(targetInstanceEnvironment));
((ERManagement) elementManagement).setTargetInstanceEnvironment(targetInstanceEnvironment);
((ERManagement) elementManagement).internalRemoveFromContext();
instancesManagement.put(uuid, elementManagement);
}

View File

@ -13,7 +13,7 @@ public enum Operation {
ADD_TO_CONTEXT,
REMOVE_FROM_CONTEXT,
QUERY(true),
// GET_METADATA e.g. getinstanceContexts
// GET_METADATA e.g. getInstanceContexts
GET_METADATA(true);
private final boolean safe;

View File

@ -12,6 +12,9 @@ import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class SharingOperationValidator implements OperationValidator {
protected static Logger logger = LoggerFactory.getLogger(SharingOperationValidator.class);

View File

@ -1,19 +1,19 @@
package org.gcube.informationsystem.resourceregistry.instances.model.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.ws.rs.ForbiddenException;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.contexts.reference.ContextState;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.reference.entities.Entity;
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.entities.EntityAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.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.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
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.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
@ -62,18 +63,18 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
/**
* The source context of an addToContex
*/
protected SecurityContext sourceSecurityContext;
protected InstanceEnvironment sourceInstanceEnvironment;
/**
* 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.
*
* 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
* constraints but under certain conditions and with some limitation
* only.
@ -102,23 +103,23 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
protected boolean honourPropagationConstraintsInContextSharing;
@Override
public void setSourceSecurityContext(SecurityContext sourceSecurityContext) {
this.sourceSecurityContext = sourceSecurityContext;
public void setSourceInstanceEnvironment(InstanceEnvironment source) {
this.sourceInstanceEnvironment = source;
}
@Override
public SecurityContext getSourceSecurityContext() {
return sourceSecurityContext;
public InstanceEnvironment getSourceInstanceEnvironment() {
return sourceInstanceEnvironment;
}
@Override
public void setTargetSecurityContext(SecurityContext targetSecurityContext) {
this.targetSecurityContext = targetSecurityContext;
public void setTargetInstanceEnvironment(InstanceEnvironment target) {
this.targetInstanceEnvironment = target;
}
@Override
public SecurityContext getTargetSecurityContext() {
return sourceSecurityContext;
public InstanceEnvironment getTargetInstanceEnvironment() {
return sourceInstanceEnvironment;
}
@Override
@ -154,14 +155,30 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
this.relationManagements = new HashMap<>();
/*
* By the default the system honour the propagation constraints
* so this variable is initialised as true.
* By default the system honor the propagation constraints
* so this variable is initialized as true.
*/
this.honourPropagationConstraintsInContextSharing = true;
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
public OVertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try {
@ -195,7 +212,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
String id = edge.getIdentity().toString();
RelationManagement<?,?> relationManagement = relationManagements.get(id);
if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement);
}
return relationManagement;
@ -298,14 +315,14 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
protected void reallyAddToContext()
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
skipped = true;
return;
}
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
@ -320,8 +337,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
relationManagement.setSourceSecurityContext(sourceSecurityContext);
relationManagement.setTargetSecurityContext(targetSecurityContext);
relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
relationManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
relationManagement.internalAddToContext();
affectedInstances.putAll(relationManagement.getAffectedInstances());
}
@ -344,7 +361,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
throw e;
} catch(Exception e) {
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);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
workingEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
setAsEntryPoint();
sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
sourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
internalAddToContext();
@ -407,14 +424,14 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(
"Error Removing " + typeName + " from " + targetSecurityContext.toString(), e.getCause());
"Error Removing " + typeName + " from " + targetInstanceEnvironment.toString(), e.getCause());
}
}
protected void reallyRemoveFromContext()
throws ContextException, ResourceRegistryException {
if(!targetSecurityContext.isElementInContext(getElement())) {
if(!targetInstanceEnvironment.isElementInContext(getElement())) {
// The element in not in the source security context. It will be skipped
return;
}
@ -426,21 +443,21 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
// Not needed relationManagement.setSourceSecurityContext(sourceSecurityContext);
relationManagement.setTargetSecurityContext(targetSecurityContext);
// Not needed relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
relationManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
relationManagement.internalRemoveFromContext();
addToRelationManagements(relationManagement);
affectedInstances.putAll(relationManagement.getAffectedInstances());
}
}
targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.removeElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
* the instance is added internalAddToContext() function after
* the update of Metadata i.e. modifiedBy, lastUpdateTime
* 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);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
workingEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
setAsEntryPoint();
// Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
// Not needed sourcesourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
internalRemoveFromContext();
@ -495,212 +512,34 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for(ODocument vertex : iterable) {
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
if(++position < offset) {
continue;
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
oDatabaseDocument, (OVertex) vertex);
try {
entityManagement.setAsEntryPoint();
JsonNode jsonNode = entityManagement.serializeAsJsonNode();
arrayNode.add(jsonNode);
if(limit > 0 && ++count >= limit) {
break;
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {
return objectMapper.writeValueAsString(arrayNode);
} catch(JsonProcessingException e) {
throw new ResourceRegistryException(e);
}
}
public boolean propertyMatchRequestedValue(OVertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
return requestedValue.compareTo(instanceValue.toString())==0;
/*
OClass oClass = ElementManagement.getOClass(v);
OProperty oProperty = oClass.getProperty(key);
if(oProperty==null){
// It is an additional property
return requestedValue.compareTo(instanceValue.toString())==0;
}
OType oType = oProperty.getType();
switch (oType) {
case BOOLEAN:
Boolean requested = Boolean.valueOf(requestedValue.toLowerCase());
return requested == (Boolean) instanceValue;
case STRING:
return requestedValue.compareTo((String) instanceValue)==0;
default:
return false;
}
*/
}
/*
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, ODirection direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<?> references = null;
if(referenceUUID != null) {
OElement element = null;
try {
element = ElementManagementUtility.getAnyElementByUUID(oDatabaseDocument, referenceUUID);
}catch (ResourceRegistryException e) {
String error = String.format("No instace with UUID %s exists", referenceUUID.toString());
throw new InvalidQueryException(error);
}
if(element instanceof OVertex) {
EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, (OVertex) element);
String elementType = entityManagement.getTypeName();
if(elementType.compareTo(referenceType) != 0) {
if(polymorphic && getOClass().isSubClassOf(referenceType)) {
// OK
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
}
List<OVertex> vertexes = new ArrayList<>();
vertexes.add((OVertex) element);
references = vertexes;
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
} else {
references = oDatabaseDocument.browseClass(referenceType, polymorphic);
}
Set<ORID> analysed = new HashSet<>();
for(Object r : references) {
OVertex v = (OVertex) r;
boolean skip = false;
// checking if the constraints are satisfied
for(String key : constraint.keySet()) {
String value = constraint.get(key);
Object o = v.getProperty(key);
if(value==null) {
if(o==null) {
//ok
}else {
skip = true;
break;
}
}else {
if(o==null) {
// The vertex has not a required property to be tested
// or the property is null
skip = true;
break;
}else {
skip = !propertyMatchRequestedValue(v, key, value, o);
if(skip) {
break;
}
}
}
}
if(skip) {
continue;
}
List<ODirection> directions = new ArrayList<>();
if(direction==ODirection.BOTH) {
directions.add(ODirection.IN);
directions.add(ODirection.OUT);
}else {
directions.add(direction);
}
for(ODirection d : directions) {
Iterable<OEdge> edges = v.getEdges(d.opposite(), relationType);
for(OEdge edge : edges) {
OVertex vertex = edge.getVertex(d);
ORID vertexORID = vertex.getIdentity();
if(analysed.contains(vertexORID)) {
continue;
}
analysed.add(vertexORID);
if(v.getIdentity().compareTo(vertexORID) == 0) {
continue;
}
OClass oClass = ElementManagementUtility.getOClass(vertex);
/*
* If the requested type (i.e. elementType)
* differs form the resulting type (i.e. oClass.getName())
* we need to evaluate if polymorphism is requested and
* if the resulting type is a subclass of the requested type
*
*/
if(oClass.getName().compareTo(typeName)!=0) {
if(polymorphic && oClass.isSubClassOf(typeName)) {
// OK
} else {
// excluding from results
continue;
}
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
oDatabaseDocument, vertex);
try {
if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
continue;
}
/*
JsonNode jsonNode;
if(includeRelationInResult) {
RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
oDatabaseDocument, edge);
jsonNode = relationManagement.serializeAsJsonNode();
}else {
jsonNode = entityManagement.serializeAsJsonNode();
}
*/
entityManagement.setAsEntryPoint();
JsonNode node = entityManagement.serializeAsJsonNode();
arrayNode.add(node);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
}
}
try {
return objectMapper.writeValueAsString(arrayNode);
@ -709,7 +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 {
ObjectMapper objectMapper = new ObjectMapper();
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());
}
// TODO check types
/*
* SELECT FROM (TRAVERSE inE('isIdentifiedBy'), outV('EService') FROM (SELECT
* FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'))
* SELECT FROM (
* TRAVERSE outV('EService'), inE('isIdentifiedBy') FROM (
* SELECT FROM SoftwareFacet WHERE group='VREManagement' AND name='SmartExecutor'
* )
* )
*
* WHERE type='EService' // Only is not polymorphic
* WHERE @class INSTANCEOF 'EService' // if polymorphic is true
*
* WHERE @class='EService' // if polymorphic is false
*/
StringBuilder selectStringBuilder = new StringBuilder("SELECT FROM (TRAVERSE ");
selectStringBuilder.append(direction.name().toLowerCase());
selectStringBuilder.append("E('");
selectStringBuilder.append(relationType);
selectStringBuilder.append("'), ");
selectStringBuilder.append(direction.opposite().name().toLowerCase());
selectStringBuilder.append("V('");
selectStringBuilder.append(typeName);
selectStringBuilder.append("') FROM (SELECT FROM ");
selectStringBuilder.append(referenceType);
StringBuffer selectStringBuffer = new StringBuffer();
selectStringBuffer.append("SELECT FROM (TRAVERSE ");
selectStringBuffer.append(direction.name().toLowerCase());
selectStringBuffer.append("V('");
selectStringBuffer.append(typeName);
selectStringBuffer.append("')");
selectStringBuffer.append(", ");
selectStringBuffer.append(direction.opposite().name().toLowerCase());
selectStringBuffer.append("E('");
selectStringBuffer.append(relationType);
selectStringBuffer.append("')");
selectStringBuffer.append(" FROM (SELECT FROM ");
selectStringBuffer.append(referenceType);
boolean first = true;
for(String key : constraint.keySet()) {
if(first) {
selectStringBuilder.append(" WHERE ");
selectStringBuffer.append(" WHERE ");
first = false;
} else {
selectStringBuilder.append(" AND ");
selectStringBuffer.append(" AND ");
}
selectStringBuilder.append(key);
selectStringBuilder.append("=");
selectStringBuffer.append(key);
selectStringBuffer.append("=");
String value = constraint.get(key).trim();
selectStringBuilder.append("'");
selectStringBuilder.append(value);
selectStringBuilder.append("'");
selectStringBuffer.append("'");
selectStringBuffer.append(value);
selectStringBuffer.append("'");
}
selectStringBuilder.append(" ))");
selectStringBuffer.append(" ))");
if(!polymorphic) {
selectStringBuilder.append(" WHERE type='");
selectStringBuilder.append(typeName);
selectStringBuilder.append("'");
selectStringBuffer.append(" WHERE @class");
if(polymorphic) {
selectStringBuffer.append(" INSTANCEOF '");
} else {
selectStringBuffer.append("='");
}
selectStringBuffer.append(typeName);
selectStringBuffer.append("'");
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(limit==null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(offset == null) {
offset = 0;
}
String select = selectStringBuilder.toString();
selectStringBuffer.append(" SKIP :offset");
selectStringBuffer.append(" LIMIT :limit");
Map<String, Object> map = new HashMap<>();
map.put("offset", offset);
map.put("limit", limit);
String select = selectStringBuffer.toString();
logger.trace(select);
OResultSet resultSet = oDatabaseDocument.command(select,new HashMap<>());
OResultSet resultSet = oDatabaseDocument.command(select, map);
while(resultSet.hasNext()) {
OResult oResult = resultSet.next();
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
if(polymorphic) {
OClass oClass = null;
try {
if(element instanceof OEdge) {
continue;
}
oClass = ElementManagementUtility.getOClass(element);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", element.toString(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
if(oClass.isSubClassOf(typeName)) {
continue;
}
}
OVertex vertex = (OVertex) element;
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
oDatabaseDocument, vertex);
try {
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,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.READER);
workingEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.READER);
setAsEntryPoint();
setOperation(Operation.QUERY);
@ -882,7 +729,6 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
break;
}
// return reallyQuery(relationType, referenceType, referenceUUID, direction, polymorphic, constraint, includeRelationInResult);
return reallyQuery(relationType, referenceType, referenceUUID, direction, polymorphic, constraint);
} catch(ResourceRegistryException e) {

View File

@ -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.FacetNotFoundException;
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.relations.ConsistsOfManagement;
import org.gcube.informationsystem.types.reference.entities.FacetType;
@ -74,8 +74,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElement(oEdge);
consistsOfManagement.setTargetEntityManagement(this);
// Not needed consistsOfManagement.setSourceSecurityContext(sourceSecurityContext);
consistsOfManagement.setTargetSecurityContext(targetSecurityContext);
// Not needed consistsOfManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
consistsOfManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance());
@ -83,8 +83,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
resourceManagement = new ResourceManagement();
resourceManagement.setElement(oVertex);
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext);
// Not needed resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.addToRelationManagements(consistsOfManagement);
}
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
return;
}
ODatabaseDocument targetSecurityContextODatabaseDocument = null;
ODatabaseDocument targetInstanceEnvironmentODatabaseDocument = null;
try {
if(resourceManagement==null) {
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
@ -134,24 +134,24 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}
switch (operation) {
case CREATE: case DELETE:
resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
resourceManagement.setODatabaseDocument(oDatabaseDocument);
break;
case ADD_TO_CONTEXT:
resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument);
resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
break;
case REMOVE_FROM_CONTEXT:
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument);
// Not needed resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
break;
default:
@ -168,8 +168,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}catch (Exception e) {
throw new ResourceRegistryException(e);
}finally {
if(targetSecurityContextODatabaseDocument!=null) {
targetSecurityContextODatabaseDocument.close();
if(targetInstanceEnvironmentODatabaseDocument!=null) {
targetInstanceEnvironmentODatabaseDocument.close();
oDatabaseDocument.activateOnCurrentThread();
}
}
@ -187,7 +187,7 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}
public OVertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
if(entryPoint && operation == Operation.CREATE) {
if(entryPoint) {
throw new SchemaViolationException("You cannot create a stand alone Facet");
}
return super.internalCreate();

View File

@ -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.types.SchemaException;
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.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
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.IsRelatedToManagement;
@ -155,7 +155,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement();
com.setWorkingContext(getWorkingContext());
com.setWorkingEnvironment(getWorkingEnvironment());
com.setODatabaseDocument(oDatabaseDocument);
com.setJsonNode(consistOfJsonNode);
com.setSourceEntityManagement(this);
@ -169,7 +169,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement();
irtm.setWorkingContext(getWorkingContext());
irtm.setWorkingEnvironment(getWorkingEnvironment());
irtm.setODatabaseDocument(oDatabaseDocument);
irtm.setJsonNode(relationJsonNode);
irtm.setSourceEntityManagement(this);
@ -191,7 +191,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement();
com.setWorkingContext(getWorkingContext());
com.setWorkingEnvironment(getWorkingEnvironment());
com.setODatabaseDocument(oDatabaseDocument);
com.setJsonNode(relationJsonNode);
com.internalCreateOrUdate();
@ -204,7 +204,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement();
irtm.setWorkingContext(getWorkingContext());
irtm.setWorkingEnvironment(getWorkingEnvironment());
irtm.setODatabaseDocument(oDatabaseDocument);
irtm.setJsonNode(relationJsonNode);
irtm.internalUpdate();
@ -238,7 +238,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(relationManagement != null) {
relationManagement.setWorkingContext(getWorkingContext());
relationManagement.setWorkingEnvironment(getWorkingEnvironment());
relationManagement.setODatabaseDocument(oDatabaseDocument);
relationManagement.setElement(edge);
relationManagement.internalDelete();
@ -262,13 +262,13 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
protected void reallyAddToContext()
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
skipped = true;
return;
}
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
@ -286,8 +286,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setDryRun(dryRun);
relationManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
relationManagement.setSourceSecurityContext(sourceSecurityContext);
relationManagement.setTargetSecurityContext(targetSecurityContext);
relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
relationManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
relationManagement.internalAddToContext();
affectedInstances.putAll(relationManagement.getAffectedInstances());
if(relationManagement instanceof ConsistsOfManagement) {
@ -317,7 +317,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
public String all(boolean polymorphic) throws ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
oDatabaseDocument = getWorkingContext().getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
return reallyGetAll(polymorphic);
} catch(ResourceRegistryException e) {
throw e;
@ -452,17 +452,19 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
case ADD_TO_CONTEXT:
if(relationManagement == null) {
try {
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge);
relationManagement.setSourceSecurityContext(sourceSecurityContext);
relationManagement = ElementManagementUtility.getRelationManagement(targetInstanceEnvironment, oDatabaseDocument, edge);
relationManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
relationManagements.put(id, relationManagement);
}catch (AvailableInAnotherContextException e) {
continue;
}
}else {
/*
* The relation has been already managed in add to context so it has been added to the targetSecurityContext.
* 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.
* The relation has been already managed in add to context
* so it has been added to the targetInstanceEnvironment.
* 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;
@ -470,12 +472,13 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
case REMOVE_FROM_CONTEXT:
if(relationManagement != null) {
/*
* The relation has been removed from the targetContext but it has not been committed.
* We must consider as not available in targetSecurityContext
* The relation has been removed from the targetContext
* but it has not been committed.
* We must consider as not available in targetInstanceEnvironment
*/
continue;
}else {
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, oDatabaseDocument, edge);
relationManagement = ElementManagementUtility.getRelationManagement(targetInstanceEnvironment, oDatabaseDocument, edge);
relationManagements.put(id, relationManagement);
}
break;
@ -483,7 +486,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
case CREATE: case UPDATE:
if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), oDatabaseDocument, edge);
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement);
/*
* 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 {
if(operation == Operation.REMOVE_FROM_CONTEXT && relationManagement!=null) {
/*
* The relation has been removed from the targetContext but it has not been committed.
* We must consider as not available in targetSecurityContext
* The relation has been removed from the targetContext
* but it has not been committed.
* We must consider as not available in targetInstanceEnvironment
*/
continue;
}

View File

@ -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.ConsistsOfNotFoundException;
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.entities.FacetManagement;
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 {
FacetManagement facetManagement = new FacetManagement();
facetManagement.setODatabaseDocument(oDatabaseDocument);
facetManagement.setWorkingContext(getWorkingContext());
facetManagement.setWorkingEnvironment(getWorkingEnvironment());
return facetManagement;
}
@ -107,7 +107,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
return;
}
ODatabaseDocument targetSecurityContextODatabaseDocument = null;
ODatabaseDocument targetInstanceEnvironmentODatabaseDocument = null;
try {
ResourceManagement resourceManagement = getSourceEntityManagement();
@ -120,12 +120,12 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
resourceManagement.setElementType(sourceEntityManagement.getTypeName());
resourceManagement.setUUID(sourceEntityManagement.getUUID());
if(operation == Operation.ADD_TO_CONTEXT) {
resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
}
resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextODatabaseDocument = targetSecurityContext.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetSecurityContextODatabaseDocument);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
break;
default:
@ -140,8 +140,8 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
}catch (Exception e) {
throw new ResourceRegistryException(e);
}finally {
if(targetSecurityContextODatabaseDocument!=null) {
targetSecurityContextODatabaseDocument.close();
if(targetInstanceEnvironmentODatabaseDocument!=null) {
targetInstanceEnvironmentODatabaseDocument.close();
oDatabaseDocument.activateOnCurrentThread();
}
}

View File

@ -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.IsRelatedToNotFoundException;
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.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
@ -60,7 +60,7 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
@Override
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
resourceManagement.setODatabaseDocument(oDatabaseDocument);
return resourceManagement;
}

View File

@ -5,13 +5,17 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.ws.rs.ForbiddenException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.informationsystem.base.reference.AccessType;
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.model.reference.entities.Entity;
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.relations.RelationNotFoundException;
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.ServerContextCache;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.Operation;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.EntityManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
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
*/
protected SecurityContext sourceSecurityContext;
protected InstanceEnvironment sourceInstanceEnvironment;
/**
* The target context of an addToContex/RemoveFromContext
*/
protected SecurityContext targetSecurityContext;
protected InstanceEnvironment targetInstanceEnvironment;
/**
* 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;
@Override
public void setSourceSecurityContext(SecurityContext sourceSecurityContext) {
this.sourceSecurityContext = sourceSecurityContext;
public void setSourceInstanceEnvironment(InstanceEnvironment source) {
this.sourceInstanceEnvironment = source;
}
@Override
public SecurityContext getSourceSecurityContext() {
return sourceSecurityContext;
public InstanceEnvironment getSourceInstanceEnvironment() {
return sourceInstanceEnvironment;
}
@Override
public void setTargetSecurityContext(SecurityContext targetSecurityContext) {
this.targetSecurityContext = targetSecurityContext;
public void setTargetInstanceEnvironment(InstanceEnvironment target) {
this.targetInstanceEnvironment = target;
}
@Override
public SecurityContext getTargetSecurityContext() {
return sourceSecurityContext;
public InstanceEnvironment getTargetInstanceEnvironment() {
return targetInstanceEnvironment;
}
@Override
@ -135,9 +143,9 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
public final PropagationConstraint defaultPropagationConstraint;
public boolean isAvailableOnContext(SecurityContext securityContext) {
public boolean isAvailableOnContext(InstanceEnvironment instanceEnvironment) {
try {
return securityContext.isElementInContext(element);
return instanceEnvironment.isElementInContext(element);
} catch (ResourceRegistryException e) {
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;
/* 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;
if(sourceResource == null) {
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingContext(),
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
oDatabaseDocument, source);
if(this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.createCompleteJsonNode();
@ -322,7 +346,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
@Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
resourceManagement.setODatabaseDocument(oDatabaseDocument);
return resourceManagement;
}
@ -380,7 +404,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if(target != null) {
FacetManagement facetManagement = new FacetManagement();
facetManagement.setWorkingContext(getWorkingContext());
facetManagement.setWorkingEnvironment(getWorkingEnvironment());
facetManagement.setODatabaseDocument(oDatabaseDocument);
facetManagement.setJsonNode(target);
facetManagement.internalUpdate();
@ -396,7 +420,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected void reallyAddToContext()
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
skipped = true;
return;
@ -433,12 +457,12 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
*/
getTargetEntityManagement().setDryRun(dryRun);
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
targetEntityManagement.setSourceSecurityContext(sourceSecurityContext);
targetEntityManagement.setTargetSecurityContext(targetSecurityContext);
targetEntityManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
targetEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
targetEntityManagement.internalAddToContext();
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
@ -456,7 +480,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break;
}
}else {
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
@ -481,7 +505,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
throw e;
} catch(Exception e) {
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 */
getSourceEntityManagement().setDryRun(dryRun);
sourceEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
sourceEntityManagement.setTargetSecurityContext(targetSecurityContext);
sourceEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
sourceEntityManagement.internalAddToContext();
affectedInstances.putAll(sourceEntityManagement.getAffectedInstances());
/* Adding target to Context */
getTargetEntityManagement().setDryRun(dryRun);
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
targetEntityManagement.setTargetSecurityContext(targetSecurityContext);
targetEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
targetEntityManagement.internalAddToContext();
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
targetSecurityContext.addElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
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);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
workingEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
setAsEntryPoint();
sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
sourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
forcedAddToContext();
@ -551,7 +575,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected Map<UUID,JsonNode> reallyRemoveFromContext()
throws ContextException, ResourceRegistryException {
if(!targetSecurityContext.isElementInContext(getElement())) {
if(!targetInstanceEnvironment.isElementInContext(getElement())) {
// The element in not in the source security context. It will be skipped
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
* avoid to have edge having a source outside of the context.
*/
targetSecurityContext.removeElement(getElement(), oDatabaseDocument);
targetInstanceEnvironment.removeElement(getElement(), oDatabaseDocument);
affectedInstances.put(uuid, serializeAsAffectedInstance());
T targetEntityManagement = getTargetEntityManagement();
targetEntityManagement.setDryRun(dryRun);
targetEntityManagement.setHonourPropagationConstraintsInContextSharing(honourPropagationConstraintsInContextSharing);
// Not needed targetEntityManagement.setSourceSecurityContext(sourceSecurityContext);
targetEntityManagement.setTargetSecurityContext(targetSecurityContext);
// Not needed targetEntityManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
targetEntityManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
if(targetEntityManagement instanceof ResourceManagement) {
((ResourceManagement) targetEntityManagement).setSanityCheckNotRequired();
}
@ -627,7 +651,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
if(count > 0) {
logger.trace(
"{} 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 {
targetEntityManagement.internalRemoveFromContext();
affectedInstances.putAll(targetEntityManagement.getAffectedInstances());
@ -657,7 +681,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
throw e;
} catch(Exception e) {
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);
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = workingContext.getDatabaseDocument(PermissionMode.WRITER);
workingEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.WRITER);
oDatabaseDocument.begin();
setAsEntryPoint();
// Not needed sourceSecurityContext = ContextUtility.getCurrentSecurityContext();
targetSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(contextUUID);
// Not needed sourceInstanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
targetInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(contextUUID);
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 {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
// Map<String,JsonNode> visitedSourceResources = new HashMap<>();
List<JsonNode> serilizedEdges = new ArrayList<>();
for(ODocument d : edges) {
if(++position < offset) {
continue;
}
OEdge edge = (OEdge) d;
if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) {
continue;
}
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(),
oDatabaseDocument, edge);
// visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
serilizedEdges.add(relationManagement.serializeAsJsonNode());
if(limit > 0 && ++count >= limit) {
break;
}
}
return serilizedEdges;
}

View File

@ -5,11 +5,12 @@ import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
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.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -32,12 +33,12 @@ public class QueryImpl implements Query {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
InstanceEnvironment instanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
oDatabaseDocument = securityContext.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument = instanceEnvironment.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.begin();
logger.debug("Going to execute query '{} limit {}'", query);
logger.debug("Going to execute query '{}'", query);
OResultSet resultSet = oDatabaseDocument.query(query);
@ -59,7 +60,7 @@ public class QueryImpl implements Query {
}
} else {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(instanceEnvironment, oDatabaseDocument,
element);
erManagement.setAsEntryPoint();
jsonNode = erManagement.serializeAsJsonNode();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,24 +1,35 @@
package org.gcube.informationsystem.resourceregistry.queries.templates;
import java.util.HashMap;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.QueryTemplatesSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
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.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType;
@ -49,7 +60,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
public QueryTemplateManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingContext();
getWorkingEnvironment();
}
protected void checkERMatch() throws ResourceRegistryException {
@ -92,11 +103,11 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if (workingContext == null) {
workingContext = QueryTemplatesSecurityContext.getInstance();
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
if (workingEnvironment == null) {
workingEnvironment = QueryTemplateEnvironment.getInstance();
}
return workingContext;
return workingEnvironment;
}
@Override
@ -129,7 +140,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
return select;
}
protected void checkIfNameAlreadyExists() throws AlreadyPresentException {
protected void checkIfNameAlreadyExists() throws QueryTemplateAlreadyPresentException {
StringBuffer select = getSelectQuery();
StringBuffer errorMessage = new StringBuffer();
@ -146,7 +157,13 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
if (resultSet != null) {
try {
if(resultSet.hasNext()) {
throw new AlreadyPresentException(errorMessage.toString());
OResult oResult = resultSet.next();
try {
element = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
} catch (ResourceRegistryException e) {
}
throw new QueryTemplateAlreadyPresentException(errorMessage.toString());
}
}finally {
resultSet.close();
@ -179,7 +196,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
if(resultSet!=null) {
resultSet.close();
}
throw new NotFoundException("Error retrieving " + QueryTemplate.NAME + " with name " + getName());
throw new QueryTemplateNotFoundException("Error retrieving " + QueryTemplate.NAME + " with name " + getName());
}
OResult oResult = resultSet.next();
@ -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
protected OVertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException {
try {
@ -218,7 +309,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}
}
@Override
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
try {
@ -238,7 +329,9 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
@Override
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to delete {} with name {}", accessType.getName(), name);
getElement().delete();
OVertex oVertex = getElement();
uuid = UUID.fromString((String) oVertex.getProperty(IdentifiableElement.ID_PROPERTY));
oVertex.delete();
}
@Override
@ -255,13 +348,28 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setElement((OVertex) vertex);
try {
JsonNode jsonObject = queryTemplateManagement.serializeAsJsonNode();
arrayNode.add(jsonObject);
if(limit > 0 && ++count >= limit) {
break;
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);

View File

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

View File

@ -5,6 +5,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
@ -14,13 +15,14 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -28,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.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath;
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.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
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.queries.Query;
import org.gcube.informationsystem.resourceregistry.queries.QueryImpl;
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.types.TypeMapper;
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 REFERENCE_TYPE_PATH_PARAMETER = "REFERENCE_TYPE_NAME";
public static final String RAW_QUERY_METHOD = "raw";
public static final String GRAPH_QUERY_METHOD = "graph";
public static final String JSON_QUERY_METHOD = "json";
public static final String PREPARED_QUERY_METHOD = "prepared";
public Access() {
super();
}
@ -69,10 +78,22 @@ public class Access extends BaseRest {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String getAllContexts() throws ResourceRegistryException {
logger.info("Requested to read all {}s", org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
CalledMethodProvider.instance.set("listContexts");
setAccountingMethod(Method.LIST, org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeAllMetaQueryParameters();
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
/*
* 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();
return contextManagement.all(false);
@ -88,19 +109,26 @@ public class Access extends BaseRest {
public String getContext(@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid)
throws ContextNotFoundException, ResourceRegistryException {
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);
CalledMethodProvider.instance.set("readContext");
setAccountingMethod(Method.READ, org.gcube.informationsystem.contexts.reference.entities.Context.NAME);
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.setUUID(UUID.fromString(uuid));
return contextManagement.readAsString();
}
/*
* GET /access/types/{TYPE_NAME}[?polymorphic=false]
* 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)
throws SchemaNotFoundException, ResourceRegistryException {
logger.info("Requested Schema for type {}", type);
CalledMethodProvider.instance.set("readType");
setAccountingMethod(Method.READ, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeAllMetaQueryParameters();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement typeManagement = new TypeManagement();
typeManagement.setTypeName(type);
@ -126,6 +155,72 @@ public class Access extends BaseRest {
throw new ResourceRegistryException(e);
}
}
/*
* GET /access/query-templates
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART)
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String allQueryTemplates() throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", QueryTemplate.NAME);
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
}
/*
* GET /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. GET /access/query-templates/GetAllEServiceWithState
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String readQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.READ, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
return queryTemplateManagement.read();
}
/*
* POST /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. POST /access/query-templates/GetAllEServiceWithState
*
* params = { "$state" : "ready" }
*
*/
@POST
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String runQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
queryTemplateManagement.setParams(params);
return queryTemplateManagement.run();
}
/*
* GET /access/instances/{TYPE_NAME}[?polymorphic=true]
@ -139,12 +234,13 @@ public class Access extends BaseRest {
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
CalledMethodProvider.instance.set("listInstances");
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
}
@ -159,12 +255,12 @@ public class Access extends BaseRest {
public Response instanceExists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to check if {} with id {} exists", type, uuid);
CalledMethodProvider.instance.set("existInstance");
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
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 {
erManagement.setUUID(UUID.fromString(uuid));
@ -196,21 +292,19 @@ public class Access extends BaseRest {
public String getInstance(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read {} with id {}", type, uuid);
CalledMethodProvider.instance.set("readInstance");
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
erManagement.setElementType(type);
erManagement.setUUID(UUID.fromString(uuid));
return erManagement.read().toString();
}
/*
* GET /access/instances/{TYPE_NAME}/{UUID}/contexts
* e.g. GET /access/instances/ContactFacet/4023d5b2-8601-47a5-83ef-49ffcbfc7d86/contexts
@ -222,13 +316,14 @@ public class Access extends BaseRest {
public String getInstanceContexts(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String instanceId) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
CalledMethodProvider.instance.set("getInstanceContexts");
setAccountingMethod(InstancesManager.GET_INSTANCE_CONTEXTS_METHOD);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(instanceId));
return erManagement.getContexts();
}
/**
* It includeSubtypes to query Entities and Relations in the current Context.<br />
* It accepts idempotent query only.. <br />
@ -241,6 +336,9 @@ public class Access extends BaseRest {
*
* e.g. GET /access/query?q=SELECT FROM V
*
* It is responsibility of the client impose manage paginated results
* according the SQL syntax (see SKIP and LIMIT parameters in the documentation indicated above)
*
* @param query Defines the query to send to the backend.
* @param raw request a raw response (not a Element based response)
* @return The JSON representation of the result
@ -253,14 +351,18 @@ public class Access extends BaseRest {
@QueryParam(AccessPath.RAW_QUERY_PARAMETER) @DefaultValue(AccessPath.RAW_QUERY_PARAMETER_DEFAULT_VALUE) Boolean raw)
throws InvalidQueryException {
logger.info("Requested query (Raw {}):\n{}", raw, query);
CalledMethodProvider.instance.set("graphQuery");
if(raw) {
setAccountingMethod(Method.QUERY, RAW_QUERY_METHOD);
}else {
setAccountingMethod(Method.QUERY, GRAPH_QUERY_METHOD);
}
ServerRequestInfo serverRequestInfo = initRequestInfo();
if(raw) {
// TODO Check if the role allow to request raw data
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
}else {
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
}
Query queryManager = new QueryImpl();
@ -312,10 +414,11 @@ public class Access extends BaseRest {
@Path(AccessPath.QUERY_PATH_PART)
public String jsonQuery(String jsonQuery) throws InvalidQueryException, ResourceRegistryException {
logger.info("Requested json query \n{}", jsonQuery);
CalledMethodProvider.instance.set("jsonQuery");
setAccountingMethod(Method.QUERY, JSON_QUERY_METHOD);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
JsonQuery jsonQueryManager = new JsonQuery();
jsonQueryManager.setJsonQuery(jsonQuery);
@ -338,12 +441,12 @@ public class Access extends BaseRest {
* All the Resources with a ContactFacet :
* /access/query/Resource/ConsistsOf/ContactFacet?_polymorphic=true&_direction=out
*
* All the Eservice having an incoming (IN) Hosts relation with an HostingNode (i.e. all smartgears services)
* All the EService having an incoming (IN) Hosts relation with an HostingNode (i.e. all smartgears services)
* GET /access/query/EService/Hosts/HostingNode?_polymorphic=true&_direction=in
*
* All the Eservice having an incoming (IN) Hosts relation (i.e. hosted by) the HostingNode with UUID
* All the EService having an incoming (IN) Hosts relation (i.e. hosted by) the HostingNode with UUID
* 16032d09-3823-444e-a1ff-a67de4f350a
* * GET /access/query/EService/hosts/HostingNode?_reference=16032d09-3823-444e-a1ff-a67de4f350a8&_polymorphic=true&_direction=in
* * GET /access/query/EService/Hosts/HostingNode?_reference=16032d09-3823-444e-a1ff-a67de4f350a8&_polymorphic=true&_direction=in
*
*/
@SuppressWarnings({"rawtypes"})
@ -363,12 +466,13 @@ public class Access extends BaseRest {
logger.info("Requested {} instances having a(n) {} ({}={}} with {} ({}={}). Request URI is {})", resourcetype, relationType,
AccessPath._DIRECTION_QUERY_PARAMETER, direction, referenceType, AccessPath._POLYMORPHIC_QUERY_PARAMETER, polymorphic, uriInfo.getRequestUri());
CalledMethodProvider.instance.set("query");
setAccountingMethod(Method.QUERY, PREPARED_QUERY_METHOD);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement erManagement = ElementManagementUtility.getERManagement(resourcetype);
ElementManagement erManagement = ERManagementUtility.getERManagement(resourcetype);
if(erManagement instanceof ResourceManagement) {
UUID refereceUUID = null;

View File

@ -3,8 +3,9 @@ package org.gcube.informationsystem.resourceregistry.rest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,14 +22,33 @@ public class BaseRest {
public BaseRest() {
}
protected void setAccountingMethod(String method) {
CalledMethodProvider.instance.set(method);
}
protected ServerRequestInfo initRequestInfo() {
ServerRequestInfo requestInfo = new ServerRequestInfo();
protected void setAccountingMethod(Method method, String type) {
StringBuffer accountingMethod = new StringBuffer();
accountingMethod.append(method.getPrefix());
accountingMethod.append(type);
accountingMethod.append(method.getSuffix());
setAccountingMethod(accountingMethod.toString());
}
private ServerRequestInfo initRequestInfo(ServerRequestInfo requestInfo) {
requestInfo.setUriInfo(uriInfo);
RequestUtility.getRequestInfo().set(requestInfo);
return requestInfo;
}
protected ServerRequestInfo initRequestInfo(int offset, int limit) {
ServerRequestInfo requestInfo = new ServerRequestInfo(offset, limit);
return initRequestInfo(requestInfo);
}
protected ServerRequestInfo initRequestInfo() {
ServerRequestInfo requestInfo = new ServerRequestInfo();
return initRequestInfo(requestInfo);
}
}

View File

@ -18,10 +18,11 @@ import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
/**
* @author Luca Frosini (ISTI - CNR)
@ -30,31 +31,51 @@ import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
public class ContextManager extends BaseRest {
public static final String CONTEXT_UUID_PATH_PARAMETER = "CONTEXT_UUID";
public ContextManager() {
super();
}
/*
/**
*
* 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
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String all() throws ContextNotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", Context.NAME);
CalledMethodProvider.instance.set("listContexts");
setAccountingMethod(Method.LIST, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
ServerRequestInfo serverRequestInfo = initRequestInfo(BaseRequestInfo.DEFAULT_OFFSET, BaseRequestInfo.UNBOUNDED_LIMIT);
serverRequestInfo.setIncludeMeta(true);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
ContextManagement contextManagement = new ContextManagement();
return contextManagement.all(false);
}
/*
/**
* GET /contexts/{UUID}
* 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)
throws ContextNotFoundException, ResourceRegistryException {
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);
CalledMethodProvider.instance.set("readContext");
setAccountingMethod(Method.READ, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setIncludeMeta(true);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
return contextManagement.readAsString();
}
/*
/**
* PUT /contexts/{UUID}
* 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)
throws ResourceRegistryException {
logger.info("Requested to update/create {} with json {} ", Context.NAME, json);
CalledMethodProvider.instance.set("updateContext");
setAccountingMethod(Method.UPDATE, Context.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setIncludeMeta(true);
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
ContextManagement contextManagement = new ContextManagement();
contextManagement.setUUID(UUID.fromString(uuid));
@ -106,6 +127,35 @@ public class ContextManager extends BaseRest {
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}
* e.g. DELETE /contexts/c0f314e7-2807-4241-a792-2a6c79ed4fd0

View File

@ -16,7 +16,6 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
@ -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.rest.InstancePath;
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.ERManagementUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
/**
* @author Luca Frosini (ISTI - CNR)
@ -36,7 +35,10 @@ import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
public class InstancesManager extends BaseRest {
public static final String UUID_PATH_PARAMETER = "UUID";
public static final String INSTANCE = "Instance";
public static final String GET_INSTANCE_CONTEXTS_METHOD = "getInstanceContexts";
public InstancesManager() {
super();
}
@ -54,12 +56,13 @@ public class InstancesManager extends BaseRest {
@QueryParam(InstancePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("true") Boolean polymorphic)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested all {}instances of {}", polymorphic ? InstancePath.POLYMORPHIC_QUERY_PARAMETER + " " : "", type);
CalledMethodProvider.instance.set("listInstances");
setAccountingMethod(Method.LIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
serverRequestInfo.checkLimitOffset();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
return erManagement.all(polymorphic);
}
@ -75,13 +78,13 @@ public class InstancesManager extends BaseRest {
public Response exists(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to check if {} with id {} exists", type, uuid);
CalledMethodProvider.instance.set("existInstance");
setAccountingMethod(Method.EXIST, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(InstancePath.HIERARCHICAL_MODE_QUERY_PARAMETER);
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
try {
erManagement.setUUID(UUID.fromString(uuid));
boolean found = erManagement.exists();
@ -113,12 +116,12 @@ public class InstancesManager extends BaseRest {
public String read(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read {} with id {}", type, uuid);
CalledMethodProvider.instance.set("readInstance");
setAccountingMethod(Method.READ, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
erManagement.setElementType(type);
erManagement.setUUID(UUID.fromString(uuid));
return erManagement.read().toString();
@ -139,13 +142,13 @@ public class InstancesManager extends BaseRest {
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid, String json) throws ResourceRegistryException {
logger.info("Requested to update/create {} with id {}", type, uuid);
logger.trace("Requested to update/create {} with id {} with json {}", type, uuid, json);
CalledMethodProvider.instance.set("updateInstance");
setAccountingMethod(Method.UPDATE, InstancesManager.INSTANCE);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeQueryParameters();
serverRequestInfo.checkAllIncludeQueryParameters();
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(uuid));
erManagement.setElementType(type);
erManagement.setJson(json);
@ -162,9 +165,9 @@ public class InstancesManager extends BaseRest {
public Response delete(@PathParam(TypeManager.TYPE_PATH_PARAMETER) String type,
@PathParam(InstancesManager.UUID_PATH_PARAMETER) String uuid) throws ResourceRegistryException {
logger.info("Requested to delete {} with id {}", type, uuid);
CalledMethodProvider.instance.set("deleteInstance");
setAccountingMethod(Method.DELETE, InstancesManager.INSTANCE);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(uuid));
erManagement.delete();
@ -189,10 +192,10 @@ public class InstancesManager extends BaseRest {
@PathParam(ContextManager.CONTEXT_UUID_PATH_PARAMETER) String contextId)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
logger.info("Requested to get contexts of {} with UUID {}", type, instanceId);
CalledMethodProvider.instance.set("getInstanceContexts");
setAccountingMethod(InstancesManager.GET_INSTANCE_CONTEXTS_METHOD);
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(instanceId));
return erManagement.getContexts();
}

View File

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

View File

@ -12,15 +12,15 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath;
import org.gcube.informationsystem.resourceregistry.queries.templates.QueryTemplateManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
/**
* @author Luca Frosini (ISTI - CNR)
@ -42,10 +42,12 @@ public class QueryTemplateManager extends BaseRest {
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String all() throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", QueryTemplate.NAME);
CalledMethodProvider.instance.set("listQueryTemplates");
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeAllMetaQueryParameters();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
@ -85,20 +87,19 @@ public class QueryTemplateManager extends BaseRest {
@Path("{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public Response updateCreate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String json)
public String updateCreate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String json)
throws InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} creation with name {} and content {}", QueryTemplate.NAME, queryTemplateName, json);
CalledMethodProvider.instance.set("createQueryTemplate");
setAccountingMethod(Method.UPDATE, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeAllMetaQueryParameters();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
queryTemplateManagement.setJson(json);
String ret = queryTemplateManagement.createOrUpdate();
return Response.status(Status.CREATED).entity(ret).type(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
.build();
return queryTemplateManagement.createOrUpdate();
}
/*
@ -111,10 +112,11 @@ public class QueryTemplateManager extends BaseRest {
public String read(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
CalledMethodProvider.instance.set("readQueryTemplate");
setAccountingMethod(Method.READ, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeAllMetaQueryParameters();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -124,7 +126,7 @@ public class QueryTemplateManager extends BaseRest {
/*
* POST /query-templates/{QUERY_TEMPLATE_NAME}
* e.g. GET /query-templates/GetAllEServiceWithState
* e.g. POST /query-templates/GetAllEServiceWithState
*
* 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)
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
CalledMethodProvider.instance.set("readQueryTemplate");
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeAllMetaQueryParameters();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
@ -157,7 +159,7 @@ public class QueryTemplateManager extends BaseRest {
public Response delete(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested to delete {} with name {} ", QueryTemplate.NAME, queryTemplateName);
CalledMethodProvider.instance.set("deleteQueryTemplate");
setAccountingMethod(Method.DELETE, QueryTemplate.NAME);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);

View File

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

View File

@ -15,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.ObjectMapper;
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.resourceregistry.ResourceInitializer;
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.rest.SharingPath;
import org.gcube.informationsystem.resourceregistry.api.rest.SharingPath.SharingOperation;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
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.utils.TypeUtility;
@ -90,7 +89,7 @@ public class SharingManager extends BaseRest {
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeQueryParameters();
serverRequestInfo.checkAllIncludeQueryParameters();
try {
StringBuffer calledMethod = new StringBuffer();
@ -110,7 +109,7 @@ public class SharingManager extends BaseRest {
calledMethod.append("RemoveFromContext");
}
calledMethod.append("NoPropagationConstraint");
CalledMethodProvider.instance.set(calledMethod.toString());
setAccountingMethod(calledMethod.toString());
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(body);
@ -172,7 +171,7 @@ public class SharingManager extends BaseRest {
throws SchemaViolationException, ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkIncludeQueryParameters();
serverRequestInfo.checkAllIncludeQueryParameters();
StringBuffer calledMethod = new StringBuffer();
if(dryRun==null) {
@ -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);
calledMethod.append("RemoveFromContext");
}
CalledMethodProvider.instance.set(calledMethod.toString());
setAccountingMethod(calledMethod.toString());
ElementManagement<?,?> elementManagement = ElementManagementUtility.getERManagement(type);
elementManagement.setUUID(UUID.fromString(instanceId));
elementManagement.setDryRun(dryRun);
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(type);
erManagement.setUUID(UUID.fromString(instanceId));
erManagement.setDryRun(dryRun);
UUID contextUUID = UUID.fromString(contextId);
if(operation == SharingOperation.ADD) {
((ERManagement) elementManagement).setForceAddToContext(forceAddToContext);
((ERManagement) elementManagement).addToContext(contextUUID);
((ERManagement) erManagement).setForceAddToContext(forceAddToContext);
((ERManagement) erManagement).addToContext(contextUUID);
}else {
((ERManagement) elementManagement).removeFromContext(contextUUID);
((ERManagement) erManagement).removeFromContext(contextUUID);
}
try {
ObjectMapper objectMapper = new ObjectMapper();
return serializeAffectedInstaces(objectMapper, elementManagement.getAffectedInstances());
return serializeAffectedInstaces(objectMapper, erManagement.getAffectedInstances());
} catch (Exception e) {
throw new ResourceRegistryException(e);
}

View File

@ -5,22 +5,23 @@ import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.CalledMethodProvider;
import org.gcube.informationsystem.resourceregistry.ResourceInitializer;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.TypePath;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.types.TypeManagement;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.Type;
@ -37,6 +38,23 @@ public class TypeManager extends BaseRest {
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}
* 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)
throws SchemaException, ResourceRegistryException {
logger.info("Requested {} creation with schema {}", typeName, json);
CalledMethodProvider.instance.set("createType");
setAccountingMethod(Method.CREATE, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement schemaManagement = new TypeManagement();
schemaManagement.setTypeName(typeName);
@ -77,11 +95,11 @@ public class TypeManager extends BaseRest {
@QueryParam(TypePath.POLYMORPHIC_QUERY_PARAMETER) @DefaultValue("false") Boolean polymorphic)
throws SchemaNotFoundException, ResourceRegistryException {
logger.info("Requested Schema for type {}", type);
CalledMethodProvider.instance.set("readType");
setAccountingMethod(Method.READ, Type.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkBooleanQueryParameter(TypePath.INCLUDE_META_QUERY_PARAMETER);
TypeManagement schemaManagement = new TypeManagement();
schemaManagement.setTypeName(type);

View File

@ -7,6 +7,9 @@ import java.lang.annotation.Target;
import javax.ws.rs.HttpMethod;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")

View File

@ -1,4 +1,4 @@
package org.gcube.informationsystem.resourceregistry.requests;
package org.gcube.informationsystem.resourceregistry.rest.requests;
/**
* @author Luca Frosini (ISTI - CNR)

View File

@ -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);
}
}

View File

@ -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.types.SchemaException;
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.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
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.reference.Type;
import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
@ -67,8 +67,8 @@ public class CachedType<T extends Type> {
ODatabaseDocument oDatabaseDocument = null;
try {
logger.debug("GettingType {} schema", typeName);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
try {

View File

@ -24,6 +24,7 @@ public class OrientDBTypeMapping {
static {
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.INTEGER, OType.INTEGER);
BASE_TYPE_TO_OTYPE.put(BaseType.SHORT, OType.SHORT);

View File

@ -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.SchemaException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.resourceregistry.types.entities.FacetTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.types.properties.PropertyTypeDefinitionManagement;
@ -227,7 +226,7 @@ public class TypeManagement {
protected List<OClass> getSuperclassesAndCheckCompliancy(ODatabaseDocument oDatabaseDocument,
Type type, String baseType) throws SchemaException, SchemaNotFoundException {
Set<String> superClasses = type.getTypeSuperTypes();
Set<String> superClasses = type.getExtendedTypes();
if(baseType != null) {
if(superClasses == null || superClasses.size() == 0) {
throw new RuntimeException(
@ -292,8 +291,8 @@ public class TypeManagement {
throw new SchemaCreationException(error);
}
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
@ -360,18 +359,18 @@ public class TypeManagement {
* Excluding the check from types used for type definition
*
*/
if(!typeList.contains(type.getName())) {
switch(propertyTypeName.getBaseType()) {
case LIST:
throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
case SET:
throw new UnsupportedDataTypeException(OType.EMBEDDEDSET
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
default:
break;
}
}
// if(!typeList.contains(type.getName())) {
// switch(propertyTypeName.getBaseType()) {
// case LIST:
// throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST
// + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
// case SET:
// throw new UnsupportedDataTypeException(OType.EMBEDDEDSET
// + " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
// default:
// break;
// }
// }
OType oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType());
@ -442,8 +441,8 @@ public class TypeManagement {
private boolean superClassesMatch(Type actualTypeDefinition, Type newTypeDefinition) {
// Checking superclasses. Must be the same. If differs the operation will be aborted.
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getTypeSuperTypes());
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getTypeSuperTypes());
Set<String> actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
Set<String> newSuperClasses = new HashSet<>(newTypeDefinition.getExtendedTypes());
if(actualSuperClasses.size()!=newSuperClasses.size()) {
return false;
@ -454,7 +453,7 @@ public class TypeManagement {
return false;
}
actualSuperClasses = new HashSet<>(actualTypeDefinition.getTypeSuperTypes());
actualSuperClasses = new HashSet<>(actualTypeDefinition.getExtendedTypes());
newSuperClasses.removeAll(actualSuperClasses);
if(newSuperClasses.size()>0) {
return false;
@ -469,8 +468,8 @@ public class TypeManagement {
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.WRITER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
@ -482,10 +481,10 @@ public class TypeManagement {
if(!superClassesMatch(actualTypeDefinition, newTypeDefinition)){
StringBuffer error = new StringBuffer();
error.append("The new type definition has a different set of superclasses. Actual version superclasses are: ");
error.append(actualTypeDefinition.getTypeSuperTypes());
error.append(". New version superclasses are: ");
error.append(newTypeDefinition.getTypeSuperTypes());
error.append("The new type definition has a different set of supertypes. Actual version supertypes are: ");
error.append(actualTypeDefinition.getExtendedTypes());
error.append(". New version supertypes are: ");
error.append(newTypeDefinition.getExtendedTypes());
error.append(". This kind update is not supported for a type.");
throw new SchemaException(error.toString());
}
@ -648,8 +647,8 @@ public class TypeManagement {
protected List<Type> getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
@ -789,8 +788,8 @@ public class TypeManagement {
protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
oDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
@ -798,7 +797,11 @@ public class TypeManagement {
oSchema.dropClass(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();

View File

@ -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.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.TypeMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType;
@ -48,11 +48,11 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if (workingContext == null) {
workingContext = TypeSecurityContext.getInstance();
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
if (workingEnvironment == null) {
workingEnvironment = TypeEnvironment.getInstance();
}
return workingContext;
return workingEnvironment;
}
public void setName(String name) {

View File

@ -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.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
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)
*/
public class PropertyTypeDefinitionManagement extends ElementManagement<OElement, PropertyType<?>> {
public class PropertyTypeDefinitionManagement extends ElementManagement<OElement, PropertyType> {
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
@ -42,10 +42,10 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
this.typeName = PropertyType.NAME;
}
public PropertyTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
public PropertyTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.oDatabaseDocument = oDatabaseDocument;
setWorkingContext(securityContext);
setWorkingEnvironment(typeEnvironment);
}
@Override
@ -54,11 +54,11 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<OElement
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if(workingContext == null) {
workingContext = TypeSecurityContext.getInstance();
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
if(workingEnvironment == null) {
workingEnvironment = TypeEnvironment.getInstance();
}
return workingContext;
return workingEnvironment;
}
public void setName(String name) {

View File

@ -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.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.types.reference.entities.FacetType;
import org.gcube.informationsystem.types.reference.relations.ConsistsOfType;
@ -20,16 +20,16 @@ public class ConsistsOfTypeDefinitionManagement
this.typeName = ConsistsOfType.NAME;
}
public ConsistsOfTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument)
public ConsistsOfTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument)
throws ResourceRegistryException {
super(securityContext, oDatabaseDocument, FacetType.class);
super(typeEnvironment, oDatabaseDocument, FacetType.class);
this.typeName = ConsistsOfType.NAME;
}
@Override
protected FacetTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
FacetTypeDefinitionManagement ftdm = new FacetTypeDefinitionManagement();
ftdm.setWorkingContext(getWorkingContext());
ftdm.setWorkingEnvironment(getWorkingEnvironment());
ftdm.setODatabaseDocument(oDatabaseDocument);
return ftdm;
}

View File

@ -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.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.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.IsRelatedToType;
@ -20,16 +20,16 @@ public class IsRelatedToTypeDefinitionManagement
this.typeName = IsRelatedToType.NAME;
}
public IsRelatedToTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument)
public IsRelatedToTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument)
throws ResourceRegistryException {
super(securityContext, oDatabaseDocument, ResourceType.class);
super(typeEnvironment, oDatabaseDocument, ResourceType.class);
this.typeName = IsRelatedToType.NAME;
}
@Override
protected ResourceTypeDefinitionManagement newTargetEntityManagement() throws ResourceRegistryException {
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
rtdm.setWorkingContext(getWorkingContext());
rtdm.setWorkingEnvironment(getWorkingEnvironment());
rtdm.setODatabaseDocument(oDatabaseDocument);
return rtdm;
}

View File

@ -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.SchemaNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaViolationException;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.base.relations.RelationElementManagement;
import org.gcube.informationsystem.resourceregistry.environments.Environment;
import org.gcube.informationsystem.resourceregistry.environments.types.TypeEnvironment;
import org.gcube.informationsystem.resourceregistry.types.entities.EntityTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.types.entities.ResourceTypeDefinitionManagement;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
@ -46,11 +46,11 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
this.forceIncludeAllMeta = true;
}
public RelationTypeDefinitionManagement(SecurityContext securityContext, ODatabaseDocument oDatabaseDocument,
public RelationTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument,
Class<TT> clz) throws ResourceRegistryException {
this(clz);
this.oDatabaseDocument = oDatabaseDocument;
setWorkingContext(securityContext);
setWorkingEnvironment(typeEnvironment);
}
@Override
@ -59,11 +59,11 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
}
@Override
protected SecurityContext getWorkingContext() throws ResourceRegistryException {
if (workingContext == null) {
this.workingContext = TypeSecurityContext.getInstance();
protected Environment getWorkingEnvironment() throws ResourceRegistryException {
if (workingEnvironment == null) {
this.workingEnvironment = TypeEnvironment.getInstance();
}
return workingContext;
return workingEnvironment;
}
public void setName(String name) {
@ -212,7 +212,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
@Override
protected ResourceTypeDefinitionManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
rtdm.setWorkingContext(getWorkingContext());
rtdm.setWorkingEnvironment(getWorkingEnvironment());
rtdm.setODatabaseDocument(oDatabaseDocument);
return rtdm;
}

View File

@ -6,7 +6,6 @@ import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
@ -46,7 +45,7 @@ public class EncryptedOrient extends ODocument implements Encrypted {
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {

View File

@ -5,7 +5,6 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
@ -37,7 +36,7 @@ public class MetadataOrient extends ODocument implements Metadata {
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {

View File

@ -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.node.ObjectNode;
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.IdentifiableElement;
import org.gcube.informationsystem.model.reference.properties.Metadata;
@ -29,13 +30,14 @@ public class MetadataUtility {
private static final Logger logger = LoggerFactory.getLogger(MetadataUtility.class);
public static String getUser() {
String user = Metadata.UNKNOWN_USER;
String username = Metadata.UNKNOWN_USER;
try {
user = SecretManagerProvider.instance.get().getUser().getUsername();
User user = SecretManagerProvider.instance.get().getUser();
username = user.getUsername();
} 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() {

View File

@ -1,4 +1,4 @@
package org.gcube.informationsystem.resourceregistry.utils;
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashMap;
import java.util.UUID;
@ -13,10 +13,10 @@ 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.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -93,8 +93,8 @@ public class OrientDBUtility {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
adminDatabaseDocument = adminSecurityContext.getDatabaseDocument(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
adminDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
} finally {
if(adminDatabaseDocument != null) {

View File

@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.Property;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
@ -36,7 +35,7 @@ public class PropagationConstraintOrient extends ODocument implements Propagatio
public List<String> getSupertypes() {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(getTypeName());
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(getTypeName());
try {
return cachedType.getSuperTypes();
} catch (Exception e) {

View File

@ -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.Secret;
import org.gcube.common.authorization.utils.secret.SecretUtility;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.iam.D4ScienceIAMClient;
import org.gcube.common.iam.D4ScienceIAMClientAuthn;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@ -39,14 +38,15 @@ public class ContextTest {
public static final String NEXTNEXT;
public static final String DEVSEC;
public static final String DEVVRE;
protected static final Properties properties;
protected static final String CLIENT_ID_PROPERTY_KEY = "client_id";
protected static final String CLIENT_SECRET_PROPERTY_KEY = "client_secret";
public static final String TYPE_PROPERTY_KEY = "type";
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String PASSWORD_PROPERTY_KEY = "password";
public static final String CLIENT_ID_PROPERTY_KEY = "clientId";
protected static final String clientID;
protected static final String clientSecret;
public static final String RESOURCE_REGISTRY_URL_PROPERTY = "RESOURCE_REGISTRY_URL";
static {
GCUBE = "/gcube";
@ -55,7 +55,7 @@ public class ContextTest {
DEVSEC = GCUBE + "/devsec";
DEVVRE = DEVSEC + "/devVRE";
PARENT_DEFAULT_TEST_SCOPE = "/gcube";
PARENT_DEFAULT_TEST_SCOPE = GCUBE;
DEFAULT_TEST_SCOPE = DEVNEXT;
ALTERNATIVE_TEST_SCOPE = NEXTNEXT;
@ -64,16 +64,16 @@ public class ContextTest {
try {
// load the properties file
properties.load(input);
clientID = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
clientSecret = properties.getProperty(CLIENT_SECRET_PROPERTY_KEY);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private enum Type{
USER, CLIENT_ID
};
public static void set(Secret secret) throws Exception {
SecretManagerProvider.instance.reset();
SecretManager secretManager = new SecretManager();
@ -83,20 +83,49 @@ public class ContextTest {
}
public static void setContextByName(String fullContextName) throws Exception {
logger.debug("Going to set credentials for context {}", fullContextName);
Secret secret = getSecretByContextName(fullContextName);
set(secret);
}
private static TokenResponse getJWTAccessToken(String context) throws Exception {
ScopeProvider.instance.set(context);
TokenResponse tr = KeycloakClientFactory.newInstance().queryUMAToken(clientID, clientSecret, context, null);
return tr;
protected static String getJWTAccessToken(String context) throws Exception {
Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString());
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 {
TokenResponse tr = getJWTAccessToken(context);
Secret secret = new JWTSecret(tr.getAccessToken());
String accessToken = getJWTAccessToken(context);
Secret secret = new JWTSecret(accessToken);
return secret;
}

View File

@ -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));
}
}
}

View File

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

View File

@ -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);
}
}

View File

@ -1,8 +1,10 @@
package org.gcube.informationsystem.resourceregistry.contexts;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
@ -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.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.contexts.entities.ContextManagement;
import org.gcube.informationsystem.resourceregistry.contexts.security.ContextSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.SecurityType;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.Environment.SecurityType;
import org.gcube.informationsystem.resourceregistry.environments.contexts.ContextEnvironment;
import org.gcube.informationsystem.resourceregistry.environments.instances.InstanceEnvironment;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -82,26 +85,26 @@ public class ContextManagementTest extends ContextTest {
}
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();
SecurityContext securityContext = null;
InstanceEnvironment instanceEnvironment = null;
if(deleted) {
securityContext = new SecurityContext(uuid);
instanceEnvironment = new InstanceEnvironment(uuid);
} else {
securityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
instanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
}
boolean[] booleanArray = new boolean[] {false, true};
for(boolean hierarchic : booleanArray) {
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);
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);
Assert.assertEquals(oUser == null, deleted);
if(oUser != null) {
@ -109,20 +112,20 @@ public class ContextManagementTest extends ContextTest {
}
if(hierarchic) {
SecurityContext parent = null;
InstanceEnvironment parent = null;
if(deleted) {
if(oldParentUUID != null) {
parent = ContextUtility.getInstance().getSecurityContextByUUID(oldParentUUID);
parent = ContextUtility.getInstance().getEnvironmentByUUID(oldParentUUID);
}
}
parent = securityContext.getParentSecurityContext();
parent = (InstanceEnvironment) instanceEnvironment.getParentEnvironment();
while(parent != null) {
String parentUser = parent.getSecurityRoleOrUserName(permissionMode, SecurityType.USER,
hierarchic);
OUser parentOUser = oSecurity.getUser(parentUser);
Assert.assertTrue(parentOUser != null);
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.setUUID(uuid);
SecurityContext securityContext = ContextUtility.getInstance().getSecurityContextByUUID(uuid);
InstanceEnvironment instanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
UUID oldParentUUID = null;
if(securityContext.getParentSecurityContext() != null) {
oldParentUUID = securityContext.getParentSecurityContext().getUUID();
if(instanceEnvironment.getParentEnvironment() != null) {
oldParentUUID = instanceEnvironment.getParentEnvironment().getUUID();
}
contextManagement.delete();
@ -441,7 +444,13 @@ public class ContextManagementTest extends ContextTest {
}
private List<Context> getAll() throws Exception {
return getAll(0, -1);
}
private List<Context> getAll(Integer forceOffset, Integer forcelimit) throws Exception {
ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceOffset(forceOffset);
contextManagement.setForceLimit(forcelimit);
String allString = contextManagement.all(false);
logger.trace(allString);
List<Context> all = ElementMapper.unmarshalList(Context.class, allString);
@ -449,9 +458,10 @@ public class ContextManagementTest extends ContextTest {
}
/*
// @Test
@Ignore
@Test
public void deleteAll() throws Exception {
ContextTest.setContextByName(PARENT_DEFAULT_TEST_SCOPE);
ContextTest.setContextByName(GCUBE);
List<Context> all = getAll();
while(all.size()>0) {
for (Context context : all) {
@ -468,37 +478,45 @@ public class ContextManagementTest extends ContextTest {
@Test
public void testGetAll() throws Exception {
List<Context> contexts = getAll();
contexts = ServerContextCache.getInstance().getContexts();
// List<Context> contexts = getAll();
// List<Context> contexts = ServerContextCache.getInstance().getContexts();
List<Context> contexts = ServerContextCache.getInstance().getFullInfoContexts();
for(Context context : contexts) {
logger.info(ElementMapper.marshal(context));
List<IsParentOf> children = context.getChildren();
for(IsParentOf child : children) {
Assert.assertTrue(child.getSource() == context);
Context childContext = child.getTarget();
logger.info("{} {}", context.getName(), context.getID());
List<IsParentOf> childrenIsParentOf = context.getChildren();
for(IsParentOf childIsParentOf : childrenIsParentOf) {
Assert.assertTrue(childIsParentOf.getSource() == context);
Context childContext = childIsParentOf.getTarget();
logger.info(" --- Child {}", childContext.getName());
Assert.assertTrue(childContext.getParent() == childIsParentOf);
Assert.assertTrue(childContext.getParent().getSource() == context);
}
roleUserAssertions(context.getID(), null, false);
}
}
@Ignore
// @Test
public void readContext() throws ResourceRegistryException, IOException {
Context context = read(UUID.fromString(""));
logger.debug("{}", context);
}
@Ignore
// @Test
public void deleteContext() throws ResourceRegistryException, IOException {
Context context = read(UUID.fromString(""));
delete(context);
}
@Test
public void testContextCache() throws Exception {
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();
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);
for(Context c : contexts) {
@ -537,4 +555,94 @@ public class ContextManagementTest extends ContextTest {
logger.debug("{} - {} : {}", uuid, fullName, context);
}
}
@Test
public void testLimitOffset() throws Exception {
int limit = 2;
int offset = limit * 0;
List<Context> contexts = getAll(offset, limit);
logger.info("Going to check {}s pagination validity", Context.NAME);
if(contexts.size()==0) {
return;
}
Assert.assertTrue(contexts.size() <= limit);
if(contexts.size()< limit) {
return;
}
Set<UUID> uuids = new HashSet<>();
for(Context context : contexts) {
UUID uuid = context.getID();
uuids.add(uuid);
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
}
offset = limit * 1;
contexts = getAll(offset, limit);
if(contexts.size()>0) {
Assert.assertTrue(contexts.size() <= limit);
for(Context context : contexts) {
UUID uuid = context.getID();
Assert.assertFalse(uuids.contains(uuid));
uuids.add(uuid);
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
}
if(contexts.size()<limit) {
return;
}
int doubleLimit = limit*2;
offset = 0;
contexts = getAll(0, doubleLimit);
Assert.assertTrue(contexts.size() <= doubleLimit);
for(Context context : contexts) {
UUID uuid = context.getID();
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, doubleLimit, Context.NAME, uuid, context.getName());
Assert.assertTrue(uuids.contains(uuid));
}
}
logger.info("Going to check all {}s", Context.NAME);
List<Context> all = getAll();
uuids = new HashSet<>();
int i = -1;
while(true) {
offset = ++i * limit;
contexts = getAll(offset, limit);
for(Context context : contexts) {
UUID uuid = context.getID();
logger.info("Using getAll({}, {}) found {} with UUID {} and name {}", offset, limit, Context.NAME, uuid, context.getName());
uuids.add(uuid);
}
if(contexts.size()<limit) {
break;
}
}
Assert.assertTrue(all.size()==uuids.size());
for(Context context : all) {
UUID uuid = context.getID();
Assert.assertTrue(uuids.contains(uuid));
logger.info("Using getAll() found {} with UUID {} and name {}", Context.NAME, uuid, context.getName());
}
logger.info("{} pagination seems properly working", Context.NAME);
}
}

View File

@ -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);
}
}
}

View File

@ -1,9 +1,9 @@
package org.gcube.informationsystem.resourceregistry.dbinitialization;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.environments.Environment.PermissionMode;
import org.gcube.informationsystem.resourceregistry.environments.administration.AdminEnvironment;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -19,20 +19,21 @@ public class DatabaseEnvironmentTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironmentTest.class);
// @Test
public void createDB() throws Exception{
@Test
public void createDB() throws Exception {
ContextTest.setContextByName(ContextTest.GCUBE);
String db = DatabaseEnvironment.DB_URI;
logger.trace("Created DB is {}", db);
}
@Test
public void testDateTimeFormat() throws ResourceRegistryException {
ODatabaseDocument oDatabaseDocument = ContextUtility.getAdminSecurityContext().getDatabaseDocument(PermissionMode.WRITER);
public void testDateTimeFormat() throws Exception {
ContextTest.setContextByName(ContextTest.GCUBE);
ODatabaseDocument oDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.WRITER);
String dateTime = oDatabaseDocument.get(ATTRIBUTES.DATETIMEFORMAT).toString();
Assert.assertTrue(dateTime.compareTo(Element.DATETIME_PATTERN)==0);
}
/*
@Test
public void generateDBKey() throws Exception {

View File

@ -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);
}
}

View File

@ -8,19 +8,24 @@ import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.impl.properties.EventImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Event;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
@ -30,14 +35,17 @@ import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.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.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.rest.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.resourcemanagement.model.impl.entities.facets.AccessPointFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
@ -86,12 +94,12 @@ import org.slf4j.LoggerFactory;
public class ERManagementTest extends ContextTest {
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
public static final String GROUP = "InformationSystem";
public static final String NAME = "resource-registry";
public static final String VERSION = "1.0.0";
public static final String NEW_VERSION = "2.0.0";
// @Before
// @After
// public void cleanInstances() throws Exception {
@ -109,14 +117,16 @@ public class ERManagementTest extends ContextTest {
// }
// }
// }
@Before
public void before() throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
requestInfo.setLimit(1000);
requestInfo.setOffset(0);
}
public static SoftwareFacet getSoftwareFacet() {
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
softwareFacet.setGroup(GROUP);
@ -124,13 +134,13 @@ public class ERManagementTest extends ContextTest {
softwareFacet.setVersion(VERSION);
return softwareFacet;
}
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, SoftwareFacet gotSoftwareFacet) {
Assert.assertTrue(gotSoftwareFacet.getGroup().compareTo(softwareFacet.getGroup()) == 0);
Assert.assertTrue(gotSoftwareFacet.getName().compareTo(softwareFacet.getName()) == 0);
Assert.assertTrue(gotSoftwareFacet.getVersion().compareTo(softwareFacet.getVersion()) == 0);
}
public static Configuration instantiateValidConfiguration() throws Exception {
Configuration configuration = new ConfigurationImpl();
@ -142,10 +152,10 @@ public class ERManagementTest extends ContextTest {
IsIdentifiedBy<Configuration, IdentifierFacet> isIdentifiedBy = new IsIdentifiedByImpl<Configuration, IdentifierFacet>(
configuration, identifierFacet);
configuration.addFacet(isIdentifiedBy);
return configuration;
}
public static EService instantiateValidEService() throws Exception {
EService eService = new EServiceImpl();
@ -161,8 +171,10 @@ public class ERManagementTest extends ContextTest {
eService.addFacet(accessPointFacet);
EventFacet eventFacet = new EventFacetImpl();
eventFacet.setDate(Calendar.getInstance().getTime());
eventFacet.setEvent("Created");
Event event = new EventImpl();
event.setWhen(Calendar.getInstance().getTime());
event.setWhat("Created");
eventFacet.setEvent(event);
eService.addFacet(eventFacet);
StateFacet stateFacet = new StateFacetImpl();
@ -171,8 +183,8 @@ public class ERManagementTest extends ContextTest {
LicenseFacet licenseFacet = new LicenseFacetImpl();
licenseFacet.setName("EUPL");
licenseFacet.setTextURL(
new URL("https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
licenseFacet.setTextURL(new URL(
"https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
eService.addFacet(licenseFacet);
return eService;
@ -219,82 +231,89 @@ public class ERManagementTest extends ContextTest {
hostingNode.addFacet(hnStateFacet);
EventFacet hnEventFacet = new EventFacetImpl();
hnEventFacet.setDate(Calendar.getInstance().getTime());
hnEventFacet.setEvent("Created");
Event event = new EventImpl();
event.setWhen(Calendar.getInstance().getTime());
event.setWhat("Created");
hnEventFacet.setEvent(event);
hostingNode.addFacet(hnEventFacet);
return hostingNode;
}
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement, IdentifiableElement createdIdentifiableElement) {
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement,
IdentifiableElement createdIdentifiableElement) {
UUID createdUUID = createdIdentifiableElement.getID();
Assert.assertTrue(createdUUID!=null);
if(identifiableElement.getID()!=null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID())==0);
Assert.assertTrue(createdUUID != null);
if (identifiableElement.getID() != null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID()) == 0);
}
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
Assert.assertTrue(createdMetadata!=null);
Assert.assertTrue(createdMetadata != null);
String createdBy = createdMetadata.getCreatedBy();
Assert.assertTrue(createdBy!=null);
Assert.assertTrue(createdBy != null);
String lastUpdateBy = createdMetadata.getLastUpdateBy();
Assert.assertTrue(lastUpdateBy!=null);
Assert.assertTrue(lastUpdateBy != null);
Date creationTime = createdMetadata.getCreationTime();
Assert.assertTrue(creationTime!=null);
Assert.assertTrue(creationTime != null);
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
Assert.assertTrue(lastUpdateTime!=null);
Assert.assertTrue(lastUpdateTime != null);
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
Metadata metadata = identifiableElement.getMetadata();
if(metadata!=null) {
if(metadata.getCreatedBy()!=null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy())==0);
}else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser())==0);
if (metadata != null) {
if (metadata.getCreatedBy() != null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy()) == 0);
} else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser()) == 0);
}
if(metadata.getLastUpdateBy()!=null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy())==0);
}else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser())==0);
if (metadata.getLastUpdateBy() != null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy()) == 0);
} else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser()) == 0);
}
if(metadata.getLastUpdateTime()!=null) {
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime()) || lastUpdateTime.compareTo(metadata.getLastUpdateTime())==0);
if (metadata.getLastUpdateTime() != null) {
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime())
|| lastUpdateTime.compareTo(metadata.getLastUpdateTime()) == 0);
}
}
}
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint, PropagationConstraint gotPropagationConstraint) {
Assert.assertTrue(propagationConstraint.getAddConstraint()==gotPropagationConstraint.getAddConstraint());
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==gotPropagationConstraint.getRemoveConstraint());
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint,
PropagationConstraint gotPropagationConstraint) {
Assert.assertTrue(propagationConstraint.getAddConstraint() == gotPropagationConstraint.getAddConstraint());
Assert.assertTrue(
propagationConstraint.getRemoveConstraint() == gotPropagationConstraint.getRemoveConstraint());
}
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf, ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf,
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
if(consistsOf.getPropagationConstraint()==null) {
if (consistsOf.getPropagationConstraint() == null) {
PropagationConstraint propagationConstraint = gotConsistsOf.getPropagationConstraint();
Assert.assertTrue(propagationConstraint.getAddConstraint()==AddConstraint.propagate);
Assert.assertTrue(propagationConstraint.getRemoveConstraint()==RemoveConstraint.cascade);
Assert.assertTrue(propagationConstraint.getAddConstraint() == AddConstraint.propagate);
Assert.assertTrue(propagationConstraint.getRemoveConstraint() == RemoveConstraint.cascade);
checkPropagationConstraint(propagationConstraint, gotConsistsOf.getPropagationConstraint());
}else {
} else {
checkPropagationConstraint(consistsOf.getPropagationConstraint(), gotConsistsOf.getPropagationConstraint());
}
Map<String, Object> additionalProperties = new HashMap<>(consistsOf.getAdditionalProperties());
additionalProperties.remove(Element.SUPERTYPES_PROPERTY);
additionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
gotAdditionalProperties.remove(Element.SUPERTYPES_PROPERTY);
Assert.assertTrue(additionalProperties.size()==gotAdditionalProperties.size());
for(String key : additionalProperties.keySet()) {
gotAdditionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Assert.assertTrue(additionalProperties.size() == gotAdditionalProperties.size());
for (String key : additionalProperties.keySet()) {
Assert.assertTrue(gotAdditionalProperties.containsKey(key));
Object additionalProperty = additionalProperties.get(key);
Object gotAdditionalProperty = gotAdditionalProperties.get(key);
@ -302,124 +321,123 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(additionalProperty.equals(gotAdditionalProperty));
}
}
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
checkUUIDAndMetadata(facet, gotFacet);
Class<? extends Facet> clz = facet.getClass();
Class<? extends Facet> gotClz = gotFacet.getClass();
Assert.assertTrue(clz==gotClz);
if(clz == SoftwareFacet.class) {
Assert.assertTrue(clz == gotClz);
if (clz == SoftwareFacet.class) {
checkSoftwareFacetAssertion((SoftwareFacet) facet, (SoftwareFacet) gotFacet);
}
}
protected static <R extends Resource> void checkResource(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for(ConsistsOf<? extends Resource, ? extends Facet> consistsOf : resourceConsistsOf) {
for (ConsistsOf<? extends Resource, ? extends Facet> consistsOf : resourceConsistsOf) {
@SuppressWarnings("unchecked")
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf = (ConsistsOf<? extends Resource, ? extends Facet>) gotResource.getConsistsOf(consistsOf.getClass(), consistsOf.getTarget().getClass()).get(0);
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf = (ConsistsOf<? extends Resource, ? extends Facet>) gotResource
.getConsistsOf(consistsOf.getClass(), consistsOf.getTarget().getClass()).get(0);
checkConsistOf(consistsOf, gotConsistsOf);
Facet facet = consistsOf.getTarget();
Facet gotFacet = gotConsistsOf.getTarget();
checkFacet(facet, gotFacet);
}
}
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for(ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
protected static <R extends Resource> void checkResourceNoMeta(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
Assert.assertNull(gotResource.getMetadata());
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for(ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(r.getTypeName());
resourceManagement.setJson(ElementMapper.marshal(r));
if(r.getID()!=null) {
if (r.getID() != null) {
resourceManagement.setUUID(r.getID());
}
return resourceManagement;
}
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(
IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
if(isRelatedTo.getID()!=null) {
if (isRelatedTo.getID() != null) {
isRelatedToManagement.setUUID(isRelatedTo.getID());
}
return isRelatedToManagement;
}
public <R extends Resource> R createResource(R r) throws Exception {
ResourceManagement resourceManagement = getResourceManagement(r);
String json = resourceManagement.create();
logger.debug("Created resource {}", json);
@SuppressWarnings("unchecked")
R createdR = (R) ElementMapper.unmarshal(r.getClass(), json);
logger.debug("Unmarshalled created resource {}", ElementMapper.marshal(createdR));
checkResource(r, createdR);
return createdR;
}
public EService createEService() throws Exception {
EService eService = ERManagementTest.instantiateValidEService();
return createResource(eService);
}
public HostingNode createHostingNode() throws Exception {
return createHostingNode(null);
}
public HostingNode createHostingNode(EService eService) throws Exception {
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
}
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint, DeleteConstraint deleteConstraint) throws Exception {
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint,
DeleteConstraint deleteConstraint) throws Exception {
HostingNode hostingNode = ERManagementTest.instantiateValidHostingNode();
if(eService!=null) {
if (eService != null) {
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
propagationConstraint.setRemoveConstraint(removeConstraint);
propagationConstraint.setDeleteConstraint(deleteConstraint);
@ -429,12 +447,12 @@ public class ERManagementTest extends ContextTest {
}
return createResource(hostingNode);
}
public Configuration createConfiguration() throws Exception {
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
return createResource(configuration);
}
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
Map<String, Resource> map = new HashMap<>();
@ -446,24 +464,23 @@ public class ERManagementTest extends ContextTest {
return map;
}
public <R extends Resource> void deleteResource(R r) throws Exception {
if(r!=null) {
if (r != null) {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.delete();
}
}
@Test
public void testCreateEService() throws Exception {
EService eService = null;
try {
eService = createEService();
}finally {
} finally {
deleteResource(eService);
}
}
@Test
@ -472,28 +489,27 @@ public class ERManagementTest extends ContextTest {
try {
eService = createEService();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
EService readEService = (EService) readResource(eService.getID());
checkResource(eService, readEService);
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceRootMetaOnly(eService, readEService);
requestInfo.setIncludeMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceNoMeta(eService, readEService);
}finally {
} finally {
deleteResource(eService);
}
}
protected Resource readResource(UUID uuid) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
@ -501,73 +517,70 @@ public class ERManagementTest extends ContextTest {
logger.debug(json);
return ElementMapper.unmarshal(Resource.class, json);
}
/*
@Test
public void testReadResource() throws Exception {
readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e"));
}
*/
* @Test public void testReadResource() throws Exception {
* readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e")); }
*/
/*
@Test
public void testDeleteResource() throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(UUID.fromString("64635295-7ced-4931-a55f-40fc8199b280"));
boolean deleted = resourceManagement.delete();
Assert.assertTrue(deleted);
}
*/
* @Test public void testDeleteResource() throws Exception { ResourceManagement
* resourceManagement = new ResourceManagement();
* resourceManagement.setUUID(UUID.fromString(
* "64635295-7ced-4931-a55f-40fc8199b280")); boolean deleted =
* resourceManagement.delete(); Assert.assertTrue(deleted); }
*/
@Test
public void testCreateHostingNode() throws Exception {
HostingNode hostingNode = null;
try {
hostingNode = createHostingNode();
}finally {
} finally {
deleteResource(hostingNode);
}
}
@Test
public void testCreateHostingNodeAndEService() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
deleteResource(map.get(HostingNode.NAME));
}
@Test
public void testCreateReadUpdateDeleteFacet() throws Exception {
EService eService = createEService();
try {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
ConsistsOf<EService, CPUFacet> consistsOf = new ConsistsOfImpl<EService, CPUFacet>(eService, cpuFacet);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(consistsOf.getTypeName());
consistsOfManagement.setJson(ElementMapper.marshal(consistsOf));
String createdConsistsOfString = consistsOfManagement.create();
@SuppressWarnings("unchecked")
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class, createdConsistsOfString);
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class,
createdConsistsOfString);
CPUFacet createdCpuFacet = createdConsistsOf.getTarget();
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(createdCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor()) == 0);
UUID uuid = createdCpuFacet.getID();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(createdCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
String readJson = facetManagement.read().toString();
CPUFacet readCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readJson);
logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet);
@ -575,21 +588,21 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getID()) == 0);
String newVendor = "Intel";
String newClockSpeed = "2 GHz";
readCpuFacet.setVendor(newVendor);
readCpuFacet.setClockSpeed(newClockSpeed);
String additionPropertyKey = "My";
String additionPropertyValue = "Test";
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.setJson(ElementMapper.marshal(readCpuFacet));
String updatedJson = facetManagement.update();
CPUFacet updatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, updatedJson);
logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, updatedCpuFacet);
@ -601,11 +614,11 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
String user = ContextTest.getUser();
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(updatedCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
String readUpdatedJson = facetManagement.read().toString();
CPUFacet readUpdatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readUpdatedJson);
logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet);
@ -615,11 +628,11 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.delete();
} finally {
deleteResource(eService);
@ -633,7 +646,7 @@ public class ERManagementTest extends ContextTest {
* not impose any particular constraint except the IdentifierFact
*/
Configuration configuration = instantiateValidConfiguration();
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEndpoint(new URI("https://localhost"));
accessPointFacet.setEntryName("port1");
@ -654,7 +667,7 @@ public class ERManagementTest extends ContextTest {
encrypted.setValue(encryptedValue);
String encryptedKey = "Enc";
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
configuration.addFacet(accessPointFacet);
String marshalled = ElementMapper.marshal(configuration);
@ -663,7 +676,7 @@ public class ERManagementTest extends ContextTest {
Configuration createdConfiguration = createResource(configuration);
AccessPointFacet apf = configuration.getFacets(AccessPointFacet.class).get(0);
Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema);
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
@ -671,33 +684,33 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
Assert.assertTrue(((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
Assert.assertTrue(
((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
deleteResource(createdConfiguration);
}
@Test
public void testUpdateFacetValue() throws Exception {
EService eService =null;
EService eService = null;
try {
eService = createEService();
eService = createEService();
final String newVersion = "1.2.0";
eService.getFacets(SoftwareFacet.class).get(0).setVersion(newVersion);
ResourceManagement resourceManagement = getResourceManagement(eService);
String json = resourceManagement.update();
EService updatedEService = ElementMapper.unmarshal(EService.class, json);
checkResource(eService, updatedEService);
SoftwareFacet softwareFacet = updatedEService.getFacets(SoftwareFacet.class).get(0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
} catch (Throwable e) {
throw e;
}finally {
} finally {
deleteResource(eService);
}
}
@ -729,5 +742,126 @@ public class ERManagementTest extends ContextTest {
String ret = resourceManagement.all(true);
logger.debug("{}", ret);
}
protected List<ERElement> getPaginatedInstances(Class<? extends ERElement> clz, int offset, int limit) throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setOffset(offset);
requestInfo.setLimit(limit);
ElementManagement<?,?> erManagement = 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);
}
}

View File

@ -37,6 +37,9 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class InvalidOperationTest extends ERManagementTest {
private static Logger logger = LoggerFactory.getLogger(InvalidOperationTest.class);

View File

@ -10,7 +10,6 @@ import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.file.FileStore;
@ -33,10 +32,12 @@ import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
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.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Event;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
@ -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.StateFacetImpl;
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.HasVolatileMemoryImpl;
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.StateFacet;
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.HasVolatileMemory;
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
@ -159,10 +158,12 @@ public class SmartgearResourcesTest extends ERManagementTest {
hostingNode.addFacet(hasPersistentMemory);
EventFacet hnEventFacet = new EventFacetImpl();
hnEventFacet.setDate(Calendar.getInstance().getTime());
ValueSchema hnEvent = new ValueSchemaImpl();
hnEvent.setSchema(new URI("Schema"));
hnEventFacet.setEvent("Created");
Event event = new EventImpl();
event.setWhen(Calendar.getInstance().getTime());
event.setWhat("Created");
hnEventFacet.setEvent(event);
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_NUMBER = "modelNumber";
public static List<CPUFacet> getFakeCPUFacets() {
List<CPUFacet> cpuFacets = new ArrayList<>();
if(cpuFacets.size()==0) {
for(int i=0; i<8; i++) {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setVendor("Apple");
cpuFacet.setModel("Apple M2 Pro");
cpuFacet.setClockSpeed("3,504 GHz");
cpuFacet.setAdditionalProperty("coreType", "Performance Cores (Avalanche)");
cpuFacets.add(cpuFacet);
}
for(int i=0; i<4; i++) {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setVendor("Apple");
cpuFacet.setModel("Apple M2 Pro");
cpuFacet.setClockSpeed("2.424 GHz");
cpuFacet.setAdditionalProperty("coreType", "Efficiency Cores (Blizzard)");
cpuFacets.add(cpuFacet);
}
}
return cpuFacets;
}
/**
* This function properly works on Linux but fails on
* other system such as Mac OS. In such case, the function
* getFakeCPUFacet() is used instead;
*/
public static List<CPUFacet> getCPUFacets() {
List<CPUFacet> cpuFacets = new ArrayList<>();
@ -453,7 +485,7 @@ public class SmartgearResourcesTest extends ERManagementTest {
if (!file.exists()) {
logger.warn("cannot acquire CPU info (no /proc/cpuinfo)");
return cpuFacets;
return getFakeCPUFacets();
}
BufferedReader input = null;
@ -531,6 +563,11 @@ public class SmartgearResourcesTest extends ERManagementTest {
}
}
}
if(cpuFacets.size()==0) {
return getFakeCPUFacets();
}
return cpuFacets;
}
}

View File

@ -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.relations.ConsistsOfManagement;
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.resourcemanagement.model.impl.entities.facets.ContactFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.CoverageFacetImpl;
@ -46,6 +46,9 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class AddToContextTest extends MultiContextTest {
private static Logger logger = LoggerFactory.getLogger(AddToContextTest.class);
@ -61,7 +64,7 @@ public class AddToContextTest extends MultiContextTest {
consistsOfManagement.setUUID(isIdentifiedBy.getID());
try {
consistsOfManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
consistsOfManagement.removeFromContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
throw new Exception("You should not be able to delete a mandatory ConsistsOf");
}catch (SchemaViolationException e) {
// As expected
@ -76,7 +79,7 @@ public class AddToContextTest extends MultiContextTest {
facetManagement.setUUID(softwareFacet.getID());
try {
facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
facetManagement.removeFromContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
throw new Exception("You should not be able to delete a mandatory Facet");
}catch (SchemaViolationException e) {
// As expected
@ -312,7 +315,7 @@ public class AddToContextTest extends MultiContextTest {
// hostingNode.setUUID(UUID.fromString("a87bb07e-5320-4fd8-a48d-bf3cc55756c4"));
// ResourceManagement resourceManagement = getResourceManagement(hostingNode);
// resourceManagement.setDryRun(false);
// UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName("/gcube/devsec").getUUID();
// UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName("/gcube/devsec").getUUID();
// resourceManagement.addToContext(contextUUID);
// }

View File

@ -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.relations.RelationAvailableInAnotherContextException;
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.relations.IsRelatedToManagement;
import org.gcube.informationsystem.serialization.ElementMapper;
@ -171,7 +171,7 @@ public class BasicTest extends MultiContextTest {
String targetContextFullName = ALTERNATIVE_TEST_SCOPE;
ResourceManagement rm = (ResourceManagement) ElementManagementUtility.getERManagement(Resource.NAME);
ResourceManagement rm = (ResourceManagement) ERManagementUtility.getERManagement(Resource.NAME);
String all = rm.all(true);
List<Resource> allResources = ElementMapper.unmarshalList(Resource.class, all);
Assert.assertTrue(allResources.size()==2);
@ -180,7 +180,7 @@ public class BasicTest extends MultiContextTest {
deleteResource(hostingNode);
rm = (ResourceManagement) ElementManagementUtility.getERManagement(Resource.NAME);
rm = (ResourceManagement) ERManagementUtility.getERManagement(Resource.NAME);
all = rm.all(true);
allResources = ElementMapper.unmarshalList(Resource.class, all);
Assert.assertTrue(allResources.size()==0);

View File

@ -26,6 +26,9 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ComplexTest extends MultiContextTest {
private static Logger logger = LoggerFactory.getLogger(ComplexTest.class);

View File

@ -32,6 +32,9 @@ import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.record.ODirection;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class MultiContextTest extends ERManagementTest {
private static Logger logger = LoggerFactory.getLogger(MultiContextTest.class);
@ -81,7 +84,7 @@ public class MultiContextTest extends ERManagementTest {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.setDryRun(dryRun);
UUID contextUUID = ContextUtility.getCurrentSecurityContext().getUUID();
UUID contextUUID = ContextUtility.getCurrentRequestEnvironment().getUUID();
resourceManagement.removeFromContext(contextUUID);
// Map<UUID, JsonNode> affectedInstances = resourceManagement.getAffectedInstances();
@ -220,7 +223,7 @@ public class MultiContextTest extends ERManagementTest {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.setDryRun(dryRun);
UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(targetContextFullName).getUUID();
UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName(targetContextFullName).getUUID();
resourceManagement.addToContext(contextUUID);
// Map<UUID, JsonNode> affectedInstances = resourceManagement.getAffectedInstances();
//
@ -279,7 +282,7 @@ public class MultiContextTest extends ERManagementTest {
IsRelatedToManagement isRelatedToManagement = getIsRelatedToManagement(isRelatedTo);
isRelatedToManagement.setDryRun(dryRun);
UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(targetContextFullName).getUUID();
UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName(targetContextFullName).getUUID();
isRelatedToManagement.addToContext(contextUUID);
// Map<UUID, JsonNode> affectedInstances = isRelatedToManagement.getAffectedInstances();

View File

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

View File

@ -14,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.IsRelatedTo;
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.base.ElementManagement;
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.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
@ -57,7 +57,7 @@ public class QueryTest extends ERManagementTest {
public void testRawQuery() throws InvalidQueryException {
QueryImpl queryImpl = new QueryImpl();
String query = "select from SoftwareFacet";
String query = "SELECT FROM SoftwareFacet";
String ret = queryImpl.query(query, false);
logger.debug(ret);
@ -90,7 +90,7 @@ public class QueryTest extends ERManagementTest {
/* Getting all instances of created specific Resources */
for (String key : resources.keySet()) {
ResourceManagement resourceManagement = (ResourceManagement) ElementManagementUtility.getERManagement(key);
ResourceManagement resourceManagement = (ResourceManagement) ERManagementUtility.getERManagement(key);
String json = resourceManagement.all(false);
List<Resource> list = ElementMapper.unmarshalList(Resource.class, json);
@ -100,7 +100,7 @@ public class QueryTest extends ERManagementTest {
/* Getting all Resources polymorphic and non polymorphic */
ResourceManagement resourceManagement = (ResourceManagement) ElementManagementUtility
ResourceManagement resourceManagement = (ResourceManagement) ERManagementUtility
.getERManagement(Resource.NAME);
String json = resourceManagement.all(true);
@ -114,7 +114,7 @@ public class QueryTest extends ERManagementTest {
/* Getting all IsRelatedTo polymorphic and non polymorphic */
IsRelatedToManagement isRelatedToManagement = (IsRelatedToManagement) ElementManagementUtility
IsRelatedToManagement isRelatedToManagement = (IsRelatedToManagement) ERManagementUtility
.getERManagement(IsRelatedTo.NAME);
json = isRelatedToManagement.all(true);
@ -130,7 +130,7 @@ public class QueryTest extends ERManagementTest {
/* Getting all ConsistsOf polymorphic and non polymorphic */
ConsistsOfManagement consistsOfManagement = (ConsistsOfManagement) ElementManagementUtility
ConsistsOfManagement consistsOfManagement = (ConsistsOfManagement) ERManagementUtility
.getERManagement(ConsistsOf.NAME);
json = consistsOfManagement.all(true);
@ -298,7 +298,7 @@ public class QueryTest extends ERManagementTest {
String type = Service.NAME;
@SuppressWarnings("rawtypes")
ElementManagement erManagement = ElementManagementUtility.getERManagement(type);
ElementManagement erManagement = ERManagementUtility.getERManagement(type);
if (erManagement instanceof ResourceManagement) {
boolean[] booleans = new boolean[] {true, false};
@ -337,7 +337,7 @@ public class QueryTest extends ERManagementTest {
@Test
public void getAllResourcesHavingFacet() throws ObjectNotFound, Exception {
String[] names = new String[]{"MyTest", "MyTest", "Aux", "MyID", "MyID"};
Object[] additionalProperties = new Object[] {5, 5.0, false, "test", null};
Object[] additionalProperties = new Object[] {5, 6.0, false, "test", null};
List<Configuration> createdConfigurations = new ArrayList<>();

View File

@ -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);
}
}

View File

@ -5,6 +5,7 @@ import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JavaType;
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.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateAlreadyPresentException;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class QueryTemplateManagementTest extends ContextTest {
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) {
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 previousMetadata = previous.getMetadata();
@ -68,10 +75,11 @@ public class QueryTemplateManagementTest extends ContextTest {
}
protected QueryTemplate create(QueryTemplate queryTemplate) throws ResourceRegistryException, IOException {
list();
//list();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
String json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
String created = queryTemplateManagement.create();
@ -79,7 +87,7 @@ public class QueryTemplateManagementTest extends ContextTest {
QueryTemplate createdQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, created);
assertions(queryTemplate, createdQueryTemplate);
list(createdQueryTemplate);
// list(createdQueryTemplate);
return createdQueryTemplate;
}
@ -222,18 +230,21 @@ public class QueryTemplateManagementTest extends ContextTest {
stateTemplateVariable.setName(STATE_VARIABLE_NAME);
stateTemplateVariable.setDescription("StateFacet value");
stateTemplateVariable.setDefaultValue("running");
stateTemplateVariable.setPropertyType("String");
queryTemplate.addTemplateVariable(stateTemplateVariable);
TemplateVariable nameTemplateVariable = new TemplateVariableImpl();
nameTemplateVariable.setName(NAME_VARIABLE_NAME);
nameTemplateVariable.setDescription("SoftwareFacet name");
nameTemplateVariable.setDefaultValue("resource-registry");
nameTemplateVariable.setPropertyType("String");
queryTemplate.addTemplateVariable(nameTemplateVariable);
TemplateVariable groupTemplateVariable = new TemplateVariableImpl();
groupTemplateVariable.setName(GROUP_VARIABLE_NAME);
groupTemplateVariable.setDescription("SoftwareFacet group");
groupTemplateVariable.setDefaultValue("information-system");
groupTemplateVariable.setPropertyType("String");
queryTemplate.addTemplateVariable(groupTemplateVariable);
return queryTemplate;
@ -241,7 +252,7 @@ public class QueryTemplateManagementTest extends ContextTest {
protected JsonNode getTemplate() throws Exception {
File queryTemplatesDirectory = getQueryTemplatesDirectory();
File jsonQueryTemplateFile = new File(queryTemplatesDirectory, "queryTemplate" + 1 + ".json");
File jsonQueryTemplateFile = new File(queryTemplatesDirectory, "queryTemplate1.json");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonQueryTemplateFile);
return jsonNode;
@ -292,4 +303,102 @@ public class QueryTemplateManagementTest extends ContextTest {
logger.debug("The DB should be now clean");
}
@Test(expected = QueryTemplateAlreadyPresentException.class)
public void doubleCreateTest() throws Exception {
QueryTemplate queryTemplate = getQueryTemplate();
try {
create(queryTemplate);
logger.info("Created {} with name '{}'", QueryTemplate.NAME, queryTemplate.getName());
create(queryTemplate);
throw new Exception("The second create should fails. You should not be here");
} catch (QueryTemplateAlreadyPresentException e) {
logger.info("As expected {} with name '{}' already exists", QueryTemplate.NAME, queryTemplate.getName());
throw e;
}finally {
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.delete();
logger.info("{} with name '{}' successfully deleted", QueryTemplate.NAME, queryTemplate.getName());
logger.debug("The DB should be now clean");
}
}
@Test
public void createUpdateTest() throws Exception {
QueryTemplate queryTemplate = getQueryTemplate();
try {
QueryTemplate createdQueryTemplate = create(queryTemplate);
// test no UUID
logger.info("Created {} with name '{}'", QueryTemplate.NAME, createdQueryTemplate.getName());
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
String updatedDescription = "My 1st udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
String json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
String updated = queryTemplateManagement.createOrUpdate();
logger.info("Updated {} is {}", QueryTemplate.NAME, updated);
QueryTemplate updatedQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, updated);
Assert.assertTrue(updatedQueryTemplate.getDescription().compareTo(updatedDescription)==0);
// test UUID null
queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
updatedDescription = "My 2nd udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
queryTemplate.setID(null);
json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
updated = queryTemplateManagement.createOrUpdate();
logger.info("Updated {} is {}", QueryTemplate.NAME, updated);
updatedQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, updated);
Assert.assertTrue(updatedQueryTemplate.getDescription().compareTo(updatedDescription)==0);
// test UUID same
queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
updatedDescription = "My 3rd udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
queryTemplate.setID(createdQueryTemplate.getID());
json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
updated = queryTemplateManagement.createOrUpdate();
logger.info("Updated {} is {}", QueryTemplate.NAME, updated);
updatedQueryTemplate = ElementMapper.unmarshal(QueryTemplate.class, updated);
Assert.assertTrue(updatedQueryTemplate.getDescription().compareTo(updatedDescription)==0);
// test another UUID
queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.setForceIncludeMeta(true);
updatedDescription = "My 4th udpated description";
queryTemplate = getQueryTemplate();
queryTemplate.setDescription(updatedDescription);
queryTemplate.setID(UUID.randomUUID());
json = ElementMapper.marshal(queryTemplate);
queryTemplateManagement.setJson(json);
try {
updated = queryTemplateManagement.createOrUpdate();
throw new Exception("Trying to udpate the " + QueryTemplate.NAME + " using a different " + QueryTemplate.ID_PROPERTY + " must fails. Please check your code");
}catch (ResourceRegistryException e) {
logger.info("Trying to update {} with name '{}' failed as expected : {} ", QueryTemplate.NAME, queryTemplate.getName(), e.getMessage());
}
}finally {
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(QUERY_TEMPLATE_NAME);
queryTemplateManagement.delete();
logger.info("{} with name '{}' successfully deleted", QueryTemplate.NAME, queryTemplate.getName());
logger.debug("The DB should be now clean");
}
}
}

View File

@ -33,7 +33,7 @@ public class AnotherEnhancedTest extends MultiContextTest {
// Map<UUID, JsonNode> expectedInstances = new HashMap<>();
// expectedInstances.put(eService.getUUID(), jsonNode);
//
// UUID contextUUID = ContextUtility.getInstance().getSecurityContextByFullName(ALTERNATIVE_TEST_SCOPE).getUUID();
// UUID contextUUID = ContextUtility.getInstance().getRequestEnvironmentByContextFullName(ALTERNATIVE_TEST_SCOPE).getUUID();
//
// try {
// ERManagementUtility.addToContextNoPropagationConstraint(expectedInstances, contextUUID, true);

View File

@ -13,10 +13,6 @@ import org.junit.Assert;
/**
* @author Luca Frosini (ISTI - CNR)
*/
/**
* @author lucafrosini
*
*/
public class FacetManagementTest extends MultiContextTest {
// private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
@ -139,7 +135,7 @@ public class FacetManagementTest extends MultiContextTest {
// facetManagement.setElementType(facetType);
// facetManagement.setUUID(facet.getUUID());
//
// facetManagement.addToContext(ContextUtility.getCurrentSecurityContext().getUUID());
// facetManagement.addToContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
// Assert.assertTrue(affectedInstances.size()==1);
@ -153,7 +149,7 @@ public class FacetManagementTest extends MultiContextTest {
// facetManagement.setElementType(facetType);
// facetManagement.setUUID(facet.getUUID());
//
// facetManagement.removeFromContext(ContextUtility.getCurrentSecurityContext().getUUID());
// facetManagement.removeFromContext(ContextUtility.getCurrentRequestEnvironment().getUUID());
// Map<UUID,JsonNode> affectedInstances = facetManagement.getAffectedInstances();
// Assert.assertTrue(affectedInstances.containsKey(facet.getUUID()));
// Assert.assertTrue(affectedInstances.size()==1);

View File

@ -284,8 +284,8 @@ public class SchemaManagementImplTest extends ContextTest {
Assert.assertTrue(type.getDescription().compareTo(typeManaged.getDescription())==0);
Assert.assertTrue(type.isAbstract() == typeManaged.isAbstract());
Assert.assertTrue(type.getTypeSuperTypes().containsAll(typeManaged.getTypeSuperTypes()));
Assert.assertTrue(typeManaged.getTypeSuperTypes().containsAll(type.getTypeSuperTypes()));
Assert.assertTrue(type.getExtendedTypes().containsAll(typeManaged.getExtendedTypes()));
Assert.assertTrue(typeManaged.getExtendedTypes().containsAll(type.getExtendedTypes()));
Map<Version, String> typeChangelog = type.getChangelog();
@ -400,4 +400,47 @@ public class SchemaManagementImplTest extends ContextTest {
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);
}
}

View File

@ -13,6 +13,9 @@ import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.metadata.schema.OClass;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class TypesCacheTest {
private static Logger logger = LoggerFactory.getLogger(TypesCacheTest.class);
@ -51,12 +54,4 @@ public class TypesCacheTest {
testCacheType(RunningPlugin.NAME);
}
@Test
public void test2() throws Exception {
logger.debug("------------------------------------------");
testCacheType(Service.NAME);
testCacheType(RunningPlugin.NAME);
}
}

View File

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