Generalizing solution by using HTTPCall provided by API

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry-publisher@144239 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2017-02-24 10:25:41 +00:00
parent 04d8be5aee
commit d0290d6bd4
2 changed files with 70 additions and 284 deletions

View File

@ -0,0 +1,36 @@
package org.gcube.informationsystem.resourceregistry.publisher.proxy;
import java.io.IOException;
import java.net.URL;
import javax.xml.ws.EndpointReference;
import org.gcube.common.clients.Call;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall;
class ResourceRegistryPublisherCall<C> implements Call<EndpointReference, C> {
protected final Class<C> clazz;
protected final HTTPCall<C> httpInputs;
public ResourceRegistryPublisherCall(Class<C> clazz, HTTPCall<C> httpInputs) {
this.clazz = clazz;
this.httpInputs = httpInputs;
}
protected String getURLStringFromEndpointReference(
EndpointReference endpoint) throws IOException {
JaxRSEndpointReference jaxRSEndpointReference = new JaxRSEndpointReference(
endpoint);
return jaxRSEndpointReference.toString();
}
@Override
public C call(EndpointReference endpoint) throws Exception {
String urlFromEndpointReference = getURLStringFromEndpointReference(endpoint);
StringBuilder callUrl = new StringBuilder(urlFromEndpointReference);
callUrl.append(httpInputs.getPath());
URL url = new URL(callUrl.toString());
return httpInputs.call(clazz, url, ResourceRegistryPublisher.class.getSimpleName());
}
}

View File

