Difference between revisions of "GxRest/GxJRS/Requests"

From Gcube Wiki
Jump to: navigation, search
(How to integrate with the FeatherWeight Stack)
(How to integrate with the FeatherWeight Stack)
Line 131: Line 131:
  
 
Here is an example how to initialize the Call object:
 
Here is an example how to initialize the Call object:
<code source="Java">
+
<source lang="Java">
 
import org.gcube.common.clients.Call;
 
import org.gcube.common.clients.Call;
 
import org.gcube.common.clients.delegates.ProxyDelegate;
 
import org.gcube.common.clients.delegates.ProxyDelegate;
Line 151: Line 151:
 
             public MultiLocatorResponse call(GXRequest manager) throws Exception {
 
             public MultiLocatorResponse call(GXRequest manager) throws Exception {
 
                 GXInboundResponse response =  manager.path(“children”) .path(id).get();
 
                 GXInboundResponse response =  manager.path(“children”) .path(id).get();
                 if (response.hasError()) {
+
                 if (response.hasGXError()) {
 
                     //manage the error
 
                     //manage the error
 
                 }
 
                 }
Line 167: Line 167:
 
}
 
}
  
</code>
+
</source>

Revision as of 04:09, 30 April 2018

Introduction

Types of Requests

GXHTTPRequest

This type of request is entirely based on plain HTTP. It does not require any other software than the standard Java java.net and java.io to work.

This is basic example that sends a Post request to create a new resource:

import org.gcube.common.gxrest.response.inbound.GXInboundResponse;
import org.gcube.common.gxrest.request.GXHTTPRequest;
 
GXHTTPRequest request = GXHTTPRequest.newRequest("http://host:port/service/").from("GXRequestTest");
 
//prepare some parameters
String context ="json serialization (not shown)";
Map<String,String> queryParams = new WeakHashMap<>();
String DEFAULT_RR_URL = "url of resource registry to contact";
queryParams.put("rrURL", DEFAULT_RR_URL);
 
try {
	GXInboundResponse response = request.path("context")
	  .queryParams(queryParams).withBody(context).post();
} catch (Exception e) {
	e.printStackTrace();
	System.err.println("Failed to send a POST request");
}

GXWebTargetAdapterRequest

This type of request is also generic but it relies on a JAX-RS runtime implementation. It dynamically loads the first WebTarget available on the classpath and uses it for modeling and sending the request. The reference implementation for JAX-RS is named Jersey, but it is not included in Java SE. If you want to use this request you must explicitly add a JAR-RS implementation to your classpath.

This is basic example that sends a Post request to create a new resource:

import org.gcube.common.gxrest.response.inbound.GXInboundResponse;
import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
 
//...
GXWebTargetAdapterRequest request = 
        GXWebTargetAdapterRequest.newRequest("http://host:port/service/").from("GXRequestTest");
 
//prepare some parameters
String context ="json serialization (not shown)";
Map<String,String> queryParams = new WeakHashMap<>();
String DEFAULT_RR_URL = "url of resource registry to contact";
queryParams.put("rrURL", DEFAULT_RR_URL);
 
 
//send the request to the context resource's collection
GXInboundResponse response = request.path("context")
		.queryParams(queryParams).withEntity(Entity.entity(context, MediaType.APPLICATION_JSON)).post();

Overriding the security context

By default, the security token available in the current thread is attached to the request.

However, if there is the need to force a specific token to be used, this can be done by invoking the setSecurityToken() method on the request object:

GXWebTargetAdapterRequest request = 
        GXWebTargetAdapterRequest.newRequest("http://host:port/service/").from("GXRequestTest");
request.setSecurityToken("my token");

Registering JAX-RS components

The following example shows how to register an instance of a custom JAX-RS component (a feature in this case) to be instantiated and used in the scope of the request:

import javax.ws.rs.core.Feature;
 
public class MyFeature implements Feature {
 @Override
    public boolean configure(FeatureContext context) {
        boolean enabled = false;
 
         //decides if the feature is enabled...
 
        return enabled;
    }
}
 
GXWebTargetAdapterRequest request = 
        GXWebTargetAdapterRequest.newRequest("http://host:port/service/").from("GXRequestTest");
request.register(MyFeature.class)

A Feature is a special type of JAX-RS configuration meta-provider. Once a feature is registered, its configure() method is invoked during JAX-RS runtime configuration and bootstrapping phase allowing the feature to further configure the runtime context in which it has been registered.

Consuming the response

Here is an example about how to consume the returned response:

import javax.ws.rs.core.Response;
import org.gcube.common.gxrest.response.inbound.GXInboundResponse;
 
 
GXInboundResponse response = //request
 
if (response.hasGXError()) {
//this means that the error response has been generated at service side with gxRest as well
	if (response.hasException()) {
		try {
			throw response.getException();
		} catch (ClassNotFoundException e) {
			// can't recreate the original exception (not on the classpath?)
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	} else {
		//if you want to use the original response
		Response jsResponse = response.getSource();
		//then consume the response from here
	}
} else {
	if (response.hasCREATEDCode()) {
		System.out.println("Resource successfully created!");
		System.out.println("Returned content: " + response.getStreamedContentAsString());
	} else {
		System.out.println("Resource creation failed. Returned status:" + response.getHTTPCode());
		//if you want to use the original response
		Response jsResponse = response.getSource();
		//then consume the response from here
	}
}

How to integrate with the FeatherWeight Stack

If common-jaxrs-client is used to discover and call a remote service, gxRest can be integrated with the call.

Here is an example how to initialize the Call object:

import org.gcube.common.clients.Call;
import org.gcube.common.clients.delegates.ProxyDelegate;
 
public class DefaultClassification implements ClassificationClient{
 
    private final ProxyDelegate<GXrequest> delegate;
 
    public DefaultClassification(ProxyDelegate<GXRequest> config){
        this.delegate = config;
    }
 
    @Override
    public Stream<TaxonomyItem> getTaxonChildrenById(final String id)
            throws UnsupportedPluginException, UnsupportedCapabilityException,
            InvalidIdentifierException {
        Call<GXRequest, MultiLocatorResponse> call = new Call<GXRequest, MultiLocatorResponse>() {
            @Override
            public MultiLocatorResponse call(GXRequest manager) throws Exception {
                GXInboundResponse response =  manager.path(“children”) .path(id).get();
                if (response.hasGXError()) {
                    //manage the error
                }
                return response.readContentAs(MultiLocatorResponse.class);
            }
        };
        try {
            MultiLocatorResponse result = delegate.make(call);
            ResultElementRecordIterator<TaxonomyItem> ri = new ResultElementRecordIterator<TaxonomyItem>(result.getEndpointId(), result.getInputLocator(), 2, TimeUnit.MINUTES);
            return Streams.convert(ri);
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}