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
156 changed files with 8620 additions and 4143 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,11 +2,23 @@ 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]

51
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>
@ -60,18 +60,23 @@
</exclusion>
</exclusions>
</dependency>
<!-- ArcadeDB dependencies -->
<dependency>
<groupId>com.arcadedb</groupId>
<artifactId>arcadedb-engine</artifactId>
<version>23.4.1</version>
<groupId>com.orientechnologies</groupId>
<!--
To work with Thinkerpop® it is required to use this artifactId
<artifactId>orientdb-graphdb</artifactId>
Giving that we just use OrientDB classes and not Thinkerpop®
implementation we use a lighter dependency
-->
<artifactId>orientdb-client</artifactId>
<version>3.0.42</version>
<exclusions>
<exclusion>
<groupId>org.graalvm.tools</groupId>
<artifactId>chromeinspector</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.arcadedb</groupId>
<artifactId>arcadedb-network</artifactId>
<version>23.4.1</version>
</dependency>
<!-- ArcadeDB dependencies -->
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>gxHTTP</artifactId>
@ -96,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

@ -23,7 +23,7 @@ public class ResourceInitializer extends ResourceConfig {
public ResourceInitializer() {
packages(Access.class.getPackage().toString());
logger.info("The server is going to use OrientDB at {}:{}/{}", DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB);
logger.info("The server is going to use OrientDB at {}", DatabaseEnvironment.DB_URI);
}
}

View File

