Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Saturday 27 July 2013

Implementing REST WebService using JAX-WS

This example was implemented on Weblogic 10.3 server.
The following example demonstrates how to implement a simple REST WebService using JAX-WS. This example shows the following two ways to pass parameters to a REST Webservice as part of a HTTP GET Request
  • Query String
    http://localhost:7001/RestfulWS/RestfulWS?i=1&j=5
  • Path Info
    http://localhost:7001/RestfulWS/RestfulWS/i/1/j/5
In order to implement you have to
More
  1. Implement the Provider Interface
    @WebServiceProvider(targetNamespace = "http://java-x.blogspot.com/wsSamples/restfulWebService1", serviceName = "RestfulWS")
    @BindingType(value = HTTPBinding.HTTP_BINDING)
    public class RestfulWS implements Provider<Source> {
    The provider interface has only one method invoke(). Setting the BindingType annotation to HTTP_BINDING ensures that HTTP GET requests are sent to this service. The most common way to implementing Provider interface is using Provider which is used to pass XML data back to the client

  2. Implementing the invoke Method: The invoke method handles the all the logic for the Service. In the following snippet, you can see how to get the request type and the handling logic based on whether the request parameters are sent in a QueryString or as part of the request path.
       String requestMethod = (String) messageContext.get(MessageContext.HTTP_REQUEST_METHOD);
    String query = (String) messageContext.get(MessageContext.QUERY_STRING);
    String path = (String) messageContext.get(MessageContext.PATH_INFO);
  3. Implementing the process request: In this method, you can see that the request parameter string is parsed by using separators "&", "=" and "/". This enables handling of both QueryString ("&" and "=") and Path Info ("/") requests.
      StringTokenizer st = new StringTokenizer(queryString, "=&/");
  4. Implementing createSource Method: This method creates an XML string that will be sent as the response as a StreamSource.
    return new StreamSource(new ByteArrayInputStream(result.getBytes()))
  5. Create a web.xml descriptor: The descriptor file should contain a servlet-mapping for the servlet "[ServiceName]Servlethttp" to accept all requests to [ServiceName]/* to allow path info requests. Make sure that you do add the servlet declaration as this is done by JWSC ant task and may create a duplicate.
    <servlet-mapping>
    <servlet-name>RestfulWSServlethttp</servlet-name>
    <url-pattern>/RestfulWS/*</url-pattern>
    </servlet-mapping>

    The reason for creating a servlet-maping is because the JWSC ant task creates the servlet and a servlet mapping in the web.xml, however, the mapping generated by JWSC maps to [ServiceName]/ and not [ServiceName]/*, which means that path info requests will not be processed.
  6. Creating the Web Service using ANT: The following ant task creates the webservice as an exploded WAR.
    <target name="build.service" description="Target that builds the Web Service">
    <echo message="${java.class.path}" />
    <mkdir dir="${ear.dir}" />
    <jwsc srcdir="./src/com/blogspot/aoj/restws/" destdir="${ear.dir}" fork="true" keepGenerated="true" deprecation="${deprecation}" debug="${debug}" verbose="false">
    <jws file="${ws.file}.java" explode="true" type="JAXWS" >
    <descriptor file="./resources/web.xml" />
    </jws>
    </jwsc>
    </target>
    The task has to contain the location of web.xml file created earlier. This file will be modified by JWSC
The complete sources
  • RestfulWS.java:
    package com.blogspot.aoj.restws;

    /**
    * @author Abhi Vuyyuru
    */

    import java.io.ByteArrayInputStream;
    import java.util.StringTokenizer;

    import javax.annotation.Resource;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.ws.BindingType;
    import javax.xml.ws.Provider;
    import javax.xml.ws.WebServiceContext;
    import javax.xml.ws.WebServiceProvider;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.http.HTTPBinding;

    @WebServiceProvider(targetNamespace = "http://java-x.blogspot.com/wsSamples/restfulWebService1", serviceName = "RestfulWS")
    @BindingType(value = HTTPBinding.HTTP_BINDING)
    public class RestfulWS implements Provider<Source> {
    public Source invoke(Source source) {
    try {
    MessageContext messageContext = wsContext.getMessageContext();
    String requestMethod = (String) messageContext.get(MessageContext.HTTP_REQUEST_METHOD);
    String query = (String) messageContext.get(MessageContext.QUERY_STRING);
    String path = (String) messageContext.get(MessageContext.PATH_INFO);

    if (requestMethod.equals("GET")) {
    if (query != null && query.contains("i=") && query.contains("j=")) {
    return processRequest(query);
    } else {
    return processRequest(path);
    }
    } else {
    throw new Exception("Unsupported operation");
    }

    } catch (Exception e) {
    e.printStackTrace();
    return createSource(1, e.getMessage());
    }
    }

    private Source processRequest(String queryString) {
    StringTokenizer st = new StringTokenizer(queryString, "=&/");
    st.nextToken();
    int i = Integer.parseInt(st.nextToken());
    st.nextToken();
    int j = Integer.parseInt(st.nextToken());

    return createSource(i + j, "Sum");
    }

    private Source createSource(int status, String errorMessage) {
    String result = null;
    result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><Response><StatusCode>" + status
    + "</StatusCode><StatusMessage>" + errorMessage + "</StatusMessage></Response>";
    return new StreamSource(new ByteArrayInputStream(result.getBytes()));
    }

    @Resource(type = Object.class)
    protected WebServiceContext wsContext;
    }
  • resources/web.xml

    <?xml version='1.0' encoding='UTF-8'?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5">
    <display-name>RestfulWSWebApp</display-name>
    <servlet-mapping>
    <servlet-name>RestfulWSServlethttp</servlet-name>
    <url-pattern>/RestfulWS/*</url-pattern>
    </servlet-mapping>
    </web-app>
  • build.xml
    <project name="wsSamples" default="all" basedir=".">
    <!-- set global properties for this build -->
    <property file="./build.properties" />
    <property name="ws.file" value="RestfulWS" />
    <property name="ear.dir" value="${build.dir}/wsSamples" />
    <taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" />
    <!--Target that builds sample Web Service and client-->
    <target name="all" description="Target that builds sample Web Service and client" depends="clean,build.service,deploy" />
    <!--Target that builds sample Web Service and client-->
    <target name="build" description="Target that builds sample Web Service and client" depends="build.service" />
    <target name="clean">
    <delete dir="${ear.dir}" />
    <delete dir="${client.dir}" />
    </target>

    <!-- Target that builds the Web Service-->
    <target name="build.service" description="Target that builds the Web Service">
    <echo message="${java.class.path}" />
    <mkdir dir="${ear.dir}" />

    <jwsc srcdir="./src/com/blogspot/aoj/restws/" destdir="${ear.dir}" fork="true" keepGenerated="true" deprecation="${deprecation}" debug="${debug}" verbose="false">
    <jws file="${ws.file}.java" explode="true" type="JAXWS" >
    <descriptor file="./resources/web.xml" />
    </jws>
    </jwsc>
    </target>

    <!-- Target that deploys the Web Service-->
    <target name="deploy" description="Target that deploys the Web Service">
    <wldeploy action="deploy" source="${ear.dir}" user="${wls.username}" password="${wls.password}" verbose="true" failonerror="${failondeploy}" adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
    </target>
    </project>
  • build.properties
    bea.home=c:/bea
    wl.home=${bea.home}/wlserver_10.3
    wls.hostname=localhost
    wls.port=7001
    wls.username=weblogic
    wls.password=password
    wls.server.name=AdminServer
    debuglevel=lines,vars,source
    sourceVersion=1.6

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...