Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

So using the common verbs of HTTP and Java object serialization, one can implement services and run them anywhere the HTTP protocol is implemented. The service developer or implementer simply creates methods for post, get, put, and delete, and a business collection such as a shopping cart, telephone directory, insurance form, or blog sites can be created. See the Tuscany module binding-rest-runtime for complete examples.

Mapping business interfaces to HTTP Operations using JAX-RS Standard Annotations

JAX-RS offers standards based annotations that allow properly configuration of the REST service endpoint and mappings of specific HTTP operations (e.g. get, put, post, delete) to java operations. The following subset of JAX-RS annotations are currently supported :

...

Code Block
@GET
@PUT
@POST
@DELETE

Enabling JAX-RS annotation processing

In order to enable JAX-RS annotation processing, a component need to be configured to use JAX-RS Operation Selector.

Code Block

        <component name="Catalog">
		<implementation.java class="services.store.FruitsCatalogImpl"/> 
		<property name="currencyCode">USD</property>
		<service name="Catalog">
			<tuscany:binding.rest uri="http://localhost:8085/Catalog">
    		            <tuscany:wireFormat.json />
			    <tuscany:operationSelector.jaxrs />
    		        </tuscany:binding.rest>
   		</service>
		<reference name="currencyConverter" target="CurrencyConverter"/>	
	</component> 
Info

Integration with a existent JAX-RS engine might help on processing the full set of JAX-RS annotations. I have started looking into leveraging Wink resourceProcessor or related code to help on this layer.

Mapping RPC style calls over HTTP GET

In some cases, there isn't a simple mapping of a business operation as resources, but there is still a desire to take advantage of HTTP caching and other benefits that HTTP GET type of operations provide. In order to accomplish this, binding.rest has built in functionality that allows you to map RPC style calls to HTTP GET operations.

Client Invocation

The URL schema follows a simple pattern :

  • <base service URI> ?method=<operation name>&parm1=<value>&parm2=<value>
Code Block

http://localhost:8085/EchoService?method=echo&msg=Hello RPC
Code Block

http://localhost:8085/EchoService?method=echoArrayString&msgArray=Hello RPC1&msgArray=Hello RPC2"

Mapping QueryStrings to Business Operation parameters

Standard JAX-RS annotation @QueryParam is used to map parameters sent over HTTP GET invocations using query string to business operation parameter

Code Block

@Remotable
public interface Echo {

    String echo(@QueryParam("msg") String msg);

    int echoInt(int param);

    boolean echoBoolean(boolean param);

    String [] echoArrayString(@QueryParam("msgArray") String[] stringArray);

    int [] echoArrayInt(int[] intArray);

}

Enabling RPC to HTTP GET mapping

In order to enable automatically mapping, a component need to be configured to use RPC Operation Selector.

Code Block

        <component name="Catalog">
		<implementation.java class="services.store.FruitsCatalogImpl"/> 
		<property name="currencyCode">USD</property>
		<service name="Catalog">
			<tuscany:binding.rest uri="http://localhost:8085/Catalog">
    		            <tuscany:wireFormat.json />
                            <tuscany:response>
                                <tuscany:operationSelector.rpc />
                            </tuscany:response>
    		        </tuscany:binding.rest>
   		</service>
		<reference name="currencyConverter" target="CurrencyConverter"/>	
	</component> 

Wire Formats

This binding will support two styles of wire formats and will be used to control what type of payload will be generated by the service:

  • hardWired : where you hard code the wire format expectations in the composite when configuring the binding. In the example below, service will be using JSON payload.
Code Block
<binding...>
   <wireFormat.json>
</binding...>
  • dynamic : based on Content-Type header for request and Accept header for response. In the case below, the request content will be parsed based on the Content-Type request header and the response payload will be based on the request Accept header.
Code Block
<binding...>
   <wireFormat.dynamic>
</binding...>
Info

In progress

Cache control using ETags, Last-Modified and other HTTP Headers

The HTTP specification provides a set of methods for HTTP clients and servers to interact. These methods form the foundation of the World Wide Web. Tuscany implements many of these methods a binding interface to a collection. The main methods are:

...

Default cache control is done by using generated ETags based on response content checksum. To avoid data to be overwriten during concurrent updates, include an HTTP If-Match header that contains the original content ETag value. If you want to force an update regardless of whether someone else has updated it since you retrieved it, then use If-Match: * and don't include the ETag.