@ -0,0 +1,219 @@
package org.gcube.informationsystem.resourceregistry.base;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
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.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
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.utils.OrientDBUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OClass;
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 ElementManagementUtility {
private static Logger logger = LoggerFactory.getLogger(ElementManagementUtility.class);
public static OElement getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
try {
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OVertex.class);
} catch(NotFoundException e) {
return OrientDBUtility.getElementByUUIDAsAdmin(null, uuid, OEdge.class);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static OElement getAnyElementByUUID(ODatabaseDocument oDatabaseDocument, UUID uuid)
throws NotFoundException, ResourceRegistryException {
try {
return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OVertex.class);
} catch(NotFoundException e) {
return OrientDBUtility.getElementByUUID(oDatabaseDocument, null, uuid, OEdge.class);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static EntityManagement<?, ?> getEntityManagement(Environment workingContext, ODatabaseDocument oDatabaseDocument,
OVertex vertex) throws ResourceRegistryException {
if(oDatabaseDocument == null) {
throw new ResourceRegistryException(
ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(vertex == null) {
throw new ResourceRegistryException(
OVertex.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
OClass oClass = null;
try {
oClass = ElementManagementUtility.getOClass(vertex);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", vertex.toString(),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
EntityManagement<?, ?> entityManagement = null;
if(oClass.isSubClassOf(Resource.NAME)) {
entityManagement = new ResourceManagement();
} else if(oClass.isSubClassOf(Facet.NAME)) {
entityManagement = new FacetManagement();
} else {
String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
entityManagement.setODatabaseDocument(oDatabaseDocument);
entityManagement.setWorkingEnvironment(workingContext);
entityManagement.setElement(vertex);
return entityManagement;
}
public static RelationManagement<?,?> getRelationManagement(Environment workingContext, ODatabaseDocument oDatabaseDocument,
OEdge edge) throws ResourceRegistryException {
if(oDatabaseDocument == null) {
throw new ResourceRegistryException(
ODatabaseDocument.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(edge == null) {
throw new ResourceRegistryException(
OEdge.class.getSimpleName() + "instance is null. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
OClass oClass = ElementManagementUtility.getOClass(edge);
RelationManagement<?,?> relationManagement = null;
if(oClass.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement();
} else if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement();
} else {
String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME,
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
relationManagement.setODatabaseDocument(oDatabaseDocument);
relationManagement.setWorkingEnvironment(workingContext);
relationManagement.setElement(edge);
return relationManagement;
}
public static <E extends OElement> E getElementFromOptional(Optional<E> optional) throws ResourceRegistryException {
if(optional.isPresent()) {
return optional.get();
}else {
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
}
}
public static OClass getOClass(OElement oElement) throws ResourceRegistryException {
Optional<OClass> optional = oElement.getSchemaType();
if(optional.isPresent()) {
return optional.get();
}else {
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,23 +14,22 @@ 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.utils.DBUtility;
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;
import com.arcadedb.database.Document;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.MutableVertex;
import com.arcadedb.graph.Vertex;
import com.arcadedb.remote.RemoteDatabase;
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 abstract class EntityElementManagement<E extends EntityElement, ET extends EntityType> extends ElementManagement<Vertex, ET> {
public abstract class EntityElementManagement<E extends EntityElement, ET extends EntityType> extends ElementManagement<OVertex, ET> {
public final static String IN_PREFIX = "in_";
public final static String OUT_PREFIX = "out_";
@ -53,10 +52,10 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
}
protected EntityElementManagement(AccessType accessType, SecurityContext workingContext, RemoteDatabase database) {
protected EntityElementManagement(AccessType accessType, Environment workingContext, ODatabaseDocument oDatabaseDocument) {
this(accessType);
this.database = database;
setWorkingContext(workingContext);
this.oDatabaseDocument = oDatabaseDocument;
setWorkingEnvironment(workingContext);
}
/*
@ -65,11 +64,11 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
* fake id starting with - (minus) sign. This not imply any collateral effect
* but a better solution is a desiderata.
*/
protected RelationElementManagement<?,?,?,?> getBaseRelationManagement(Edge edge) throws ResourceRegistryException {
protected RelationElementManagement<?,?,?,?> getBaseRelationManagement(OEdge edge) throws ResourceRegistryException {
String id = edge.getIdentity().toString();
RelationElementManagement<?,?,?,?> relationManagement = relationManagements.get(id);
if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge);
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement);
}
return relationManagement;
@ -77,7 +76,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
protected void addToRelationManagement(RelationElementManagement<?,?,?,?> baseRelationManagement)
throws ResourceRegistryException {
Document elem = baseRelationManagement.getElement();
OElement elem = baseRelationManagement.getElement();
String id = elem.getIdentity().toString();
if(relationManagements.get(id) != null && relationManagements.get(id) != baseRelationManagement) {
StringBuilder errorMessage = new StringBuilder();
@ -86,7 +85,7 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". ");
errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
relationManagements.put(id, baseRelationManagement);
@ -109,24 +108,23 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
return sourceResource;
}
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode);
try {
// TODO
// if(documentType.isAbstract()) {
// String error = String.format(
// "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
// accessType.getName(), typeName);
// throw new ResourceRegistryException(error);
// }
if(oClass.isAbstract()) {
String error = String.format(
"Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
accessType.getName(), typeName);
throw new ResourceRegistryException(error);
}
try {
if(uuid != null) {
Vertex v = getElement();
OVertex v = getElement();
if(v != null) {
String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString());
throw getSpecificAlreadyPresentException(error);
@ -135,10 +133,10 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
} catch(NotFoundException e) {
try {
Document el = ElementManagementUtility.getAnyElementByUUID(uuid);
OElement el = ElementManagementUtility.getAnyElementByUUID(uuid);
String error = String.format("UUID %s is already used by another Element. This is not allowed.",
uuid.toString(),
(el instanceof Vertex) ? EntityElement.NAME : RelationElement.NAME);
(el instanceof OVertex) ? EntityElement.NAME : RelationElement.NAME);
throw new ResourceRegistryException(error);
} catch(NotFoundException e1) {
@ -148,23 +146,23 @@ public abstract class EntityElementManagement<E extends EntityElement, ET extend
throw e;
}
MutableVertex vertexEntity = database.newVertex(typeName);
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName);
this.element = vertexEntity;
if(accessType == AccessType.RESOURCE) {
// Facet and relation are created in calling method
} else {
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
}
logger.info("Created {} is {}", Vertex.class.getSimpleName(),
DBUtility.getAsStringForLogging(element));
logger.info("Created {} is {}", OVertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging(element));
return element;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}

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,29 +12,28 @@ 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;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.UUIDUtility;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
@ -52,31 +51,36 @@ public class PropertyElementManagement {
PROPERTY_IGNORE_START_WITH_KEYS = new HashSet<String>();
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.AT);
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.UNDERSCORE);
PROPERTY_IGNORE_START_WITH_KEYS.add(ElementManagement.DOLLAR);
}
public static Document getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException {
Document document = null;
public static ODocument getPropertyDocument(JsonNode jsonNodeOrig) throws ResourceRegistryException {
ODocument oDocument = null;
if(jsonNodeOrig.isNull()) {
return null;
}
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);
if(type!=null) {
// Complex type
DocumentType documentType = null;
OClass oClass = null;
try {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
documentType = cachedType.getDocumentType();
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(type);
oClass = cachedType.getOClass();
AccessType gotAccessType = cachedType.getAccessType();
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName());
@ -112,10 +116,10 @@ public class PropertyElementManagement {
* Resource Registry must decrypt the value with the Context Key and Encrypt it with DB key.
* The opposite operation is done when the value is read by clients.
*/
if(documentType.isSubTypeOf(Encrypted.NAME)) {
if(oClass.isSubClassOf(Encrypted.NAME)) {
EncryptedOrient encrypted = new EncryptedOrient();
document = encrypted;
document.fromJSON(jsonNode.toString());
oDocument = encrypted;
oDocument.fromJSON(jsonNode.toString());
try {
String contextEncryptedValue = encrypted.getEncryptedValue();
@ -126,21 +130,21 @@ public class PropertyElementManagement {
} catch(Exception e) {
throw new ResourceRegistryException("Unable to manage " + Encrypted.NAME + " " + org.gcube.informationsystem.model.reference.properties.Property.NAME);
}
return document;
return oDocument;
}
document = new Document(type);
oDocument = new ODocument(type);
} else {
document = new Document();
oDocument = new ODocument();
}
return document.fromJSON(jsonNode.toString());
return oDocument.fromJSON(jsonNode.toString());
}
public static JsonNode getJsonNode(Document oDocument) throws ResourceRegistryException {
public static JsonNode getJsonNode(ODocument oDocument) throws ResourceRegistryException {
try {
String type = oDocument.getTypeName();
String json = DBUtility.toJsonString(oDocument);
String type = oDocument.getClassName();
String json = OrientDBUtility.toJsonString(oDocument);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
@ -152,8 +156,8 @@ public class PropertyElementManagement {
TypesCache typesCache = TypesCache.getInstance();
@SuppressWarnings("unchecked")
CachedType<PropertyType<PropertyElement>> cachedType = (CachedType<PropertyType<PropertyElement>>) typesCache.getCachedType(type);
DocumentType documentType = cachedType.getDocumentType();
CachedType<PropertyType> cachedType = (CachedType<PropertyType>) typesCache.getCachedType(type);
OClass oClass = cachedType.getOClass();
AccessType gotAccessType = cachedType.getAccessType();
if(!AccessType.PROPERTY_ELEMENT.getClass().isAssignableFrom(gotAccessType.getClass())) {
throw new SchemaException(type + " is not a " + AccessType.PROPERTY_ELEMENT.getName());
@ -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
@ -169,11 +173,11 @@ public class PropertyElementManagement {
* The opposite operation is done when the value is set from clients.
* see {@link PropertyManagement#getPropertyDocument(JsonNode) getPropertyDocument()}
*/
if(documentType.isSubTypeOf(Encrypted.NAME)) {
if(oClass.isSubClassOf(Encrypted.NAME)) {
try {
EncryptedOrient encrypted = null;
String encryptedValue = (String) oDocument.getString(Encrypted.VALUE);
String encryptedValue = (String) oDocument.getProperty(Encrypted.VALUE);
if(oDocument instanceof EncryptedOrient) {
encrypted = (EncryptedOrient) oDocument;
@ -182,7 +186,7 @@ public class PropertyElementManagement {
}
}else {
encrypted = new EncryptedOrient();
oDocument = (Document) encrypted;
oDocument = (ODocument) encrypted;
// Decrypting with DB Key
Key databaseKey = DatabaseEnvironment.getDatabaseKey();

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,25 +13,24 @@ 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.utils.DBUtility;
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;
import org.gcube.informationsystem.utils.UUIDUtility;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public abstract class RelationElementManagement<SEM extends EntityElementManagement<? extends EntityElement, SET>, TEM extends EntityElementManagement<? extends EntityElement, TET>, SET extends EntityType, TET extends EntityType>
extends ElementManagement<Edge, RelationType<SET, TET>> {
extends ElementManagement<OEdge, RelationType<SET, TET>> {
public final static String IN = "in";
public final static String OUT = "out";
@ -74,15 +73,15 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
this.includeTarget = includeTarget;
}
protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass, SecurityContext workingContext, RemoteDatabase database) {
protected RelationElementManagement(AccessType accessType, Class<? extends EntityElement> sourceEntityClass, Class<? extends EntityElement> targetEntityClass, Environment workingContext, ODatabaseDocument orientGraph) {
this(accessType, sourceEntityClass, targetEntityClass);
this.database = database;
setWorkingContext(workingContext);
this.oDatabaseDocument = orientGraph;
setWorkingEnvironment(workingContext);
}
public SEM getSourceEntityManagement() throws ResourceRegistryException {
if(sourceEntityManagement == null) {
Vertex source = getElement().getVertex(DIRECTION.OUT);
OVertex source = getElement().getVertex(ODirection.OUT);
sourceEntityManagement = newSourceEntityManagement();
sourceEntityManagement.setElement(source);
}
@ -92,7 +91,7 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
public TEM getTargetEntityManagement() throws ResourceRegistryException {
if(targetEntityManagement == null) {
Vertex target = getElement().getVertex(DIRECTION.IN);
OVertex target = getElement().getVertex(ODirection.IN);
targetEntityManagement = newTargetEntityManagement();
targetEntityManagement.setElement(target);
}
@ -124,10 +123,10 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e;
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}
@ -137,7 +136,7 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
protected abstract void checksourceAndTargetEntityCompliancy() throws NotFoundException, AvailableInAnotherContextException, SchemaViolationException, ResourceRegistryException;
@Override
protected Edge reallyCreate() throws ResourceRegistryException {
protected OEdge reallyCreate() throws ResourceRegistryException {
if(sourceEntityManagement == null) {
@ -179,16 +178,16 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
}
}
Vertex source = (Vertex) getSourceEntityManagement().getElement();
Vertex target = (Vertex) getTargetEntityManagement().getElement();
OVertex source = (OVertex) getSourceEntityManagement().getElement();
OVertex target = (OVertex) getTargetEntityManagement().getElement();
checksourceAndTargetEntityCompliancy();
logger.trace("Going to create {} beetween {} -> {}", typeName, source.toString(), target.toString());
element = source.newEdge(typeName, target, true);
element = oDatabaseDocument.newEdge(source, target, typeName);
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
return element;
}
@ -198,12 +197,12 @@ public abstract class RelationElementManagement<SEM extends EntityElementManagem
protected abstract TEM newTargetEntityManagement() throws ResourceRegistryException;
@Override
protected Edge reallyUpdate() throws ResourceRegistryException {
protected OEdge reallyUpdate() throws ResourceRegistryException {
logger.debug("Trying to update {} : {}", typeName, jsonNode);
Edge edge = getElement();
updateProperties(documentType, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
OEdge edge = getElement();
updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
if(accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);

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,22 +13,21 @@ 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.utils.DBUtility;
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;
import org.slf4j.LoggerFactory;
import com.arcadedb.graph.MutableVertex;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -36,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;
@ -55,130 +55,120 @@ 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 {
// ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
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);
database = getAdminSecurityContext().getRemoteDatabase(PermissionMode.READER);
oDatabaseDocument = AdminEnvironment.getInstance().getDatabaseDocument(PermissionMode.READER);
MutableVertex contextVertex = getContextVertexByFullName(database, fullName);
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;
} catch(Exception e) {
throw new ContextException("Unable to retrieve Context UUID from current Context", e);
} finally {
if(database!=null) {
database.close();
if(oDatabaseDocument!=null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
public SecurityContext getSecurityContextByUUID(UUID uuid) throws ResourceRegistryException {
return getSecurityContextByUUID(uuid, null);
public InstanceEnvironment getEnvironmentByUUID(UUID uuid) throws ResourceRegistryException {
return getEnvironmentByUUID(uuid, null);
}
public static RemoteDatabase getCurrentODatabaseDocumentFromThreadLocal() {
RemoteDatabase current = null;
public static ODatabaseDocument getCurrentODatabaseDocumentFromThreadLocal() {
ODatabaseDocument current = null;
try {
// current = (RemoteDatabase) ODatabaseRecordThreadLocal.instance().get();
current = (ODatabaseDocument) ODatabaseRecordThreadLocal.instance().get();
}catch (Exception e) {
// It is possible that there is no current ODatabaseDocument
}
return current;
}
private Vertex getContextVertexByUUID(UUID uuid) throws ResourceRegistryException {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
try {
database = getAdminSecurityContext().getRemoteDatabase(PermissionMode.READER);
Vertex vertex = DBUtility.getElementByUUID(database, Context.NAME, uuid,
Vertex.class);
return vertex;
} finally {
if(database!=null) {
database.close();
}
private InstanceEnvironment getEnvironmentByUUID(UUID uuid, OVertex contextVertex) throws ResourceRegistryException {
InstanceEnvironment instanceEnvironment = contexts.get(uuid);
if(instanceEnvironment == null) {
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
instanceEnvironment = new InstanceEnvironment(uuid);
private SecurityContext getSecurityContextByUUID(UUID uuid, Vertex contextVertex) throws ResourceRegistryException {
SecurityContext securityContext = contexts.get(uuid);
if(securityContext == null) {
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);
}
Vertex parentVertex = contextVertex.getVertices(DIRECTION.IN, IsParentOf.NAME).iterator().next();
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;
}
/*
@ -188,8 +178,8 @@ public class ContextUtility {
}
*/
private MutableVertex getContextVertexByFullName(RemoteDatabase database , String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} with full name '{}'", Context.NAME, Vertex.class.getSimpleName(), fullName);
private OVertex getContextVertexByFullName(ODatabaseDocument oDatabaseDocument, String fullName) throws ResourceRegistryException {
logger.trace("Going to get {} {} with full name '{}'", Context.NAME, OVertex.class.getSimpleName(), fullName);
ScopeBean scopeBean = new ScopeBean(fullName);
String name = scopeBean.name();
@ -199,16 +189,16 @@ public class ContextUtility {
Map<String, String> map = new HashMap<>();
map.put("name", name);
ResultSet resultSet = database.command("sql", select, map);
OResultSet resultSet = oDatabaseDocument.query(select, map);
if(resultSet == null || !resultSet.hasNext()) {
throw new ContextNotFoundException("Error retrieving context with name " + fullName);
}
Result result = resultSet.next();
MutableVertex context = (MutableVertex) ElementManagementUtility.getElementFromOptional(result.getVertex());
OResult oResult = resultSet.next();
OVertex context = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
logger.trace("Context Representing Vertex : {}", DBUtility.getAsStringForLogging(context));
logger.trace("Context Representing Vertex : {}", OrientDBUtility.getAsStringForLogging(context));
if(resultSet.hasNext()) {
throw new ContextNotFoundException("Found more than one context with name " + name

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);
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);
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);
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,15 +32,18 @@ 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.utils.DBUtility;
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;
import org.gcube.informationsystem.utils.UUIDManager;
@ -41,21 +51,34 @@ import org.gcube.informationsystem.utils.UUIDUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
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);
@ -63,6 +86,8 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
this.typeName = Context.NAME;
this.forceIncludeMeta = true;
this.forceIncludeAllMeta = true;
this.forceOffset = null;
this.forceLimit = null;
}
public ContextManagement() {
@ -70,10 +95,10 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
init();
}
public ContextManagement(RemoteDatabase database) throws ResourceRegistryException {
public ContextManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.database = database;
getWorkingContext();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingEnvironment();
}
@Override
@ -88,18 +113,18 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
name = jsonNode.get(Context.NAME_PROPERTY).asText();
}
} else {
name = element.getString(Context.NAME_PROPERTY);
name = element.getProperty(Context.NAME_PROPERTY);
}
}
return name;
}
@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");
@ -166,7 +191,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
logger.trace("Checking if {} -> {}", errorMessage, select);
ResultSet resultSet = database.command("sql", select.toString(), new HashMap<>());
OResultSet resultSet = oDatabaseDocument.command(select.toString(), new HashMap<>());
if (resultSet != null && resultSet.hasNext()) {
throw new ContextAlreadyPresentException(errorMessage.toString());
@ -174,19 +199,26 @@ 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<Edge> parents = getElement().getEdges(DIRECTION.IN);
for (Edge edge : parents) {
Iterable<OEdge> parents = getElement().getEdges(ODirection.IN);
for (OEdge edge : parents) {
if (++count > 1) {
throw new ContextException("A " + Context.NAME + " can not have more than one parent");
}
try {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setElement(edge);
isParentOfManagement.includeSource(true);
isParentOfManagement.includeTarget(false);
@ -195,24 +227,24 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
((ObjectNode) context).replace(Context.PARENT_PROPERTY, isParentOf);
}
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ContextException("");
}
}
Iterable<Edge> childrenEdges = getElement().getEdges(DIRECTION.OUT);
for (Edge edge : childrenEdges) {
Iterable<OEdge> childrenEdges = getElement().getEdges(ODirection.OUT);
for (OEdge edge : childrenEdges) {
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setElement(edge);
try {
JsonNode isParentOf = isParentOfManagement.serializeAsJsonNode();
context = addRelation(context, isParentOf, Context.CHILDREN_PROPERTY);
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e;
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e);
}
}
@ -220,10 +252,22 @@ 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 Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
SecurityContext securityContext = null;
SecurityContext parentSecurityContext = null;
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
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);
@ -231,19 +275,41 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
if (isParentOfJsonNode != null && !(isParentOfJsonNode instanceof NullNode)) {
JsonNode parentJsonNode = isParentOfJsonNode.get(Relation.SOURCE_PROPERTY);
ContextManagement parentContextManagement = new ContextManagement(database);
ContextManagement parentContextManagement = new ContextManagement(oDatabaseDocument);
parentContextManagement.setJsonNode(parentJsonNode);
UUID parentUUID = parentContextManagement.uuid;
parentSecurityContext = ContextUtility.getInstance().getSecurityContextByUUID(parentUUID);
UUID parentUUID = parentContextManagement.getUUID();
parentInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(parentUUID);
checkContext(parentContextManagement);
if (uuid == null) {
uuid = UUIDManager.getInstance().generateValidUUID();
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
*/
}
createVertex();
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.");
}
}
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
checkContext(parentContextManagement);
logFullPath();
createVertex();
vertexCreated = true;
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setJsonNode(isParentOfJsonNode);
isParentOfManagement.setSourceEntityManagement(parentContextManagement);
isParentOfManagement.setTargetEntityManagement(this);
@ -251,44 +317,82 @@ 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(database);
this.element.setProperty(Context.STATE, ContextState.CREATED.getState());
ContextUtility.getInstance().addSecurityContext(securityContext);
newInstanceEnvironment.setParentEnvironment(parentInstanceEnvironment);
newInstanceEnvironment.create(oDatabaseDocument);
ContextUtility.getInstance().addInstanceEnvironment(newInstanceEnvironment);
return getElement();
} catch (Exception e) {
database.rollback();
if (securityContext != null) {
securityContext.delete(database);
if (parentSecurityContext != null && securityContext != null) {
parentSecurityContext.getChildren().remove(securityContext);
oDatabaseDocument.rollback();
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 Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
Set<String> allowedRoles = Environment.getAllOperationsAllowedRoles();
if(!workingEnvironment.isUserAllowed(allowedRoles)) {
throw new ForbiddenException("You are not allowed to update a " + Context.NAME +". Allowed roles are " + allowedRoles);
}
boolean parentChanged = false;
boolean nameChanged = false;
boolean stateChanged = false;
Vertex parent = null;
OVertex parent = null;
boolean found = false;
Iterable<Vertex> iterable = getElement().getVertices(DIRECTION.IN, IsParentOf.NAME);
for (Vertex p : iterable) {
Iterable<OVertex> iterable = getElement().getVertices(ODirection.IN, IsParentOf.NAME);
for (OVertex p : iterable) {
if (found) {
String message = String.format("{} has more than one parent. {}", Context.NAME,
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(message.toString());
}
parent = p;
@ -297,7 +401,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
ContextManagement actualParentContextManagement = null;
if (parent != null) {
actualParentContextManagement = new ContextManagement(database);
actualParentContextManagement = new ContextManagement(oDatabaseDocument);
actualParentContextManagement.setElement(parent);
}
@ -320,7 +424,7 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
if (parentChanged) {
newParentContextManagement = new ContextManagement(database);
newParentContextManagement = new ContextManagement(oDatabaseDocument);
newParentContextManagement.setJsonNode(parentContextJsonNode);
}
} else {
@ -331,22 +435,41 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
}
String oldName = getElement().getString(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);
}
element = (Vertex) updateProperties(documentType, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
if (parentChanged || nameChanged) {
logFullPath();
}
element = (OVertex) updateProperties(oClass, getElement(), jsonNode, ignoreKeys, ignoreStartWithKeys);
ServerContextCache.getInstance().cleanCache();
@ -359,51 +482,91 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
checkContext(newParentContextManagement);
}
SecurityContext newParentSecurityContext = null;
InstanceEnvironment newParentInstanceEnvironment = null;
// Removing the old parent relationship if any
Iterable<Edge> edges = getElement().getEdges(DIRECTION.IN, IsParentOf.NAME);
Iterable<OEdge> edges = getElement().getEdges(ODirection.IN, IsParentOf.NAME);
if (edges != null && edges.iterator().hasNext()) {
Iterator<Edge> edgeIterator = edges.iterator();
Edge edge = edgeIterator.next();
Iterator<OEdge> edgeIterator = edges.iterator();
OEdge edge = edgeIterator.next();
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 (edgeIterator.hasNext()) {
throw new ContextException(
"Seems that the Context has more than one Parent. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
if (newParentContextManagement != null) {
JsonNode isParentOfJsonNode = jsonNode.get(Context.PARENT_PROPERTY);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(database);
IsParentOfManagement isParentOfManagement = new IsParentOfManagement(oDatabaseDocument);
isParentOfManagement.setJsonNode(isParentOfJsonNode);
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, database);
InstanceEnvironment thisInstanceEnvironment = ContextUtility.getInstance().getEnvironmentByUUID(uuid);
thisInstanceEnvironment.changeParentEnvironment(newParentInstanceEnvironment, oDatabaseDocument);
}
@Override
protected void reallyDelete() throws NotFoundException, ResourceRegistryException {
Iterable<Edge> iterable = getElement().getEdges(DIRECTION.OUT);
Iterator<Edge> iterator = iterable.iterator();
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(database);
instanceEnvironment.delete(oDatabaseDocument);
ServerContextCache.getInstance().cleanCache();
}
@ -412,18 +575,48 @@ public class ContextManagement extends EntityElementManagement<Context, EntityTy
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<Document> iterable = database.browseClass(typeName, polymorphic);
for (Document vertex : iterable) {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
Integer limit = requestInfo.getLimit();
if(forceLimit!=null) {
limit = forceLimit;
}
if(limit == null) {
limit = -1;
}
Integer offset = requestInfo.getOffset();
if(forceOffset!=null) {
offset = forceOffset;
}
if(offset == null) {
offset = 0;
}
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for (ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
ContextManagement contextManagement = new ContextManagement();
contextManagement.setForceIncludeMeta(forceIncludeMeta);
contextManagement.setForceIncludeAllMeta(forceIncludeAllMeta);
contextManagement.setElement((Vertex) vertex);
contextManagement.setElement((OVertex) vertex);
try {
JsonNode jsonObject = contextManagement.serializeAsJsonNode();
arrayNode.add(jsonObject);
if(limit > 0 && ++count >= limit) {
break;
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {
@ -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,17 +14,16 @@ 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.utils.DBUtility;
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;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
@ -35,10 +34,10 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
super(AccessType.IS_PARENT_OF, Context.class, Context.class);
}
public IsParentOfManagement(RemoteDatabase database) throws ResourceRegistryException {
public IsParentOfManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.database = database;
getWorkingContext();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingEnvironment();
this.includeSource = false;
this.includeTarget = true;
this.forceIncludeMeta = true;
@ -51,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
@ -74,16 +73,16 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
JsonNode relation = serializeSelfAsJsonNode();
try {
Vertex source = element.getVertex(DIRECTION.OUT);
ContextManagement sourceContextManagement = new ContextManagement(database);
OVertex source = element.getVertex(ODirection.OUT);
ContextManagement sourceContextManagement = new ContextManagement(oDatabaseDocument);
sourceContextManagement.setElement(source);
if (includeSource) {
((ObjectNode) relation).replace(Relation.SOURCE_PROPERTY,
sourceContextManagement.serializeSelfAsJsonNode());
}
Vertex target = element.getVertex(DIRECTION.IN);
ContextManagement targetContextManagement = new ContextManagement(database);
OVertex target = element.getVertex(ODirection.IN);
ContextManagement targetContextManagement = new ContextManagement(oDatabaseDocument);
targetContextManagement.setElement(target);
if (includeTarget) {
((ObjectNode) relation).replace(Relation.TARGET_PROPERTY,
@ -91,10 +90,10 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
}
} catch (ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e;
} catch (Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}
@ -103,12 +102,12 @@ public class IsParentOfManagement extends RelationElementManagement<ContextManag
@Override
protected ContextManagement newSourceEntityManagement() throws ResourceRegistryException {
return new ContextManagement(database);
return new ContextManagement(oDatabaseDocument);
}
@Override
protected ContextManagement newTargetEntityManagement() throws ResourceRegistryException {
return new ContextManagement(database);
return new ContextManagement(oDatabaseDocument);
}
@Override

View File

@ -1,71 +0,0 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.dbinitialization.DatabaseEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.remote.RemoteDatabase;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class AdminSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
private static final String ADMIN_SECURITY_CONTEXT;
private static final UUID ADMIN_SECURITY_CONTEXT_UUID;
static {
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
}
private static AdminSecurityContext instance;
public static AdminSecurityContext getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new AdminSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(ADMIN_SECURITY_CONTEXT, instance);
}
return instance;
}
private AdminSecurityContext() throws ResourceRegistryException {
super(ADMIN_SECURITY_CONTEXT_UUID, false);
}
@Override
public void create() {
throw new RuntimeException("Cannot use this method for Admin Context");
}
@Override
protected Role getSuperRole(RemoteDatabase database, PermissionMode permissionMode) {
return database.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
}
@Override
protected Role addExtraRules(Role role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(Rule.ResourceGeneric.BYPASS_RESTRICTED, null, Role.PERMISSION_ALL);
break;
case READER:
role.addRule(Rule.ResourceGeneric.BYPASS_RESTRICTED, null, Role.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -1,62 +0,0 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ContextSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
private static final String CONTEXT_SECURITY_CONTEXT;
private static final UUID CONTEXT_SECURITY_CONTEXT_UUID;
static {
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
}
private static ContextSecurityContext instance;
public static ContextSecurityContext getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new ContextSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(CONTEXT_SECURITY_CONTEXT, instance);
}
return instance;
}
private ContextSecurityContext() throws ResourceRegistryException {
super(CONTEXT_SECURITY_CONTEXT_UUID, false);
}
@Override
protected Role addExtraRules(Role role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_ALL);
role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_ALL);
role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_ALL);
break;
case READER:
role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_READ);
role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_READ);
role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -1,62 +0,0 @@
package org.gcube.informationsystem.resourceregistry.contexts.security;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class QueryTemplatesSecurityContext extends SecurityContext {
private static Logger logger = LoggerFactory.getLogger(SecurityContext.class);
private static final String QUERY_TEMPLATES_SECURITY_CONTEXT;
private static final UUID QUERY_TEMPLATES_SECURITY_CONTEXT_UUID;
static {
QUERY_TEMPLATES_SECURITY_CONTEXT = "dddddddd-dddd-dddd-dddd-dddddddddddd";
QUERY_TEMPLATES_SECURITY_CONTEXT_UUID = UUID.fromString(QUERY_TEMPLATES_SECURITY_CONTEXT);
}
private static QueryTemplatesSecurityContext instance;
public static QueryTemplatesSecurityContext getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new QueryTemplatesSecurityContext();
ContextUtility contextUtility = ContextUtility.getInstance();
contextUtility.addSecurityContext(QUERY_TEMPLATES_SECURITY_CONTEXT, instance);
}
return instance;
}
private QueryTemplatesSecurityContext() throws ResourceRegistryException {
super(QUERY_TEMPLATES_SECURITY_CONTEXT_UUID, false);
}
@Override
protected Role addExtraRules(Role role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_ALL);
role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_ALL);
role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_ALL);
break;
case READER:
role.addRule(Rule.ResourceGeneric.CLUSTER, null, Role.PERMISSION_READ);
role.addRule(Rule.ResourceGeneric.SYSTEM_CLUSTERS, null, Role.PERMISSION_READ);
role.addRule(Rule.ResourceGeneric.CLASS, null, Role.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -1,653 +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.DBUtility;
import org.gcube.informationsystem.utils.UUIDManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.database.Identifiable;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.database.RID;
import com.arcadedb.database.Record;
import com.arcadedb.remote.RemoteDatabase;
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.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,RemoteDatabase>> databasesMap;
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 RemoteDatabase getAdminDatabaseDocument() throws ResourceRegistryException {
return ContextUtility.getAdminSecurityContext().getRemoteDatabase(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, RemoteDatabase database) 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(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
final String error = errorMessage.toString();
logger.error(error);
throw new RuntimeException(error);
}
// OSecurity oSecurity = getOSecurity(database);
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(database, oldParents, allChildren);
setParentSecurityContext(newParentSecurityContext);
if(newParentSecurityContext!=null){
for(PermissionMode permissionMode : PermissionMode.values()) {
List<Role> roles = new ArrayList<>();
for(SecurityContext child : allChildren) {
String roleName = child.getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, true);
Role role = database.getRole(roleName);
roles.add(role);
}
newParentSecurityContext.addHierarchicalRoleToParent(database, permissionMode, roles.toArray(new Role[allChildren.size()]));
}
}
}
protected SecurityContext(UUID context, boolean hierarchical) throws ResourceRegistryException {
this.context = context;
this.databasesMap = new HashMap<>();
this.hierarchical = hierarchical;
this.children = new HashSet<>();
}
public SecurityContext(UUID context) throws ResourceRegistryException {
this(context, true);
}
private synchronized RemoteDatabase getPool(PermissionMode permissionMode, boolean recreate) {
RemoteDatabase db = null;
Boolean h = isHierarchicalMode();
Map<PermissionMode,RemoteDatabase> databases = databasesMap.get(h);
if(databases == null) {
databases = new HashMap<>();
databasesMap.put(h, databases);
} else {
if(recreate) {
db = databases.get(permissionMode);
if(db!=null) {
db.close();
databases.remove(permissionMode);
}
}
}
db = databases.get(permissionMode);
if(db == null) {
String username = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, h);
String password = DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode);
db = new RemoteDatabase(DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB ,username, password);
databases.put(permissionMode, db);
}
return db;
}
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();
}
public static Set<String> getContexts(Document element) {
Set<String> contexts = new HashSet<>();
ORecordLazySet oRecordLazySet = element.getProperty(OSecurity.ALLOW_ALL_FIELD);
for (Identifiable identifiable : oRecordLazySet) {
Document oDocument = (Document) identifiable;
String name = oDocument.getString("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(Document element) throws ResourceRegistryException {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase adminDatabase = null;
try {
adminDatabase = getAdminDatabaseDocument();
addElement(element, adminDatabase);
}finally {
if(adminDatabase!=null) {
adminDatabase.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
protected void allow(RemoteDatabase database, Document document, boolean hierarchic) {
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchic);
oSecurity.allowRole(document, RestrictedOperation.ALLOW_ALL, writerRoleName);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchic);
oSecurity.allowRole(document, RestrictedOperation.ALLOW_READ, readerRoleName);
}
public boolean isElementInContext(final Document element) throws ResourceRegistryException {
RID rid = element.getIdentity();
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
try {
database = getRemoteDatabase(PermissionMode.READER);
return database.existsRecord(rid);
} finally {
if(database!=null) {
database.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
public void addElement(Document document, RemoteDatabase database) {
allow(database, document, false);
if(hierarchical) {
allow(database, document, true);
}
// document.save();
}
public void removeElement(Document document) throws ResourceRegistryException {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase adminDatabase = null;
try {
adminDatabase = getAdminDatabaseDocument();
removeElement(document, adminDatabase);
}finally {
if(adminDatabase!=null) {
adminDatabase.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
protected void deny(RemoteDatabase database, Document document, 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(document, RestrictedOperation.ALLOW_ALL, writerUserName);
String readerUserName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.USER, hierarchical);
oSecurity.denyUser(document, RestrictedOperation.ALLOW_READ, readerUserName);
String writerRoleName = getSecurityRoleOrUserName(PermissionMode.WRITER, SecurityType.ROLE, hierarchical);
oSecurity.denyRole(document, RestrictedOperation.ALLOW_ALL, writerRoleName);
String readerRoleName = getSecurityRoleOrUserName(PermissionMode.READER, SecurityType.ROLE, hierarchical);
oSecurity.denyRole(document, RestrictedOperation.ALLOW_READ, readerRoleName);
}
public void removeElement(Document document, RemoteDatabase database) {
deny(database, document, false);
if(hierarchical) {
deny(database, document, true);
}
// document.save();
}
protected boolean allowed(final ORole role, final Document document) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
RequestUtility.getRequestInfo().get().setHierarchicalMode(false);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
try {
database = getRemoteDatabase(PermissionMode.READER);
// database.activateOnCurrentThread();
return database.existsRecord(document.getIdentity());
} catch(Exception e) {
return false;
} finally {
if(database!=null) {
database.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 {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase adminDatabase = null;
try {
adminDatabase = getAdminDatabaseDocument();
create(adminDatabase);
adminDatabase.commit();
} finally {
if(adminDatabase!=null) {
adminDatabase.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
protected Role addExtraRules(Role role, PermissionMode permissionMode) {
return role;
}
protected Role getSuperRole(RemoteDatabase database, PermissionMode permissionMode) {
String superRoleName = permissionMode.name().toLowerCase();
return database.getRole(superRoleName);
}
protected void addHierarchicalRoleToParent(RemoteDatabase database, PermissionMode permissionMode, ORole... roles) {
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
User user = database.getUser(userName);
for(Role role : roles) {
user.addRole(role);
}
user.save();
if(getParentSecurityContext() != null) {
getParentSecurityContext().addHierarchicalRoleToParent(database, permissionMode, roles);
}
}
protected void createRolesAndUsers(RemoteDatabase database) {
boolean[] booleanArray;
if(hierarchical) {
booleanArray = new boolean[] {false, true};
} else {
booleanArray = new boolean[] {false};
}
for(boolean hierarchical : booleanArray) {
for(PermissionMode permissionMode : PermissionMode.values()) {
Role superRole = getSuperRole(database, permissionMode);
String roleName = getSecurityRoleOrUserName(permissionMode, SecurityType.ROLE, hierarchical);
Role role = database.createRole(roleName, superRole, ALLOW_MODES.DENY_ALL_BUT);
addExtraRules(role, permissionMode);
role.save();
logger.trace("{} created", role);
if(hierarchical && getParentSecurityContext() != null) {
getParentSecurityContext().addHierarchicalRoleToParent(database, permissionMode, role);
}
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchical);
User user = database.createUser(userName, DatabaseEnvironment.DEFAULT_PASSWORDS.get(permissionMode),
role);
user.save();
logger.trace("{} created", user);
}
}
}
public void create(RemoteDatabase database) {
createRolesAndUsers(database);
logger.trace("Security Context (roles and users) with UUID {} successfully created", context.toString());
}
private void drop(RemoteDatabase database, String name, SecurityType securityType) {
switch(securityType) {
case ROLE:
database.dropRole(name);
break;
case USER:
database.dropUser(name);
break;
default:
break;
}
logger.trace("{} successfully dropped", name);
}
public void delete() throws ResourceRegistryException {
RemoteDatabase remoteDatabase = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
try {
database = getAdminDatabaseDocument();
delete(database);
database.commit();
} finally {
if(database!=null) {
database.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase) {
Set<SecurityContext> parents = getAllParents();
Set<SecurityContext> allChildren = getAllChildren();
removeChildrenHRolesFromParents(remoteDatabase, parents, allChildren);
}
protected void removeChildrenHRolesFromParents(RemoteDatabase remoteDatabase, Set<SecurityContext> parents, Set<SecurityContext> children) {
for(SecurityContext parent : parents) {
parent.removeChildrenHRolesFromMyHUsers(remoteDatabase, children);
}
}
protected void removeChildrenHRolesFromMyHUsers(RemoteDatabase database, Set<SecurityContext> children) {
for(PermissionMode permissionMode : PermissionMode.values()) {
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
User user = database.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(RemoteDatabase database, PermissionMode permissionMode, String roleName) {
String userName = getSecurityRoleOrUserName(permissionMode, SecurityType.USER, true);
User user = database.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(RemoteDatabase remoteDatabase) {
boolean[] booleanArray;
if(hierarchical) {
booleanArray = new boolean[] {false, true};
} else {
booleanArray = new boolean[] {false};
}
for(boolean hierarchic : booleanArray) {
if(hierarchic) {
removeChildrenHRolesFromParents(remoteDatabase);
}
for(PermissionMode permissionMode : PermissionMode.values()) {
for(SecurityType securityType : SecurityType.values()) {
String name = getSecurityRoleOrUserName(permissionMode, securityType, hierarchic);
drop(remoteDatabase, name, securityType);
}
}
}
}
public void delete(RemoteDatabase remoteDatabase) {
// OSecurity oSecurity = getOSecurity(orientGraph);
logger.trace("Going to remove Security Context (roles and users) with UUID {}", context.toString());
deleteRolesAndUsers(remoteDatabase);
logger.trace("Security Context (roles and users) with UUID {} successfully removed", context.toString());
}
public RemoteDatabase getRemoteDatabase(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);
// }
return null;
}
@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;
@ -45,8 +45,22 @@ import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.client.remote.OStorageRemote.CONNECTION_STRATEGY;
import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES;
import com.orientechnologies.orient.core.db.ODatabasePool;
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.OElement;
/**
* @author Luca Frosini (ISTI - CNR)
@ -57,13 +71,12 @@ public class DatabaseEnvironment {
protected static final String PROPERTY_FILENAME = "config.properties";
public static final String HOST;
private static final String HOST_VARNAME = "HOST";
public static final int PORT;
private static final String PORT_VARNAME = "REMOTE_PROTOCOL";
private static final String REMOTE_PROTOCOL;
private static final String REMOTE_PROTOCOL_VARNAME = "REMOTE_PROTOCOL";
public static final String DB;
private static final String DB;
private static final String DB_VARNAME = "DB";
private static final String ROOT_USERNAME;
@ -74,25 +87,36 @@ public class DatabaseEnvironment {
public static final String DEFAULT_ADMIN_ROLE = "admin";
private static final String ADMIN_USERNAME;
private static final String ADMIN_USERNAME_VARNAME = "ADMIN_USERNAME";
private static final String CHANGED_ADMIN_USERNAME;
private static final String CHANGED_ADMIN_USERNAME_VARNAME = "CHANGED_ADMIN_USERNAME";
private static final String ADMIN_PASSWORD;
private static final String ADMIN_PASSWORD_VARNAME = "ADMIN_PASSWORD";
private static final String CHANGED_ADMIN_PASSWORD;
private static final String CHANGED_ADMIN_PASSWORD_VARNAME = "CHANGED_ADMIN_PASSWORD";
private static final String WRITER_USER_PASSWORD;
private static final String WRITER_USER_PASSWORD_VARNAME = "WRITER_USER_PASSWORD";
private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD;
private static final String DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_WRITER_USER_PASSWORD";
private static final String READER_USER_PASSWORD;
private static final String READER_USER_PASSWORD_VARNAME = "READER_USER_PASSWORD";
private static final String DEFAULT_CREATED_READER_USER_PASSWORD;
private static final String DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME = "DEFAULT_CREATED_READER_USER_PASSWORD";
public static final Map<PermissionMode,String> DEFAULT_PASSWORDS;
private static final String HOSTS;
private static final String SERVER_URI;
public static final String DB_URI;
public static final CONNECTION_STRATEGY CONNECTION_STRATEGY_PARAMETER = CONNECTION_STRATEGY.ROUND_ROBIN_CONNECT;
protected static final String DB_KEY_FILENAME_VARNAME = "DB_KEY_FILENAME";
protected static final String DB_KEY_ALGORITHM_VARNAME = "DB_KEY_ALGORITHM";
private static final Key KEY;
public static final String VERTEX_CLASS_NAME = OClass.VERTEX_CLASS_NAME;
public static final String EDGE_CLASS_NAME = OClass.EDGE_CLASS_NAME;
static {
Properties properties = new Properties();
InputStream input = null;
@ -104,25 +128,41 @@ public class DatabaseEnvironment {
// load a properties file
properties.load(input);
HOST = properties.getProperty(HOST_VARNAME);
HOSTS = properties.getProperty(HOST_VARNAME);
PORT = Integer.valueOf(properties.getProperty(PORT_VARNAME));
REMOTE_PROTOCOL = properties.getProperty(REMOTE_PROTOCOL_VARNAME);
DB = properties.getProperty(DB_VARNAME);
SERVER_URI = REMOTE_PROTOCOL + HOSTS;
DB_URI = SERVER_URI + "/" + DB;
ROOT_USERNAME = properties.getProperty(ROOT_USERNAME_VARNAME);
ROOT_PASSWORD = properties.getProperty(ROOT_PASSWORD_VARNAME);
ADMIN_USERNAME = properties.getProperty(ADMIN_USERNAME_VARNAME);
ADMIN_PASSWORD = properties.getProperty(ADMIN_PASSWORD_VARNAME);
String changedAdminUsername = null;
try {
changedAdminUsername = properties.getProperty(CHANGED_ADMIN_USERNAME_VARNAME);
if(changedAdminUsername == null) {
// To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB;
}
} catch(Exception e) {
// To be compliant with old configuration.properties which does not have
// CHANGED_ADMIN_USERNAME property we use the db name as admin username
changedAdminUsername = DB;
}
CHANGED_ADMIN_USERNAME = changedAdminUsername;
WRITER_USER_PASSWORD = properties.getProperty(WRITER_USER_PASSWORD_VARNAME);
READER_USER_PASSWORD = properties.getProperty(READER_USER_PASSWORD_VARNAME);
CHANGED_ADMIN_PASSWORD = properties.getProperty(CHANGED_ADMIN_PASSWORD_VARNAME);
DEFAULT_CREATED_WRITER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_WRITER_USER_PASSWORD_VARNAME);
DEFAULT_CREATED_READER_USER_PASSWORD = properties.getProperty(DEFAULT_CREATED_READER_USER_PASSWORD_VARNAME);
DEFAULT_PASSWORDS = new HashMap<PermissionMode,String>();
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, WRITER_USER_PASSWORD);
DEFAULT_PASSWORDS.put(PermissionMode.READER, READER_USER_PASSWORD);
DEFAULT_PASSWORDS.put(PermissionMode.WRITER, DEFAULT_CREATED_WRITER_USER_PASSWORD);
DEFAULT_PASSWORDS.put(PermissionMode.READER, DEFAULT_CREATED_READER_USER_PASSWORD);
} catch(Throwable e) {
logger.error("Unable to load properties from {}", PROPERTY_FILENAME);
@ -132,19 +172,20 @@ public class DatabaseEnvironment {
// Used to Persist Context and their relations
try {
logger.info("Connecting as {} to {}:{}/{}", ROOT_USERNAME, HOST, PORT, DB);
RemoteDatabase database = new RemoteDatabase(HOST, PORT, DB, ADMIN_USERNAME, ADMIN_PASSWORD);
boolean created = initGraphDB(database);
boolean created = initGraphDB();
if(created) {
ODatabasePool pool = new ODatabasePool(DatabaseEnvironment.DB_URI, CHANGED_ADMIN_USERNAME,
CHANGED_ADMIN_PASSWORD);
ODatabaseDocument oDatabaseDocument = pool.acquire();
AdminEnvironment.getInstance().create(oDatabaseDocument);
oDatabaseDocument.commit();
oDatabaseDocument.close();
pool.close();
AdminSecurityContext.getInstance().create(database);
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<>();
@ -168,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 {
@ -183,19 +224,19 @@ 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<>();
schemaToBeCreated.add(Property.class);
schemaToBeCreated.add(Metadata.class);
for(Class<? extends Element> clazz : schemaToBeCreated) {
ElementManagement<? extends Document,?> erManagement = new PropertyTypeDefinitionManagement();
ElementManagement<? extends OElement,?> erManagement = new PropertyTypeDefinitionManagement();
erManagement.setJson(TypeMapper.serializeType(clazz));
erManagement.create();
}
@ -269,15 +310,15 @@ public class DatabaseEnvironment {
}
}
protected static void setDateTimeFormat(RemoteDatabase database) {
// TODO
// oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, Element.DATETIME_PATTERN);
protected static void setDateTimeFormat(ODatabaseDocument oDatabaseDocument) {
oDatabaseDocument.set(ATTRIBUTES.DATETIMEFORMAT, Element.DATETIME_PATTERN);
}
protected static void setRecordLevelSecurity(RemoteDatabase database) {
logger.trace("Setting Record-level Security");
/*
@Deprecated
// This code must be removed for OrientDB versions higher than 3.2.X
protected static void setRecordLevelSecurity(OMetadata oMetadata) {
logger.trace(
"Setting Record-level Security (see https://orientdb.org/docs/3.2.x/security/Database-Security.html#record-level-security-deprecated-in-v-31)");
OSchema oSchema = oMetadata.getSchema();
OClass oRestricted = oSchema.getClass(OSecurity.RESTRICTED_CLASSNAME);
@ -286,41 +327,51 @@ public class DatabaseEnvironment {
OClass e = oSchema.getClass(EDGE_CLASS_NAME);
e.addSuperClass(oRestricted);
*/
}
private static boolean initGraphDB(RemoteDatabase database) throws Exception {
private static boolean initGraphDB() throws Exception {
OLogManager.instance().setWarnEnabled(false);
OLogManager.instance().setErrorEnabled(false);
OLogManager.instance().setInfoEnabled(false);
OLogManager.instance().setDebugEnabled(false);
logger.info("Connecting as {} to {}", ROOT_USERNAME, DB_URI);
OrientDB orientDB = new OrientDB(SERVER_URI, ROOT_USERNAME, ROOT_PASSWORD, OrientDBConfig.defaultConfig());
try {
if(!!database.exists()) {
if(!orientDB.exists(DB)) {
logger.info("The database {} does not exist. Going to create it.", DB);
database.create();
logger.info("The database {} does not exist. Going to create it.", DB_URI);
orientDB.create(DB, ODatabaseType.PLOCAL);
DatabaseEnvironment.setDateTimeFormat(database);
ODatabasePool pool = new ODatabasePool(orientDB, DB, ROOT_USERNAME, ROOT_PASSWORD);
ODatabaseSession oDatabaseSession = pool.acquire();
List<String> databases = new ArrayList<>();
databases.add(DB);
DatabaseEnvironment.setDateTimeFormat(oDatabaseSession);
// TODO Create Role
// ORole adminRole = oSecurity.getRole(DEFAULT_ADMIN_ROLE);
// OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
//
logger.trace("Creating new admin named '{}'", ADMIN_USERNAME);
database.createUser(ADMIN_USERNAME, ADMIN_PASSWORD, databases);
OMetadata oMetadata = oDatabaseSession.getMetadata();
OSecurity oSecurity = oMetadata.getSecurity();
setRecordLevelSecurity(database);
database.commit();
logger.trace("Creating new admin named '{}'", CHANGED_ADMIN_USERNAME);
ORole adminRole = oSecurity.getRole(DEFAULT_ADMIN_ROLE);
OUser newAdminUser = oSecurity.createUser(CHANGED_ADMIN_USERNAME, CHANGED_ADMIN_PASSWORD, adminRole);
newAdminUser.save();
DatabaseEnvironment.changeDefaultAdminPassword(oSecurity);
setRecordLevelSecurity(oMetadata);
oDatabaseSession.commit();
oDatabaseSession.close();
pool.close();
return true;
}
return false;
} finally {
database.close();
orientDB.close();
}
}
@ -328,4 +379,28 @@ public class DatabaseEnvironment {
return KEY;
}
@Deprecated
// This code must be removed for OrientDB versions higher than 3.2.X
public static void changeDefaultAdminPassword(OSecurity oSecurity) {
for(PermissionMode permissionMode : DEFAULT_PASSWORDS.keySet()) {
try {
logger.trace("Going to update password for user {}", permissionMode.toString());
OUser oUser = oSecurity.getUser(permissionMode.toString());
oUser.setPassword(DEFAULT_PASSWORDS.get(permissionMode));
oUser.save();
logger.trace("Updated password for user {}", permissionMode.toString());
}catch (Exception e) {
logger.trace("Unable to update password for user {}. {}", permissionMode.toString(), e.getMessage());
throw new RuntimeException(e);
}
}
try {
logger.trace("Removing 'admin' user");
oSecurity.dropUser("admin");
}catch (Exception e) {
logger.info("Unable to delete admin user. {}", e.getMessage());
}
}
}

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

@ -0,0 +1,74 @@
package org.gcube.informationsystem.resourceregistry.environments.administration;
import java.util.UUID;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
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;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
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 AdminEnvironment extends SystemEnvironment {
private static Logger logger = LoggerFactory.getLogger(Environment.class);
private static final String ADMIN_SECURITY_CONTEXT;
private static final UUID ADMIN_SECURITY_CONTEXT_UUID;
static {
ADMIN_SECURITY_CONTEXT = "00000000-0000-0000-0000-000000000000";
ADMIN_SECURITY_CONTEXT_UUID = UUID.fromString(ADMIN_SECURITY_CONTEXT);
}
private static AdminEnvironment instance;
public static AdminEnvironment getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new AdminEnvironment();
}
return instance;
}
private AdminEnvironment() throws ResourceRegistryException {
super(ADMIN_SECURITY_CONTEXT_UUID);
}
@Override
public void create() {
throw new RuntimeException("Cannot use this method for Admin Context");
}
@Override
protected ORole getSuperRole(OSecurity oSecurity, PermissionMode permissionMode) {
return oSecurity.getRole(DatabaseEnvironment.DEFAULT_ADMIN_ROLE);
}
@Override
protected ORole addExtraRules(ORole role, PermissionMode permissionMode) {
logger.trace("Adding extra rules for {}", role.getName());
switch(permissionMode) {
case WRITER:
role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL);
break;
case READER:
role.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_READ);
break;
default:
break;
}
return role;
}
}

View File

@ -0,0 +1,68 @@
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)
* This SystemEnvironment is used to pesists
* Contexts information and their relations among
* others, e.g. a Context is parent of another.
*/
public class ContextEnvironment extends SystemEnvironment {
private static Logger logger = LoggerFactory.getLogger(Environment.class);
private static final String CONTEXT_SECURITY_CONTEXT;
private static final UUID CONTEXT_SECURITY_CONTEXT_UUID;
static {
CONTEXT_SECURITY_CONTEXT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
CONTEXT_SECURITY_CONTEXT_UUID = UUID.fromString(CONTEXT_SECURITY_CONTEXT);
}
private static ContextEnvironment instance;
public static ContextEnvironment getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new ContextEnvironment();
}
return instance;
}
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());
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,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

@ -0,0 +1,65 @@
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.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)
* Contains all the query templates
*/
public class QueryTemplateEnvironment extends SystemEnvironment {
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;
static {
QUERY_TEMPLATES_SECURITY_CONTEXT = "dddddddd-dddd-dddd-dddd-dddddddddddd";
QUERY_TEMPLATES_SECURITY_CONTEXT_UUID = UUID.fromString(QUERY_TEMPLATES_SECURITY_CONTEXT);
}
private static QueryTemplateEnvironment instance;
public static QueryTemplateEnvironment getInstance() throws ResourceRegistryException {
if(instance==null) {
instance = new QueryTemplateEnvironment();
}
return instance;
}
private QueryTemplateEnvironment() throws ResourceRegistryException {
super(QUERY_TEMPLATES_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

@ -1,18 +1,25 @@
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;
import com.orientechnologies.orient.core.metadata.security.ORole;
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;
@ -22,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

@ -1,203 +0,0 @@
package org.gcube.informationsystem.resourceregistry.instances.base;
import java.util.Optional;
import java.util.UUID;
import org.gcube.informationsystem.base.reference.AccessType;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.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.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.DBUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.DocumentType;
/**
* @author Luca Frosini (ISTI - CNR)
*/
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, RemoteDatabase database,
Document element) throws ResourceRegistryException {
if(element instanceof Vertex) {
return getEntityManagement(workingContext, database, (Vertex) element);
} else if(element instanceof Edge) {
return getRelationManagement(workingContext, database, (Edge) element);
}
throw new ResourceRegistryException(String.format("%s is not a %s nor a %s", element.getClass().getSimpleName(),
Entity.NAME, Relation.NAME));
}
public static Document getAnyElementByUUID(UUID uuid) throws NotFoundException, ResourceRegistryException {
try {
return DBUtility.getElementByUUIDAsAdmin(null, uuid, Vertex.class);
} catch(NotFoundException e) {
return DBUtility.getElementByUUIDAsAdmin(null, uuid, Edge.class);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static Document getAnyElementByUUID(RemoteDatabase database, UUID uuid)
throws NotFoundException, ResourceRegistryException {
try {
return DBUtility.getElementByUUID(database, null, uuid, Vertex.class);
} catch(NotFoundException e) {
return DBUtility.getElementByUUID(database, null, uuid, Edge.class);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static ElementManagement<?, ?> getERManagementFromUUID(SecurityContext workingContext, RemoteDatabase database,
UUID uuid) throws ResourceRegistryException {
try {
Document element = getAnyElementByUUID(database, uuid);
return getERManagement(workingContext, database, 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, RemoteDatabase database,
Vertex vertex) throws ResourceRegistryException {
if(database == null) {
throw new ResourceRegistryException("Database instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(vertex == null) {
throw new ResourceRegistryException(Vertex.class.getSimpleName() + " instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
DocumentType documentType = null;
try {
documentType = ElementManagementUtility.getDocumentType(vertex);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", vertex.toString(),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
EntityManagement<?, ?> entityManagement = null;
if(documentType.isSubTypeOf(Resource.NAME)) {
entityManagement = new ResourceManagement();
} else if(documentType.isSubTypeOf(Facet.NAME)) {
entityManagement = new FacetManagement();
} else {
String error = String.format("{%s is not a %s nor a %s. %s", vertex, Resource.NAME, Facet.NAME,
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
entityManagement.setDatabase(database);
entityManagement.setWorkingContext(workingContext);
entityManagement.setElement(vertex);
return entityManagement;
}
public static RelationManagement<?,?> getRelationManagement(SecurityContext workingContext, RemoteDatabase database,
Edge edge) throws ResourceRegistryException {
if(database == null) {
throw new ResourceRegistryException("Database instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(edge == null) {
throw new ResourceRegistryException(
Edge.class.getSimpleName() + " instance is null. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
DocumentType documentType = ElementManagementUtility.getDocumentType(edge);
RelationManagement<?,?> relationManagement = null;
if(documentType.isSubTypeOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement();
} else if(documentType.isSubTypeOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement();
} else {
String error = String.format("{%s is not a %s nor a %s. %s", edge, ConsistsOf.NAME, IsRelatedTo.NAME,
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
relationManagement.setDatabase(database);
relationManagement.setWorkingContext(workingContext);
relationManagement.setElement(edge);
return relationManagement;
}
public static <E extends Document> E getElementFromOptional(Optional<E> optional) throws ResourceRegistryException {
if(optional.isPresent()) {
return optional.get();
}else {
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
}
}
public static DocumentType getDocumentType(Document document) throws ResourceRegistryException {
DocumentType documentType = document.getType();
if(documentType==null) {
throw new ResourceRegistryException("An element not belonging to any defined type should not exists. Please contact the administrator.");
}
return documentType;
}
}

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,37 +6,106 @@ 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.arcadedb.remote.RemoteDatabase;
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();
staticLogger.info("Going to add {} to Context with UUID {} not following Propagation Constraints", instances, contextUUID);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
database.begin();
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.setDatabase(database);
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,19 +130,19 @@ public class ERManagementUtility {
/*
for(UUID uuid : uuids) {
ElementManagement<?,?> elementManagement = instancesManagement.get(uuid);
((ERManagement) elementManagement).contextSanityCheck(targetSecurityContext, expectedInstances);
((ERManagement) elementManagement).contextSanityCheck(targetInstanceEnvironment, expectedInstances);
}
*/
/*
SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.ADD);
if(operationValidator.isValidOperation(enforcedInstances)) {
database.commit();
oDatabaseDocument.commit();
}
*/
// database.activateOnCurrentThread();
database.commit();
oDatabaseDocument.activateOnCurrentThread();
oDatabaseDocument.commit();
staticLogger.info("{} successfully added to Context with UUID {} not following Propagation Constraints", instances, contextUUID);
/*
@ -85,24 +154,24 @@ public class ERManagementUtility {
return expectedInstances;
} catch(ResourceRegistryException e) {
staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage());
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw e;
} catch(Exception e) {
staticLogger.error("Unable to add {} to Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage());
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ContextException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
@ -110,28 +179,28 @@ public class ERManagementUtility {
throws NotFoundException, ContextException, ResourceRegistryException {
Set<UUID> instances = expectedInstances.keySet();
staticLogger.info("Going to remove {} from Context with UUID {} not following Propagation Constraints", instances, contextUUID);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
database.begin();
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.setDatabase(database);
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);
}
@ -146,11 +215,11 @@ public class ERManagementUtility {
SharingOperationValidator operationValidator = new SharingOperationValidator(expectedInstances, SharingOperation.REMOVE);
if(operationValidator.isValidOperation(enforcedInstances)) {
database.commit();
oDatabaseDocument.commit();
}
*/
database.commit();
oDatabaseDocument.commit();
staticLogger.info("{} successfully removed from Context with UUID {} not following Propagation Constraints", instances, contextUUID);
/*
@ -162,24 +231,24 @@ public class ERManagementUtility {
return expectedInstances;
} catch(ResourceRegistryException e) {
staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints - Reason is {}", instances, contextUUID, e.getMessage());
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw e;
} catch(Exception e) {
staticLogger.error("Unable to remove {} from Context with UUID {} not following Propagation Constraints.", instances, contextUUID, e.getMessage());
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ContextException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}

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,33 +26,34 @@ 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.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import com.arcadedb.database.Document;
import com.arcadedb.database.RID;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.MutableVertex;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -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,8 +155,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
this.relationManagements = new HashMap<>();
/*
* By the default the system honour the propagation constraints
* so this variable is initialised as true.
* By default the system honor the propagation constraints
* so this variable is initialized as true.
*/
this.honourPropagationConstraintsInContextSharing = true;
@ -163,7 +164,23 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
@Override
public Vertex getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
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 {
element = super.getElement();
} catch(NotFoundException e) {
@ -191,11 +208,11 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* fake id starting with - (minus) sign. This not imply any collateral effect
* but a better solution is a desiderata.
*/
protected RelationManagement<?,?> getRelationManagement(Edge edge) throws ResourceRegistryException {
protected RelationManagement<?,?> getRelationManagement(OEdge edge) throws ResourceRegistryException {
String id = edge.getIdentity().toString();
RelationManagement<?,?> relationManagement = relationManagements.get(id);
if(relationManagement == null) {
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(), database, edge);
relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(), oDatabaseDocument, edge);
relationManagements.put(id, relationManagement);
}
return relationManagement;
@ -203,7 +220,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
public void addToRelationManagements(RelationManagement<?,?> relationManagement)
throws ResourceRegistryException {
Edge elem = relationManagement.getElement();
OElement elem = relationManagement.getElement();
String id = elem.getIdentity().toString();
if(relationManagements.get(id) != null && relationManagements.get(id) != relationManagement) {
StringBuilder errorMessage = new StringBuilder();
@ -212,7 +229,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
errorMessage.append(" point to the same ");
errorMessage.append(elem.getClass().getSimpleName());
errorMessage.append(". ");
errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
relationManagements.put(id, relationManagement);
@ -236,26 +253,25 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
@Override
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode);
try {
// TODO
// if(documentType.isAbstract()) {
// String error = String.format(
// "Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
// accessType.getName(), typeName);
// throw new SchemaViolationException(error);
// }
if(oClass.isAbstract()) {
String error = String.format(
"Trying to create an instance of %s of type %s which is abstract. The operation will be aborted.",
accessType.getName(), typeName);
throw new SchemaViolationException(error);
}
MutableVertex vertexEntity = database.newVertex(typeName);
OVertex vertexEntity = oDatabaseDocument.newVertex(typeName);
try {
if(uuid != null) {
Vertex v = getElement();
OVertex v = getElement();
if(v != null) {
String error = String.format("A %s with UUID %s already exist", typeName, uuid.toString());
throw getSpecificAlreadyPresentException(error);
@ -264,9 +280,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} catch(NotFoundException e) {
try {
Document el = ElementManagementUtility.getAnyElementByUUID(uuid);
OElement el = ElementManagementUtility.getAnyElementByUUID(uuid);
String error = String.format("UUID %s is already used by another %s. This is not allowed.",
uuid.toString(), (el instanceof Vertex) ? Entity.NAME : Relation.NAME);
uuid.toString(), (el instanceof OVertex) ? Entity.NAME : Relation.NAME);
throw getSpecificAvailableInAnotherContextException(error);
} catch(NotFoundException e1) {
@ -281,17 +297,17 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
if(accessType == AccessType.RESOURCE) {
// Facet and relation are created in calling method
} else {
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
}
logger.debug("Created {} is {}", Vertex.class.getSimpleName(),
DBUtility.getAsStringForLogging((Vertex) element));
logger.debug("Created {} is {}", OVertex.class.getSimpleName(),
OrientDBUtility.getAsStringForLogging((OVertex) element));
return element;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}
@ -299,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(), database);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
@ -315,14 +331,14 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
* the update of Metadata i.e. modifiedBy, lastUpdateTime
*/
if(honourPropagationConstraintsInContextSharing) {
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(Edge edge : edges) {
for(OEdge edge : edges) {
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());
}
@ -337,7 +353,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
reallyAddToContext();
if(!skipped) {
MetadataUtility.updateModifiedByAndLastUpdate(element);
// element.save();
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
}
@ -345,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());
}
}
@ -353,44 +369,44 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.info("Going to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid, contextUUID, contextFullName);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
database.begin();
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();
if(!dryRun) {
database.commit();
oDatabaseDocument.commit();
}else {
database.rollback();
oDatabaseDocument.rollback();
}
logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName);
} catch(ResourceRegistryException e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {}) - Reason is {}", typeName, uuid, contextUUID, contextFullName, e.getMessage());
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw e;
} catch(Exception e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", typeName, uuid, contextUUID, contextFullName, e);
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ContextException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
@ -401,47 +417,47 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext();
MetadataUtility.updateModifiedByAndLastUpdate(element);
// element.save();
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
sanityCheck();
} catch(ResourceRegistryException e) {
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;
}
if(honourPropagationConstraintsInContextSharing) {
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(Edge edge : edges) {
for(OEdge edge : edges) {
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(), database);
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
*/
}
@ -450,45 +466,45 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
database.begin();
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();
if(!dryRun) {
database.commit();
oDatabaseDocument.commit();
}else {
database.rollback();
oDatabaseDocument.rollback();
}
logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID);
} catch(ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw e;
} catch(Exception e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID,
e);
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ContextException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
@ -497,209 +513,31 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<Document> iterable = database.browseClass(typeName, polymorphic);
for(Document vertex : iterable) {
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
database, (Vertex) vertex);
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
int limit = requestInfo.getLimit();
int offset = requestInfo.getOffset();
int position = -1;
int count = 0;
Iterable<ODocument> iterable = oDatabaseDocument.browseClass(typeName, polymorphic);
for(ODocument vertex : iterable) {
if(++position < offset) {
continue;
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(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(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {
return objectMapper.writeValueAsString(arrayNode);
} catch(JsonProcessingException e) {
throw new ResourceRegistryException(e);
}
}
public boolean propertyMatchRequestedValue(Vertex v, String key, String requestedValue, Object instanceValue) throws SchemaException, ResourceRegistryException {
return requestedValue.compareTo(instanceValue.toString())==0;
/*
OClass documentType = ElementManagement.getOClass(v);
OProperty oProperty = documentType.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, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint, boolean includeRelationInResult) throws ResourceRegistryException {
*/
public String reallyQuery(String relationType, String referenceType, UUID referenceUUID, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<?> references = null;
if(referenceUUID != null) {
Document element = null;
try {
element = ElementManagementUtility.getAnyElementByUUID(database, referenceUUID);
}catch (ResourceRegistryException e) {
String error = String.format("No instace with UUID %s exists", referenceUUID.toString());
throw new InvalidQueryException(error);
}
if(element instanceof Vertex) {
EntityManagement<?, ?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
database, (Vertex) element);
String elementType = entityManagement.getTypeName();
if(elementType.compareTo(referenceType) != 0) {
if(polymorphic && getDocumentType().isSubTypeOf(referenceType)) {
// OK
} else {
String error = String.format("Referenced instace with UUID %s is not a %s", referenceUUID, referenceType);
throw new InvalidQueryException(error);
}
}
List<Vertex> vertexes = new ArrayList<>();
vertexes.add((Vertex) 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 = database.browseClass(referenceType, polymorphic);
}
Set<RID> analysed = new HashSet<>();
for(Object r : references) {
Vertex v = (Vertex) r;
boolean skip = false;
// checking if the constraints are satisfied
for(String key : constraint.keySet()) {
String value = constraint.get(key);
Object o = v.get(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<DIRECTION> directions = new ArrayList<>();
if(direction==DIRECTION.BOTH) {
directions.add(DIRECTION.IN);
directions.add(DIRECTION.OUT);
}else {
directions.add(direction);
}
for(DIRECTION d : directions) {
Iterable<Edge> edges = v.getEdges(ElementManagement.opposite(d), relationType);
for(Edge edge : edges) {
Vertex vertex = edge.getVertex(d);
RID vertexRID = vertex.getIdentity();
if(analysed.contains(vertexRID)) {
continue;
}
analysed.add(vertexRID);
if(v.getIdentity().compareTo(vertexRID) == 0) {
continue;
}
DocumentType documentType = ElementManagementUtility.getDocumentType(vertex);
/*
* If the requested type (i.e. elementType)
* differs form the resulting type (i.e. documentType.getName())
* we need to evaluate if polymorphism is requested and
* if the resulting type is a subclass of the requested type
*
*/
if(documentType.getName().compareTo(typeName)!=0) {
if(polymorphic && documentType.isSubTypeOf(typeName)) {
// OK
} else {
// excluding from results
continue;
}
}
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
database, vertex);
try {
if(referenceUUID!=null && entityManagement.getUUID().compareTo(referenceUUID) == 0) {
continue;
}
/*
JsonNode jsonNode;
if(includeRelationInResult) {
RelationManagement<?,?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
database, 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(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -710,8 +548,8 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
}
}
public String reallyQueryTraversal(String relationType, String referenceType, UUID referenceUUID,
DIRECTION direction, boolean polymorphic, Map<String,String> constraint) 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();
@ -719,81 +557,93 @@ 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(ElementManagement.opposite(direction).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);
ResultSet resultSet = database.command("sql", select);
OResultSet resultSet = oDatabaseDocument.command(select, map);
while(resultSet.hasNext()) {
Result oResult = resultSet.next();
Document element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
OResult oResult = resultSet.next();
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
if(polymorphic) {
DocumentType documentType = null;
try {
if(element instanceof Edge) {
continue;
}
documentType = ElementManagementUtility.getDocumentType(element);
} catch(Exception e) {
String error = String.format("Unable to detect type of %s. %s", element.toString(),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error, e);
throw new ResourceRegistryException(error);
}
OVertex vertex = (OVertex) element;
if(documentType.isSubTypeOf(typeName)) {
continue;
}
}
Vertex vertex = (Vertex) element;
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingContext(),
database, vertex);
EntityManagement<?,?> entityManagement = ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
oDatabaseDocument, vertex);
try {
if(constraint.containsKey(Entity.ID_PROPERTY)) {
String uuid = constraint.get(Entity.ID_PROPERTY);
@ -806,7 +656,7 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
arrayNode.add(jsonNode);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
vertex.toString(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -817,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, DIRECTION direction,
boolean polymorphic, Map<String,String> constraint) throws ResourceRegistryException {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
database = workingContext.getRemoteDatabase(PermissionMode.READER);
workingEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = workingEnvironment.getDatabaseDocument(PermissionMode.READER);
setAsEntryPoint();
setOperation(Operation.QUERY);
@ -854,9 +700,9 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
if(relationAccessType == AccessType.CONSISTS_OF) {
if(direction != DIRECTION.OUT) {
if(direction != ODirection.OUT) {
String error = String.format("%s can only goes %s from %s.", relationType,
DIRECTION.OUT.name(), typeName);
ODirection.OUT.name(), typeName);
throw new InvalidQueryException(error);
} else {
if(referenceAccessType != AccessType.FACET) {
@ -870,10 +716,10 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
break;
case FACET:
if(relationAccessType != AccessType.CONSISTS_OF || direction != DIRECTION.IN
if(relationAccessType != AccessType.CONSISTS_OF || direction != ODirection.IN
|| referenceAccessType != AccessType.RESOURCE) {
String error = String.format("%s can only has %s %s from a %s.", typeName,
DIRECTION.IN.name(), ConsistsOf.NAME, Resource.NAME);
ODirection.IN.name(), ConsistsOf.NAME, Resource.NAME);
throw new InvalidQueryException(error);
}
@ -883,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) {
@ -891,12 +736,12 @@ public abstract class EntityManagement<E extends Entity, ET extends EntityType>
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}

View File

@ -11,15 +11,15 @@ 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;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
@ -55,14 +55,14 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}
@Override
protected Vertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
protected OVertex reallyCreate() throws FacetAlreadyPresentException, ResourceRegistryException {
return createVertex();
}
@Override
protected Vertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException {
Vertex facet = getElement();
facet = (Vertex) updateProperties(documentType, facet, jsonNode, ignoreKeys, ignoreStartWithKeys);
protected OVertex reallyUpdate() throws FacetNotFoundException, ResourceRegistryException {
OVertex facet = getElement();
facet = (OVertex) updateProperties(oClass, facet, jsonNode, ignoreKeys, ignoreStartWithKeys);
return facet;
}
@ -70,21 +70,21 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
protected void reallyRemoveFromContext()
throws ContextException, ResourceRegistryException {
if(entryPoint) {
Edge edge = getElement().getEdges(DIRECTION.IN).iterator().next();
OEdge oEdge = getElement().getEdges(ODirection.IN).iterator().next();
consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElement(edge);
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());
Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next();
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
resourceManagement = new ResourceManagement();
resourceManagement.setElement(vertex);
// Not needed resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setElement(oVertex);
// Not needed resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.addToRelationManagements(consistsOfManagement);
}
super.reallyRemoveFromContext();
@ -93,15 +93,15 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
@Override
protected void reallyDelete() throws FacetNotFoundException, ResourceRegistryException {
if(entryPoint) {
Edge edge = getElement().getEdges(DIRECTION.IN).iterator().next();
OEdge oEdge = getElement().getEdges(ODirection.IN).iterator().next();
consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElement(edge);
consistsOfManagement.setElement(oEdge);
consistsOfManagement.setTargetEntityManagement(this);
affectedInstances.put(uuid, consistsOfManagement.serializeAsAffectedInstance());
Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next();
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
resourceManagement = new ResourceManagement();
resourceManagement.setElement(vertex);
resourceManagement.setElement(oVertex);
resourceManagement.addToRelationManagements(consistsOfManagement);
}
@ -125,33 +125,33 @@ 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;
}
RemoteDatabase targetSecurityContextDatabase = null;
ODatabaseDocument targetInstanceEnvironmentODatabaseDocument = null;
try {
if(resourceManagement==null) {
Vertex vertex = getElement().getVertices(DIRECTION.IN).iterator().next();
OVertex oVertex = getElement().getVertices(ODirection.IN).iterator().next();
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElement(vertex);
resourceManagement.setElement(oVertex);
}
switch (operation) {
case CREATE: case DELETE:
resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setDatabase(database);
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
resourceManagement.setODatabaseDocument(oDatabaseDocument);
break;
case ADD_TO_CONTEXT:
resourceManagement.setSourceSecurityContext(sourceSecurityContext);
resourceManagement.setTargetSecurityContext(targetSecurityContext);
resourceManagement.setWorkingContext(targetSecurityContext);
targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER);
resourceManagement.setDatabase(targetSecurityContextDatabase);
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);
targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER);
resourceManagement.setDatabase(targetSecurityContextDatabase );
// Not needed resourceManagement.setSourceInstanceEnvironment(sourceInstanceEnvironment);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
break;
default:
@ -168,9 +168,9 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
}catch (Exception e) {
throw new ResourceRegistryException(e);
}finally {
if(targetSecurityContextDatabase !=null) {
targetSecurityContextDatabase.close();
// database.activateOnCurrentThread();
if(targetInstanceEnvironmentODatabaseDocument!=null) {
targetInstanceEnvironmentODatabaseDocument.close();
oDatabaseDocument.activateOnCurrentThread();
}
}
}
@ -186,8 +186,8 @@ public class FacetManagement extends EntityManagement<Facet, FacetType> {
throw new SchemaViolationException("You cannot create a stand alone Facet");
}
public Vertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
if(entryPoint && operation == Operation.CREATE) {
public OVertex internalCreate() throws AlreadyPresentException, ResourceRegistryException {
if(entryPoint) {
throw new SchemaViolationException("You cannot create a stand alone Facet");
}
return super.internalCreate();

View File

@ -23,24 +23,24 @@ 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;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.RelationManagement;
import org.gcube.informationsystem.resourceregistry.types.CachedType;
import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.properties.LinkedEntity;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
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.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
@ -89,8 +89,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
* ConsistsOf.NAME); TODO Looks for a different query
*/
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
for(Edge edge : edges) {
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(OEdge edge : edges) {
RelationManagement<?,?> relationManagement = getRelationManagement(edge);
relationManagement.setReload(reload);
@ -104,7 +104,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
errorMessage.append("SourceEntityManagement for ");
errorMessage.append(relationManagement.getClass().getSimpleName());
errorMessage.append(" is not the one expected. ");
errorMessage.append(DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
errorMessage.append(OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(errorMessage.toString());
}
@ -114,10 +114,10 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode consistsOf = relationManagement.serializeAsJsonNode();
sourceResource = addConsistsOf(sourceResource, consistsOf);
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw e;
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", edge, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error("Unable to correctly serialize {}. {}", edge, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(e);
}
@ -146,7 +146,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
}
@Override
protected Vertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
protected OVertex reallyCreate() throws ResourceAlreadyPresentException, ResourceRegistryException {
createVertex();
@ -155,8 +155,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode consistOfJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement();
com.setWorkingContext(getWorkingContext());
com.setDatabase(database);
com.setWorkingEnvironment(getWorkingEnvironment());
com.setODatabaseDocument(oDatabaseDocument);
com.setJsonNode(consistOfJsonNode);
com.setSourceEntityManagement(this);
com.internalCreate();
@ -169,8 +169,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement();
irtm.setWorkingContext(getWorkingContext());
irtm.setDatabase(database);
irtm.setWorkingEnvironment(getWorkingEnvironment());
irtm.setODatabaseDocument(oDatabaseDocument);
irtm.setJsonNode(relationJsonNode);
irtm.setSourceEntityManagement(this);
irtm.internalCreate();
@ -182,7 +182,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
}
@Override
protected Vertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
protected OVertex reallyUpdate() throws ResourceNotFoundException, ResourceRegistryException {
getElement();
@ -191,8 +191,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode relationJsonNode : jsonNodeArray) {
ConsistsOfManagement com = new ConsistsOfManagement();
com.setWorkingContext(getWorkingContext());
com.setDatabase(database);
com.setWorkingEnvironment(getWorkingEnvironment());
com.setODatabaseDocument(oDatabaseDocument);
com.setJsonNode(relationJsonNode);
com.internalCreateOrUdate();
addToRelationManagement(com);
@ -204,8 +204,8 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
JsonNode jsonNodeArray = jsonNode.get(property);
for(JsonNode relationJsonNode : jsonNodeArray) {
IsRelatedToManagement irtm = new IsRelatedToManagement();
irtm.setWorkingContext(getWorkingContext());
irtm.setDatabase(database);
irtm.setWorkingEnvironment(getWorkingEnvironment());
irtm.setODatabaseDocument(oDatabaseDocument);
irtm.setJsonNode(relationJsonNode);
irtm.internalUpdate();
addToRelationManagement(irtm);
@ -221,25 +221,25 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
getElement();
Iterable<Edge> iterable = element.getEdges(DIRECTION.OUT);
Iterator<Edge> iterator = iterable.iterator();
Iterable<OEdge> iterable = element.getEdges(ODirection.OUT);
Iterator<OEdge> iterator = iterable.iterator();
while(iterator.hasNext()) {
Edge edge = iterator.next();
DocumentType documentType = ElementManagementUtility.getDocumentType(edge);
OEdge edge = iterator.next();
OClass oClass = ElementManagementUtility.getOClass(edge);
RelationManagement<?,?> relationManagement = null;
if(documentType.isSubTypeOf(IsRelatedTo.NAME)) {
if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
relationManagement = new IsRelatedToManagement();
} else if(documentType.isSubTypeOf(ConsistsOf.NAME)) {
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
relationManagement = new ConsistsOfManagement();
} else {
logger.warn("{} is not a {} nor a {}. {}", DBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME,
ConsistsOf.NAME, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn("{} is not a {} nor a {}. {}", OrientDBUtility.getAsStringForLogging(edge), IsRelatedTo.NAME,
ConsistsOf.NAME, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
if(relationManagement != null) {
relationManagement.setWorkingContext(getWorkingContext());
relationManagement.setDatabase(database);
relationManagement.setWorkingEnvironment(getWorkingEnvironment());
relationManagement.setODatabaseDocument(oDatabaseDocument);
relationManagement.setElement(edge);
relationManagement.internalDelete();
affectedInstances.putAll(relationManagement.getAffectedInstances());
@ -247,7 +247,7 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
}
iterable = element.getEdges(DIRECTION.OUT);
iterable = element.getEdges(ODirection.OUT);
iterator = iterable.iterator();
while(iterator.hasNext()) {
// in relations are affected because is the system which ensure this integrity
@ -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(), database);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
@ -278,16 +278,16 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
*/
if(honourPropagationConstraintsInContextSharing) {
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
int facetCounter = 0;
for(Edge edge : edges) {
for(OEdge edge : edges) {
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) {
@ -315,21 +315,21 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
@Override
public String all(boolean polymorphic) throws ResourceRegistryException {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
database = getWorkingContext().getRemoteDatabase(PermissionMode.READER);
oDatabaseDocument = getWorkingEnvironment().getDatabaseDocument(PermissionMode.READER);
return reallyGetAll(polymorphic);
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
@ -439,9 +439,9 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
Map<LinkedEntity, Integer> satisfiedConsistsOfFacet = new HashMap<>();
Iterable<Edge> edges = getElement().getEdges(DIRECTION.OUT);
Iterable<OEdge> edges = getElement().getEdges(ODirection.OUT);
for(Edge edge : edges) {
for(OEdge edge : edges) {
String id = edge.getIdentity().toString();
RelationManagement<?,?> relationManagement = relationManagements.get(id);
@ -452,17 +452,19 @@ public class ResourceManagement extends EntityManagement<Resource, ResourceType>
case ADD_TO_CONTEXT:
if(relationManagement == null) {
try {
relationManagement = ElementManagementUtility.getRelationManagement(targetSecurityContext, database, 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, database, 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(), database, 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,16 +16,16 @@ 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;
import org.gcube.informationsystem.types.reference.entities.FacetType;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
/**
* @author Luca Frosini (ISTI - CNR)
@ -64,20 +64,20 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
@Override
protected FacetManagement newTargetEntityManagement() throws ResourceRegistryException {
FacetManagement facetManagement = new FacetManagement();
facetManagement.setDatabase(database);
facetManagement.setWorkingContext(getWorkingContext());
facetManagement.setODatabaseDocument(oDatabaseDocument);
facetManagement.setWorkingEnvironment(getWorkingEnvironment());
return facetManagement;
}
@Override
protected Edge reallyCreate() throws ResourceRegistryException {
Edge thisEdge = super.reallyCreate();
protected OEdge reallyCreate() throws ResourceRegistryException {
OEdge thisOEdge = super.reallyCreate();
Vertex target = (Vertex) getTargetEntityManagement().getElement();
OVertex target = (OVertex) getTargetEntityManagement().getElement();
int count = 0;
Iterable<Edge> iterable = target.getEdges(DIRECTION.IN);
Iterator<Edge> iterator = iterable.iterator();
Iterable<OEdge> iterable = target.getEdges(ODirection.IN);
Iterator<OEdge> iterator = iterable.iterator();
while(iterator.hasNext()) {
iterator.next();
++count;
@ -87,7 +87,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
throw new SchemaViolationException("It is not possible to create multiple " + ConsistsOf.NAME + " between the same " + Facet.NAME);
}
return thisEdge;
return thisOEdge;
}
protected void checkResource() throws SchemaViolationException, ResourceRegistryException {
@ -107,7 +107,7 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
return;
}
RemoteDatabase targetSecurityContextDatabase = 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);
targetSecurityContextDatabase = targetSecurityContext.getRemoteDatabase(PermissionMode.READER);
resourceManagement.setDatabase(targetSecurityContextDatabase);
resourceManagement.setTargetInstanceEnvironment(targetInstanceEnvironment);
resourceManagement.setWorkingEnvironment(targetInstanceEnvironment);
targetInstanceEnvironmentODatabaseDocument = targetInstanceEnvironment.getDatabaseDocument(PermissionMode.READER);
resourceManagement.setODatabaseDocument(targetInstanceEnvironmentODatabaseDocument);
break;
default:
@ -140,9 +140,9 @@ public class ConsistsOfManagement extends RelationManagement<FacetManagement, Fa
}catch (Exception e) {
throw new ResourceRegistryException(e);
}finally {
if(targetSecurityContextDatabase!=null) {
targetSecurityContextDatabase.close();
// database.activateOnCurrentThread();
if(targetInstanceEnvironmentODatabaseDocument!=null) {
targetInstanceEnvironmentODatabaseDocument.close();
oDatabaseDocument.activateOnCurrentThread();
}
}
}

View File

@ -17,9 +17,9 @@ 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.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
@ -60,8 +60,8 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
@Override
protected ResourceManagement newTargetEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setDatabase(database);
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
resourceManagement.setODatabaseDocument(oDatabaseDocument);
return resourceManagement;
}
@ -88,10 +88,10 @@ public class IsRelatedToManagement extends RelationManagement<ResourceManagement
}
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw e;
} catch(Exception e) {
logger.error("Unable to correctly serialize {}. {}", element, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
logger.error("Unable to correctly serialize {}. {}", element, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE, e);
throw new ResourceRegistryException(e);
}

View File

@ -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,35 +31,37 @@ 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.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.resourceregistry.utils.PropagationConstraintOrient;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
import com.arcadedb.database.Document;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.Type;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ODirection;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
@ -66,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
@ -106,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
@ -137,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;
}
@ -159,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 */
@ -168,7 +190,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected boolean skipped;
@Override
public Edge getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
public OEdge getElement() throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException {
try {
element = super.getElement();
} catch(NotFoundException e) {
@ -202,7 +224,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
protected Map<String,JsonNode> fullSerialize(Map<String,JsonNode> visitedSourceResources)
throws ResourceRegistryException {
Vertex source = getElement().getVertex(DIRECTION.OUT);
OVertex source = getElement().getVertex(ODirection.OUT);
String id = source.getIdentity().toString();
@ -210,8 +232,8 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
ResourceManagement resourceManagement = null;
if(sourceResource == null) {
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingContext(),
database, source);
resourceManagement = (ResourceManagement) ElementManagementUtility.getEntityManagement(getWorkingEnvironment(),
oDatabaseDocument, source);
if(this instanceof IsRelatedToManagement) {
sourceResource = resourceManagement.createCompleteJsonNode();
} else if(this instanceof ConsistsOfManagement) {
@ -221,7 +243,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else {
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
}
@ -233,7 +255,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} else {
String error = String.format("{%s is not a %s nor a %s. %s", this,
IsRelatedToManagement.class.getSimpleName(), ConsistsOfManagement.class.getSimpleName(),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
throw new ResourceRegistryException(error);
}
@ -242,23 +264,23 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
return visitedSourceResources;
}
protected PropagationConstraintOrient getPropagationConstraint(Document document)
protected PropagationConstraintOrient getPropagationConstraint(ODocument oDocument)
throws ResourceRegistryException {
PropagationConstraintOrient propagationConstraintOrient = new PropagationConstraintOrient();
PropagationConstraint propagationConstraint = null;
if(document == null) {
if(oDocument == null) {
propagationConstraint = defaultPropagationConstraint;
} else if(document instanceof PropagationConstraintOrient) {
propagationConstraint = (PropagationConstraint) document;
} else if(oDocument instanceof PropagationConstraintOrient) {
propagationConstraint = (PropagationConstraint) oDocument;
} else {
try {
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, DBUtility.toJsonString(document));
propagationConstraint = ElementMapper.unmarshal(PropagationConstraint.class, OrientDBUtility.toJsonString(oDocument));
} catch(Exception e) {
logger.warn("Unable to recreate {}. {}", PropagationConstraint.NAME,
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -305,13 +327,13 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
}
protected void checkPropagationConstraint() throws ResourceRegistryException {
Object object = getElement().get(Relation.PROPAGATION_CONSTRAINT_PROPERTY);
PropagationConstraintOrient pc = getPropagationConstraint((Document) object);
((MutableDocument) getElement()).set(Relation.PROPAGATION_CONSTRAINT_PROPERTY, pc, Type.EMBEDDED);
Object object = getElement().getProperty(Relation.PROPAGATION_CONSTRAINT_PROPERTY);
PropagationConstraintOrient pc = getPropagationConstraint((ODocument) object);
getElement().setProperty(Relation.PROPAGATION_CONSTRAINT_PROPERTY, pc, OType.EMBEDDED);
}
@Override
protected Edge reallyCreate() throws ResourceRegistryException {
protected OEdge reallyCreate() throws ResourceRegistryException {
element = super.reallyCreate();
checkPropagationConstraint();
@ -324,8 +346,8 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
@Override
protected ResourceManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setWorkingContext(getWorkingContext());
resourceManagement.setDatabase(database);
resourceManagement.setWorkingEnvironment(getWorkingEnvironment());
resourceManagement.setODatabaseDocument(oDatabaseDocument);
return resourceManagement;
}
@ -370,20 +392,20 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
}
@Override
protected Edge reallyUpdate() throws ResourceRegistryException {
protected OEdge reallyUpdate() throws ResourceRegistryException {
logger.trace("Trying to update {} with UUID {}", typeName, uuid);
logger.trace("Trying to update {} : {}", typeName, jsonNode);
Edge edge = getElement();
updateProperties(documentType, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
OEdge edge = getElement();
updateProperties(oClass, edge, jsonNode, ignoreKeys, ignoreStartWithKeys);
if(accessType.compareTo(AccessType.CONSISTS_OF) == 0) {
JsonNode target = jsonNode.get(Relation.TARGET_PROPERTY);
if(target != null) {
FacetManagement facetManagement = new FacetManagement();
facetManagement.setWorkingContext(getWorkingContext());
facetManagement.setDatabase(database);
facetManagement.setWorkingEnvironment(getWorkingEnvironment());
facetManagement.setODatabaseDocument(oDatabaseDocument);
facetManagement.setJsonNode(target);
facetManagement.internalUpdate();
}
@ -398,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;
@ -408,21 +430,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
AddConstraint addConstraint = AddConstraint.unpropagate;
try {
propagationConstraint = DBUtility.getPropertyDocument(PropagationConstraint.class, element,
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getAddConstraint() != null) {
addConstraint = propagationConstraint.getAddConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.ADD_PROPERTY, DBUtility.getAsStringForException(element),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.ADD_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing AddToContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, DBUtility.getAsStringForException(element),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.warn(error);
throw new ResourceRegistryException(error, e);
}
@ -435,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(), database);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
@ -458,7 +480,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break;
}
}else {
targetSecurityContext.addElement(getElement(), database);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
/*
* DO NOT UNCOMMENT
* // affectedInstances.put(uuid, serializeSelfOnly());
@ -476,14 +498,14 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
reallyAddToContext();
if(!skipped && propagationConstraint.getAddConstraint()==PropagationConstraint.AddConstraint.propagate) {
MetadataUtility.updateModifiedByAndLastUpdate(element);
// element.save();
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
}
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
throw new ResourceRegistryException(
"Error Adding " + typeName + " to " + targetSecurityContext.toString(), e.getCause());
"Error Adding " + typeName + " to " + targetInstanceEnvironment.toString(), e.getCause());
}
}
@ -494,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(), database);
targetInstanceEnvironment.addElement(getElement(), oDatabaseDocument);
affectedInstances.put(uuid, serializeAsAffectedInstance());
}
@ -514,46 +536,46 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
public void addToContext(UUID contextUUID) throws SchemaViolationException, NotFoundException, ContextException, ResourceRegistryException {
String contextFullName = ServerContextCache.getInstance().getContextFullNameByUUID(contextUUID);
logger.debug("Going to add {} with UUID {} to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
database = workingContext.getRemoteDatabase(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();
sanityCheck();
if(!dryRun) {
database.commit();
oDatabaseDocument.commit();
}else {
database.rollback();
oDatabaseDocument.rollback();
}
logger.info("{} with UUID {} successfully added to Context with UUID {} (i.e {})", accessType.getName(), uuid, contextUUID, contextFullName);
} catch(Exception e) {
logger.error("Unable to add {} with UUID {} to Context with UUID {} (i.e. {})", accessType.getName(), uuid,
contextUUID, contextFullName, e);
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ContextException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
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;
}
@ -563,21 +585,21 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
RemoveConstraint removeConstraint = RemoveConstraint.keep;
try {
propagationConstraint = DBUtility.getPropertyDocument(PropagationConstraint.class, element,
propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class, element,
Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getRemoveConstraint() != null) {
removeConstraint = propagationConstraint.getRemoveConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.REMOVE_PROPERTY, DBUtility.getAsStringForException(element),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.REMOVE_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error);
}
} catch(Exception e) {
String error = String.format("Error while getting %s from %s while performing RemoveFromContext. %s",
Relation.PROPAGATION_CONSTRAINT_PROPERTY, DBUtility.getAsStringForException(element),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
Relation.PROPAGATION_CONSTRAINT_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
logger.error(error);
throw new ResourceRegistryException(error, e);
@ -587,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(), database);
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();
}
@ -606,17 +628,17 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break;
case cascadeWhenOrphan:
Vertex target = (Vertex) targetEntityManagement.getElement();
OVertex target = (OVertex) targetEntityManagement.getElement();
Iterable<Edge> iterable = target.getEdges(DIRECTION.IN);
Iterator<Edge> iterator = iterable.iterator();
Iterable<OEdge> iterable = target.getEdges(ODirection.IN);
Iterator<OEdge> iterator = iterable.iterator();
int count = 0;
Edge edge = null;
OEdge edge = null;
while(iterator.hasNext()) {
edge = (Edge) iterator.next();
Edge thisEdge = (Edge) getElement();
if(edge.compareTo(thisEdge) != 0) {
if(thisEdge.getVertex(DIRECTION.OUT).compareTo(edge.getVertex(DIRECTION.OUT)) != 0) {
edge = (OEdge) iterator.next();
OEdge thisOEdge = (OEdge) getElement();
if(edge.compareTo(thisOEdge) != 0) {
if(thisOEdge.getVertex(ODirection.OUT).compareTo(edge.getVertex(ODirection.OUT)) != 0) {
count++;
break;
}
@ -629,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());
@ -653,13 +675,13 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
setOperation(Operation.REMOVE_FROM_CONTEXT);
reallyRemoveFromContext();
MetadataUtility.updateModifiedByAndLastUpdate(element);
// element.save();
element.save();
affectedInstances.put(uuid, serializeAsAffectedInstance());
} catch(ResourceRegistryException e) {
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,48 +689,48 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
public void removeFromContext(UUID contextUUID)
throws NotFoundException, ContextException, ResourceRegistryException {
logger.debug("Going to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
workingContext = ContextUtility.getAdminSecurityContext();
database = workingContext.getRemoteDatabase(PermissionMode.WRITER);
database.begin();
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();
sanityCheck();
if(!dryRun) {
database.commit();
oDatabaseDocument.commit();
}else {
database.rollback();
oDatabaseDocument.rollback();
}
logger.info("{} with UUID {} successfully removed from Context with UUID {}", typeName, uuid, contextUUID);
} catch(ResourceRegistryException e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID);
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw e;
} catch(Exception e) {
logger.error("Unable to remove {} with UUID {} from Context with UUID {}", typeName, uuid, contextUUID,
e);
if(database != null) {
database.rollback();
if(oDatabaseDocument != null) {
oDatabaseDocument.rollback();
}
throw new ContextException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
@ -724,14 +746,14 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
DeleteConstraint deleteConstraint = DeleteConstraint.keep;
try {
PropagationConstraint propagationConstraint = DBUtility.getPropertyDocument(PropagationConstraint.class,
PropagationConstraint propagationConstraint = OrientDBUtility.getPropertyDocument(PropagationConstraint.class,
element, Relation.PROPAGATION_CONSTRAINT_PROPERTY);
if(propagationConstraint.getDeleteConstraint() != null) {
deleteConstraint = propagationConstraint.getDeleteConstraint();
} else {
String error = String.format("%s.%s in %s is null. %s", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
PropagationConstraint.DELETE_PROPERTY, DBUtility.getAsStringForException(element),
DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
PropagationConstraint.DELETE_PROPERTY, OrientDBUtility.getAsStringForException(element),
OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
deleteConstraint = DeleteConstraint.values()[propagationConstraint.getRemoveConstraint().ordinal()];
throw new ResourceRegistryException(error);
@ -739,7 +761,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
} catch(Exception e) {
logger.warn("Error while getting {} from {}. Assuming {}. {}", Relation.PROPAGATION_CONSTRAINT_PROPERTY,
DBUtility.getAsStringForException(element), deleteConstraint, DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.getAsStringForException(element), deleteConstraint, OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
// pre-loading target entity because after deleting the relation we will not be able to get it
@ -757,9 +779,9 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
break;
case cascadeWhenOrphan:
Vertex target = t.getElement();
Iterable<Edge> iterable = target.getEdges(DIRECTION.IN);
Iterator<Edge> iterator = iterable.iterator();
OVertex target = t.getElement();
Iterable<OEdge> iterable = target.getEdges(ODirection.IN);
Iterator<OEdge> iterator = iterable.iterator();
if(iterator.hasNext()) {
logger.trace("{} point to {} which is not orphan. Giving {} directive, it will be keep.", element,
target, deleteConstraint);
@ -779,21 +801,36 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
}
protected Collection<JsonNode> serializeEdges(Iterable<Document> 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(Document d : edges) {
Edge edge = (Edge) d;
if(postFilterPolymorphic && getDocumentType().isSubTypeOf(typeName)) {
for(ODocument d : edges) {
if(++position < offset) {
continue;
}
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingContext(),
database, edge);
OEdge edge = (OEdge) d;
if(postFilterPolymorphic && getOClass().isSubClassOf(typeName)) {
continue;
}
RelationManagement<?, ?> relationManagement = ElementManagementUtility.getRelationManagement(getWorkingEnvironment(),
oDatabaseDocument, edge);
// visitedSourceResources = relationManagement.fullSerialize(visitedSourceResources);
serilizedEdges.add(relationManagement.serializeAsJsonNode());
if(limit > 0 && ++count >= limit) {
break;
}
}
return serilizedEdges;
}
@ -810,7 +847,7 @@ public abstract class RelationManagement<T extends EntityManagement<? extends En
@Override
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
Iterable<Document> edges = database.browseClass(typeName, polymorphic);
Iterable<ODocument> edges = oDatabaseDocument.browseClass(typeName, polymorphic);
Collection<JsonNode> collection = serializeEdges(edges, false);
return serializeJsonNodeCollectionAsString(collection);
}

View File

@ -5,19 +5,20 @@ 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.utils.DBUtility;
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;
import com.arcadedb.database.Document;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -28,38 +29,38 @@ public class QueryImpl implements Query {
@Override
public String query(String query, boolean raw) throws InvalidQueryException {
RemoteDatabase oDatabaseDocument = null;
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
InstanceEnvironment instanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
oDatabaseDocument = securityContext.getRemoteDatabase(PermissionMode.READER);
oDatabaseDocument = instanceEnvironment.getDatabaseDocument(PermissionMode.READER);
oDatabaseDocument.begin();
logger.debug("Going to execute query '{} limit {}'", query);
logger.debug("Going to execute query '{}'", query);
ResultSet resultSet = oDatabaseDocument.command("sql", query);
OResultSet resultSet = oDatabaseDocument.query(query);
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
while(resultSet.hasNext()) {
Result result = resultSet.next();
OResult oResult = resultSet.next();
try {
JsonNode jsonNode = null;
if(raw) {
if(result.isElement()) {
Document element = ElementManagementUtility.getElementFromOptional(result.getElement());
jsonNode = DBUtility.toJsonNode(element);
if(oResult.isElement()) {
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
jsonNode = OrientDBUtility.toJsonNode(element);
}else {
ObjectMapper mapper = new ObjectMapper();
jsonNode = mapper.readTree(DBUtility.toJsonString(result));
jsonNode = mapper.readTree(OrientDBUtility.toJsonString(oResult));
}
} else {
Document element = ElementManagementUtility.getElementFromOptional(result.getElement());
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, oDatabaseDocument,
OElement element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
ElementManagement<?,?> erManagement = ERManagementUtility.getERManagement(instanceEnvironment, oDatabaseDocument,
element);
erManagement.setAsEntryPoint();
jsonNode = erManagement.serializeAsJsonNode();
@ -68,7 +69,7 @@ public class QueryImpl implements Query {
} catch(ResourceRegistryException e) {
logger.error("Unable to correctly serialize {}. It will be excluded from results. {}",
DBUtility.toJsonString(result), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
OrientDBUtility.toJsonString(oResult), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -80,9 +81,9 @@ public class QueryImpl implements Query {
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}

View File

@ -2,38 +2,43 @@ 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.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.utils.TypeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -42,12 +47,10 @@ 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;
protected RemoteDatabase database;
protected ODatabaseDocument oDatabaseDocument;
public JsonQuery() {
this.objectMapper = new ObjectMapper();
@ -98,68 +101,100 @@ 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 {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
database = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
oDatabaseDocument = null;
try {
SecurityContext securityContext = ContextUtility.getCurrentSecurityContext();
InstanceEnvironment instanceEnvironment = ContextUtility.getCurrentRequestEnvironment();
database = securityContext.getRemoteDatabase(PermissionMode.READER);
database.begin();
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));
ResultSet resultSet = database.command("sql", query, map);
OResultSet resultSet = oDatabaseDocument.query(query, map);
ArrayNode arrayNode = objectMapper.createArrayNode();
boolean projection = entryPoint.isProjection();
boolean first = true;
Set<String> keys = new HashSet<>();
while(resultSet.hasNext()) {
Result oResult = resultSet.next();
Document element = ElementManagementUtility.getElementFromOptional(oResult.getElement());
OResult oResult = resultSet.next();
try {
JsonNode jsonNodeResult = null;
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(securityContext, database,
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
for(String key : keys) {
Object value = oResult.getProperty(key);
String requestedType = entryPoint.getType();
String gotType = erManagement.getTypeName();
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());
}
if(requestedType.compareTo(gotType)==0) {
}
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(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
@ -168,12 +203,12 @@ public class JsonQuery {
} catch(Exception e) {
throw new InvalidQueryException(e.getMessage());
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}

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 abstract StringBuffer analize(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException;
public boolean isProjection() {
return projection;
}
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);
}
}
protected StringBuffer addConstraints(JsonNode jsonNode, QueryLogicalOperator queryLogicalOperator, String fieldNamePrefix) throws InvalidQueryException {
public List<JsonQueryERElement> getBreadcrumb() {
return breadcrumb;
}
public void setBreadcrumb(List<JsonQueryERElement> breadcrumb) {
this.breadcrumb = breadcrumb;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getAlias() {
return alias;
}
public String getAlias(boolean generateifNull) {
if(alias==null && generateifNull) {
alias = generateAlias().toString();
}
return alias;
}
protected StringBuffer generateAlias() {
StringBuffer sb = new StringBuffer();
sb.append(type.toLowerCase());
for(JsonQueryERElement elem : breadcrumb) {
sb.append(elem.getPosition());
}
sb.append(this.position);
return sb;
}
/**
* Add a field to emit only if this instance is the entry point
* @param fieldToEmit
*/
protected void addFieldToEmit(String fieldToEmit) {
fieldsToEmit.add(fieldToEmit);
logger.trace("The field to emit ({}) has been added to {} with alias {}", fieldToEmit, this.type, this.alias);
if(!entryPoint) {
logger.trace("The field to emit ({}) will be added to the parent too", fieldToEmit);
breadcrumb.get(breadcrumb.size()-2).addFieldToEmit(fieldToEmit);
}
}
public boolean isTraverseBack() {
return traverseBack;
}
public void setTraverseBack(boolean traverseBack) {
this.traverseBack = traverseBack;
}
public StringBuffer createQuery(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException {
return createMatchQuery(stringBuffer);
}
public abstract StringBuffer createTraversalQuery(StringBuffer stringBuffer) throws SchemaNotFoundException, InvalidQueryException, SchemaException, ResourceRegistryException;
protected StringBuffer addConstraints(JsonNode jsonNode, LogicalOperator queryLogicalOperator, String fieldNamePrefix) throws InvalidQueryException {
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() {
@ -28,38 +36,105 @@ public class JsonQueryIsRelatedTo extends JsonQueryRelation {
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;
}
int size = jsonNode.size();
public StringBuffer createSelect(StringBuffer stringBuffer, boolean wrapInnerQuery) throws SchemaException, ResourceRegistryException {
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT FROM ");
// Remove type from size
--size;
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;
}
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
}
if(matchQuery) {
direction = direction.opposite();
}
}
}else {
if(entryPoint) {
buffer.append("SELECT FROM ");
buffer.append(type);
}
@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 ");
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("V(\"");
buffer.append(requestedResourceType);
buffer.append("\") FROM ( ");
}
buffer.append("TRAVERSE ");
buffer.append(direction.name().toLowerCase());
buffer.append("E(\"");
buffer.append(type);
buffer.append("\") FROM ( ");
buffer.append(stringBuffer);
buffer.append(")");
if(requestedResourceType!=null) {
buffer.append(")");
}
stringBuffer = buffer;
if(sourceJsonNode!=null && targetJsonNode!=null) {
// Target has still to be analised
jsonQueryResource = new JsonQueryResource(targetJsonNode);
jsonQueryResource.setDirection(Direction.IN);
jsonQueryResource.setEntryPoint(false);
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;
buffer.append("E('");
buffer.append(type);
buffer.append("') ");
buffer.append(" { where: ($matched.");
buffer.append(getAlias(true));
buffer.append(" == $currentMatch)}");
}
return stringBuffer;
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,33 +1,46 @@
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.utils.DBUtility;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.graph.Vertex;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -44,14 +57,14 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
this.typeName = QueryTemplate.NAME;
}
public QueryTemplateManagement(RemoteDatabase database) throws ResourceRegistryException {
public QueryTemplateManagement(ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.database = database;
getWorkingContext();
this.oDatabaseDocument = oDatabaseDocument;
getWorkingEnvironment();
}
protected void checkERMatch() throws ResourceRegistryException {
getDocumentType();
getOClass();
}
protected void checkNameMatch() throws ResourceRegistryException {
@ -83,18 +96,18 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
name = jsonNode.get(QueryTemplate.NAME_PROPERTY).asText();
}
} else {
name = element.getString(QueryTemplate.NAME_PROPERTY);
name = element.getProperty(QueryTemplate.NAME_PROPERTY);
}
}
return name;
}
@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
@ -102,7 +115,7 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
try {
JsonNode queryTemplate = serializeSelfAsJsonNode();
ObjectMapper objectMapper = new ObjectMapper();
String templateString = element.getString(QueryTemplate.TEMPLATE_PROPERTY);
String templateString = element.getProperty(QueryTemplate.TEMPLATE_PROPERTY);
JsonNode templateJsonNode = objectMapper.readTree(templateString);
((ObjectNode) queryTemplate).replace(QueryTemplate.TEMPLATE_PROPERTY, templateJsonNode);
return queryTemplate;
@ -127,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();
@ -139,12 +152,18 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
logger.trace("Checking if {} -> {}", errorMessage, select);
ResultSet resultSet = database.command("sql", select.toString());
OResultSet resultSet = oDatabaseDocument.command(select.toString(), new HashMap<>());
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();
@ -168,22 +187,22 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
}
@Override
public Vertex retrieveElement() throws NotFoundException, ResourceRegistryException {
public OVertex retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
StringBuffer select = getSelectQuery();
ResultSet resultSet = database.query("sql", select.toString());
OResultSet resultSet = oDatabaseDocument.query(select.toString(), new HashMap<>());
if(resultSet == null || !resultSet.hasNext()) {
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());
}
Result result = resultSet.next();
Vertex queryTemplate = ElementManagementUtility.getElementFromOptional(result.getVertex());
OResult oResult = resultSet.next();
OVertex queryTemplate = ElementManagementUtility.getElementFromOptional(oResult.getVertex());
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, DBUtility.getAsStringForLogging(queryTemplate));
logger.trace("{} representing vertex is {}", QueryTemplate.NAME, OrientDBUtility.getAsStringForLogging(queryTemplate));
if(resultSet.hasNext()) {
resultSet.close();
@ -202,7 +221,81 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
}
@Override
protected Vertex reallyCreate() throws AlreadyPresentException, InvalidQueryException, ResourceRegistryException {
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 {
checkIfNameAlreadyExists();
tryTemplate();
@ -211,23 +304,23 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}
}
@Override
protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
try {
tryTemplate();
Vertex queryTemplate = getElement();
queryTemplate = (Vertex) updateProperties(documentType, queryTemplate, jsonNode, ignoreKeys, ignoreStartWithKeys);
OVertex queryTemplate = getElement();
queryTemplate = (OVertex) updateProperties(oClass, queryTemplate, jsonNode, ignoreKeys, ignoreStartWithKeys);
return getElement();
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}
@ -236,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
@ -253,16 +348,31 @@ public class QueryTemplateManagement extends EntityElementManagement<QueryTempla
public String reallyGetAll(boolean polymorphic) throws ResourceRegistryException {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
Iterable<Document> iterable = database.browseClass(typeName, polymorphic);
for (Document vertex : iterable) {
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((Vertex) vertex);
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(), DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
vertex.toString(), OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
try {

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,24 +30,26 @@ 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;
import com.arcadedb.graph.Vertex.DIRECTION;
import com.orientechnologies.orient.core.record.ODirection;
/**
* @author Luca Frosini (ISTI - CNR)
@ -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);
@ -127,6 +156,72 @@ public class Access extends BaseRest {
}
}
/*
* GET /access/query-templates
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART)
@Consumes({MediaType.TEXT_PLAIN, ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8})
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String allQueryTemplates() throws NotFoundException, ResourceRegistryException {
logger.info("Requested to read all {}s", QueryTemplate.NAME);
setAccountingMethod(Method.LIST, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
serverRequestInfo.checkLimitOffset();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
return queryTemplateManagement.all(false);
}
/*
* GET /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. GET /access/query-templates/GetAllEServiceWithState
*/
@GET
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String readQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName)
throws NotFoundException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.READ, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.setAllMeta(true);
serverRequestInfo.checkBooleanQueryParameter(ContextPath.INCLUDE_META_QUERY_PARAMETER);
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
return queryTemplateManagement.read();
}
/*
* POST /access/query-templates/{QUERY_TEMPLATE_NAME}
* e.g. POST /access/query-templates/GetAllEServiceWithState
*
* params = { "$state" : "ready" }
*
*/
@POST
@Path(AccessPath.QUERY_TEMPLATES_PATH_PART + "/{" + QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER + "}")
@Produces(ResourceInitializer.APPLICATION_JSON_CHARSET_UTF_8)
public String runQueryTemplate(@PathParam(QueryTemplateManager.QUERY_TEMPLATE_NAME_PATH_PARAMETER) String queryTemplateName, String params)
throws NotFoundException, InvalidQueryException, ResourceRegistryException {
logger.info("Requested {} with name", QueryTemplate.NAME, queryTemplateName);
setAccountingMethod(Method.RUN, QueryTemplate.NAME);
ServerRequestInfo serverRequestInfo = initRequestInfo();
serverRequestInfo.checkAllBooleanQueryParameters();
QueryTemplateManagement queryTemplateManagement = new QueryTemplateManagement();
queryTemplateManagement.setName(queryTemplateName);
queryTemplateManagement.setParams(params);
return queryTemplateManagement.run();
}
/*
* GET /access/instances/{TYPE_NAME}[?polymorphic=true]
* e.g. GET /access/instances/ContactFacet?polymorphic=true
@ -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,16 +466,17 @@ 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;
DIRECTION directionEnum = DIRECTION.OUT;
ODirection directionEnum = ODirection.OUT;
Map<String,String> constraint = new HashMap<>();
@ -414,9 +518,9 @@ public class Access extends BaseRest {
}
}
try {
directionEnum = DIRECTION.valueOf(direction.toUpperCase());
directionEnum = ODirection.valueOf(direction.toUpperCase());
} catch(Exception e) {
String error = String.format("%s is not a valid. Allowed values are %s", direction, DIRECTION.values());
String error = String.format("%s is not a valid. Allowed values are %s", direction, ODirection.values());
throw new InvalidQueryException(error);
}

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;
@ -22,13 +23,32 @@ public class BaseRest {
}
protected ServerRequestInfo initRequestInfo() {
ServerRequestInfo requestInfo = new ServerRequestInfo();
protected void setAccountingMethod(String method) {
CalledMethodProvider.instance.set(method);
}
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)
@ -35,26 +36,46 @@ public class ContextManager extends BaseRest {
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)
@ -37,6 +36,9 @@ 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,19 +10,22 @@ 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
/**
* @author Luca Frosini (ISTI - CNR)
@ -43,7 +46,7 @@ public class CachedType<T extends Type> {
protected final String typeName;
protected DocumentType documentType;
protected OClass oClass;
protected AccessType accessType;
@ -59,21 +62,21 @@ public class CachedType<T extends Type> {
this.typeName = typeName;
}
private DocumentType retrieveDocumentType() throws SchemaException, SchemaNotFoundException, ResourceRegistryException {
RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
RemoteDatabase database = null;
private OClass retrieveOClass() throws SchemaException, SchemaNotFoundException, ResourceRegistryException {
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
ODatabaseDocument oDatabaseDocument = null;
try {
logger.debug("GettingType {} schema", typeName);
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
OMetadata oMetadata = database.getMetadata();
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
try {
DocumentType documentType = oSchema.getClass(typeName);
if(documentType == null) {
OClass oClass = oSchema.getClass(typeName);
if(oClass == null) {
throw new SchemaNotFoundException(typeName + " was not registered");
}
return documentType;
return oClass;
} catch(SchemaNotFoundException snfe) {
throw snfe;
} catch(Exception e) {
@ -84,29 +87,29 @@ public class CachedType<T extends Type> {
} catch(Exception e) {
throw new ResourceRegistryException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
public synchronized void setDocumentType(DocumentType documentType) throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(this.documentType==null) {
this.documentType = documentType;
public synchronized void setOClass(OClass oClass) throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(this.oClass==null) {
this.oClass = oClass;
}
}
private AccessType getAccessTypeFromDocumentType(DocumentType documentType) throws ResourceRegistryException {
private AccessType getAccessTypeFromOClass(OClass oClass) throws ResourceRegistryException {
AccessType[] accessTypes = AccessType.values();
for(int i=accessTypes.length-1; i>=0; i--) {
AccessType accessType = accessTypes[i];
if(documentType.isSubTypeOf(accessType.getName())) {
if(oClass.isSubClassOf(accessType.getName())) {
return accessType;
}
}
@ -120,14 +123,14 @@ public class CachedType<T extends Type> {
// Instead of using getAllSuperClasses() we get just the first level superclasses and so on.
// This allow to have an order list where the first superclass is a a first level superclass.
List<DocumentType> superClasses = internalGetDocumentType().getSuperTypes();
List<OClass> superClasses = internalGetOClass().getSuperClasses();
while(superClasses.size()>0) {
List<DocumentType> toBeAnalysed = new ArrayList<>(superClasses);
List<OClass> toBeAnalysed = new ArrayList<>(superClasses);
superClasses = new ArrayList<>();
for(DocumentType oSuperClass : toBeAnalysed) {
for(OClass oSuperClass : toBeAnalysed) {
String name = oSuperClass.getName();
CachedType<?> cachedType = typesCache.getCachedType(name);
cachedType.setDocumentType(oSuperClass);
cachedType.setOClass(oSuperClass);
if(name.compareTo(DatabaseEnvironment.VERTEX_CLASS_NAME) == 0 || name.compareTo(DatabaseEnvironment.EDGE_CLASS_NAME) == 0
|| name.compareTo(OSecurity.RESTRICTED_CLASSNAME) == 0) {
continue;
@ -137,7 +140,7 @@ public class CachedType<T extends Type> {
continue;
}
allSuperClasses.add(allSuperClasses.size(), name);
superClasses.addAll(oSuperClass.getSuperTypes());
superClasses.addAll(oSuperClass.getSuperClasses());
}
}
return allSuperClasses;
@ -147,32 +150,32 @@ public class CachedType<T extends Type> {
TypesCache typesCache = TypesCache.getInstance();
List<String> allSubClasses = new ArrayList<>();
Collection<DocumentType> subclasses = internalGetDocumentType().getSubTypes();
Collection<OClass> subclasses = internalGetOClass().getSubclasses();
while(subclasses.size()>0) {
List<DocumentType> toBeAnalysed = new ArrayList<>(subclasses);
List<OClass> toBeAnalysed = new ArrayList<>(subclasses);
subclasses = new ArrayList<>();
for(DocumentType oSubClass : toBeAnalysed) {
for(OClass oSubClass : toBeAnalysed) {
String name = oSubClass.getName();
CachedType<?> cachedType = typesCache.getCachedType(name);
cachedType.setDocumentType(oSubClass);
cachedType.setOClass(oSubClass);
allSubClasses.add(allSubClasses.size(), name);
subclasses.addAll(oSubClass.getSubTypes());
subclasses.addAll(oSubClass.getSubclasses());
}
}
return allSubClasses;
}
private DocumentType internalGetDocumentType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(documentType==null) {
documentType = retrieveDocumentType();
private OClass internalGetOClass() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(oClass==null) {
oClass = retrieveOClass();
}
return documentType;
return oClass;
}
@SuppressWarnings("unchecked")
private T internalGetType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
if(type==null) {
ElementManagement<?,?> erManagement = TypeManagement.getTypeManagement(internalGetDocumentType());
ElementManagement<?,?> erManagement = TypeManagement.getTypeManagement(internalGetOClass());
String typeString = erManagement.read();
try {
type = (T) TypeMapper.deserializeTypeDefinition(typeString);
@ -188,7 +191,7 @@ public class CachedType<T extends Type> {
if(type!=null) {
accessType = type.getAccessType();
}else {
accessType = getAccessTypeFromDocumentType(internalGetDocumentType());
accessType = getAccessTypeFromOClass(internalGetOClass());
}
}
return accessType;
@ -209,8 +212,8 @@ public class CachedType<T extends Type> {
}
public synchronized DocumentType getDocumentType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
return internalGetDocumentType();
public synchronized OClass getOClass() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {
return internalGetOClass();
}
public synchronized T getType() throws SchemaNotFoundException, SchemaException, ResourceRegistryException {

View File

@ -1,57 +0,0 @@
package org.gcube.informationsystem.resourceregistry.types;
import java.util.HashMap;
import java.util.Map;
import org.gcube.informationsystem.types.PropertyTypeName.BaseType;
import com.arcadedb.schema.Type;
/**
* @author Luca Frosini (ISTI - CNR)
*
* Create a mapping between OrientDB {@link Type}
* https://orientdb.gitbooks.io/orientdb-manual/content/orientdb.wiki/Types.html
* and {@link BaseType}
*/
public class DBTypeMapping {
protected static final Map<BaseType,Type> IS_BASE_TYPE_TO_DB_TYPE;
protected static final Map<Type,BaseType> DB_TYPE_TO_IS_BASE_TYPE;
static {
IS_BASE_TYPE_TO_DB_TYPE = new HashMap<>();
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.BOOLEAN, Type.BOOLEAN);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.INTEGER, Type.INTEGER);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.SHORT, Type.SHORT);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.LONG, Type.LONG);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.FLOAT, Type.FLOAT);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.DOUBLE, Type.DOUBLE);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.DATE, Type.DATETIME);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.STRING, Type.STRING);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.BINARY, Type.BINARY);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.BYTE, Type.BYTE);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.PROPERTY, Type.EMBEDDED);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.LIST, Type.LIST);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.SET, Type.LIST);
IS_BASE_TYPE_TO_DB_TYPE.put(BaseType.MAP, Type.MAP);
DB_TYPE_TO_IS_BASE_TYPE = new HashMap<>();
for(BaseType baseType : IS_BASE_TYPE_TO_DB_TYPE.keySet()) {
DB_TYPE_TO_IS_BASE_TYPE.put(IS_BASE_TYPE_TO_DB_TYPE.get(baseType), baseType);
}
}
public static Type getDBType(final BaseType baseType) {
return IS_BASE_TYPE_TO_DB_TYPE.get(baseType);
}
public static BaseType getISBaseType(final Type oType) {
return DB_TYPE_TO_IS_BASE_TYPE.get(oType);
}
}

View File

@ -0,0 +1,58 @@
package org.gcube.informationsystem.resourceregistry.types;
import java.util.HashMap;
import java.util.Map;
import org.gcube.informationsystem.types.PropertyTypeName.BaseType;
import com.orientechnologies.orient.core.metadata.schema.OType;
/**
* @author Luca Frosini (ISTI - CNR)
*
* Create a mapping between OrientDB {@link OType}
* https://orientdb.gitbooks.io/orientdb-manual/content/orientdb.wiki/Types.html
* and {@link BaseType}
*/
public class OrientDBTypeMapping {
protected static final Map<BaseType,OType> BASE_TYPE_TO_OTYPE;
protected static final Map<OType,BaseType> OTYPE_TO_BASE_TYPE;
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);
BASE_TYPE_TO_OTYPE.put(BaseType.LONG, OType.LONG);
BASE_TYPE_TO_OTYPE.put(BaseType.FLOAT, OType.FLOAT);
BASE_TYPE_TO_OTYPE.put(BaseType.DOUBLE, OType.DOUBLE);
BASE_TYPE_TO_OTYPE.put(BaseType.DATE, OType.DATETIME);
BASE_TYPE_TO_OTYPE.put(BaseType.STRING, OType.STRING);
BASE_TYPE_TO_OTYPE.put(BaseType.BINARY, OType.BINARY);
BASE_TYPE_TO_OTYPE.put(BaseType.BYTE, OType.BYTE);
BASE_TYPE_TO_OTYPE.put(BaseType.PROPERTY, OType.EMBEDDED);
BASE_TYPE_TO_OTYPE.put(BaseType.LIST, OType.EMBEDDEDLIST);
BASE_TYPE_TO_OTYPE.put(BaseType.SET, OType.EMBEDDEDSET);
BASE_TYPE_TO_OTYPE.put(BaseType.MAP, OType.EMBEDDEDMAP);
OTYPE_TO_BASE_TYPE = new HashMap<>();
for(BaseType baseType : BASE_TYPE_TO_OTYPE.keySet()) {
OTYPE_TO_BASE_TYPE.put(BASE_TYPE_TO_OTYPE.get(baseType), baseType);
}
}
public static OType getOTypeByBaseType(final BaseType baseType) {
return BASE_TYPE_TO_OTYPE.get(baseType);
}
public static BaseType getBaseTypeByOType(final OType oType) {
return OTYPE_TO_BASE_TYPE.get(oType);
}
}

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;
@ -56,9 +55,14 @@ import org.gcube.informationsystem.types.reference.relations.RelationType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.remote.RemoteDatabase;
import com.arcadedb.schema.DocumentType;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.exception.OSchemaException;
import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.OElement;
/**
* @author Luca Frosini (ISTI - CNR)
@ -106,8 +110,8 @@ public class TypeManagement {
}
protected DocumentType getOClass(RemoteDatabase database, String typeName) throws SchemaException {
return database.getClass(typeName);
protected OClass getOClass(OSchema oSchema, String typeName) throws SchemaException {
return oSchema.getClass(typeName);
}
public String getTypeName() {
@ -129,7 +133,7 @@ public class TypeManagement {
}
private static ElementManagement<?,?> getTypeManagement(AccessType accessType, String name) {
ElementManagement<? extends MutableDocument,?> erManagement = null;
ElementManagement<? extends OElement,?> erManagement = null;
switch(accessType) {
case PROPERTY:
@ -159,23 +163,23 @@ public class TypeManagement {
return erManagement;
}
public static ElementManagement<?,?> getTypeManagement(DocumentType documentType) {
public static ElementManagement<?,?> getTypeManagement(OClass oClass) {
ElementManagement<?,?> erManagement = null;
if(documentType.isSubTypeOf(Property.NAME)) {
if(oClass.isSubClassOf(Property.NAME)) {
erManagement = new PropertyTypeDefinitionManagement();
((PropertyTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(documentType.isSubTypeOf(Resource.NAME)) {
((PropertyTypeDefinitionManagement) erManagement).setName(oClass.getName());
} else if(oClass.isSubClassOf(Resource.NAME)) {
erManagement = new ResourceTypeDefinitionManagement();
((ResourceTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(documentType.isSubTypeOf(Facet.NAME)) {
((ResourceTypeDefinitionManagement) erManagement).setName(oClass.getName());
} else if(oClass.isSubClassOf(Facet.NAME)) {
erManagement = new FacetTypeDefinitionManagement();
((FacetTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(documentType.isSubTypeOf(IsRelatedTo.NAME)) {
((FacetTypeDefinitionManagement) erManagement).setName(oClass.getName());
} else if(oClass.isSubClassOf(IsRelatedTo.NAME)) {
erManagement = new IsRelatedToTypeDefinitionManagement();
((IsRelatedToTypeDefinitionManagement) erManagement).setName(documentType.getName());
} else if(documentType.isSubTypeOf(ConsistsOf.NAME)) {
((IsRelatedToTypeDefinitionManagement) erManagement).setName(oClass.getName());
} else if(oClass.isSubClassOf(ConsistsOf.NAME)) {
erManagement = new ConsistsOfTypeDefinitionManagement();
((ConsistsOfTypeDefinitionManagement) erManagement).setName(documentType.getName());
((ConsistsOfTypeDefinitionManagement) erManagement).setName(oClass.getName());
}
return erManagement;
}
@ -192,9 +196,9 @@ public class TypeManagement {
}
}
private String getTypeAsString(DocumentType documentType) throws SchemaException {
private String getTypeAsString(OClass oClass) throws SchemaException {
try {
ElementManagement<?,?> erManagement = getTypeManagement(documentType);
ElementManagement<?,?> erManagement = getTypeManagement(oClass);
return getTypeAsString(erManagement);
} catch(Exception e) {
throw new SchemaException(e);
@ -210,19 +214,19 @@ public class TypeManagement {
}
}
private Type getType(DocumentType documentType) throws SchemaException {
private Type getType(OClass oClass) throws SchemaException {
try {
String typeString = getTypeAsString(documentType);
String typeString = getTypeAsString(oClass);
return TypeMapper.deserializeTypeDefinition(typeString);
} catch(Exception e) {
throw new SchemaException(e);
}
}
protected List<DocumentType> getSuperTypesAndCheckCompliancy(RemoteDatabase database,
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(
@ -231,27 +235,27 @@ public class TypeManagement {
}
}
OMetadata oMetadata = database.getMetadata();
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
List<DocumentType> superTypes = new ArrayList<>();
List<OClass> oSuperclasses = new ArrayList<>();
for(String superClass : superClasses) {
DocumentType superType = getOClass(oSchema, superClass);
if(superType == null) {
OClass oSuperClass = getOClass(oSchema, superClass);
if(oSuperClass == null) {
throw new SchemaNotFoundException("Superclass " + superClass + " does not exists");
}
if(baseType != null) {
if(type.getName().compareTo(baseType) != 0) {
if(!superType.isSubTypeOf(baseType)) {
if(!oSuperClass.isSubClassOf(baseType)) {
throw new RuntimeException(superClass + " is not a subsclass of " + baseType
+ ". Each Superclass MUST be a subclass of " + baseType);
}
}
}
superTypes.add(superType);
oSuperclasses.add(oSuperClass);
}
return superTypes;
return oSuperclasses;
}
private static Set<String> baseElementTypes;
@ -277,7 +281,7 @@ public class TypeManagement {
protected void registerTypeSchema()
throws SchemaAlreadyPresentException, SchemaException {
RemoteDatabase database = null;
ODatabaseDocument oDatabaseDocument = null;
try {
if(typeName.compareTo(type.getName()) != 0) {
@ -287,24 +291,24 @@ public class TypeManagement {
throw new SchemaCreationException(error);
}
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
OMetadata oMetadata = database.getMetadata();
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
DocumentType documentType = null;
OClass oClass = null;
AccessType accessType = type.getAccessType();
Class<? extends Element> typeClass = accessType.getTypeClass();
String typeName = type.getName();
if(EntityElement.class.isAssignableFrom(typeClass)) {
documentType = database.createVertexClass(typeName);
oClass = oDatabaseDocument.createVertexClass(typeName);
} else if(RelationElement.class.isAssignableFrom(typeClass)) {
documentType = database.createEdgeClass(typeName);
oClass = oDatabaseDocument.createEdgeClass(typeName);
} else if(PropertyElement.class.isAssignableFrom(typeClass)) {
documentType = oSchema.createClass(typeName);
oClass = oSchema.createClass(typeName);
} else {
String error = String.format("Allowed superclass are %s, %s, %s, or any subclasses of them.",
Entity.NAME, Relation.NAME, Property.NAME);
@ -316,7 +320,7 @@ public class TypeManagement {
String description = type.getDescription();
if(description != null && description.compareTo("") != 0) {
try {
documentType.setDescription(description);
oClass.setDescription(description);
} catch(Exception e) {
logger.warn(
"Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
@ -324,9 +328,9 @@ public class TypeManagement {
}
try {
// documentType.setAbstract(false); // Used to allow to persist Schema in Context
// oClass.setAbstract(false); // Used to allow to persist Schema in Context
// Management
documentType.setAbstract(type.isAbstract());
oClass.setAbstract(type.isAbstract());
} catch(Exception e) {
logger.error(
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
@ -334,9 +338,9 @@ public class TypeManagement {
}
if(!baseElementTypes.contains(type.getName())) {
List<DocumentType> oSuperclasses = getSuperTypesAndCheckCompliancy(database, type,
List<OClass> oSuperclasses = getSuperclassesAndCheckCompliancy(oDatabaseDocument, type,
accessType.getName());
documentType.setSuperClasses(oSuperclasses);
oClass.setSuperClasses(oSuperclasses);
}
if(!(type instanceof ResourceType)) {
@ -355,22 +359,22 @@ 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;
// }
// }
com.arcadedb.schema.Type oType = DBTypeMapping.getDBType(propertyTypeName.getBaseType());
OType oType = OrientDBTypeMapping.getOTypeByBaseType(propertyTypeName.getBaseType());
com.arcadedb.schema.Property op = documentType.createProperty(propertyDefinition.getName(), oType);
OProperty op = oClass.createProperty(propertyDefinition.getName(), oType);
op.setDescription(propertyDefinition.getDescription());
/*
@ -389,7 +393,7 @@ public class TypeManagement {
if (propertyTypeName.isGenericType()) {
if (propertyTypeName.getGenericClassName() != null) {
DocumentType linkedClass = getOClass(oSchema, propertyTypeName.getGenericClassName());
OClass linkedClass = getOClass(oSchema, propertyTypeName.getGenericClassName());
if (linkedClass == null) {
logger.trace("Class {} not found.", propertyTypeName.getGenericClassName());
@ -404,8 +408,8 @@ public class TypeManagement {
op.setLinkedClass(linkedClass);
} else {
OType linkedOType = DBTypeMapping
.getDBType(propertyTypeName.getGenericBaseType());
OType linkedOType = OrientDBTypeMapping
.getOTypeByBaseType(propertyTypeName.getGenericBaseType());
op.setLinkedType(OType.getById(Integer.valueOf(linkedOType.ordinal()).byteValue()));
}
@ -414,7 +418,7 @@ public class TypeManagement {
}
}
database.commit();
oDatabaseDocument.commit();
logger.info("{} {} registered successfully", accessType.getName(), type.getName());
} catch(Exception e) {
@ -431,14 +435,14 @@ public class TypeManagement {
} catch(Exception ex) {
throw new SchemaCreationException(ex);
} finally {
database.close();
oDatabaseDocument.close();
}
}
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;
@ -449,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;
@ -461,26 +465,26 @@ public class TypeManagement {
protected void updateTypeSchema(Type actualTypeDefinition, Type newTypeDefinition, AccessType baseElementAccessType)
throws SchemaNotFoundException, SchemaException {
RemoteDatabase database = null;
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.WRITER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.WRITER);
OMetadata oMetadata = database.getMetadata();
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
DocumentType documentType = oSchema.getClass(typeName);
if(documentType == null) {
OClass oClass = oSchema.getClass(typeName);
if(oClass == null) {
throw new SchemaNotFoundException(typeName + " does not Exists");
}
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());
}
@ -490,7 +494,7 @@ public class TypeManagement {
String description = newTypeDefinition.getDescription();
if(description != null && description.compareTo("") != 0) {
try {
documentType.setDescription(description);
oClass.setDescription(description);
} catch(Exception e) {
logger.warn(
"Unable to set description. This is an orient bug. See https://github.com/orientechnologies/orientdb/issues/7065");
@ -498,9 +502,9 @@ public class TypeManagement {
}
try {
// documentType.setAbstract(false); // Used to allow to persist Schema in Context
// oClass.setAbstract(false); // Used to allow to persist Schema in Context
// Management
documentType.setAbstract(newTypeDefinition.isAbstract());
oClass.setAbstract(newTypeDefinition.isAbstract());
} catch(Exception e) {
logger.error(
"Unable to set the Vertex Type {} as abstract. This is an OrientDB <= 2.2.12 bug. The Type will be created as it is not abstract.",
@ -542,7 +546,7 @@ public class TypeManagement {
}
PropertyTypeName newPropertyTypeName = ((PropertyDefinitionImpl) newPropertyDefinition).getPropertyTypeName();
com.arcadedb.schema.Type dbType = DBTypeMapping.getDBType(newPropertyTypeName.getBaseType());
OType oType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getBaseType());
/*
* Excluding EMBEDDEDLIST and EMBEDDEDSET
@ -550,8 +554,8 @@ public class TypeManagement {
*
*/
if(!typeList.contains(newTypeDefinition.getName())) {
switch(dbType) {
case LIST:
switch(oType) {
case EMBEDDEDLIST:
throw new UnsupportedDataTypeException(OType.EMBEDDEDLIST
+ " support is currently disabled due to OrientDB bug see https://github.com/orientechnologies/orientdb/issues/7354");
case EMBEDDEDSET:
@ -562,15 +566,15 @@ public class TypeManagement {
}
}
com.arcadedb.schema.Property dbProperty;
OProperty op;
if(actualPropertyDefinition!=null) {
// The property already exists and has changed (the check has been performed few lines above).
dbProperty = documentType.getProperty(propertyName);
op = oClass.getProperty(propertyName);
}else {
dbProperty = documentType.createProperty(propertyName, dbType);
op = oClass.createProperty(propertyName, oType);
}
dbProperty.setDescription(newPropertyDefinition.getDescription());
op.setDescription(newPropertyDefinition.getDescription());
/*
* Mandatory and notNull does not work in distributed mode: so that on Type
@ -579,16 +583,16 @@ public class TypeManagement {
* ovp.setNotNull(property.isNotnull()); This information are persisted in
* Management Context
*/
dbProperty.setMandatory(false);
dbProperty.setNotNull(false);
op.setMandatory(false);
op.setNotNull(false);
dbProperty.setReadonly(newPropertyDefinition.isReadonly());
dbProperty.setRegexp(newPropertyDefinition.getRegexp());
op.setReadonly(newPropertyDefinition.isReadonly());
op.setRegexp(newPropertyDefinition.getRegexp());
if (newPropertyTypeName.isGenericType()) {
if (newPropertyTypeName.getGenericClassName() != null) {
DocumentType linkedClass = getOClass(oSchema, newPropertyTypeName.getGenericClassName());
OClass linkedClass = getOClass(oSchema, newPropertyTypeName.getGenericClassName());
if (linkedClass == null) {
logger.trace("Class {} not found.", newPropertyTypeName.getGenericClassName());
@ -601,10 +605,10 @@ public class TypeManagement {
"A PropertyType cannot be an Entity type or a Relation type");
}
dbProperty.setLinkedClass(linkedClass);
op.setLinkedClass(linkedClass);
} else {
com.arcadedb.schema.Type linkedOType = DBTypeMapping.getDBType(newPropertyTypeName.getGenericBaseType());
dbProperty.setLinkedType(Type.getById(Integer.valueOf(linkedOType.ordinal()).byteValue()));
OType linkedOType = OrientDBTypeMapping.getOTypeByBaseType(newPropertyTypeName.getGenericBaseType());
op.setLinkedType(OType.getById(Integer.valueOf(linkedOType.ordinal()).byteValue()));
}
}
@ -617,12 +621,12 @@ public class TypeManagement {
// Removing old properties which are no more present in the new type definition
for(String propertyNameToRemove : actualPropertyDefinitionMap.keySet()) {
documentType.dropProperty(propertyNameToRemove);
oClass.dropProperty(propertyNameToRemove);
}
}
database.commit();
oDatabaseDocument.commit();
logger.info("{} {} updated successfully", baseElementAccessType.getName(), newTypeDefinition.getName());
} catch(Exception e) {
@ -636,30 +640,30 @@ public class TypeManagement {
} catch(Exception ex) {
throw new SchemaException(ex);
} finally {
database.close();
oDatabaseDocument.close();
}
}
protected List<Type> getSchema(boolean includeSubtypes) throws SchemaNotFoundException, SchemaException {
RemoteDatabase database = null;
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
OMetadata oMetadata = database.getMetadata();
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
DocumentType baseDocumentType = oSchema.getClass(typeName);
if(baseDocumentType == null) {
OClass baseOClass = oSchema.getClass(typeName);
if(baseOClass == null) {
throw new SchemaNotFoundException(typeName + " does not Exists");
}
List<Type> typeDefinitions = new ArrayList<>();
typeDefinitions.add(getType(baseDocumentType));
typeDefinitions.add(getType(baseOClass));
if(includeSubtypes) {
Collection<DocumentType> subClasses = baseDocumentType.getAllSubclasses();
for(DocumentType documentType : subClasses) {
typeDefinitions.add(getType(documentType));
Collection<OClass> subClasses = baseOClass.getAllSubclasses();
for(OClass oClass : subClasses) {
typeDefinitions.add(getType(oClass));
}
}
@ -671,8 +675,8 @@ public class TypeManagement {
} catch(Exception e) {
throw new SchemaException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
}
}
@ -782,20 +786,24 @@ public class TypeManagement {
}
protected boolean delete(AccessType accessType) throws SchemaException, SchemaNotFoundException{
RemoteDatabase database = null;
ODatabaseDocument oDatabaseDocument = null;
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
database = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
oDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
OMetadata oMetadata = database.getMetadata();
OMetadata oMetadata = oDatabaseDocument.getMetadata();
OSchema oSchema = oMetadata.getSchema();
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();
}
database.commit();
oDatabaseDocument.commit();
return true;
} catch(SchemaException e) {
@ -811,8 +819,8 @@ public class TypeManagement {
} catch(Exception e) {
throw new SchemaException(e);
} finally {
if(database != null) {
database.close();
if(oDatabaseDocument != null) {
oDatabaseDocument.close();
}
}
}

View File

@ -1,5 +1,6 @@
package org.gcube.informationsystem.resourceregistry.types.entities;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@ -12,19 +13,19 @@ 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.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.base.entities.EntityElementManagement;
import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.graph.Vertex;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -47,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) {
@ -65,7 +66,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
name = jsonNode.get(EntityType.NAME_PROPERTY).asText();
}
} else {
name = element.getString(EntityType.NAME_PROPERTY);
name = element.getProperty(EntityType.NAME_PROPERTY);
}
}
return name;
@ -77,16 +78,16 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
}
@Override
protected Vertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
protected OVertex reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", this.typeName, getName());
return createVertex();
}
@Override
protected Vertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected OVertex reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", this.typeName, getName());
Vertex entityTypeDefinition = getElement();
entityTypeDefinition = (Vertex) updateProperties(documentType, entityTypeDefinition, jsonNode, ignoreKeys,
OVertex entityTypeDefinition = getElement();
entityTypeDefinition = (OVertex) updateProperties(oClass, entityTypeDefinition, jsonNode, ignoreKeys,
ignoreStartWithKeys);
return entityTypeDefinition;
}
@ -98,7 +99,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
}
@Override
public Vertex getElement() throws NotFoundException, ResourceRegistryException {
public OVertex getElement() throws NotFoundException, ResourceRegistryException {
if (element == null) {
try {
element = retrieveElement();
@ -119,7 +120,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
}
@Override
public Vertex retrieveElement() throws NotFoundException, ResourceRegistryException {
public OVertex retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if (getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
@ -128,7 +129,7 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
String select = "SELECT FROM " + typeName + " WHERE " + EntityType.NAME_PROPERTY + " = \"" + getName()
+ "\"";
ResultSet resultSet = database.command("sql", select);
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if (resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", typeName, getName());
@ -136,10 +137,10 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
throw new NotFoundException(error);
}
Result oResult = resultSet.next();
Vertex element = (Vertex) ElementManagementUtility.getElementFromOptional(oResult.getElement());
OResult oResult = resultSet.next();
OVertex element = (OVertex) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
if (resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -157,24 +158,24 @@ public abstract class EntityTypeDefinitionManagement<E extends EntityType> exten
}
@Override
protected Vertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
protected OVertex createVertex() throws EntityAlreadyPresentException, ResourceRegistryException {
logger.trace("Going to create {} for {} ({}) using {}", Vertex.class.getSimpleName(), accessType.getName(),
logger.trace("Going to create {} for {} ({}) using {}", OVertex.class.getSimpleName(), accessType.getName(),
typeName, jsonNode);
try {
this.element = database.newVertex(typeName);
this.element = oDatabaseDocument.newVertex(typeName);
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", Vertex.class.getSimpleName(), DBUtility.getAsStringForLogging(element));
logger.debug("Created {} is {}", OVertex.class.getSimpleName(), OrientDBUtility.getAsStringForLogging(element));
return element;
} catch (ResourceRegistryException e) {
throw e;
} catch (Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", Vertex.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", OVertex.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}

View File

@ -1,5 +1,6 @@
package org.gcube.informationsystem.resourceregistry.types.properties;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@ -11,25 +12,26 @@ 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.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.utils.DBUtility;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class PropertyTypeDefinitionManagement extends ElementManagement<Document, PropertyType<?>> {
public class PropertyTypeDefinitionManagement extends ElementManagement<OElement, PropertyType> {
private static Logger logger = LoggerFactory.getLogger(PropertyTypeDefinitionManagement.class);
@ -40,10 +42,10 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
this.typeName = PropertyType.NAME;
}
public PropertyTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database) throws ResourceRegistryException {
public PropertyTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument) throws ResourceRegistryException {
this();
this.database = database;
setWorkingContext(securityContext);
this.oDatabaseDocument = oDatabaseDocument;
setWorkingEnvironment(typeEnvironment);
}
@Override
@ -52,11 +54,11 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
}
@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) {
@ -70,7 +72,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
name = jsonNode.get(PropertyType.NAME_PROPERTY).asText();
}
} else {
name = element.getString(PropertyType.NAME_PROPERTY);
name = element.getProperty(PropertyType.NAME_PROPERTY);
}
}
return name;
@ -82,16 +84,16 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
}
@Override
protected Document reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
protected OElement reallyCreate() throws AlreadyPresentException, ResourceRegistryException {
logger.debug("Going to create {} for {}", PropertyType.NAME, getName());
return createElement();
}
@Override
protected Document reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected OElement reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", PropertyType.NAME, getName());
Document propertyTypeDefinition = getElement();
propertyTypeDefinition = updateProperties(documentType, propertyTypeDefinition, jsonNode,
OElement propertyTypeDefinition = getElement();
propertyTypeDefinition = updateProperties(oClass, propertyTypeDefinition, jsonNode,
ignoreKeys, ignoreStartWithKeys);
return propertyTypeDefinition;
}
@ -103,7 +105,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
}
@Override
public Document getElement() throws NotFoundException, ResourceRegistryException {
public OElement getElement() throws NotFoundException, ResourceRegistryException {
if(element == null) {
try {
element = retrieveElement();
@ -124,7 +126,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
}
@Override
public Document retrieveElement() throws NotFoundException, ResourceRegistryException {
public OElement retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if(getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
@ -133,7 +135,7 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
String select = "SELECT FROM " + typeName + " WHERE " + PropertyType.NAME_PROPERTY + " = \""
+ getName() + "\"";
ResultSet resultSet = database.query("sql", select);
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", typeName, getName());
@ -141,10 +143,10 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
throw new NotFoundException(error);
}
Result oResult = resultSet.next();
Document element = (Document) ElementManagementUtility.getElementFromOptional(oResult.getElement());
OResult oResult = resultSet.next();
OElement element = (OElement) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -161,19 +163,19 @@ public class PropertyTypeDefinitionManagement extends ElementManagement<Document
}
}
protected Document createElement() throws AlreadyPresentException, ResourceRegistryException {
protected OElement createElement() throws AlreadyPresentException, ResourceRegistryException {
try {
this.element = database.newDocument(typeName);
this.element = new ODocument(typeName);
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
logger.debug("Created {} is {}", PropertyType.NAME, DBUtility.getAsStringForLogging(element));
logger.debug("Created {} is {}", PropertyType.NAME, OrientDBUtility.getAsStringForLogging(element));
return element;
} catch(ResourceRegistryException e) {
throw e;
} catch(Exception e) {
logger.trace("Error while creating {} for {} ({}) using {}", Document.class.getSimpleName(),
logger.trace("Error while creating {} for {} ({}) using {}", OElement.class.getSimpleName(),
accessType.getName(), typeName, jsonNode, e);
throw new ResourceRegistryException("Error Creating " + typeName + " with " + jsonNode, e.getCause());
}

View File

@ -2,12 +2,12 @@ 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;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/**
* @author Luca Frosini (ISTI - CNR)
@ -20,17 +20,17 @@ public class ConsistsOfTypeDefinitionManagement
this.typeName = ConsistsOfType.NAME;
}
public ConsistsOfTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database)
public ConsistsOfTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument)
throws ResourceRegistryException {
super(securityContext, database, 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.setDatabase(database);
ftdm.setWorkingEnvironment(getWorkingEnvironment());
ftdm.setODatabaseDocument(oDatabaseDocument);
return ftdm;
}

View File

@ -2,12 +2,12 @@ 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;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/**
* @author Luca Frosini (ISTI - CNR)
@ -20,17 +20,17 @@ public class IsRelatedToTypeDefinitionManagement
this.typeName = IsRelatedToType.NAME;
}
public IsRelatedToTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database)
public IsRelatedToTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument)
throws ResourceRegistryException {
super(securityContext, database, 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.setDatabase(database);
rtdm.setWorkingEnvironment(getWorkingEnvironment());
rtdm.setODatabaseDocument(oDatabaseDocument);
return rtdm;
}

View File

@ -1,5 +1,6 @@
package org.gcube.informationsystem.resourceregistry.types.relations;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@ -14,22 +15,22 @@ 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.SecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.TypeSecurityContext;
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.DBUtility;
import org.gcube.informationsystem.resourceregistry.utils.OrientDBUtility;
import org.gcube.informationsystem.types.reference.entities.EntityType;
import org.gcube.informationsystem.types.reference.entities.ResourceType;
import org.gcube.informationsystem.types.reference.relations.RelationType;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
@ -45,11 +46,11 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
this.forceIncludeAllMeta = true;
}
public RelationTypeDefinitionManagement(SecurityContext securityContext, RemoteDatabase database,
public RelationTypeDefinitionManagement(TypeEnvironment typeEnvironment, ODatabaseDocument oDatabaseDocument,
Class<TT> clz) throws ResourceRegistryException {
this(clz);
this.database = database;
setWorkingContext(securityContext);
this.oDatabaseDocument = oDatabaseDocument;
setWorkingEnvironment(typeEnvironment);
}
@Override
@ -58,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) {
@ -76,14 +77,14 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
name = jsonNode.get(RelationType.NAME_PROPERTY).asText();
}
} else {
name = element.getString(RelationType.NAME_PROPERTY);
name = element.getProperty(RelationType.NAME_PROPERTY);
}
}
return name;
}
@Override
protected Edge reallyCreate() throws ResourceRegistryException {
protected OEdge reallyCreate() throws ResourceRegistryException {
logger.debug("Going to create {} for {}", RelationType.NAME, getName());
if (sourceEntityManagement == null) {
if (!jsonNode.has(Relation.SOURCE_PROPERTY)) {
@ -106,23 +107,23 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
targetEntityManagement.setJsonNode(jsonNode.get(Relation.TARGET_PROPERTY));
}
Vertex source = (Vertex) getSourceEntityManagement().getElement();
Vertex target = (Vertex) getTargetEntityManagement().getElement();
OVertex source = (OVertex) getSourceEntityManagement().getElement();
OVertex target = (OVertex) getTargetEntityManagement().getElement();
logger.trace("Creating {} beetween {} -> {}", typeName, source.toString(), target.toString());
element = source.newEdge(typeName, target, true);
element = oDatabaseDocument.newEdge(source, target, typeName);
updateProperties(documentType, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
updateProperties(oClass, element, jsonNode, ignoreKeys, ignoreStartWithKeys);
return element;
}
@Override
protected Edge reallyUpdate() throws NotFoundException, ResourceRegistryException {
protected OEdge reallyUpdate() throws NotFoundException, ResourceRegistryException {
logger.debug("Going to update {} for {}", RelationType.NAME, getName());
Edge relationTypeDefinition = getElement();
relationTypeDefinition = (Edge) updateProperties(documentType, relationTypeDefinition, jsonNode, ignoreKeys,
OEdge relationTypeDefinition = getElement();
relationTypeDefinition = (OEdge) updateProperties(oClass, relationTypeDefinition, jsonNode, ignoreKeys,
ignoreStartWithKeys);
return relationTypeDefinition;
@ -135,7 +136,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
}
@Override
public Edge getElement() throws NotFoundException, ResourceRegistryException {
public OEdge getElement() throws NotFoundException, ResourceRegistryException {
if (element == null) {
try {
element = retrieveElement();
@ -156,7 +157,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
}
@Override
public Edge retrieveElement() throws NotFoundException, ResourceRegistryException {
public OEdge retrieveElement() throws NotFoundException, ResourceRegistryException {
try {
if (getName() == null) {
throw new NotFoundException("null name does not allow to retrieve the Element");
@ -165,7 +166,7 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
String select = "SELECT FROM " + typeName + " WHERE " + RelationType.NAME_PROPERTY + " = \"" + getName()
+ "\"";
ResultSet resultSet = database.query("sql",select);
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if (resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with name %s was found", typeName, getName());
@ -173,10 +174,10 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
throw new NotFoundException(error);
}
Result oResult = resultSet.next();
Edge element = (Edge) ElementManagementUtility.getElementFromOptional(oResult.getElement());
OResult oResult = resultSet.next();
OEdge element = (OEdge) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", typeName, getName(), DBUtility.getAsStringForLogging(element));
logger.trace("{} with id {} is : {}", typeName, getName(), OrientDBUtility.getAsStringForLogging(element));
if (resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + typeName + " with name " + getName()
@ -211,8 +212,8 @@ public abstract class RelationTypeDefinitionManagement<T extends EntityTypeDefin
@Override
protected ResourceTypeDefinitionManagement newSourceEntityManagement() throws ResourceRegistryException {
ResourceTypeDefinitionManagement rtdm = new ResourceTypeDefinitionManagement();
rtdm.setWorkingContext(getWorkingContext());
rtdm.setDatabase(database);
rtdm.setWorkingEnvironment(getWorkingEnvironment());
rtdm.setODatabaseDocument(oDatabaseDocument);
return rtdm;
}

View File

@ -1,142 +0,0 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.relations.Relation;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.contexts.ContextUtility;
import org.gcube.informationsystem.resourceregistry.contexts.security.AdminSecurityContext;
import org.gcube.informationsystem.resourceregistry.contexts.security.SecurityContext.PermissionMode;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.database.MutableEmbeddedDocument;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.Vertex;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.remote.RemoteDatabase;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class DBUtility {
private static final Logger logger = LoggerFactory.getLogger(DBUtility.class);
public static final String DB_TYPE_PROPERTY = "@type";
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JsonNode toJsonNode(Document document) throws ResourceRegistryException {
try {
ObjectMapper objectMapper = new ObjectMapper();
String string = toJsonString(document);
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(string);
return objectNode;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static String replaceType(String s) {
s = s.replace("\"" + DB_TYPE_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\"");
return s;
}
public static String toJsonString(Document document) {
String ret = document.toJSON().toString();
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
}
public static String getAsStringForLogging(Document document) {
return document.toJSON().toString();
}
public static String getAsStringForException(Document document) {
return toJsonString(document);
}
public static <El extends Document> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
RemoteDatabase adminDatabase = null;
// RemoteDatabase current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
AdminSecurityContext adminSecurityContext = ContextUtility.getAdminSecurityContext();
adminDatabase = adminSecurityContext.getRemoteDatabase(PermissionMode.READER);
return DBUtility.getElementByUUID(adminDatabase, elementType, uuid, clz);
} finally {
if(adminDatabase != null) {
adminDatabase.close();
}
// if(current!=null) {
// current.activateOnCurrentThread();
// }
}
}
public static <El extends Document> El getElementByUUID(RemoteDatabase database, String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
if(elementType == null || elementType.compareTo("") == 0) {
if(Vertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME;
}
if(Edge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME;
}
}
// TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE " + IdentifiableElement.ID_PROPERTY + " = \"" + uuid.toString() + "\"";
ResultSet resultSet = database.command("sql", select);
if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with UUID %s was found", elementType, uuid.toString());
logger.debug(error);
throw new NotFoundException(error);
}
Result result = resultSet.next();
@SuppressWarnings("unchecked")
El element = (El) ElementManagementUtility.getElementFromOptional(result.getElement());
logger.trace("{} with id {} is : {}", elementType, uuid.toString(), DBUtility.getAsStringForLogging(element));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
+ ". This is a fatal error please contact Admnistrator");
}
return element;
}
public static <P extends PropertyElement> P getPropertyDocument(Class<P> clz, Document element, String property)
throws ResourceRegistryException {
try {
MutableEmbeddedDocument document = (MutableEmbeddedDocument) element.getEmbedded(property);
P e = ElementMapper.unmarshal(clz, DBUtility.toJsonString(document));
return e;
} catch(Exception ex) {
String error = String.format("Error while getting %s from %s", property, getAsStringForException(element));
throw new ResourceRegistryException(error, ex);
}
}
}

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;
@ -15,12 +14,12 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.arcadedb.database.MutableDocument;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class EncryptedOrient extends MutableDocument implements Encrypted {
public class EncryptedOrient extends ODocument implements Encrypted {
public static final String NAME = "Encrypted";
public static final String VALUE = "value";
@ -46,7 +45,7 @@ public class EncryptedOrient extends MutableDocument 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) {
@ -62,11 +61,11 @@ public class EncryptedOrient extends MutableDocument implements Encrypted {
}
public String getEncryptedValue() {
return this.getString(EncryptedOrient.VALUE);
return this.field(EncryptedOrient.VALUE);
}
public void setEncryptedValue(String encryptedValue) {
this.set(EncryptedOrient.VALUE, encryptedValue);
this.field(EncryptedOrient.VALUE, encryptedValue);
}
public String getDecryptedValue() {
@ -133,7 +132,7 @@ public class EncryptedOrient extends MutableDocument implements Encrypted {
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = DBUtility.replaceType(ret);
ret = OrientDBUtility.replaceType(ret);
return ret;
}

View File

@ -5,8 +5,6 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.lucene.document.Document;
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;
@ -14,12 +12,12 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.arcadedb.database.MutableDocument;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class MetadataOrient extends MutableDocument implements Metadata {
public class MetadataOrient extends ODocument implements Metadata {
public MetadataOrient() {
super(Metadata.NAME);
@ -38,7 +36,7 @@ public class MetadataOrient extends MutableDocument 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) {
@ -112,7 +110,7 @@ public class MetadataOrient extends MutableDocument implements Metadata {
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = DBUtility.replaceType(ret);
ret = OrientDBUtility.replaceType(ret);
return ret;
}

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;
@ -18,9 +19,8 @@ import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.database.Document;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.database.MutableEmbeddedDocument;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
@ -30,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() {
@ -64,7 +65,7 @@ public class MetadataUtility {
return null;
}
MetadataOrient metadata = new MetadataOrient();
metadataNode.set(DBUtility.DB_TYPE_PROPERTY, metadataNode.get(Element.TYPE_PROPERTY));
metadataNode.set(OrientDBUtility.ORIENTDB_CLASS_PROPERTY, metadataNode.get(Element.TYPE_PROPERTY));
metadataNode.remove(Element.TYPE_PROPERTY);
metadata.fromJSON(metadataNode.toString());
return metadata;
@ -72,13 +73,13 @@ public class MetadataUtility {
return null;
}
public static MetadataOrient getMetadataOrient(Document document) throws ResourceRegistryException {
if(document instanceof MetadataOrient) {
return (MetadataOrient) document;
public static MetadataOrient getMetadataOrient(ODocument oDocument) throws ResourceRegistryException {
if(oDocument instanceof MetadataOrient) {
return (MetadataOrient) oDocument;
} else {
try {
MetadataOrient metadataOrient = new MetadataOrient();
String json = DBUtility.toJsonString(document);
String json = OrientDBUtility.toJsonString(oDocument);
Metadata metadata = ElementMapper.unmarshal(Metadata.class, json);
metadataOrient.setCreatedBy(metadata.getCreatedBy());
metadataOrient.setCreationTime(metadata.getCreationTime());
@ -87,28 +88,28 @@ public class MetadataUtility {
return metadataOrient;
} catch(Exception e) {
throw new ResourceRegistryException(
"Unable to recreate Metadata. " + DBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
"Unable to recreate Metadata. " + OrientDBUtility.SHOULD_NOT_OCCUR_ERROR_MESSAGE);
}
}
}
public static Metadata addMetadata(Document element) {
public static Metadata addMetadata(OElement element) {
Metadata metadata = createMetadata();
((MutableDocument) element).set(IdentifiableElement.METADATA_PROPERTY, metadata);
element.setProperty(IdentifiableElement.METADATA_PROPERTY, metadata);
return metadata;
}
public static Metadata getMetadata(Document element) throws ResourceRegistryException {
return DBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY);
public static Metadata getMetadata(OElement element) throws ResourceRegistryException {
return OrientDBUtility.getPropertyDocument(Metadata.class, element, IdentifiableElement.METADATA_PROPERTY);
}
public static void updateModifiedByAndLastUpdate(Document element) throws ResourceRegistryException {
MutableEmbeddedDocument document = (MutableEmbeddedDocument) element.getEmbedded(IdentifiableElement.METADATA_PROPERTY);
public static void updateModifiedByAndLastUpdate(OElement element) throws ResourceRegistryException {
ODocument oDocument = element.getProperty(IdentifiableElement.METADATA_PROPERTY);
String lastUpdateBy = getUser();
document.set(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
oDocument.field(Metadata.LAST_UPDATE_BY_PROPERTY, lastUpdateBy);
Date lastUpdateTime = Calendar.getInstance().getTime();
document.set(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
((MutableDocument) element).set(IdentifiableElement.METADATA_PROPERTY, document);
oDocument.field(Metadata.LAST_UPDATE_TIME_PROPERTY, lastUpdateTime);
element.setProperty(IdentifiableElement.METADATA_PROPERTY, oDocument);
}
}

View File

@ -0,0 +1,159 @@
package org.gcube.informationsystem.resourceregistry.utils;
import java.util.HashMap;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.informationsystem.base.reference.Element;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.base.reference.properties.PropertyElement;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.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.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;
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.ORecord;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class OrientDBUtility {
private static final Logger logger = LoggerFactory.getLogger(OrientDBUtility.class);
public static final String ORIENTDB_CLASS_PROPERTY = ODocumentHelper.ATTRIBUTE_CLASS;
public static final String SHOULD_NOT_OCCUR_ERROR_MESSAGE = "This is really strange and should not occur. Please contact the system administrator.";
public static JsonNode toJsonNode(OElement element) throws ResourceRegistryException {
ORecord oRecord = element.getRecord();
return OrientDBUtility.toJsonNode(oRecord);
}
public static JsonNode toJsonNode(ORecord oRecord) throws ResourceRegistryException {
try {
ObjectMapper objectMapper = new ObjectMapper();
String string = toJsonString(oRecord);
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(string);
return objectNode;
} catch(Exception e) {
throw new ResourceRegistryException(e);
}
}
public static String replaceType(String s) {
s = s.replace("\"" + ORIENTDB_CLASS_PROPERTY + "\"", "\"" + Element.TYPE_PROPERTY + "\"");
return s;
}
public static String toJsonString(OResult oResult) {
String ret = oResult.toJSON();
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
}
public static String toJsonString(ORecord oRecord) {
String ret = oRecord.toJSON("class");
// The above method set the type in @class property
// We want to use the property set in Element.TYPE_PROPERTY
ret = replaceType(ret);
return ret;
}
public static String getAsStringForLogging(ORecord oRecord) {
return oRecord.toJSON();
}
public static String getAsStringForException(ORecord oRecord) {
return toJsonString(oRecord);
}
public static <El extends OElement> El getElementByUUIDAsAdmin(String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
ODatabaseDocument adminDatabaseDocument = null;
ODatabaseDocument current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
try {
current = ContextUtility.getCurrentODatabaseDocumentFromThreadLocal();
AdminEnvironment adminEnvironment = AdminEnvironment.getInstance();
adminDatabaseDocument = adminEnvironment.getDatabaseDocument(PermissionMode.READER);
return OrientDBUtility.getElementByUUID(adminDatabaseDocument, elementType, uuid, clz);
} finally {
if(adminDatabaseDocument != null) {
adminDatabaseDocument.close();
}
if(current!=null) {
current.activateOnCurrentThread();
}
}
}
public static <El extends OElement> El getElementByUUID(ODatabaseDocument oDatabaseDocument, String elementType, UUID uuid,
Class<? extends El> clz) throws NotFoundException, ResourceRegistryException {
if(elementType == null || elementType.compareTo("") == 0) {
if(OVertex.class.isAssignableFrom(clz)) {
elementType = Entity.NAME;
}
if(OEdge.class.isAssignableFrom(clz)) {
elementType = Relation.NAME;
}
}
// TODO Rewrite using Gremlin
String select = "SELECT FROM " + elementType + " WHERE " + IdentifiableElement.ID_PROPERTY + " = \"" + uuid.toString() + "\"";
OResultSet resultSet = oDatabaseDocument.query(select, new HashMap<>());
if(resultSet == null || !resultSet.hasNext()) {
String error = String.format("No %s with UUID %s was found", elementType, uuid.toString());
logger.debug(error);
throw new NotFoundException(error);
}
OResult oResult = resultSet.next();
@SuppressWarnings("unchecked")
El element = (El) ElementManagementUtility.getElementFromOptional(oResult.getElement());
logger.trace("{} with id {} is : {}", elementType, uuid.toString(), OrientDBUtility.getAsStringForLogging(element));
if(resultSet.hasNext()) {
throw new ResourceRegistryException("Found more than one " + elementType + " with uuid " + uuid.toString()
+ ". This is a fatal error please contact Admnistrator");
}
return element;
}
public static <P extends PropertyElement> P getPropertyDocument(Class<P> clz, OElement element, String property)
throws ResourceRegistryException {
try {
ODocument oDocument = element.getProperty(property);
P e = ElementMapper.unmarshal(clz, OrientDBUtility.toJsonString(oDocument));
return e;
} catch(Exception ex) {
String error = String.format("Error while getting %s from %s", property, getAsStringForException(element));
throw new ResourceRegistryException(error, ex);
}
}
}

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;
@ -12,12 +11,12 @@ import org.gcube.informationsystem.resourceregistry.types.TypesCache;
import org.gcube.informationsystem.types.reference.properties.PropertyType;
import org.gcube.informationsystem.utils.TypeUtility;
import com.arcadedb.database.MutableDocument;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class PropagationConstraintOrient extends MutableDocument implements PropagationConstraint {
public class PropagationConstraintOrient extends ODocument implements PropagationConstraint {
public PropagationConstraintOrient() {
super(PropagationConstraint.NAME);
@ -36,7 +35,7 @@ public class PropagationConstraintOrient extends MutableDocument implements Prop
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) {
@ -104,7 +103,7 @@ public class PropagationConstraintOrient extends MutableDocument implements Prop
@Override
public String toJSON(String iFormat) {
String ret = super.toJSON(iFormat);
ret = DBUtility.replaceType(ret);
ret = OrientDBUtility.replaceType(ret);
return ret;
}

View File

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

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;
@ -42,11 +41,12 @@ public class ContextTest {
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,19 +18,22 @@ 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;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
/**
* @author Luca Frosini (ISTI - CNR)
@ -80,47 +85,47 @@ public class ContextManagementTest extends ContextTest {
}
protected void roleUserAssertions(UUID uuid, UUID oldParentUUID, boolean deleted) throws ResourceRegistryException {
ContextSecurityContext contextSecurityContext = ContextSecurityContext.getInstance();
ContextEnvironment contextEnvironment = ContextEnvironment.getInstance();
RemoteDatabase database = contextSecurityContext.getRemoteDatabase(PermissionMode.READER);
// OSecurity oSecurity = oDatabaseDocument.getMetadata().getSecurity();
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);
Role oRole = oSecurity.getRole(role);
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);
User oUser = oSecurity.getUser(user);
String user = instanceEnvironment.getSecurityRoleOrUserName(permissionMode, SecurityType.USER, hierarchic);
OUser oUser = oSecurity.getUser(user);
Assert.assertEquals(oUser == null, deleted);
if(oUser != null) {
Assert.assertTrue(oUser.hasRole(oRole.getName(), false));
}
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);
User parentOUser = oSecurity.getUser(parentUser);
OUser parentOUser = oSecurity.getUser(parentUser);
Assert.assertTrue(parentOUser != null);
Assert.assertEquals(parentOUser.hasRole(oRole.getName(), false), !deleted);
parent = parent.getParentSecurityContext();
parent = (InstanceEnvironment) parent.getParentEnvironment();
}
}
@ -163,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();
@ -439,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);
@ -447,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) {
@ -466,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();
@ -525,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) {
@ -535,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,15 +1,16 @@
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;
import org.slf4j.LoggerFactory;
import com.arcadedb.remote.RemoteDatabase;
import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
/**
* @author Luca Frosini (ISTI - CNR)
@ -18,19 +19,21 @@ public class DatabaseEnvironmentTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseEnvironmentTest.class);
// @Test
public void createDB() throws Exception{
logger.trace("Created DB is {}:{}/{}", DatabaseEnvironment.HOST, DatabaseEnvironment.PORT, DatabaseEnvironment.DB);
@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 {
RemoteDatabase database = ContextUtility.getAdminSecurityContext().getRemoteDatabase(PermissionMode.WRITER);
String dateTime = database.get(ATTRIBUTES.DATETIMEFORMAT).toString();
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;
@ -115,6 +123,8 @@ public class ERManagementTest extends ContextTest {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
requestInfo.setLimit(1000);
requestInfo.setOffset(0);
}
public static SoftwareFacet getSoftwareFacet() {
@ -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);
Assert.assertTrue(createdUUID != null);
if(identifiableElement.getID()!=null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID())==0);
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 != null) {
if(metadata.getCreatedBy()!=null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy())==0);
}else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser())==0);
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);
@ -307,9 +326,9 @@ public class ERManagementTest extends ContextTest {
checkUUIDAndMetadata(facet, gotFacet);
Class<? extends Facet> clz = facet.getClass();
Class<? extends Facet> gotClz = gotFacet.getClass();
Assert.assertTrue(clz==gotClz);
Assert.assertTrue(clz == gotClz);
if(clz == SoftwareFacet.class) {
if (clz == SoftwareFacet.class) {
checkSoftwareFacetAssertion((SoftwareFacet) facet, (SoftwareFacet) gotFacet);
}
}
@ -322,9 +341,10 @@ public class ERManagementTest extends ContextTest {
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();
@ -334,7 +354,6 @@ public class ERManagementTest extends ContextTest {
}
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
@ -343,14 +362,13 @@ public class ERManagementTest extends ContextTest {
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());
@ -359,7 +377,7 @@ public class ERManagementTest extends ContextTest {
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());
}
@ -370,24 +388,23 @@ public class ERManagementTest extends ContextTest {
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();
@ -417,9 +434,10 @@ public class ERManagementTest extends ContextTest {
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);
@ -448,19 +466,18 @@ public class ERManagementTest extends ContextTest {
}
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);
}
@ -487,13 +504,12 @@ public class ERManagementTest extends ContextTest {
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);
@ -503,28 +519,24 @@ public class ERManagementTest extends ContextTest {
}
/*
@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);
}
@ -554,7 +566,8 @@ public class ERManagementTest extends ContextTest {
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();
@ -671,15 +684,15 @@ 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();
@ -697,7 +710,7 @@ public class ERManagementTest extends ContextTest {
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
} catch (Throwable e) {
throw e;
}finally {
} finally {
deleteResource(eService);
}
}
@ -730,4 +743,125 @@ public class ERManagementTest extends ContextTest {
logger.debug("{}", ret);
}
protected List<ERElement> getPaginatedInstances(Class<? extends ERElement> clz, int offset, int limit) throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setOffset(offset);
requestInfo.setLimit(limit);
ElementManagement<?,?> erManagement = 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

@ -30,8 +30,11 @@ import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arcadedb.graph.Vertex.DIRECTION;
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();
@ -136,16 +139,16 @@ public class MultiContextTest extends ERManagementTest {
@SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getIncomingIsRelatedTo(Resource r) throws Exception {
return getIsRelatedTo(r, DIRECTION.OUT);
return getIsRelatedTo(r, ODirection.OUT);
}
@SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getOutcomingIsRelatedTo(Resource r) throws Exception {
return getIsRelatedTo(r, DIRECTION.IN);
return getIsRelatedTo(r, ODirection.IN);
}
@SuppressWarnings("rawtypes")
protected List<IsRelatedTo> getIsRelatedTo(Resource r, DIRECTION direction) throws Exception {
protected List<IsRelatedTo> getIsRelatedTo(Resource r, ODirection oDirection) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(Resource.NAME);
@ -153,7 +156,7 @@ public class MultiContextTest extends ERManagementTest {
UUID resourceUUID = r.getID();
// resourceManagement.setUUID(resourceUUID);
String ret = resourceManagement.query(IsRelatedTo.NAME, resourceType, resourceUUID, direction, true,
String ret = resourceManagement.query(IsRelatedTo.NAME, resourceType, resourceUUID, oDirection, true,
new HashMap<>());
List<IsRelatedTo> isRelatedToList = ElementMapper.unmarshalList(IsRelatedTo.class, ret);
return isRelatedToList;
@ -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);
}
}
}

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