Compare commits

...

22 Commits

Author SHA1 Message Date
Luca Frosini f932721e5f Removed uneeded import 2024-05-24 10:58:29 +02:00
luca.frosini 1168cb3bbf Added support for paginated result 2023-11-09 19:17:37 +01:00
luca.frosini d8cb6081bf Removed -SNAPSHOT for release 2023-07-21 14:30:19 +02:00
luca.frosini d643e3cfe6 Ignored MacOs File 2023-06-21 11:45:58 +02:00
Luca Frosini 1061c80911 Added missing query parameters to requests 2023-05-05 12:22:23 +02:00
Luca Frosini 0b6700cd40 Fixed code to comply with uuid property rename to id 2023-04-28 11:49:46 +02:00
Luca Frosini 1bd0ecfffa Changed '@class' to 'type' 2023-04-26 21:45:56 +02:00
Luca Frosini 12a38af3e8 Migrated code to reorganized E/R format ref. #24992 2023-04-26 10:49:39 +02:00
Luca Frosini 563024eea5 Porting code to redesigned E/R format 2023-04-19 11:38:42 +02:00
Luca Frosini b53f9e9b25 Redesigning E/R instance definition 2023-04-18 17:53:01 +02:00
Luca Frosini 38b3d0bbb7 Removed -SNAPSHOT to release the component 2023-03-03 12:09:53 +01:00
Luca Frosini b6aef097c1 Merge branch 'master' of gitea@code-repo.d4science.org:gCubeSystem/resource-registry-query-template-client.git 2023-03-02 14:53:15 +01:00
Luca Frosini c371748ca7 Added facilities to use the client outside of container 2023-03-02 14:52:37 +01:00
Luca Frosini 23c715a204 Added addHeader in the interface 2023-03-01 14:25:31 +01:00
Luca Frosini ac4b3ac056 Fixed changelog 2023-02-27 18:55:12 +01:00
Luca Frosini 18df6a0257 Added the possibility to create a client instance by context 2023-02-27 18:55:03 +01:00
Luca Frosini b0c8db59ee Added the possibility for a client to add additional HTTP headers 2023-02-27 18:26:44 +01:00
Luca Frosini e7fa9ab604 common-utility 1.X.X has been renamed to common-utility-sg3 2023-02-24 14:57:43 +01:00
Luca Frosini 3bdb961fdb Added usage of common-utility 2023-02-22 15:15:38 +01:00
Luca Frosini ed772b366d authorization-utils added as test dependency 2023-02-16 16:00:34 +01:00
Luca Frosini e4d10b92f2 Enhanced gcube-bom version 2023-02-10 15:33:17 +01:00
Luca Frosini 01dac78793 Fixed method signature 2022-12-13 11:20:23 +01:00
9 changed files with 285 additions and 165 deletions

2
.gitignore vendored
View File

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

View File