Declarative cache control

In order to allow for better flexibility, and re-usability of the components exposed as REST services, there is an option to declare cache controls when configuring the REST Binding as show the example below :

Code Block

	<component name="CustomerService">
		<implementation.java class="services.customer.CustomerServiceImpl"/> 
		<service name="CustomerService">
			<tuscany:binding.rest uri="http://localhost:8085/Customer">
    		    <tuscany:wireFormat.xml />
			    <tuscany:operationSelector.jaxrs />
			    <tuscany:http-headers>
			       <tuscany:header name="Cache-Control" value="no-cache"/>
			       <tuscany:header name="Expires" value="-1"/>
			       <tuscany:header name="X-Tuscany" value="tuscany"/> 
			    </tuscany:http-headers>
    		</tuscany:binding.rest>
   		</service>
	</component>
Info

This could be enhanced to enable more complex injection of fields to cache control headers.

Store scenarios goes REST - Catalog Services using binding.rest

Below is our Store Catalog exposed as REST services utilizing the new binding.rest.

Let's start by looking on how the component gets defined and configured in the composite file, particularly the following details :

  • binding.rest uri defines the Catalog service endpoint
  • wireFormat.json configure the service to use JSON as the payload
  • operationSelector.jaxrs configure the binding to use JAX-RS annotations to map the HTTP operations to business operations
Code Block
<composite	xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912"
		xmlns:tuscany="http://tuscany.apache.org/xmlns/sca/1.1"
		targetNamespace="http://store"
		name="store">
		
	<component name="Catalog">
		<implementation.java class="services.store.FruitsCatalogImpl"/> 
		<property name="currencyCode">USD</property>
		<service name="Catalog">
			<tuscany:binding.rest uri="http://localhost:8085/Catalog">
    		            <tuscany:wireFormat.json />
			    <tuscany:operationSelector.jaxrs />
    		        </tuscany:binding.rest>
   		</service>
		<reference name="currencyConverter" target="CurrencyConverter"/>	
	</component> 
    
	<component name="CurrencyConverter">
		<implementation.java class="services.store.CurrencyConverterImpl"/>
	</component>     

</composite>

Below is the Catalog Interface utilizing JAX-RS standard annotations to map HTTP operations to business operations.

Code Block
package services.store;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import org.oasisopen.sca.annotation.Remotable;


@Remotable
public interface Catalog {
    
    @GET
    Item[] getAll();
    
    @GET
    @Path("{id}")
    Item getItemById(@PathParam("id") String itemId);
    
    @POST
    void addItem(Item item);
    
    @PUT
    void updateItem(Item item);
    
    @DELETE
    @Path("{id}")
    void deleteItem(@PathParam("id") String itemId);
}

Below is the Fuit catalog implementation

Code Block
@Scope("COMPOSITE")
public class FruitsCatalogImpl implements Catalog {
    
    @Property
    public String currencyCode = "USD";
    
    @Reference
    public CurrencyConverter currencyConverter;
    
    private Map<String, Item> catalog = new HashMap<String, Item>();

    @Init
    public void init() {
        String currencySymbol = currencyConverter.getCurrencySymbol(currencyCode);
        catalog.put("Apple", new Item("Apple",  currencySymbol + currencyConverter.getConversion("USD", currencyCode, 2.99)));
        catalog.put("Orange", new Item("Orange", currencySymbol + currencyConverter.getConversion("USD", currencyCode, 3.55)));
        catalog.put("Pear", new Item("Pear", currencySymbol + currencyConverter.getConversion("USD", currencyCode, 1.55)));
    }

    public Item[] getAll() {
        Item[] catalogArray = new Item[catalog.size()];
        catalog.values().toArray(catalogArray);
        return catalogArray;
    }
    
    public Item getItemById(String itemId) {
        return catalog.get(itemId);
    }
    
    public void addItem(Item item) {
        catalog.put(item.getName(),item);
    }
    
    public void updateItem(Item item) {
        if(catalog.get(item.getName()) != null) {
            catalog.put(item.getName(), item);
        }
    }
    
    public void deleteItem(String itemId) {
        if(catalog.get(itemId) != null) {
            catalog.remove(itemId);
        }        
    }
}