Compare commits

..

No commits in common. "master" and "v4.0.1" have entirely different histories.

8 changed files with 196 additions and 307 deletions

2
.gitignore vendored
View File

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

View File

@ -2,24 +2,6 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Resource Registry Context Client
## [v4.2.0-SNAPSHOT]
- Added support for paginated results [#24648]
## [v4.1.1]
- Migrated code to reorganized E/R format [#24992]
## [v4.1.0]
- 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
## [v4.0.1]
- Uniformed raised exception [#21993]

19
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-context-client</artifactId>
<version>4.2.0-SNAPSHOT</version>
<version>4.0.1</version>
<name>Resource Registry Context Client</name>
<description>Resource Registry Context Client is a library designed to interact with Resource Registry Context APIs</description>
@ -30,7 +30,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-bom</artifactId>
<version>2.4.0</version>
<version>2.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -38,6 +38,14 @@
</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>
@ -54,7 +62,6 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
@ -67,11 +74,5 @@
<artifactId>logback-classic</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

@ -4,7 +4,6 @@ import java.util.List;
import java.util.UUID;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
@ -14,10 +13,6 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.Cont
*/
public interface ResourceRegistryContextClient {
public void addHeader(String name, String value);
public ContextCache getContextCache();
public List<Context> all() throws ResourceRegistryException;
public Context create(Context context) throws ContextAlreadyPresentException, ResourceRegistryException;

View File

@ -1,5 +1,8 @@
package org.gcube.informationsystem.resourceregistry.contexts;
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;
@ -11,25 +14,20 @@ import org.slf4j.LoggerFactory;
public class ResourceRegistryContextClientFactory {
private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryContextClientFactory.class);
public static String getResourceRegistryURL() {
String address = String.format("%s/%s", ServiceInstance.getServiceURL(),Constants.SERVICE_NAME);
return address;
}
public static String getResourceRegistryURL(String context) {
String address = String.format("%s/%s", ServiceInstance.getServiceURL(context),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 ResourceRegistryContextClient create() {
String address = getResourceRegistryURL();
logger.trace("The {} will be contacted at {}", Constants.SERVICE_NAME, address);
return new ResourceRegistryContextClientImpl(address);
}
public static ResourceRegistryContextClient create(String context) {
String address = getResourceRegistryURL(context);
String address = String.format("%s/%s", ServiceInstance.getServiceURL(),Constants.SERVICE_NAME);
logger.trace("The {} will be contacted at {}", Constants.SERVICE_NAME, address);
return new ResourceRegistryContextClientImpl(address);
}

View File

@ -1,141 +1,55 @@
package org.gcube.informationsystem.resourceregistry.contexts;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.common.context.ContextUtility;
import org.gcube.common.gxhttp.reference.GXConnection;
import org.gcube.common.gxhttp.request.GXHTTPStringRequest;
import org.gcube.common.http.GXHTTPUtility;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal;
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo;
import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.UUIDManager;
import org.gcube.informationsystem.utils.ElementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ResourceRegistryContextClientImpl extends BaseRequestInfo implements ResourceRegistryContextClient {
public class ResourceRegistryContextClientImpl implements ResourceRegistryContextClient {
private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryContextClientImpl.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;
protected ContextCache contextCache;
private void addOptionalQueryParameters(Map<String,String> queryParams) throws UnsupportedEncodingException {
addIncludeMeta(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{
addIncludeMeta(queryParams, includeMeta);
}
private void addIncludeMeta(Map<String,String> queryParams, boolean includeMeta) throws UnsupportedEncodingException{
if(includeMeta) {
queryParams.put(ContextPath.INCLUDE_META_QUERY_PARAMETER, Boolean.toString(includeMeta));
}
}
/*
private void addOffset(Map<String,String> queryParams) throws UnsupportedEncodingException{
addOffset(queryParams, offset);
}
*/
private void addOffset(Map<String,String> queryParams, Integer offset) throws UnsupportedEncodingException{
if(offset!=null) {
queryParams.put(ContextPath.OFFSET_QUERY_PARAMETER, offset.toString());
}
}
/*
private void addLimit(Map<String,String> queryParams) throws UnsupportedEncodingException{
addLimit(queryParams, limit);
}
*/
private void addLimit(Map<String,String> queryParams, Integer limit) throws UnsupportedEncodingException{
if(limit!=null) {
queryParams.put(ContextPath.LIMIT_QUERY_PARAMETER, limit.toString());
}
}
protected ContextCacheRenewal contextCacheRenewal = new ContextCacheRenewal() {
@Override
public List<Context> renew() throws ResourceRegistryException {
return getAllContextFromServer(true, 0, BaseRequestInfo.UNBOUNDED_LIMIT);
return getAllContextFromServer();
}
};
@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 ResourceRegistryContextClientImpl(String address) {
this(address, true);
}
public ResourceRegistryContextClientImpl(String address, boolean sharedContextCache) {
this.address = address;
this.headers = new HashMap<>();
this.includeMeta = false;
if(sharedContextCache) {
contextCache = ContextCache.getInstance();
}else {
contextCache = new ContextCache();
}
ContextCache contextCache = ContextCache.getInstance();
contextCache.setContextCacheRenewal(contextCacheRenewal);
}
private void forceCacheRefresh() {
try {
ContextCache contextCache = ContextCache.getInstance();
contextCache.cleanCache();
contextCache.refreshContextsIfNeeded();
}catch (Exception e) {
@ -143,30 +57,14 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
}
}
/**
* It reads all the contexts from server.
* The cache used for contexts is bypassed and not updated.
* @return All Contexts read from server
* @throws ResourceRegistryException
*/
public List<Context> getAllContextFromServer() throws ResourceRegistryException {
return getAllContextFromServer(includeMeta, offset, limit);
}
protected List<Context> getAllContextFromServer(boolean includeMeta, Integer offset, Integer limit) throws ResourceRegistryException {
protected List<Context> getAllContextFromServer() throws ResourceRegistryException {
try {
logger.info("Going to read all {}s", Context.NAME);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
logger.trace("Going to read {} with UUID {}", Context.NAME);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryContextClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(ContextPath.CONTEXTS_PATH_PART);
Map<String,String> parameters = new HashMap<>();
addIncludeMeta(parameters, includeMeta);
addOffset(parameters, offset);
addLimit(parameters, limit);
gxHTTPStringRequest.queryParams(parameters);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.get();
String all = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -184,35 +82,30 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
@Override
public List<Context> all() throws ResourceRegistryException {
ContextCache contextCache = ContextCache.getInstance();
return contextCache.getContexts();
}
@Override
public ContextCache getContextCache() {
return contextCache;
}
protected String internalCreate(Context context) throws ContextAlreadyPresentException, ResourceRegistryException {
try {
UUID uuid = context.getID();
if(uuid == null) {
uuid = UUIDManager.getInstance().generateValidUUID();
context.setID(uuid);
Header header = context.getHeader();
if(header == null) {
header = new HeaderImpl(UUID.randomUUID());
context.setHeader(header);
}
UUID uuid = context.getHeader().getUUID();
String contextString = ElementMapper.marshal(context);
logger.trace("Going to create {}", contextString);
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 gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryContextClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header("Content-type", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(ContextPath.CONTEXTS_PATH_PART);
gxHTTPStringRequest.path(uuid.toString());
includeAdditionalQueryParameters(gxHTTPStringRequest);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.put(contextString);
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -261,8 +154,9 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
public boolean existFromServer(String uuid) throws ContextNotFoundException, ResourceRegistryException {
try {
logger.trace("Going to read {} with UUID {}", Context.NAME, uuid);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryContextClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(ContextPath.CONTEXTS_PATH_PART);
gxHTTPStringRequest.path(uuid);
@ -298,12 +192,13 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
@Override
public Context read(Context context) throws ContextNotFoundException, ResourceRegistryException {
return read(context.getID());
return read(context.getHeader().getUUID());
}
@Override
public Context read(UUID uuid) throws ContextNotFoundException, ResourceRegistryException {
Context context = contextCache.getContextByUUID(uuid);;
ContextCache contextCache = ContextCache.getInstance();
Context context = ContextCache.getInstance().getContextByUUID(uuid);;
if(context == null) {
String contextJson = readFromServer(uuid.toString());
try {
@ -312,7 +207,7 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
throw new RuntimeException(e);
}
forceCacheRefresh();
Context c = contextCache.getContextByUUID(context.getID());
Context c = contextCache.getContextByUUID(context.getHeader().getUUID());
if(c!=null){
context = c;
}else {
@ -324,9 +219,29 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
@Override
public Context readCurrentContext() throws ContextNotFoundException, ResourceRegistryException {
String contextFullName = ContextUtility.getCurrentContextFullName();
String contextFullName = ResourceRegistryContextClientFactory.getCurrentContextFullName();
ContextCache contextCache = ContextCache.getInstance();
UUID uuid = contextCache.getUUIDByFullName(contextFullName);
return read(uuid);
Context context = null;
if(uuid == null) {
String contextJson = readFromServer(ContextPath.CURRENT_CONTEXT_PATH_PART);
try {
context = ElementMapper.unmarshal(Context.class, contextJson);
} catch (IOException e) {
throw new RuntimeException(e);
}
contextCache.cleanCache();
contextCache.refreshContextsIfNeeded();
Context c = contextCache.getContextByUUID(context.getHeader().getUUID());
if(c!=null){
context = c;
}else {
logger.error("Current Context is {}. It is possibile to get it from the server but not from the cache. This is very strange and should not occur.", contextFullName);
}
}else {
context = contextCache.getContextByUUID(uuid);
}
return context;
}
@Override
@ -345,13 +260,12 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
public String readFromServer(String uuid) throws ContextNotFoundException, ResourceRegistryException {
try {
logger.trace("Going to read {} with UUID {}", Context.NAME, uuid);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryContextClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(ContextPath.CONTEXTS_PATH_PART);
gxHTTPStringRequest.path(uuid);
includeAdditionalQueryParameters(gxHTTPStringRequest);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.get();
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -371,16 +285,15 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
String contextString = ElementMapper.marshal(context);
logger.trace("Going to update {}", contextString);
UUID uuid = context.getID();
UUID uuid = context.getHeader().getUUID();
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 gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryContextClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.header("Content-type", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(ContextPath.CONTEXTS_PATH_PART);
gxHTTPStringRequest.path(uuid.toString());
includeAdditionalQueryParameters(gxHTTPStringRequest);
HttpURLConnection httpURLConnection = gxHTTPStringRequest.put(contextString);
String c = HTTPUtility.getResponse(String.class, httpURLConnection);
@ -428,7 +341,7 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
@Override
public boolean delete(Context context) throws ContextNotFoundException, ResourceRegistryException {
return delete(context.getID());
return delete(context.getHeader().getUUID());
}
@Override
@ -440,8 +353,9 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
public boolean delete(String uuid) throws ContextNotFoundException, ResourceRegistryException {
try {
logger.trace("Going to delete {} with UUID {}", Context.NAME, uuid);
GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest();
gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
GXHTTPStringRequest gxHTTPStringRequest = GXHTTPStringRequest.newRequest(address);
gxHTTPStringRequest.from(ResourceRegistryContextClient.class.getSimpleName());
gxHTTPStringRequest.header("Accept", GXConnection.APPLICATION_JSON_CHARSET_UTF_8);
gxHTTPStringRequest.path(ContextPath.CONTEXTS_PATH_PART);
gxHTTPStringRequest.path(uuid);
@ -450,6 +364,8 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
boolean deleted = true;
logger.info("{} with UUID {} {}", Context.NAME, uuid,
deleted ? " successfully deleted" : "was NOT deleted");
return deleted;
@ -461,7 +377,9 @@ public class ResourceRegistryContextClientImpl extends BaseRequestInfo implement
throw new RuntimeException(e);
}finally {
try {
forceCacheRefresh();
ContextCache contextCache = ContextCache.getInstance();
contextCache.cleanCache();
contextCache.refreshContextsIfNeeded();
}catch (Exception e) {
}

View File

@ -7,15 +7,14 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
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.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.scope.api.ScopeProvider;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
@ -23,107 +22,77 @@ 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 final String CONFIG_INI_FILENAME = "config.ini";
protected static Properties properties;
protected static final String PROPERTIES_FILENAME = "token.properties";
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 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;
public static final String DEFAULT_TEST_SCOPE_ANOTHER_USER;
public static final String RESOURCE_REGISTRY_URL_PROPERTY = "RESOURCE_REGISTRY_URL";
public static final String RESOURCE_REGISTRY_URL;
static {
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);
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
try {
// load the properties file
properties.load(input);
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) {
} catch(IOException e) {
throw new RuntimeException(e);
}
}
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;
// 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;
try {
user = SecretManagerProvider.instance.get().getUser().getUsername();
setContextByName(DEFAULT_TEST_SCOPE);
} catch(Exception e) {
logger.error("Unable to retrieve user. {} will be used", user);
throw new RuntimeException(e);
}
return 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));
}
@BeforeClass
@ -133,7 +102,8 @@ public class ContextTest {
@AfterClass
public static void afterClass() throws Exception {
SecretManagerProvider.instance.reset();
SecurityTokenProvider.instance.reset();
ScopeProvider.instance.reset();
}
}

View File

@ -7,16 +7,21 @@ import java.util.Map;
import java.util.UUID;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
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.contexts.impl.entities.ContextImpl;
import org.gcube.informationsystem.contexts.reference.entities.Context;
import org.gcube.informationsystem.contexts.reference.relations.IsParentOf;
import org.gcube.informationsystem.model.reference.properties.Header;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.ElementMapper;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -40,32 +45,54 @@ public class ResourceRegistryContextClientTest extends ContextTest {
public static final String CTX_NAME_B = "B";
public static final String CTX_NAME_C = "C";
public static void checkUUIDAndMetadata(IdentifiableElement er, UUID uuid, boolean create) {
Assert.assertTrue(er.getMetadata() != null);
Assert.assertTrue(er.getID() != null);
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 er, UUID uuid, boolean create) {
Assert.assertTrue(er.getHeader() != null);
Assert.assertTrue(er.getHeader().getUUID() != null);
if(uuid != null) {
Assert.assertTrue(er.getID().compareTo(uuid) == 0);
Assert.assertTrue(er.getHeader().getUUID().compareTo(uuid) == 0);
}
String user = getUser();
Assert.assertTrue(er.getMetadata().getLastUpdateBy().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getLastUpdateBy().compareTo(user) == 0);
if(create) {
Assert.assertTrue(er.getMetadata().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getMetadata().getCreationTime().compareTo(er.getMetadata().getLastUpdateTime()) == 0);
Assert.assertTrue(er.getHeader().getCreatedBy().compareTo(user) == 0);
Assert.assertTrue(er.getHeader().getCreationTime().compareTo(er.getHeader().getLastUpdateTime()) == 0);
} else {
Assert.assertTrue(er.getMetadata().getCreationTime().before(er.getMetadata().getLastUpdateTime()));
Assert.assertTrue(er.getHeader().getCreationTime().before(er.getHeader().getLastUpdateTime()));
}
}
protected void assertions(Context pre, Context post, boolean checkParent, boolean create) {
if(checkParent) {
if(pre.getMetadata() != null) {
checkUUIDAndMetadata(post, pre.getID(), create);
if(pre.getHeader() != null) {
checkHeader(post, pre.getHeader().getUUID(), create);
} else {
checkUUIDAndMetadata(post, null, create);
checkHeader(post, null, create);
}
}
@ -79,9 +106,9 @@ public class ResourceRegistryContextClientTest extends ContextTest {
protected Context read(UUID uuid) throws ResourceRegistryException, IOException {
Context c = resourceRegistryContextClient.read(uuid);
Assert.assertTrue(c.getMetadata() != null);
Assert.assertTrue(c.getID() != null);
Assert.assertTrue(c.getID().compareTo(uuid) == 0);
Assert.assertTrue(c.getHeader() != null);
Assert.assertTrue(c.getHeader().getUUID() != null);
Assert.assertTrue(c.getHeader().getUUID().compareTo(uuid) == 0);
return c;
}
@ -105,7 +132,7 @@ public class ResourceRegistryContextClientTest extends ContextTest {
}
protected boolean delete(Context context) throws ResourceRegistryException {
return delete(context.getID());
return delete(context.getHeader().getUUID());
}
protected void invalidCreate(Context context) throws ResourceRegistryException, IOException {
@ -317,7 +344,7 @@ public class ResourceRegistryContextClientTest extends ContextTest {
delete(contextA5);
} catch(ContextNotFoundException e) {
logger.debug("The context with uuid {} was not found. (Was already deleted)",
contextA5.getID());
contextA5.getHeader().getUUID());
}
delete(contextB3);
@ -441,11 +468,11 @@ public class ResourceRegistryContextClientTest extends ContextTest {
for(Context c : contexts) {
UUID uuid = c.getID();
UUID uuid = c.getHeader().getUUID();
if(c.getParent()!=null) {
IsParentOf isParentOf = c.getParent();
Context parentContext = isParentOf.getSource();
UUID parentUUID = parentContext.getID();
UUID parentUUID = parentContext.getHeader().getUUID();
Assert.assertEquals(parentContext, contextCache.getContextByUUID(parentUUID));
List<IsParentOf> children = parentContext.getChildren();
boolean found = false;
@ -456,9 +483,9 @@ public class ResourceRegistryContextClientTest extends ContextTest {
}
}
Assert.assertTrue(found);
logger.debug("{} : {} (parent {} : {})", c.getID(), contextCache.getContextFullNameByUUID(uuid), parentUUID, contextCache.getContextFullNameByUUID(parentUUID));
logger.debug("{} : {} (parent {} : {})", c.getHeader().getUUID(), contextCache.getContextFullNameByUUID(uuid), parentUUID, contextCache.getContextFullNameByUUID(parentUUID));
}else {
logger.debug("{} : {}", c.getID(), contextCache.getContextFullNameByUUID(uuid));
logger.debug("{} : {}", c.getHeader().getUUID(), contextCache.getContextFullNameByUUID(uuid));
}
}
@ -466,7 +493,7 @@ public class ResourceRegistryContextClientTest extends ContextTest {
logger.debug("Current context : {}", currentContext);
for(Context c : contexts) {
UUID uuid = c.getID();
UUID uuid = c.getHeader().getUUID();
Context context = resourceRegistryContextClient.read(uuid);
String fullName = ContextCache.getInstance().getContextFullNameByUUID(uuid);
logger.debug("{} - {} : {}", uuid, fullName, context);