Space: Apache Tuscany Docs 2.x 
(http://cwiki.apache.org/confluence/display/TUSCANYxDOCx2x)
Page: SCA Java binding.rest 
(http://cwiki.apache.org/confluence/display/TUSCANYxDOCx2x/SCA+Java+binding.rest)


Edited by Luciano Resende:
---------------------------------------------------------------------
h3. <binding.rest> Introduction

The Tuscany Java SCA runtime supports Representational State Transfer (REST) 
services invocations via the <binding.rest> extension. Tuscany REST binding 
leverage JAX-RS Standards based annotations to map business operations to HTTP 
operations such as POST, GET, PUT and DELETE and utilizes Tuscany Databindings 
to provide support for different wire formats such as JSON, XML, Binary, etc 
shielding the application developer from contaminating his business logic with 
code to handle payload production/transformation details.

h3. Using the Tuscany REST binding

The primary use of the REST binding is to provide business services over HTTP 
in a distributed fashion. The simplest way to use the REST binding is to 
declare a business service that can be shared over the web and provide an HTTP 
address where one can access the service. This service is declared in an SCA 
composite file.

{code}  
    <component name="Catalog">
        <implementation.java class="services.store.FruitsCatalogImpl"/> 
        <service name="Catalog">
            <tuscany:binding.rest uri="http://localhost:8085/Catalog";>
                <tuscany:wireFormat.json />
                <tuscany:operationSelector.jaxrs />
            </tuscany:binding.rest>
        </service>
    </component>
{code}


Another way of implementing a REST service is to use a collection interface 
that matches the actions of the HTTP protocol. In this case, the methods must 
be named post, get, put, and delete. Tuscany ensures that the proper method is 
invoked via the request and response protocol of HTTP:
{code}
public class TestGetImpl {
    
    public InputStream get(String id) {
        return new ByteArrayInputStream(("<html><body><p>This is the service 
GET method, item=" + id + "</body></html>").getBytes());

    }
}
{code}

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.


h4. Mapping business interfaces to HTTP Operations

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 :

h4. URI Mappings

{code}
@Path
@Path("{id}")
@PathParam("id")
{code}

h4. Operation Mappings

{code}
@GET
@PUT
@POST
@DELETE
{code}

h4. 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}
<binding...>
   <wireFormat.json>
</binding...>
{code}

- 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}
<binding...>
   <wireFormat.dynamic>
</binding...>
{code}


h3. Store scenarios goes REST - Catalog Services using binding.rest


{code}
<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>
{code}


{code}
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);
}
{code}


{code}
@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);
        }        
    }
}
{code}

h3. Advanced Features of the Tuscany HTTP Binding

h4. HTTP Conditional Actions and Caching using ETags and Last-Modified

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:

* GET - retrieves an item from a collection
* POST - creates or adds an item to a collection
* PUT - updates or replaces an item in a collection
* DELETE - removes an item in a a collection

The HTTP specification (HTTP 1.1 Chapter 13 - Caching) also provides a 
mechanism by which these methods may be executed conditionally. To perform 
conditional methods, an HTTP client puts 3 items in the HTTP request header:

* ETag - entity tag, a unique identifier to an item in a collection. Normally 
created and returned by the server when creating (POST) a new item.
* LastModified - an updated field. Normally a string containing a date and time 
of the last modification of the item.
* Predicate - a logical test (e.g. IfModified, IfUnmodified) to use with the 
ETag and LastModified to determine whether to act.

The complete list of predicates is given in the HTTP specification.

The most common use of conditional methods is to prevent two requests to the 
server instead of one conditional request. For example, a common scenario is to 
check if an item has been modified, if not changed update it with a new 
version, if changed do not update it. With a conditional PUT method (using the 
IfUnmodifed predicate and a LastModified date), this can be done in one action. 
Another common use is to prevent multiple GETs of an item to ensure we have a 
valid copy. Rather than doing a second request of a large item, one can do a 
conditional GET request (using an IfModified predicate and a LastModified 
date), and avoid the second request if our object is still valid. The server 
responds with either a normal response body, or status code 304 (Not Modified), 
or status code 412 (precondition failed).

Tuscany implements the logic to move these caching items to and from the HTTP 
request and response headers, and deliver them to the collection 
implementation. The items are delivered to a user implementation via a 
serializable object called CacheContext. This object contains the value of the 
ETag, the LastModified value, and any predicates. It is up to the implementer 
of a collection to provide the correct server logic to act on these predicates. 
The CacheContext class is found in found in the Tuscany module package 
org.apache.tuscany.sca.binding.http.

To implement conditional actions on your service, the developer or implementer 
implements any of the condional HTTP actions: conditionalPost, conditionalGet, 
conditionalPut, or conditionalDelete. Tuscany automatically routes a request 
with proper request header fields (ETag, LastModified, and predicates) to the 
proper collection method.

For example, the TestBindingCacheImpl class in package 
org.apache.tuscany.sca.binding.http implements a server collection which pays 
attention to conditional methods. Notice that this collection implements 
conditionalGet, conditionalPut, conditionalPost, and conditionalDelete methods 
as well as get, put, post, delete. The server collection can look at the 
CacheContext obect to determine whether an item or a status code should be 
returned. In this example code, the conditionalGet checked the If-Modified 
predicate and determines whether the item is not modified and if so, throws a 
NotModifiedException.
{code}
        public InputStream conditionalGet(String id, HTTPCacheContext 
cacheContext)
                        throws NotModifiedException, 
PreconditionFailedException {

                if (cacheContext != null) {
                        if (cacheContext.ifModifiedSince) {
                                if ((id.equals("1"))
                                                && (0 > 
cacheContext.lastModifiedDate
                                                                .compareTo(new 
Date())))
                                        throw new NotModifiedException("item 1 
was modified on "
                                                        + new Date());
                        }
                ...
        ...
{code}

For a full example of all conditional methods and many combinations of 
predicates, one can look to the module http-binding unit tests to understand 
how these conditional request work. The HTTPBindingCacheTestCase contains 36 
tests of all 4 HTTP conditonal methods. Various predicates are tested with 
various ETags and LastModified fields. The fields are tested in both the 
positive and negative cases.

Here is a complete list of the tests:
* testGet() - tests normal GET method of collection, expects item
* testConditionalGetIfModifiedNegative() - tests not modified GET, expects item
* testConditionalGetIfModifiedPositive() - tests modified GET, expect code 304
* testConditionalGetIfUnmodifiedNegative() - tests unmodifed GET, expects item
* testConditionalGetIfUnmodifiedPositive() - tests modified GET, expects code 
412
* testConditionalGetIfMatchNegative() - tests matching GET, expects code 412
* testConditionalGetIfMatchPositive() - tests matching GET, expects item
* testConditionalGetIfNoneMatchNegative - tests unmatching GET, expects item
* testConditionalGetIfNoneMatchPositive() - tests unmatching GET, expects code 
412

Similarly, there are 9 tests each for DELETE, POST, and PUT, making a total of 
36 test cases.


Change your notification preferences: 
http://cwiki.apache.org/confluence/users/viewnotifications.action    

Reply via email to