Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:Review of REST Web Services for the Web Service Developer Exam II

    In this article, we will look at REST Web Services looking at characteristics for REST Web services.We will also cover JSON Web Services and make comparisons between these two types of Web services and SOAP web services. This is part of a larger series of articles to help you prepare for the web service developer exam. You can review the first article on REST Web Services, “Tutorial:Review of REST Web Services for the Web Service Developer Exam I”, if needed.

    More REST Web Services Feature

    In the previous article, we did an overview of REST Web services where we outlined the architecture principles of REST, the mapping of REST verbs to HTTP methods and then looked at some of the features of REST services. In this article, we will look at sending data to the RESTful Web services.

    REST Web Services Using XML, JSON, or Both

    A resource representation is the current state of a resource along with its attributes at the point of the request by the client application. They are just a snapshot of the resource at a particular point of time. A resource could be from a record in a database that is mapped between column names and row values to the XML tags and element values respectively to a system has a data model, then according to this definition a resource representation is a snapshot of the attributes of one of the things in your system's data model. These are the things you want your REST Web service to serve up.

    The last set of constraints that goes into a RESTful Web service design has to do with the format of the data that the application and service exchange in the request/response payload or in the HTTP body. This is where it really pays to keep things simple, human-readable, and connected.

    The objects in your data model are usually related in some way, and the relationships between data model objects (resources) should be reflected in the way they are represented for transfer to a client application. In the listing below, we show the discussion threading service which connects resource representations that might include a root discussion topic, its attributes as well as embed links to the responses given to that topic.

    XML Code: XML Representation of Discussion Thread
    <?xml version="1.0"?>
    <discussion date="{date}" topic="{topic}">
      <comment>{comment}</comment>
      <replies>
        <reply from="james@mail.com" href="/discussion/topics/{topic}/james"/>
        <reply from="kate@hotmail.com" href="/discussion/topics/{topic}/kate"/>
      </replies>
    </discussion>
    Also you can give your client applications the ability to request a specific content type that fits with their needs and to create a service that used the built-in HTTP Accept header, when the value of the header is a MIME type. In the table below is a list of the most common MIME types used by RESTful services:.

    Tutorial:Review of REST Web Services for the Web Service Developer Exam II-b10-restfulservicesmimetypes.jpg
    Table: RESTful Services Commonly Used MIME Types

    The benefit of this flexibility with the types of context is that it allows the service to be available to multiple clients written in various languages running on different platforms in various form factors and devices. The use of MIME types in conjunction with the HTTP Accept header is called content negotiation. This mechanism allows the clients to choose the appropriate data format for them and decouples the data from the service and the application using the data.

    Data Transformation with XSLT

    One of the key core components of any SOA system is its capability to do data transformation from one format to another. This capability is often found in the Web Services context using eXtensible Stylesheet Language Transformations (XSLT). XSLT is a sophisticated data transformation language. The data transformations required by most SOA applications use only a small part of the XSLT language. In any case, XSLT is a key tool for transformation within SOA integration frameworks. As it is universally accepted standard, there has been significant effort to improve the transformation engines. This has led to the transformation engines interpreting XSLT to perform better and faster data transformations.

    If we consider a scenario where new orders are accessed from the OMS serves as the means to create customer history records updating the customer history database, we can demonstrate the power of XSLT for doing data transformation. From a business standpoint, the reason for doing this is to allow users of the customer history database to have quick access to real-time records of the transactions a customer has done with the company. This information would need to be available in real-time to facilitate proper handling of telephone calls to customer support. If the customer support representative is handling a call from a customer, they need to be able to see the latest details of all transactions in the customer’s history. The information stored there from the OMS provides the OrderKey and ITM_NUMBER that enables more detailed information to be retrieved from the OMS rapidly. The figure below shows the data mapping transforming an OMS order record into a customer history record:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam II-b10-datamappingsalesordtocusthist.jpg
    Figure: Data Mapping between Sales Order to Customer History Record

    In the figure above, the Customer Number in the Order provides a foreign key in the Customer History Record. It links it back to other information about the customer such as the Order Number, PO Number, and Item Number which are mapped between the two systems since having them in the customer history database will enable additional SOA components to be built providing quick lookups from a customer history record to detailed order, purchase order, and item information in the OMS and other systems. Note that there may be multiple instances of an item number in a customer history record, if an order includes more than one type of item.

    The figure above also refers to examples in the previous article, “Tutorial:Review of REST Web Services for the Web Service Developer Exam I”, where we showed an example where a set of orders is formatted as an oms:Orders element in the schema http://acmesoa.com/oms/orders.xsd as well as a set of customer histories being formatted as a css:CustomerHistoryEntries element in the schema http://acmesoa.com/css/custhistentries.xsd.

    XSLT is a declarative language that defines transformations of source documents to target documents. For any XSL transformation there is a set of template rules represented by instances of the xsl:template element that are children of the root xsl:stylesheet element. It is for this reason that an XSLT document will often be referred to as a stylesheet. The template elements in the stylesheet define the structure of the target document that is created from the source.

    In order to identify the various groupings of data ,such as Order Key, in a source document, XSLT will use XPath language to do this. XPath in conjunction with the template rules determines where chunks of data are placed in the target document.
    In the example below, we use a stylesheet for transforming orders to customer histories. We will look at the stylesheet in smaller chunks to facilitate comprehension. The example shows the beginning of the XSLT document, including the xsl:stylesheet namespace declarations and xsl:output element.

    XML Code: XSLT showing Namespace and Output Elements
    <xsl:stylesheet version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:oms="http://www.acme.com/oms">
      <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
    In this listing we use the prefix oms to denote the Order Management System namespace: http://www.acme.com/oms. The xsl:output element is used to control the format of the stylesheet output. The attribute method="xml" indicates the format that the result should use for output. Note that the stylesheet does not specify any indentation for the output. To do this you would need to include the attribute, indent=yes. It is never a good idea to specify visual formatting in the base level transformations. Instead you should use a separate XSLT stylesheet to format XML into a human-readable output when required. Also we have specified the encoding as UTF-8. The next part of the XSLT is shown in the listing below. It covers the rules for processing the oms:Orders element:

    XML Code: XSLT for Creating Customer History Entry
    <xsl:template match="oms:Orders">
        <CustomerHistoryEntries xmlns="http://www.acme.com/css"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.acme.com/css
          http://acmesoa.com/css/custhistentries.xsd">
          <xsl:apply-templates/>
        </CustomerHistoryEntries>
      </xsl:template>
      <xsl:template match="oms:Order">
        <CustomerHistoryEntry xmlns="http://www.acme.com/css">
          <CustomerNumber>
            <xsl:apply-templates select="./oms:OrderHeader/oms:CUST_NO"/>
          </CustomerNumber>
          <OrderLookupInfo>
            <xsl:apply-templates select="./oms:OrderKey"/>
            <xsl:apply-templates 
              select="./oms:OrderHeader/oms:PURCH_ORD_NO"/>
            <xsl:apply-templates 
              select="./oms:OrderItems/oms:item/oms:ITM_NUMBER"/>
            <xsl:apply-templates select="./oms:OrderText"/>        
          </OrderLookupInfo>
        </CustomerHistoryEntry>
      </xsl:template>
    Here, the template is defined to match the pattern “oms:Orders” at the beginning by matching the oms:Orders element in the source document. Within the template, there is the definition of a CustomerHistoryEntries element. The contents within the template form the output for the target document. The template just provides the rules for transforming an oms:Orders element into a css:CustomerHistoryEntries element.

    Now, notice that this template has the instruction <xsl:apply-templates/> inside it. Inside a template, XML in the xsl namespace is interpreted as instructions and not as content to be output to the target document. This particular instruction tells the XSLT processor to apply the other templates in the stylesheet to the children of the oms:Orders node and insert the results into the target document. So, that is how the css:CustomerHistoryEntries element gets constructed in the target document. Its opening and closing tags are specified in this template. Its children are defined by the results of the <xsl:apply-templates> instruction and are inserted between the opening and closing tags.

    Next, in the bottom half of the listing is defined another template for matching the oms:Order element. This template will process any children of oms:Orders that are instances of oms:Order and then insert the results with the CustomerHistoryEntries tags. Within this template for oms:Order is the contents for an element, CustomerHistoryEntry, as well as the two top-level elements, CustomerNumber and OrderLookupInfo. Also inside the tags for CustomerNumber is another xsl:apply-templates instruction with the following attribute:

    XML Code: XPath Exression for CustomerNumber Element Population
    select="./oms:OrderHeader/oms:CUST_NO"
    This template provides instructions for populating the contents of the CustomerNumber element. The XPath expression ./oms:OrderHeader/oms:CUST_NO filters the children of oms:Order to which this template is applied. It tells the XSLT processor apply only this templates to oms:CUST_NO elements that are children of oms:OrderHeader. This allows for the XPath expression to reach into the source document, pulls out the oms:CUST_NO element, processes it, and then insert the results inside CustomerNumber tags. This is the way that oms:CUST_NO is transformed into css:CustomerNumber and then inserted into the correct place in the target document.

    There are also other xsl:apply-templates instructions in the listing. For example, there is the <OrderLookupInfo> element that is populated from the source elements specified by the XPath expressions:
    XML Code: XPath Expression
    ./oms:OrderKey
    XML Code: XPath Expression
    ./oms:OrderHeader/PURCH_ORD_NO
    XML Code: XPath Expression
    ./oms:OrderItems/ item/ITM_NUMBER
    XML Code: XPath Expression
    ./oms:OrderText
    Note the correspondence between the XPath expressions and figure showing the data mappings. In the next listing, we show templates matching the above XPath expressions:
    XML Code: XSLT for Detail-Level Templates
    <xsl:template match="oms:CUST_NO">
        <xsl:value-of select="."/>
      </xsl:template>
      <xsl:template match="oms:OrderKey">
        <OrderNumber xmlns="http://www.acme.com/css">
          <xsl:value-of select="."/>
        </OrderNumber>
      </xsl:template>
      <xsl:template match="oms:PURCH_ORD_NO">
        <PURCH_ORD_NO xmlns="http://www.acme.com/css">
          <xsl:value-of select="."/>
        </PURCH_ORD_NO>
      </xsl:template>
      <xsl:template match="oms:ITM_NUMBER">
        <ITM_NUMBER xmlns="http://www.acme.com/css">
          <xsl:value-of select="."/>
        </ITM_NUMBER>
      </xsl:template>
      <xsl:template match="oms:OrderText">
        <OrderText xmlns="http://www.acme.com/css">
          <xsl:value-of select="."/>
        </OrderText>
      </xsl:template>
    In this listing the template matching oms:OrderKey returns the value of that element which returns the string value of the current node (i.e. <xsl:value-of select="."/>). Overall this stylesheet maps the value of oms:OrderKey to a subelement named OrderNumber in the target document. This subelement is a child of the CustomerHistoryEntry element.

    XSLT Processing Using JAXP

    With the inception of Java API for XML Processing (JAXP), the processing of XSLTin Java is was facilitated for all developments requiring transformations. In JAXP, we use the javax.xml.transform.Transformer class to convert from a source document to a target document applying the rules specified in a stylesheet. JAXP lays the foundation on which all Java XML processing is built. You can use JAXP API with variety of different types of Java applications including servlets, JSPs, and EJBs. The different types of Java application use JAXP to access the various capabilities that are part of any JAXP implementation, such as a SAX parser, a DOM implementation, or an XSL processor that supports XSLT. The package javax.xml.parsers provides a common factory interface to access different implementations of SAX and DOM (e.g., Xerces) as well as XSLT (e.g., Xalan). The interfaces for SAX and DOM are found in the org.xml.sax and org.w3c.dom packages, respectively. The XSLT APIs are found in the javax.xml.transform packages. The architecture for JAXP is shown in the diagram below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam II-b10-jaxparchitecture.jpg
    Figure: JAXP Architecture

    The figure above shows how JAXP decouples a Java application in any form such as client application, servlets, JSP or EJB from the implementation of the all of the JAXP implementations such as XSLT transformer, and the SAX and DOM parsers. JAXP defines factory classes that instantiate wrapper objects on the transformer and parser implementations which are determined by system properties and/or classpath settings at runtime.

    JAXP is one of a number of important enabling standard technologies that make it possible to create SOA-style systems using Java and Web Services. It does the integration of XML parsing and transformation standards with Java but separates the DOM, SAX and XSLT implementations from SOA application components. This is critical for the development and deployment of better and faster implementations of each implementation. This also allows SOA components to leverage them in order improve performance without requiring that a SOA component need rewriting.

    If you use the JAXP architecture and XML for messaging, then you will only need to write an XSLT in order to do data transformation work for integrating SOA components. The example used to demonstrate this is illustrated in Figure 3–9. This application reads orders from an OMS Web service, transforms them into customer history updates, and writes these updates to a CSS Web service.

    Tutorial:Review of REST Web Services for the Web Service Developer Exam II-b10-xslt-soaintegration.jpg
    Figure: SOA Integration Using XSLT

    In the figure above XSLT is used to transform the orders into customer histories. The steps in the process are shown below:
    1. A Service instance is used to create two Dispatch<Source> instances. The first one is used to invoke the OMS Web service, and the second one is used to invoke the CSS Web service.
    2. The first Dispatch<Source> instance’s invoke method is used to get the orders from the OMS Web service.
    3. The orders are part of an XML document that is returned from invoke() as a Source instance.
    4. The XSLT stylesheet file (order_to_history.xslt) is used next by a TransformerFactory, to construct a Transformer instance based on the stylesheet.
    5. The Transfomer.transform() method is invoked to apply the stylesheet rules to the Source instance which in this case is the orders. The resulting XML document contains the customer histories. They are written to a Result instance that has been created for this purpose.
    6. The Result instance is created as a wrapper from a ByteArrayInputStream. The XML is extracted from the underlying array and wrapped in a StreamSource object that can be consumed by the second Dispatch instance.
    7. The Dispatch.invoke() method is used to post the customer histories XML to the CSS Web service.


    The listing below shows the implementation of the steps shown above. Note how the creation and invocation of the Dispatch instances is similar to how it was done with or without JAX-WS clients to access and use RESTful Web services:

    Java Code: Java Code for Applying XSLT to Customer History
    // Get the new orders
    Service svc = Service.create(svcQName);
    svc.addPort(orderQName, HTTPBinding.HTTP_BINDING, newOrdersUrl);
    Dispatch<Source> getOrdersDispatch =
      svc.createDispatch(orderQName, Source.class, Service.Mode.PAYLOAD);
    Source newOrdersSource = 
      getOrdersDispatch.invoke(new StreamSource(new StringReader("<empty/>")));
    // Instantiate a Transformer using our XSLT file
    Transformer transformer = 
      TransformerFactory.newInstance().newTransformer
      (new StreamSource(new File(xsltFile)));
    // Transform the new orders into history entry files
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    transformer.transform(newOrdersSource, new StreamResult(ba));
    // Update the customer histories
    svc.addPort(histQName, HTTPBinding.HTTP_BINDING, addCustHistUrl);
    Dispatch<Source> postCustomerHistoryDispatch =
      svc.createDispatch(histQName, Source.class, Service.Mode.PAYLOAD);
    postCustomerHistoryDispatch
    .invoke(new StreamSource(new StringReader(ba.toString())));
    In the listing there is an instance of the default TransformerFactory which is obtained using TransformerFactory.newInstance(). The factory, a Transformer is created by passing the XSLT file as a StreamSource to the newTransformer() method. The Transformer then applies the XSLT to the Source instance obtained by invoking the getOrdersDispatch instance. The StreamResult wrapping an underlying ByteArrayOutputStream is the second parameter for the transformer.transform() method. The results of the XSL transformation are then written to that byte array. The last part of the listing shows the byte array wrapped inside a StreamSource that is passed to the postCustomerHistoryDispatch.invoke() method in order to post the customer histories to the CSS Web service.

    Enabling a REST Service without JWS

    Next we will look at how to deploy a Java method as a Web service without using Java Web Services. We will use a mock object implementation of the getNewOrders() method in order to demonstrate this since we don’t have real back-end systems required to do Order Management or Customer Service. In this mock implementation of OrderManager is a “mock-up” of a real OrderManager class. It is a stub implementation of the server side. The getNewOrders() method returns the contents of a hard-coded orders.xml file rather than generating one from a running interface to an Order Management System. Below is the listing for the mock Order Management implementation:

    Java Code: Mock OrderManagement Implementation
    public class OrderManager {
      
      public Source getNewOrders() throws FileNotFoundException {
        // get the resource the provides the new orders
        InputStream src = getClass().getResourceAsStream("/orders.xml");
        if ( src == null ) {
          throw new FileNotFoundException("/orders.xml");
        }
        return new StreamSource(src);
      }
      
    }
    When you are enabling a Web Service, there are a number of questions that need to be answered. These are the following:
    1. How is the class instantiated?
    2. How is the Source instance returned by getNewOrders() converted into an XML stream in an HTTP response message?
    3. How is the class deployed as a Web service?

    The first of the three questions is on the invocation of the Web service because to invoke a Web service, you need to get an instance of its implementation class. The second of the three questions is about serialization because any Java object returned by a Web service must be serialized to XML that can be written out “onto the wire.” The last of the three questions is about deployment because the Web service must be deployed in order to use it. A figure showing a RESTful service deployed by HTTPServlet is shown below:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam II-b10-restful-service-deployment-httpservlet.jpg
    Figure: RESTful Service Deployment with HttpServlet

    We will provide straightforward answers to the questions based on deploying a Java method as a Web service using a dedicated servlet. Even with this simple case, the solutions must respond to all three of the core Web services platform architecture components (i.e. invocation, serialization and deployment).

    In the above figure we show the basic architecture for using a HTTP GET request to access the Web service. The servlet must handle the HTTP GET request, instantiate the Java class, invoke the getNewOrder() method, and then output the results out as XML in the response to the HTTP GET request. This simple architecture deploys a RESTful Web service using the java.servlet.http.HttpServlet class. We use as a front-end to the OrderManager, the GetNewOrdersServlet to mediate between the HTTP request/response messages. The GetNewOrdersServlet class invokes the Java method that implements the Web service. The steps from the figure are the following:
    1. The HTTP GET request is sent by the client to the appropriate URL that is associated in the web container’s configuration with the GetNewOrders class.
    2. The HTTP request stream is wrapped in an instance of HTTPServletRequest and passed to the GetNewOrdersServlet’s doGet() method.
    3. The doGet() method creates an instance of the OrderManager class and invokes the getNewOrders() method by the web container.
    4. The new orders XML document is returned by the getNewOrders() method as an instance of javax.xml.transform.Source.
    5. The New orders Source is written to the ServletOutputStream, wrapped in an instance of javax.xml.transform.stream.StreamResult by an instance of javax.xml.transform.Transformer.
    6. The new orders XML document is returned to the client as an HTTPResponse from the call to the getNewOrders() method.


    In the listing below, we show the code for he GetNewOrdersServlet’s doGet() method:

    Java Code: GetNewOrdersServlet&#8217;s doGet Method
    public void doGet(HttpServletRequest req, 
          HttpServletResponse res)
      throws IOException, ServletException {
        // invoke the Java method
        OrderManager om = new OrderManager();
        Source src = om.getNewOrders();
        // write the file to the HTTP response stream
        ServletOutputStream out = res.getOutputStream();
        res.setContentType("text/xml");
        StreamResult strRes = new StreamResult(out);
        try {
          TransformerFactory.newInstance().newTransformer()
          .transform(src, strRes);
        } catch (Exception e) {
          throw new IOException(e.getMessage());
        } 
        out.close();    
      }
    The listing above shows the servlet first instantiating the OrderManager class. We are here assuming that the OrderManager class is available to the class loader. We have simply added this class in the WAR that is deployed. This is straightforward but not always a feasible manner to deploy a class as a Web service. If the class was an EJB, You would get its interface from the EJB container rather than instantiating an instance. This is because the class would require other container services for such things as JNDI or database connections.

    Also we have used of the HttpServletResponse.setContentType("text/xml") method to set the content type of the HTTP response. This is due to many REST clients failing to properly process content if the content type was not set to "text/xml." Be wary of this as some of the HttpServletResponse methods such as sendError(int sc, String msg) on certain servlet containers will change the content type to "text/xml" because the error messages are implemented as HTML content.

    Finally note that the default instance of Transformer simply writes XML from a Source to a Result. We are not doing any XSL transformation but using the Transformer to write the XML returned by the OrderManager to the ServletOutputStream. The listing below shows the standard web.xml deployment descriptor for the GetNewOrdersServlet class which together with the OrderManager are the Web service implementation. It is located in the WEB-INF subdirectory of the WAR package that is used for deploying the Web service. The listing is shown below:

    XML Code: Deployment Descriptor in GetNewOrdersServlet WAR
    <web-app>
      <servlet>
        <servlet-name>GetNewOrdersServlet</servlet-name>
        <servlet-class> com.acme.retail.service.GetNewOrdersServlet </servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>GetNewOrdersServlet</servlet-name>
        <url-pattern>/NewOrders</url-pattern>
      </servlet-mapping>
    </web-app>
    In this deployment descriptor, we have mapped the servlet GetNewOrdersServlet to the URL pattern /NewOrders. This determines the context root for the Web application that you deploy in the WAR. As you can tell, creating and deploying a simple REST Web service using a servlet to invoke a Java method is not very difficult. As for the three questions we asked in relation to the deployment of RESTful Web services without using Java Web Services, the answers are as follows:
    1. The Web service implementation class, in our case, the OrderManager is instantiated using the no-arg default constructor assuming that the constructor exists, the definition of the class is on the classpath and all the resources need by the class are available.
    2. The Transformer takes the object returned by getNewOrders() and converts it into an XML stream. Generally the result will be a Java object that is not an XML infoset representation and will need to be serialized.
    3. We deploy the class by bundling it with a dedicated servlet.

    These answers are correct insofar as they go. When you deploy multiple services, you are like to encounter problems. In the architecture we just used, you would need to deploy a servlet per Web service. This is cumbersome and inefficient. Instead we would like an invocation subsystem that allows a single servlet to be used to invoke more than one service. This requires a method of mapping URLs to services at a finer granularity than provided by the web.xml file. A work around for doing this is to map all base URLs of the following form to the servlet:

    XML Code: Base URL for All Web Services
    http://www.acme.com/services/*
    The local paths would then be something like the following:
    • /getNewOrder
    • /addCustomerHistory

    These would be mapped to individual Web services. This is the approach used by a variety of Web Services engines such as Apache Axis. In the last part we will look at deploying a RESTful Service using JWS. This offers a variation on this approach which we can discuss when we deploy the “New Orders” Web service using JAX-WS and JSR-181 annotations.

    Enabling a RESTful Service with JWS

    If we look at deploying the same Web service using JWS. The operation of the service is very different when it is deployed using JWS. The primary difference is that the JWS version employs an instance of Provider<Source> to implement the RESTful service. The listing below shows how a Web service using JWS is implemented:

    Java Code: RESTful Web Service GetNewOrdersProvider using JWS
    import javax.xml.transform.Source;
    import javax.xml.ws.BindingType;
    import javax.xml.ws.Provider;
    import javax.xml.ws.WebServiceProvider;
    import javax.xml.ws.http.HTTPBinding;
    import javax.xml.ws.http.HTTPException;
    
    @WebServiceProvider
    @BindingType(value=HTTPBinding.HTTP_BINDING)
    public class GetNewOrdersProvider implements Provider<Source> {
      
      public Source invoke(Source xml) {
        OrderManager om = new OrderManager();
        try {
          return om.getNewOrders();
        } catch (Throwable t) {
          t.printStackTrace();
          throw new HTTPException(500);
        }
      }
      
    }
    In the listing, the @WebServiceProvider annotation is defined by the JAX-WS 2.0 specification. It is required in order to deploy a RESTful Web service and is used to declare a reference to a Web Service that implements a Provider<Source> interface. The Provider<Source> interface is the server-side version of Dispatch<Source>. Like the Dispatch<Source> interface, the Provider<Source> interface enables you to create a Web service that works directly with the XML message as an instance of javax.xml.transform.Source instead of an JAXB 2.0 representation of the XML message. The @BindingType annotation is used in the listing is defined by the JAX-WS 2.0 specification and is used to specify the binding that should be employed when publishing an endpoint. The property value indicates the actual binding. In this case, you can see that the value is specified as follow:

    XML Code: Binding Value
    value=HTTPBinding.HTTP_BINDING
    The value indicates that the XML/HTTP binding is used, rather than the default SOAP 1.1/HTTP. All REST endpoints are specified in JAX-WS 2.0 by setting the @BindingType in this manner. The default value for the @BindingType annotation would be for a bindind consistent with a SOAP envelope instead of for REST (i.e. XML over HTTP).

    Next the Provider<Source> interface specifies the invoke() method that receives and returns an instance of Source. Within the invoke() message, the OrderManager class is instantiated and will invoke the getNewOrders() method in order to implement the Web service functionality. So, here the service implementation class is wrapped inside a Provider.invoke() method.

    Let’s consider the three key questions that we asked in relation to Web services in terms of enabling a Web service:
    1. How is the class instantiated?
    2. How is the Source instance returned by getNewOrders() converted into an XML stream in an HTTP response message?
    3. How is the class deployed as a Web service?

    The listing shows that the answers differ significantly when a RESTful Web service is implemented as a Provider<Source> rather than when it is implemented using an HttpServlet. These differences highlight a JAX-WS 2.0 approach to Web Services deployment versus the servlet implementation of the preceding section.

    Let’s look at the responses one by one:
    1. How is the class instantiated? The class is instantiated each time the service is invoked.
    2. How is the Source instance returned by getNewOrders() converted into an XML stream in an HTTP response message? The Source instance can be returned directly. It does not need to be converted into a stream and written out to the HTTP response message. These details related to the binding of the service to the HTTP transport are handled by the JAX-WS run-time implementation.
    3. How is the class deployed as a Web service? You can deploy Web services using a number of options in Java EE 5. The deployment descriptor can be used although it is not required. You can deploy a JWS Web service without any deployment descriptors since with a Java EE 5 container, one can often deploy a service based entirely on its annotations.

    The figure below shows how to create and deploy a RESTful Web service using JAX-WS 2.0:

    Tutorial:Review of REST Web Services for the Web Service Developer Exam II-b10-restfulservicedeployedusingprovider.jpg
    Figure: RESTful Service Deployed using Provider<Source>

    The figure shows the deployment of the RESTful Web Service using Java Web Services using the java.servlet.http.Provider<Source> class. In this case, the GetNewOrdersProvider class serves as a front-end to the OrderManager mediating between the XML request/response messages and the invocation of the Java method that implements the Web service. The steps shown in the figure are shown below:
    1. The client makes a HTTP POST request to the URL that is specified at deployment time either in a deployment descriptor or a deployment tool. We are using a POST request because early implementations of JAX-WS allowed RESTful Web services only accepted POST requests.
    2. The Java Web Service container extracts the XML message from the HTTP POST request and passes it to the GetNewOrders.invoke() method. The extraction of the XML message from the HTTP Post and the invocation of the invoke method with the XML message contents is provided by the JAX-WS runtime.
    3. An instance of the OrderManager class is created by the invoke() method and then the getNewOrders() method is invoked.
    4. The new orders XML document is returned by the getNewOrders() method as an instance of javax.xml.transform.Source.
    5. The Web service’s return XML message is wrapped into the HTTP response message as an instance of Source and then returned to the caller. The wrapping of the XML response message inside the HTTP response message is provided by the JAX-WS runtime.


    From the figure and the steps outlined, we can see that the JWS implementation of this RESTful Web service is simpler in certain aspects than the servlet-based counterpart discussed previously. This is because we are no longer translating between HTTP request/ response messages and the XML request/response messages. JAX-WS handles that translation automatically and leaves the developer to work directly with the XML messages. The downside is that with JWS implementation you are required to use two annotations (i.e. @WebServiceProvider and @BindingType) in order to leverage this functionality. For those who have not used these annotations, enabling the Web Service can seem confusing.

    Conclusions

    So now we you should be up to date with consuming, creating, and deploying RESTful Web Services using standard java.net.* classes and servlets, as well as the JAX-WS 2.0 APIs and annotations. We have also shown the similarities and differences between traditional Java techniques and the JAX-WS 2.0 approach to Web Services and look at the basic XML processing techniques used to implement SOA-style integration of RESTful Web services. We will look at

    In the next chapter, I look at the Java/XML data binding problem and how it can be addressed using traditional JAXP approaches, as well as using JAXB. As I did in this chapter, I compare and contrast the approaches so that you can see the power available to you from the JAXB machinery, but also some of the drawbacks. I help you to determine in which situation JAXB provides the most value and where you are better off using other binding tools.
    Last edited by Java Exam; 03-07-2012 at 04:53 PM.

Similar Threads

  1. Replies: 0
    Last Post: 03-07-2012, 04:04 PM
  2. Replies: 0
    Last Post: 02-24-2012, 12:33 PM
  3. Replies: 0
    Last Post: 02-15-2012, 02:28 PM
  4. Replies: 0
    Last Post: 02-14-2012, 08:21 PM
  5. Replies: 0
    Last Post: 01-17-2012, 05:53 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •