implementing Publisher

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/information-system/resource-registry-publisher@131368 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2016-09-14 16:08:46 +00:00
parent 0efff0d87f
commit b1e3b8ea73
8 changed files with 262 additions and 91 deletions

View File

@ -84,6 +84,13 @@
<version>1.0.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>gcube-resources</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,34 @@
package org.gcube.informationsystem.resourceregistry.publisher.plugin;
import org.gcube.common.clients.fw.plugin.Plugin;
import org.gcube.informationsystem.resourceregistry.Constants;
/**
*
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
*
* @param <S>
* @param <P>
*/
public abstract class AbstractPlugin<S, P> implements Plugin<S, P> {
public final String name;
public AbstractPlugin(String name) {
this.name = name;
}
public String serviceClass() {
return Constants.SERVICE_CLASS;
}
public String serviceName() {
return Constants.SERVICE_NAME;
}
public String name() {
return name;
}
}

View File

@ -9,13 +9,14 @@ import org.gcube.common.clients.config.ProxyConfig;
import org.gcube.common.clients.delegates.ProxyDelegate;
import org.gcube.informationsystem.resourceregistry.Constants;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.publisher.proxy.ResourceRegistryPublisher;
import org.gcube.informationsystem.resourceregistry.publisher.proxy.ResourceRegistryPublisherImpl;
/**
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
*
*/
public class ResourceRegistryPublisherPlugin extends AbstractPlugin<EndpointReference, ResourceRegistryPublisherImpl>{
public class ResourceRegistryPublisherPlugin extends AbstractPlugin<EndpointReference, ResourceRegistryPublisher>{
public ResourceRegistryPublisherPlugin(){
super(Constants.SERVICE_ENTRY_NAME);
@ -46,7 +47,7 @@ public class ResourceRegistryPublisherPlugin extends AbstractPlugin<EndpointRefe
}
@Override
public ResourceRegistryPublisherImpl newProxy(
public ResourceRegistryPublisher newProxy(
ProxyDelegate<EndpointReference> delegate) {
return new ResourceRegistryPublisherImpl(delegate);
}

View File

@ -0,0 +1,44 @@
package org.gcube.informationsystem.resourceregistry.publisher.proxy;
import org.gcube.informationsystem.model.embedded.Embedded;
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;
public interface ResourceRegistryPublisher {
public <E extends Embedded> E createEmbedded(E embedded);
public <E extends Embedded> E updateEmbedded(E embedded);
public <E extends Embedded> E deleteEmbedded(E embedded);
public <F extends Facet> F createFacet(Class<F> facetClass, F facet);
public <F extends Facet> F updateFacet(F facet);
public <F extends Facet> F deleteFacet(F facet);
public <R extends Resource> R createResource(R resource);
public <R extends Resource> R deleteResource(R resource);
public <C extends ConsistsOf<Resource, Facet>> C createConsistsOf(C consistsOf);
public <C extends ConsistsOf<Resource, Facet>> C updateConsistsOf(C consistsOf);
public <C extends ConsistsOf<Resource, Facet>> C deleteConsistsOf(C consistsOf);
public <I extends IsRelatedTo<Resource, Resource>> I create(I isRelatedTo);
public <I extends IsRelatedTo<Resource, Resource>> I update(I isRelatedTo);
public <I extends IsRelatedTo<Resource, Resource>> I delete(I isRelatedTo);
}

View File

@ -1,17 +1,22 @@
package org.gcube.informationsystem.resourceregistry.publisher.proxy;
import javax.xml.ws.EndpointReference;
import org.gcube.common.clients.fw.builders.StatelessBuilderImpl;
import org.gcube.informationsystem.resourceregistry.publisher.plugin.ResourceRegistryPublisherPlugin;
public class ResourceRegistryPublisherFactory {
private static ResourceRegistryPublisher singleton = new ResourceRegistryPublisherImpl();
protected static ResourceRegistryPublisher singleton;
public static ResourceRegistryPublisher create(){
if(singleton==null){
ResourceRegistryPublisherPlugin plugin = new ResourceRegistryPublisherPlugin();
singleton = new StatelessBuilderImpl<EndpointReference, ResourceRegistryPublisher>(plugin).build();
}
return singleton;
}
public static void setPublisher(ResourceRegistryPublisher registryPublisher){
singleton = registryPublisher;
}
}

View File

@ -1,18 +1,21 @@
package org.gcube.informationsystem.resourceregistry.publisher.proxy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Random;
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.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.GCoreEndpoint.Profile.Endpoint;
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.Entities;
import org.gcube.informationsystem.model.embedded.Embedded;
@ -21,9 +24,6 @@ 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.rest.EntityPath;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.icclient.ICFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -32,72 +32,84 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryPublisher.class);
private static final Random random;
protected final List<GCoreEndpoint> endpoints;
static {
random = new Random();
}
protected static List<GCoreEndpoint> getServiceEndpoint(){
SimpleQuery query = ICFactory.queryFor(GCoreEndpoint.class);
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'", org.gcube.informationsystem.resourceregistry.Constants.SERVICE_CLASS));
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'", org.gcube.informationsystem.resourceregistry.Constants.SERVICE_NAME));
query.setResult("$resource");
DiscoveryClient<GCoreEndpoint> client = ICFactory.clientFor(GCoreEndpoint.class);
return client.submit(query);
}
protected ResourceRegistryPublisherImpl(){
this.endpoints = getServiceEndpoint();
};
private static int randInt(int min, int max) {
int randomNum = random.nextInt((max - min) + 1) + min;
return randomNum;
}
protected URL getBaseURL() throws MalformedURLException {
GCoreEndpoint gCoreEndpoint = endpoints.get(randInt(0, endpoints.size()-1));
Endpoint endpoint = gCoreEndpoint.profile().endpointMap().get(org.gcube.informationsystem.resourceregistry.Constants.SERVICE_ENTRY_NAME);
return endpoint.uri().toURL();
}
protected AuthorizationEntry getAuthorizationEntry() {
try{
AuthorizationEntry info = Constants.authorizationService().get(SecurityTokenProvider.instance.get());
logger.info("Context is {} ",info.getContext());
return info;
}catch(Exception e){
String error = "Error retreiving security token";
logger.warn(error,e);
throw new RuntimeException(error,e);
}
}
private HttpURLConnection makeRequest(URL url, String method) throws Exception{
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.setRequestMethod(method);
connection.setDoOutput(true);
return connection;
}
protected HttpURLConnection getHttpURLConnection(String path, String method, Map<String,String> paramenter) throws Exception {
URL url = new URL(getBaseURL(), path);
HttpURLConnection connection = makeRequest(url, method);
return connection;
}
private final AsyncProxyDelegate<EndpointReference> delegate;
public static final String PATH_SEPARATOR ="/";
public static final String PARAM_STARTER ="?";
public static final String PARAM_EQUALS = "=";
public static final String PARAM_SEPARATOR ="&";
public ResourceRegistryPublisherImpl(ProxyDelegate<EndpointReference> config) {
this.delegate = new AsyncProxyDelegate<EndpointReference>(config);
}
class ResourceRegistryCall<C> implements Call<EndpointReference, C> {
protected final Class<C> clazz;
protected final StringWriter stringWriter;
protected final String method;
public ResourceRegistryCall(Class<C> clazz, StringWriter stringWriter, String method){
this.clazz = clazz;
this.stringWriter = stringWriter;
this.method = method;
}
protected String getURLStringFromEndpointReference(EndpointReference endpoint) throws IOException {
JaxRSEndpointReference jaxRSEndpointReference = new JaxRSEndpointReference(endpoint);
return jaxRSEndpointReference.toString();
}
protected HttpURLConnection makeRequest(URL url, String method) throws Exception {
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.setDoInput(true);
connection.setRequestProperty("Content-type", "text/plain");
connection.setRequestMethod(method);
return connection;
}
@Override
public C call(EndpointReference endpoint) throws Exception {
String urlFromEndpointReference = getURLStringFromEndpointReference(endpoint);
StringBuilder callUrl = new StringBuilder(urlFromEndpointReference);
callUrl.append(stringWriter.toString());
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, method);
logger.debug("Response code for {} is {} : {}",
callUrl.toString(), connection.getResponseCode(),
connection.getResponseMessage());
if (connection.getResponseCode() != 200) {
throw new Exception("Error Contacting Resource Registry Service");
}
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
(InputStream) connection.getContent()))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
return Entities.unmarshal(clazz, result.toString());
}
}
@Override
public <E extends Embedded> E createEmbedded(E embedded) {
return null;
@ -117,13 +129,27 @@ public class ResourceRegistryPublisherImpl implements ResourceRegistryPublisher
@Override
public <F extends Facet> F createFacet(F facet) {
String marshalledFacet = Entities.marshal(facet);
String path = EntityPath.ENTITY_PATH_PART + "/" + EntityPath.FACET_PATH_PART + "/" + facet.NAME + "?" + EntityPath.DEFINITION_PARAM + "=" + marshalledFacet;
HttpURLConnection connection = getHttpURLConnection(path,);
public <F extends Facet> F createFacet(Class<F> facetClass, F facet) {
// TODO Auto-generated method stub
return null;
try {
StringWriter stringWriter = new StringWriter();
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.ENTITY_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(EntityPath.FACET_PATH_PART);
stringWriter.append(PATH_SEPARATOR);
stringWriter.append(facetClass.getSimpleName());
stringWriter.append(PARAM_STARTER);
stringWriter.append(EntityPath.DEFINITION_PARAM);
stringWriter.append(PARAM_EQUALS);
Entities.marshal(facet, stringWriter);
ResourceRegistryCall<F> call = new ResourceRegistryCall<>(facetClass, stringWriter, "PUT");
return delegate.make(call);
} catch (Exception e) {
logger.error("Error Creating Facet", e);
throw new ServiceException(e);
}
}
@Override

View File

@ -0,0 +1,38 @@
/**
*
*/
package org.gcube.informationsystem.resourceregistry.publisher;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.impl.entity.facet.ContactFacetImpl;
import org.gcube.informationsystem.model.entity.facet.ContactFacet;
import org.gcube.informationsystem.resourceregistry.publisher.proxy.ResourceRegistryPublisher;
import org.gcube.informationsystem.resourceregistry.publisher.proxy.ResourceRegistryPublisherFactory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
*
*/
public class ResourceRegistryPublisherTest {
private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryPublisherTest.class);
@Test
public void testCreateFacet(){
ScopeProvider.instance.set("/gcube/devNext/NextNext");
ResourceRegistryPublisher resourceRegistryPublisher =
ResourceRegistryPublisherFactory.create();
ContactFacet contactFacet = new ContactFacetImpl();
contactFacet.setName("Luca");
contactFacet.setSurname("Frosini");
contactFacet.setEMail("info@lucafrosini.com");
ContactFacet created = resourceRegistryPublisher.createFacet(ContactFacet.class, contactFacet);
logger.trace("Created {} is {}", ContactFacet.NAME, created);
}
}

View File

@ -0,0 +1,16 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{0}: %msg%n</pattern>
</encoder>
</appender>
<logger name="org.gcube" level="TRACE" />
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>