@ -2,6 +2,25 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Resource Registry Query Template Client
## [v1.2.0-SNAPSHOT]
- Added support for paginated results [#24648]
## [v1.1.1]
- Migrated code to reorganized E/R format [#24992]
## [v1.1.0]
- Fixed result of run from List<Entity> to List<ERElement>
- Enhanced gcube-bom version
- Added usage of common-utility to overcome issues with different Smartgears version (i.e. 3 and 4)
- Added the possibility for a client to add additional HTTP headers
- Added the possibility to create a client instance by specifying context
## [v1.0.0]
- First Release

18
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-query-template-client</artifactId>
<version>1.0.0</version>
<version>1.2.0-SNAPSHOT</version>
<name>Resource Registry Query Template Client</name>
<description>Resource Registry Query Template Client is a library designed to interact with Resource Registry Query Template APIs</description>
@ -30,7 +30,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-bom</artifactId>
<version>2.1.0</version>
<version>2.4.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -38,14 +38,6 @@
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-api</artifactId>
@ -79,5 +71,11 @@
<artifactId>gcube-model</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-utils</artifactId>
<version>[2.2.0, 3.0.0-SNAPSHOT)</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -3,17 +3,20 @@ package org.gcube.informationsystem.resourceregistry.queries.templates;
import java.util.List;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
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.request.RequestInfo;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public interface ResourceRegistryQueryTemplateClient {
public interface ResourceRegistryQueryTemplateClient extends RequestInfo {
public void addHeader(String name, String value);
public List<QueryTemplate> all() throws ResourceRegistryException;
public QueryTemplate create(QueryTemplate queryTemplate) throws QueryTemplateAlreadyPresentException, ResourceRegistryException;
@ -36,15 +39,15 @@ public interface ResourceRegistryQueryTemplateClient {
public String runGetString(String name) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends Entity> List<E> run(String name) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends ERElement> List<E> run(String name) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends Entity> List<E> run(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends ERElement> List<E> run(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException;
public String run(String name, String params) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends Entity> List<E> run(String name, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends ERElement> List<E> run(String name, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends Entity> List<E> run(QueryTemplate queryTemplate, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException;
public <E extends ERElement> List<E> run(QueryTemplate queryTemplate, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException;
public boolean delete(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException;

View File

@ -1,8 +1,5 @@
package org.gcube.informationsystem.resourceregistry.queries.templates;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.resourceregistry.api.Constants;
import org.gcube.informationsystem.resourceregistry.api.rest.ServiceInstance;
import org.slf4j.Logger;
@ -14,20 +11,25 @@ import org.slf4j.LoggerFactory;
public class ResourceRegistryQueryTemplateClientFactory {
private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryQueryTemplateClientFactory.class);
public static String getResourceRegistryURL() {
String address = String.format("%s/%s", ServiceInstance.getServiceURL(),Constants.SERVICE_NAME);
return address;
}
public static String getCurrentContextFullName() {
String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null;
try {
authorizationEntry = org.gcube.common.authorization.client.Constants.authorizationService().get(token);
} catch(Exception e) {
return ScopeProvider.instance.get();
}
return authorizationEntry.getContext();
public static String getResourceRegistryURL(String context) {
String address = String.format("%s/%s", ServiceInstance.getServiceURL(context),Constants.SERVICE_NAME);
return address;
}
public static ResourceRegistryQueryTemplateClient create() {
String address = String.format("%s/%s", ServiceInstance.getServiceURL(),Constants.SERVICE_NAME);
String address = getResourceRegistryURL();
logger.trace("The {} will be contacted at {}", Constants.SERVICE_NAME, address);
return new ResourceRegistryQueryTemplateClientImpl(address);
}
public static ResourceRegistryQueryTemplateClient create(String context) {
String address = getResourceRegistryURL(context);
logger.trace("The {} will be contacted at {}", Constants.SERVICE_NAME, address);
return new ResourceRegistryQueryTemplateClientImpl(address);
}

View File

@ -1,48 +1,126 @@
package org.gcube.informationsystem.resourceregistry.queries.templates;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gcube.com.fasterxml.jackson.databind.JavaType;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.common.gxhttp.reference.GXConnection;
import org.gcube.common.gxhttp.request.GXHTTPStringRequest;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.common.http.GXHTTPUtility;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
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.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath;
import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPUtility;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistryQueryTemplateClient {
public class ResourceRegistryQueryTemplateClientImpl extends BaseRequestInfo implements ResourceRegistryQueryTemplateClient {
private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryQueryTemplateClientImpl.class);
private static final String ACCEPT_HTTP_HEADER_KEY = "Accept";
private static final String CONTENT_TYPE_HTTP_HEADER_KEY = "Content-Type";
protected final String address;
protected Map<String, String> headers;
private void addOptionalQueryParameters(Map<String,String> queryParams) throws UnsupportedEncodingException {
addIncludeMeta(queryParams);
addIncludeAllMeta(queryParams);
}
private GXHTTPStringRequest includeAdditionalQueryParameters(GXHTTPStringRequest gxHTTPStringRequest) throws UnsupportedEncodingException{
Map<String,String> queryParams = new HashMap<>();
return includeAdditionalQueryParameters(gxHTTPStringRequest, queryParams);
}
private GXHTTPStringRequest includeAdditionalQueryParameters(GXHTTPStringRequest gxHTTPStringRequest, Map<String,String> queryParams) throws UnsupportedEncodingException{
if(queryParams==null) {
queryParams = new HashMap<>();
}
addOptionalQueryParameters(queryParams);
return gxHTTPStringRequest.queryParams(queryParams);
}
private void addIncludeMeta(Map<String,String> queryParams) throws UnsupportedEncodingException{
if(includeMeta) {
queryParams.put(AccessPath.INCLUDE_META_QUERY_PARAMETER, Boolean.toString(includeMeta));
}
}
private void addIncludeAllMeta(Map<String,String> queryParams) throws UnsupportedEncodingException{
if(allMeta) {
queryParams.put(AccessPath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER, Boolean.toString(allMeta));
}
}
private void addOffset(Map<String,String> queryParams) throws UnsupportedEncodingException{
if(offset!=null) {
queryParams.put(AccessPath.OFFSET_QUERY_PARAMETER, offset.toString());
}
}
private void addLimit(Map<String,String> queryParams) throws UnsupportedEncodingException{
if(limit!=null) {
queryParams.put(AccessPath.LIMIT_QUERY_PARAMETER, limit.toString());
}
}
@Override
public void addHeader(String name, String value) {
headers.put(name, value);
}
protected GXHTTPStringRequest getGXHTTPStringRequest() {
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPUtility.getGXHTTPStringRequest(address);
gxHTTPStringRequest.from(this.getClass().getSimpleName());
for(String name : headers.keySet()) {
gxHTTPStringRequest.header(name, headers.get(name));
}
return gxHTTPStringRequest;
}
public ResourceRegistryQueryTemplateClientImpl(String address) {
this.address = address;
this.headers = new HashMap<>();
this.hierarchicalMode = false;
this.includeContexts = false;
this.includeMeta = false;
this.allMeta = false;
}
@Override
public List<QueryTemplate> all() throws ResourceRegistryException {
try {
logger.trace("Going to list {}s", QueryTemplate.NAME);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
Map<String,String> parameters = new HashMap<>();
addIncludeMeta(parameters);
addIncludeAllMeta(parameters);
addOffset(parameters);
addLimit(parameters);
gxHTTPStringRequest.queryParams(parameters);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.get();
String all = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -79,13 +157,17 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
logger.trace("Going to create: {}", queryTemplate);
QueryTemplate qt = ElementMapper.unmarshal(QueryTemplate.class, queryTemplate);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header("Content-type", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header(CONTENT_TYPE_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
gxHTTPStringRequest.path(qt.getName());
Map<String,String> parameters = new HashMap<>();
addIncludeMeta(parameters);
addIncludeAllMeta(parameters);
gxHTTPStringRequest.queryParams(parameters);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.put(queryTemplate);
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -103,9 +185,8 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
public boolean exist(String queryTemplateName) throws ResourceRegistryException {
try {
logger.trace("Going to read {} with name {}", QueryTemplate.NAME, queryTemplateName);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
gxHTTPStringRequest.path(queryTemplateName);
@ -147,12 +228,16 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
public String readAsString(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException {
try {
logger.trace("Going to read {} with name {}", QueryTemplate.NAME, queryTemplateName);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
gxHTTPStringRequest.path(queryTemplateName);
Map<String,String> parameters = new HashMap<>();
addIncludeMeta(parameters);
addIncludeAllMeta(parameters);
gxHTTPStringRequest.queryParams(parameters);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.get();
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -184,13 +269,18 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
logger.trace("Going to update: {}", queryTemplate);
QueryTemplate qt = ElementMapper.unmarshal(QueryTemplate.class, queryTemplate);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header("Content-type", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header(CONTENT_TYPE_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
gxHTTPStringRequest.path(qt.getName());
Map<String,String> parameters = new HashMap<>();
addIncludeMeta(parameters);
addIncludeAllMeta(parameters);
gxHTTPStringRequest.queryParams(parameters);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.put(queryTemplate);
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -210,10 +300,10 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
}
@Override
public <E extends Entity> List<E> run(String name) throws QueryTemplateNotFoundException, ResourceRegistryException {
public <E extends ERElement> List<E> run(String name) throws QueryTemplateNotFoundException, ResourceRegistryException {
try {
String ret = runGetString(name);
JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, Entity.class);
JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, ERElement.class);
return ElementMapper.getObjectMapper().readValue(ret, type);
} catch(ResourceRegistryException e) {
throw e;
@ -223,7 +313,7 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
}
@Override
public <E extends Entity> List<E> run(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException {
public <E extends ERElement> List<E> run(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException {
return run(queryTemplate.getName());
}
@ -237,13 +327,14 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
logger.trace("Going to run {} with the following parameters {}", QueryTemplate.NAME, params);
}
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header("Content-type", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header(CONTENT_TYPE_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
gxHTTPStringRequest.path(name);
includeAdditionalQueryParameters(gxHTTPStringRequest);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.post(params);
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -257,11 +348,11 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
}
@Override
public <E extends Entity> List<E> run(String name, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException {
public <E extends ERElement> List<E> run(String name, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException {
try {
ObjectMapper objectMapper = new ObjectMapper();
String ret = run(name, objectMapper.writeValueAsString(jsonNode));
JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, Entity.class);
JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, ERElement.class);
return ElementMapper.getObjectMapper().readValue(ret, type);
} catch(ResourceRegistryException e) {
throw e;
@ -271,7 +362,7 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
}
@Override
public <E extends Entity> List<E> run(QueryTemplate queryTemplate, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException {
public <E extends ERElement> List<E> run(QueryTemplate queryTemplate, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException {
return run(queryTemplate.getName(), jsonNode);
}
@ -284,9 +375,8 @@ public class ResourceRegistryQueryTemplateClientImpl implements ResourceRegistry
public boolean delete(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException {
try {
logger.trace("Going to delete {} with name {}", QueryTemplate.NAME, queryTemplateName);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryQueryTemplateClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART);
gxHTTPStringRequest.path(queryTemplateName);

View File

@ -7,14 +7,15 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.gcube.common.authorization.client.Constants;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.authorization.utils.manager.SecretManager;
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.informationsystem.model.reference.properties.Metadata;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
@ -22,78 +23,107 @@ import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
@SuppressWarnings("deprecation")
public class ContextTest {
private static final Logger logger = LoggerFactory.getLogger(ContextTest.class);
protected static Properties properties;
protected static final String PROPERTIES_FILENAME = "token.properties";
protected static final String CONFIG_INI_FILENAME = "config.ini";
public static final String PARENT_DEFAULT_TEST_SCOPE;
public static final String DEFAULT_TEST_SCOPE;
public static final String ALTERNATIVE_TEST_SCOPE;
public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER;
public static final String GCUBE;
public static final String DEVNEXT;
public static final String NEXTNEXT;
public static final String DEVSEC;
public static final String DEVVRE;
protected static final Properties properties;
protected static final String CLIENT_ID_PROPERTY_KEY = "client_id";
protected static final String CLIENT_SECRET_PROPERTY_KEY = "client_secret";
protected static final String clientID;
protected static final String clientSecret;
protected static final String REGISTRY_PROPERTIES_FILENAME = "registry.properties";
public static final String RESOURCE_REGISTRY_URL_PROPERTY = "RESOURCE_REGISTRY_URL";
public static final String RESOURCE_REGISTRY_URL;
static {
properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
GCUBE = "/gcube";
DEVNEXT = GCUBE + "/devNext";
NEXTNEXT = DEVNEXT + "/NextNext";
DEVSEC = GCUBE + "/devsec";
DEVVRE = DEVSEC + "/devVRE";
PARENT_DEFAULT_TEST_SCOPE = "/gcube";
DEFAULT_TEST_SCOPE = DEVNEXT;
ALTERNATIVE_TEST_SCOPE = NEXTNEXT;
properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(CONFIG_INI_FILENAME);
try {
// load the properties file
properties.load(input);
} catch(IOException e) {
clientID = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
clientSecret = properties.getProperty(CLIENT_SECRET_PROPERTY_KEY);
RESOURCE_REGISTRY_URL = properties.getProperty(RESOURCE_REGISTRY_URL_PROPERTY);
} catch (IOException e) {
throw new RuntimeException(e);
}
// PARENT_DEFAULT_TEST_SCOPE = "/pred4s"
// DEFAULT_TEST_SCOPE_NAME = PARENT_DEFAULT_TEST_SCOPE + "/preprod";
// ALTERNATIVE_TEST_SCOPE = DEFAULT_TEST_SCOPE_NAME + "/preVRE";
PARENT_DEFAULT_TEST_SCOPE = "/gcube";
DEFAULT_TEST_SCOPE = PARENT_DEFAULT_TEST_SCOPE + "/devNext";
ALTERNATIVE_TEST_SCOPE = DEFAULT_TEST_SCOPE + "/NextNext";
DEFAULT_TEST_SCOPE_ANOTHER_USER = "lucio.lelii_" + DEFAULT_TEST_SCOPE;
}
public static void set(Secret secret) throws Exception {
SecretManagerProvider.instance.reset();
SecretManager secretManager = new SecretManager();
secretManager.addSecret(secret);
SecretManagerProvider.instance.set(secretManager);
SecretManagerProvider.instance.get().set();
}
public static void setContextByName(String fullContextName) throws Exception {
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;
}
public static Secret getSecretByContextName(String context) throws Exception {
TokenResponse tr = getJWTAccessToken(context);
Secret secret = new JWTSecret(tr.getAccessToken());
return secret;
}
public static void setContext(String token) throws Exception {
Secret secret = getSecret(token);
set(secret);
}
private static Secret getSecret(String token) throws Exception {
Secret secret = SecretUtility.getSecretByTokenString(token);
return secret;
}
public static String getUser() {
String user = Metadata.UNKNOWN_USER;
try {
setContextByName(DEFAULT_TEST_SCOPE);
user = SecretManagerProvider.instance.get().getUser().getUsername();
} catch(Exception e) {
throw new RuntimeException(e);
logger.error("Unable to retrieve user. {} will be used", user);
}
RESOURCE_REGISTRY_URL = properties.getProperty(RESOURCE_REGISTRY_URL_PROPERTY);
}
public static String getCurrentScope(String token) throws ObjectNotFound, Exception {
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
String context = authorizationEntry.getContext();
logger.info("Context of token {} is {}", token, context);
return context;
}
public static void setContextByName(String fullContextName) throws ObjectNotFound, Exception {
String token = ContextTest.properties.getProperty(fullContextName);
setContext(token);
}
private static void setContext(String token) throws ObjectNotFound, Exception {
SecurityTokenProvider.instance.set(token);
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
ClientInfo clientInfo = authorizationEntry.getClientInfo();
logger.debug("User : {} - Type : {}", clientInfo.getId(), clientInfo.getType().name());
String qualifier = authorizationEntry.getQualifier();
Caller caller = new Caller(clientInfo, qualifier);
AuthorizationProvider.instance.set(caller);
ScopeProvider.instance.set(getCurrentScope(token));
return user;
}
@BeforeClass
@ -103,8 +133,7 @@ public class ContextTest {
@AfterClass
public static void afterClass() throws Exception {
SecurityTokenProvider.instance.reset();
ScopeProvider.instance.reset();
SecretManagerProvider.instance.reset();
}
}

View File

@ -8,20 +8,16 @@ import java.util.List;
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.common.authorization.client.Constants;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.reference.entities.Entity;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.queries.templates.impl.entities.QueryTemplateImpl;
import org.gcube.informationsystem.queries.templates.impl.properties.TemplateVariableImpl;
import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate;
import org.gcube.informationsystem.queries.templates.reference.properties.TemplateVariable;
import org.gcube.informationsystem.resourceregistry.api.exceptions.AlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.utils.ElementMapper;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -48,52 +44,33 @@ public class ResourceRegistryQueryTemplateClientTest extends ContextTest {
resourceRegistryQueryTemplateClient = ResourceRegistryQueryTemplateClientFactory.create();
}
}
public static String getUser() {
String user = Header.UNKNOWN_USER;
try {
String token = SecurityTokenProvider.instance.get();
if(token != null) {
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
if(authorizationEntry != null) {
ClientInfo clientInfo = authorizationEntry.getClientInfo();
String clientId = clientInfo.getId();
if(clientId != null && clientId.compareTo("") != 0) {
user = clientId;
} else {
throw new Exception("Username null or empty");
}
}
}
} catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user);
}
return user;
}
public static void checkHeader(IdentifiableElement previous, IdentifiableElement got) {
Header gotHeader = got.getHeader();
Header previousHeader = previous.getHeader();
public static void checkUUIDAndMetadata(IdentifiableElement previous, IdentifiableElement got) {
Metadata gotMetadata = got.getMetadata();
Metadata previousMetadata = previous.getMetadata();
Assert.assertTrue(gotHeader != null);
Assert.assertTrue(gotHeader.getUUID() != null);
Assert.assertTrue(gotMetadata != null);
Assert.assertTrue(got.getID() != null);
String user = getUser();
Assert.assertTrue(gotHeader.getLastUpdateBy().compareTo(user) == 0);
String user = ContextTest.getUser();
Assert.assertTrue(gotMetadata.getLastUpdateBy().compareTo(user) == 0);
if(previousHeader != null) {
Assert.assertTrue(gotHeader.getUUID().compareTo(previousHeader.getUUID()) == 0);
Assert.assertTrue(gotHeader.getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(gotHeader.getCreatedBy().compareTo(previousHeader.getCreatedBy()) == 0);
Assert.assertTrue(gotHeader.getCreationTime().compareTo(previousHeader.getCreationTime()) == 0);
if(previous.getID()!=null) {
Assert.assertTrue(got.getID().compareTo(previous.getID()) == 0);
}
if(previousMetadata != null) {
Assert.assertTrue(gotMetadata.getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(gotMetadata.getCreatedBy().compareTo(previousMetadata.getCreatedBy()) == 0);
Assert.assertTrue(gotMetadata.getCreationTime().compareTo(previousMetadata.getCreationTime()) == 0);
}
Assert.assertFalse(gotHeader.getCreationTime().after(gotHeader.getLastUpdateTime()));
Assert.assertFalse(gotMetadata.getCreationTime().after(gotMetadata.getLastUpdateTime()));
}
protected void assertions(QueryTemplate expected, QueryTemplate got) {
checkHeader(expected, got);
checkUUIDAndMetadata(expected, got);
Assert.assertTrue(expected.getName().compareTo(got.getName()) == 0);
Assert.assertTrue(expected.getDescription().compareTo(got.getDescription()) == 0);
// Template and TemplateVariable should be compared

View File

@ -1,20 +1,20 @@
{
"@class": "EService",
"type": "EService",
"consistsOf": [
{
"@class": "ConsistsOf",
"type": "ConsistsOf",
"propagationConstraint" : {
"add": "propagate"
},
"target": {
"@class": "StateFacet",
"type": "StateFacet",
"value": "$state"
}
},
{
"@class": "IsIdentifiedBy",
"type": "IsIdentifiedBy",
"target": {
"@class": "SoftwareFacet",
"type": "SoftwareFacet",
"name": "$name",
"group": "$group"
}