@ -1,18 +1,6 @@
package org.gcube.informationsystem.resourceregistry.publisher.proxy;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import javax.xml.ws.EndpointReference;
@ -20,24 +8,23 @@ 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;
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.ISMapper;
import org.gcube.informationsystem.model.ISManageable;
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.ExceptionMapper;
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.facet.FacetNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.rest.ERPath;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall;
import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPCall.HTTPMETHOD;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -53,46 +40,10 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
public static final String PATH_SEPARATOR = "/";
public final class RREntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public RREntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@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() {
return this.name();
}
}
private static String getCurrentContext() {
String token = SecurityTokenProvider.instance.get();
@ -105,207 +56,6 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
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 final String body;
protected String getParametersDataString(
List<Entry<String, String>> parameters)
throws UnsupportedEncodingException {
if (parameters == null) {
return null;
}
StringBuilder result = new StringBuilder();
boolean first = true;
for (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));
}
return result.toString();
}
public HTTPInputs(String path, HTTPMETHOD method,
List<Map.Entry<String, String>> parameters)
throws UnsupportedEncodingException {
this(path, method, parameters, null);
}
/**
* @param path
* @param method
* @param requestProperties
* @throws UnsupportedEncodingException
*/
public HTTPInputs(String path, HTTPMETHOD method,
List<Map.Entry<String, String>> parameters, String body)
throws UnsupportedEncodingException {
super();
this.path = path;
this.method = method;
this.urlParameters = getParametersDataString(parameters);
this.body = body;
}
/**
* @return the path
*/
public String getPath() {
return this.path;
}
/**
* @return the method
*/
public HTTPMETHOD getMethod() {
return this.method;
}
/**
* @return the urlParameters
*/
public String getUrlParameters() {
return this.urlParameters;
}
public String getBody() {
return this.body;
}
}
class ResourceRegistryPublisherCall<C> implements Call<EndpointReference, C> {
protected final Class<C> clazz;
protected final HTTPInputs httpInputs;
public ResourceRegistryPublisherCall(Class<C> clazz, HTTPInputs httpInputs) {
this.clazz = clazz;
this.httpInputs = httpInputs;
}
protected String getURLStringFromEndpointReference(
EndpointReference endpoint) throws IOException {
JaxRSEndpointReference jaxRSEndpointReference = new JaxRSEndpointReference(
endpoint);
return jaxRSEndpointReference.toString();
}
protected HttpURLConnection getConnection(URL url, HTTPMETHOD method)
throws Exception {
if (httpInputs.getUrlParameters() != null) {
url = new URL(url + "?" + httpInputs.getUrlParameters());
}
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
if (SecurityTokenProvider.instance.get() == null) {
if (ScopeProvider.instance.get() == null) {
throw new RuntimeException(
"Null Token and Scope. Please set your token first.");
}
connection.setRequestProperty("gcube-scope",
ScopeProvider.instance.get());
} else {
connection.setRequestProperty(Constants.TOKEN_HEADER_ENTRY,
SecurityTokenProvider.instance.get());
}
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("User-Agent",
ResourceRegistryPublisher.class.getSimpleName());
connection.setRequestMethod(method.toString());
String body = httpInputs.getBody();
if (body != null
&& (method == HTTPMETHOD.POST || method == HTTPMETHOD.PUT)) {
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
return connection;
}
@SuppressWarnings("unchecked")
@Override
public C call(EndpointReference endpoint) throws Exception {
String urlFromEndpointReference = getURLStringFromEndpointReference(endpoint);
StringBuilder callUrl = new StringBuilder(urlFromEndpointReference);
callUrl.append(httpInputs.getPath());
URL url = new URL(callUrl.toString());
HttpURLConnection connection = getConnection(url, httpInputs.method);
String responseMessage = connection.getResponseMessage();
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
logger.error("Response code for {} is {} : {}",
connection.getURL(), responseCode,
responseMessage);
ResourceRegistryException rre = null;
try {
rre = ExceptionMapper.unmarshal(ResourceRegistryException.class, responseMessage);
}catch (Exception e) {
rre = new ResourceRegistryException(responseMessage);
}
throw rre;
}else{
logger.debug("Response code for {} is {} : {}",
connection.getURL(), responseCode,
responseMessage);
}
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader((InputStream) connection.getContent()))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
String res = result.toString();
logger.trace("Server returned content : {}", res);
if(Boolean.class.isAssignableFrom(clazz)){
return (C) ((Boolean) Boolean.valueOf(res)) ;
}else if(ISManageable.class.isAssignableFrom(clazz)){
return (C) ISMapper.unmarshal((Class<ISManageable>) clazz, res);
}
return (C) res;
}
}
@Override
public <F extends Facet> F createFacet(Class<F> facetClass, F facet) {
@ -321,11 +71,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
String body = ISMapper.marshal(facet);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<F> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.PUT, null, body);
ResourceRegistryPublisherCall<F> call = new ResourceRegistryPublisherCall<>(
facetClass, httpInputs);
facetClass, httpCall);
F f = delegate.make(call);
logger.info("{} successfully created", f);
@ -349,11 +99,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(facet.getHeader().getUUID().toString());
String body = ISMapper.marshal(facet);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<F> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.POST, null, body);
ResourceRegistryPublisherCall<F> call = new ResourceRegistryPublisherCall<>(
facetClass, httpInputs);
facetClass, httpCall);
F f = delegate.make(call);
logger.info("{} successfully updated", f);
@ -376,11 +126,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(facet.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean deleted = delegate.make(call);
logger.info("{} {}", facet, deleted ? " successfully deleted"
@ -407,11 +157,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
String body = ISMapper.marshal(resource);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<R> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.PUT, null, body);
ResourceRegistryPublisherCall<R> call = new ResourceRegistryPublisherCall<>(
resourceClass, httpInputs);
resourceClass, httpCall);
R r = delegate.make(call);
logger.info("{} successfully created", r);
@ -437,11 +187,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
String body = ISMapper.marshal(resource);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<R> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.POST, null, body);
ResourceRegistryPublisherCall<R> call = new ResourceRegistryPublisherCall<>(
resourceClass, httpInputs);
resourceClass, httpCall);
R r = delegate.make(call);
logger.info("{} update created", r);
@ -464,11 +214,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(resource.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean deleted = delegate.make(call);
logger.info("{} {}", resource, deleted ? " successfully deleted"
@ -505,11 +255,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
String body = ISMapper.marshal(consistsOf);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<C> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.PUT, null, body);
ResourceRegistryPublisherCall<C> call = new ResourceRegistryPublisherCall<>(
consistsOfClass, httpInputs);
consistsOfClass, httpCall);
C c = delegate.make(call);
logger.info("{} successfully created", c);
@ -533,11 +283,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(consistsOf.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean deleted = delegate.make(call);
logger.info("{} {}", consistsOf, deleted ? " successfully deleted"
@ -574,12 +324,12 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(isRelatedToClass.getSimpleName());
String body = ISMapper.marshal(isRelatedTo);
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<I> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.PUT, null, body);
ResourceRegistryPublisherCall<I> call = new ResourceRegistryPublisherCall<>(
isRelatedToClass, httpInputs);
isRelatedToClass, httpCall);
I i = delegate.make(call);
logger.info("{} successfully created", i);
@ -603,11 +353,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(isRelatedTo.getHeader().getUUID().toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.DELETE, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean deleted = delegate.make(call);
logger.info("{} {}", isRelatedTo, deleted ? " successfully deleted"
@ -638,11 +388,11 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(uuid.toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.POST, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean added = delegate.make(call);
logger.info("{} with UUID {} was {} added to current {} : {}",
@ -680,12 +430,12 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(ERPath.FACET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(uuid.toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.POST, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean added = delegate.make(call);
logger.info("{} with UUID {} was {} added to current {} : {}",
@ -725,12 +475,12 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(ERPath.RESOURCE_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(uuid.toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.POST, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean removed = delegate.make(call);
logger.info("{} with UUID {} was {} removed from current {} : {}",
@ -769,12 +519,12 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
stringWriter.append(ERPath.FACET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(uuid.toString());
HTTPInputs httpInputs = new HTTPInputs(stringWriter.toString(),
HTTPCall<Boolean> httpCall = new HTTPCall<>(stringWriter.toString(),
HTTPMETHOD.POST, null);
ResourceRegistryPublisherCall<Boolean> call = new ResourceRegistryPublisherCall<>(
Boolean.class, httpInputs);
Boolean.class, httpCall);
boolean removed = delegate.make(call);
logger.info("{} with UUID {} was {} removed from current {} : {}",