refs #5748: Add "Add To Context API" in Resource Registry Publisher

https://support.d4science.org/issues/5748

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry-publisher@134116 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2016-11-14 11:33:14 +00:00
parent 8ff76e17ea
commit 72f5aa25e7
1 changed files with 272 additions and 140 deletions

View File

@ -12,10 +12,12 @@ import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.ws.EndpointReference;
import org.gcube.common.authorization.client.Constants;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.clients.Call;
import org.gcube.common.clients.delegates.AsyncProxyDelegate;
@ -23,10 +25,15 @@ import org.gcube.common.clients.delegates.ProxyDelegate;
import org.gcube.common.clients.exceptions.ServiceException;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.impl.utils.Entities;
import org.gcube.informationsystem.model.entity.Context;
import org.gcube.informationsystem.model.entity.Facet;
import org.gcube.informationsystem.model.entity.Resource;
import org.gcube.informationsystem.model.relation.ConsistsOf;
import org.gcube.informationsystem.model.relation.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.EntityPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -42,97 +49,110 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
private final AsyncProxyDelegate<EndpointReference> delegate;
public static final String PATH_SEPARATOR = "/";
public final class RREntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
private V value;
public RREntry(K key, V value) {
this.key = key;
this.value = value;
}
public RREntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
}
public ResourceRegistryPublisherImpl(ProxyDelegate<EndpointReference> config) {
this.delegate = new AsyncProxyDelegate<EndpointReference>(config);
}
protected enum HTTPMETHOD {
GET, POST, PUT, DELETE;
@Override
public String toString(){
public String toString() {
return this.name();
}
}
private static String getCurrentContext() {
String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = null;
try {
authorizationEntry = Constants.authorizationService().get(token);
} catch (Exception e) {
return ScopeProvider.instance.get();
}
return authorizationEntry.getContext();
}
class HTTPInputs {
public static final String PARAM_STARTER = "?";
public static final String PARAM_EQUALS = "=";
public static final String PARAM_SEPARATOR = "&";
public static final String UTF8 = "UTF-8";
protected final String path;
protected final HTTPMETHOD method;
protected final String urlParameters;
protected String getParametersDataString(List<Map.Entry<String, String>> parameters) throws UnsupportedEncodingException {
if(parameters==null){
return null;
}
protected String getParametersDataString(
List<Map.Entry<String, String>> parameters)
throws UnsupportedEncodingException {
if (parameters == null) {
return null;
}
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : parameters){
if (first) {
first = false;
} else {
result.append(PARAM_SEPARATOR);
}
boolean first = true;
for (Map.Entry<String, String> entry : parameters) {
if (first) {
first = false;
} else {
result.append(PARAM_SEPARATOR);
}
result.append(URLEncoder.encode(entry.getKey(), UTF8));
result.append(PARAM_EQUALS);
result.append(URLEncoder.encode(entry.getValue(), UTF8));
result.append(URLEncoder.encode(entry.getKey(), UTF8));
result.append(PARAM_EQUALS);
result.append(URLEncoder.encode(entry.getValue(), UTF8));
}
}
return result.toString();
}
return result.toString();
}
/**
* @param path
* @param method
* @param requestProperties
* @throws UnsupportedEncodingException
* @throws UnsupportedEncodingException
*/
public HTTPInputs(String path, HTTPMETHOD method,
List<Map.Entry<String, String>> parameters) throws UnsupportedEncodingException {
List<Map.Entry<String, String>> parameters)
throws UnsupportedEncodingException {
super();
this.path = path;
this.method = method;
this.urlParameters = getParametersDataString(parameters);
}
/**
* @return the path
*/
@ -153,9 +173,9 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
public String getUrlParameters() {
return urlParameters;
}
}
class ResourceRegistryCall<C> implements Call<EndpointReference, C> {
protected final Class<C> clazz;
@ -176,11 +196,12 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
protected HttpURLConnection getConnection(URL url, HTTPMETHOD method)
throws Exception {
/*
if(method!=HTTPMETHOD.POST && httpInputs.getUrlParameters()!=null){
*/
* if(method!=HTTPMETHOD.POST &&
* httpInputs.getUrlParameters()!=null){
*/
url = new URL(url + "?" + httpInputs.getUrlParameters());
//}
// }
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
if (SecurityTokenProvider.instance.get() == null) {
@ -195,22 +216,21 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
SecurityTokenProvider.instance.get());
}
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("User-Agent", ResourceRegistryPublisher.class.getSimpleName());
connection.setRequestProperty("User-Agent",
ResourceRegistryPublisher.class.getSimpleName());
connection.setRequestMethod(method.toString());
/*
if(method==HTTPMETHOD.POST){
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(httpInputs.getUrlParameters());
wr.flush();
wr.close();
}*/
* if(method==HTTPMETHOD.POST){ connection.setDoOutput(true);
* DataOutputStream wr = new
* DataOutputStream(connection.getOutputStream());
* wr.writeBytes(httpInputs.getUrlParameters()); wr.flush();
* wr.close(); }
*/
return connection;
}
@ -222,10 +242,9 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
URL url = new URL(callUrl.toString());
HttpURLConnection connection = getConnection(url, httpInputs.method);
logger.debug("Response code for {} is {} : {}",
connection.getURL(),
connection.getResponseCode(),
logger.debug("Response code for {} is {} : {}",
connection.getURL(), connection.getResponseCode(),
connection.getResponseMessage());
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
@ -242,9 +261,9 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
}
}
String res = result.toString();
String res = result.toString();
logger.trace("Server returned content : {}", res);
return Entities.unmarshal(clazz, res);
}
@ -264,14 +283,17 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(facetClass.getSimpleName());
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(EntityPath.DEFINITION_PARAM, Entities.marshal(facet)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.PUT, parameters);
ResourceRegistryCall<F> call = new ResourceRegistryCall<>(facetClass, httpInputs);
parameters.add(new RREntry<String, String>(
EntityPath.DEFINITION_PARAM, Entities.marshal(facet)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.PUT, parameters);
ResourceRegistryCall<F> call = new ResourceRegistryCall<>(
facetClass, httpInputs);
F f = delegate.make(call);
logger.info("{} successfully created", f);
logger.info("{} successfully created", f);
return f;
} catch (Exception e) {
logger.error("Error Creating {}", facet, e);
@ -290,16 +312,19 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(EntityPath.FACET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(facet.getHeader().getUUID().toString());
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(EntityPath.DEFINITION_PARAM, Entities.marshal(facet)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.POST, parameters);
ResourceRegistryCall<F> call = new ResourceRegistryCall<>(facetClass, httpInputs);
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(
EntityPath.DEFINITION_PARAM, Entities.marshal(facet)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.POST, parameters);
ResourceRegistryCall<F> call = new ResourceRegistryCall<>(
facetClass, httpInputs);
F f = delegate.make(call);
logger.info("{} successfully updated", f);
logger.info("{} successfully updated", f);
return f;
} catch (Exception e) {
logger.error("Error Updating {}", facet, e);
@ -319,12 +344,15 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(facet.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(Boolean.class, httpInputs);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(
Boolean.class, httpInputs);
boolean deleted = delegate.make(call);
logger.info("{} {}", facet, deleted?" successfully deleted": "was NOT deleted");
logger.info("{} {}", facet, deleted ? " successfully deleted"
: "was NOT deleted");
return deleted;
} catch (Exception e) {
logger.error("Error Removing {}", facet, e);
@ -344,16 +372,19 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(EntityPath.RESOURCE_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(resourceClass.getSimpleName());
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(EntityPath.DEFINITION_PARAM, Entities.marshal(resource)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.PUT, parameters);
ResourceRegistryCall<R> call = new ResourceRegistryCall<>(resourceClass, httpInputs);
parameters.add(new RREntry<String, String>(
EntityPath.DEFINITION_PARAM, Entities.marshal(resource)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.PUT, parameters);
ResourceRegistryCall<R> call = new ResourceRegistryCall<>(
resourceClass, httpInputs);
R r = delegate.make(call);
logger.info("{} successfully created", r);
logger.info("{} successfully created", r);
return r;
} catch (Exception e) {
logger.error("Error Creating Facet", e);
@ -373,12 +404,15 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(resource.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(Boolean.class, httpInputs);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(
Boolean.class, httpInputs);
boolean deleted = delegate.make(call);
logger.info("{} {}", resource, deleted?" successfully deleted": "was NOT deleted");
logger.info("{} {}", resource, deleted ? " successfully deleted"
: "was NOT deleted");
return deleted;
} catch (Exception e) {
logger.error("Error Removing {}", resource, e);
@ -399,23 +433,28 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.SOURCE_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(consistsOf.getSource().getHeader().getUUID().toString());
stringWriter.append(consistsOf.getSource().getHeader().getUUID()
.toString());
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.TARGET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(consistsOf.getTarget().getHeader().getUUID().toString());
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(EntityPath.TYPE_PARAM, consistsOfClass.getSimpleName()));
parameters.add(new RREntry<String, String>(EntityPath.PROPERTIES_PARAM, Entities.marshal(consistsOf)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.PUT, parameters);
stringWriter.append(consistsOf.getTarget().getHeader().getUUID()
.toString());
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(EntityPath.TYPE_PARAM,
consistsOfClass.getSimpleName()));
parameters.add(new RREntry<String, String>(
EntityPath.PROPERTIES_PARAM, Entities.marshal(consistsOf)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.PUT, parameters);
ResourceRegistryCall<C> call = new ResourceRegistryCall<>(
consistsOfClass, httpInputs);
ResourceRegistryCall<C> call = new ResourceRegistryCall<>(consistsOfClass, httpInputs);
C c = delegate.make(call);
logger.info("{} successfully created", c);
logger.info("{} successfully created", c);
return c;
} catch (Exception e) {
logger.error("Error Creating Facet", e);
@ -436,12 +475,15 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(consistsOf.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(Boolean.class, httpInputs);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(
Boolean.class, httpInputs);
boolean deleted = delegate.make(call);
logger.info("{} {}", consistsOf, deleted?" successfully deleted": "was NOT deleted");
logger.info("{} {}", consistsOf, deleted ? " successfully deleted"
: "was NOT deleted");
return deleted;
} catch (Exception e) {
logger.error("Error Removing {}", consistsOf, e);
@ -463,23 +505,30 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.SOURCE_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(isRelatedTo.getSource().getHeader().getUUID().toString());
stringWriter.append(isRelatedTo.getSource().getHeader().getUUID()
.toString());
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.TARGET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(isRelatedTo.getTarget().getHeader().getUUID().toString());
stringWriter.append(isRelatedTo.getTarget().getHeader().getUUID()
.toString());
List<Map.Entry<String, String>> parameters = new ArrayList<>();
parameters.add(new RREntry<String, String>(EntityPath.TYPE_PARAM, isRelatedToClass.getSimpleName()));
parameters.add(new RREntry<String, String>(EntityPath.PROPERTIES_PARAM, Entities.marshal(isRelatedTo)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.PUT, parameters);
parameters.add(new RREntry<String, String>(EntityPath.TYPE_PARAM,
isRelatedToClass.getSimpleName()));
parameters
.add(new RREntry<String, String>(
EntityPath.PROPERTIES_PARAM, Entities
.marshal(isRelatedTo)));
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.PUT, parameters);
ResourceRegistryCall<I> call = new ResourceRegistryCall<>(
isRelatedToClass, httpInputs);
I i = delegate.make(call);
logger.info("{} successfully created", i);
logger.info("{} successfully created", i);
return i;
} catch (Exception e) {
logger.error("Error Creating Facet", e);
@ -488,7 +537,8 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
}
@Override
public <I extends IsRelatedTo<? extends Resource, ? extends Resource>> boolean deleteIsRelatedTo(I isRelatedTo) {
public <I extends IsRelatedTo<? extends Resource, ? extends Resource>> boolean deleteIsRelatedTo(
I isRelatedTo) {
try {
logger.info("Going to delete: {}", isRelatedTo);
StringWriter stringWriter = new StringWriter();
@ -499,12 +549,15 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(isRelatedTo.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(Boolean.class, httpInputs);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(
Boolean.class, httpInputs);
boolean deleted = delegate.make(call);
logger.info("{} {}", isRelatedTo, deleted?" successfully deleted": "was NOT deleted");
logger.info("{} {}", isRelatedTo, deleted ? " successfully deleted"
: "was NOT deleted");
return deleted;
} catch (Exception e) {
logger.error("Error Removing {}", isRelatedTo, e);
@ -512,4 +565,83 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
}
}
@Override
public boolean addResourceToContext(UUID uuid)
throws ResourceNotFoundException, ContextNotFoundException,
ResourceRegistryException {
String context = getCurrentContext();
try {
logger.info("Going to add {} with UUID {} to current {} : {}",
Resource.NAME, uuid, Context.NAME, context);
StringWriter stringWriter = new StringWriter();
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.ADD_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.RESOURCE_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(uuid.toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.POST, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(Boolean.class, httpInputs);
boolean added = delegate.make(call);
logger.info("{} with UUID {} was {} added to current {} : {}",
Resource.NAME, uuid, added ? "successfully": "NOT",
Context.NAME, context);
return added;
} catch (Exception e) {
logger.error("Error Adding {} with UUID {} to current {} : {}",
Resource.NAME, uuid, Context.NAME, context, e);
throw new ServiceException(e);
}
}
@Override
public <R extends Resource> boolean addResourceToContext(R resource)
throws ResourceNotFoundException, ContextNotFoundException,
ResourceRegistryException {
return addFacetToContext(resource.getHeader().getUUID());
}
@Override
public boolean addFacetToContext(UUID uuid) throws FacetNotFoundException,
ContextNotFoundException, ResourceRegistryException {
String context = getCurrentContext();
try {
logger.info("Going to add {} with UUID {} to current {} : {}",
Facet.NAME, uuid, Context.NAME, context);
StringWriter stringWriter = new StringWriter();
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.ADD_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.FACET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(uuid.toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(), HTTPMETHOD.POST, null);
ResourceRegistryCall<Boolean> call = new ResourceRegistryCall<>(Boolean.class, httpInputs);
boolean added = delegate.make(call);
logger.info("{} with UUID {} was {} added to current {} : {}",
Facet.NAME, uuid, added ? "successfully": "NOT",
Context.NAME, context);
return added;
} catch (Exception e) {
logger.error("Error Adding {} with UUID {} to current {} : {}",
Facet.NAME, uuid, Context.NAME, context, e);
throw new ServiceException(e);
}
}
@Override
public <F extends Facet> boolean addFacetToContext(F facet)
throws FacetNotFoundException, ContextNotFoundException,
ResourceRegistryException {
return addFacetToContext(facet.getHeader().getUUID());
}
}