Loading
Jax Ws RestFul Service Example

Java Quick Notes

Refresh Your Java - Before Java Interview

We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

Go to SiteMap

Q)  Jax-Ws RestFul Service Example


Ans)

 

Client :

public class RESTclient {
    private Service service;
        private JAXBContext jc;
    private static final String url = "http://127.0.0.1:9090/restfulwebservice-war/poservice/";
    private static final QName qname = new QName("", "");
    private static final String poXML = "<tns:PurchaseOrderDocument  
        xmlns:tns=\"urn:PurchaseOrderDocument\">\n" ;
   
        public RESTclient() {
        try {
            jc = JAXBContext.newInstance("com.sun.examples.rest");
        } catch(JAXBException je) {
            System.out.println("Cannot create JAXBContext " + je);
        }
       
    }
       
         private void acceptPO() {
                service = Service.create(qname);
                service.addPort(qname, HTTPBinding.HTTP_BINDING, url + "acceptPO");
        Dispatch<Source> dispatcher = service.createDispatch(qname, Source.class, Service.Mode.MESSAGE);
        Map<String, Object> requestContext = dispatcher.getRequestContext();

        requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "POST");
        Source result = dispatcher.invoke(new StreamSource(new StringReader(poXML)));
        printSource(result);
    }
       
         public static void main(String argsp[]) throws Exception{
        RESTclient client= new RESTclient();
        client.acceptPO();
        client.acceptPOJAXB();
    }

}

Server Side :

@javax.xml.ws.WebServiceProvider
@javax.xml.ws.ServiceMode(value=javax.xml.ws.Service.Mode.MESSAGE)

public class PurchaseOrderService  implements Provider<Source>{


 

        private JAXBContext jc;
   
    @javax.annotation.Resource(type=Object.class)
    protected WebServiceContext wsContext;
   
    public PurchaseOrderService() {
        try {
            jc = JAXBContext.newInstance("com.sun.examples.rest");
           
        } catch(JAXBException je) {
            System.out.println("Exception " + je);
            throw new WebServiceException("Cannot create JAXBContext", je);
        }
    }

 public Source invoke(Source source) {
        try{
            MessageContext mc = wsContext.getMessageContext();
            String path = (String)mc.get(MessageContext.PATH_INFO);
            String method = (String)mc.get(MessageContext.HTTP_REQUEST_METHOD);
            System.out.println("Got HTTP "+method+" request for "+path);
                    if (method.equals("GET"))
 
                       return get(mc);
                        if (method.equals("POST"))
                                    return post(source, mc);
                if (method.equals("PUT"))
                                        return put(source, mc);
                if (method.equals("DELETE"))
                                        return delete(source, mc);
                        throw new WebServiceException("Unsupported method:" +method); 
        } catch(JAXBException je) {
            throw new WebServiceException(je);
        }
    }
 

    /**
     * Handles HTTP GET.
     */
 private Source get(MessageContext mc) throws JAXBException {
        String path = (String)mc.get(MessageContext.PATH_INFO);
            if((path.indexOf("/errortest")!=-1)  || path.equals("") || path.equals("/")){
                         mc.put(MessageContext.HTTP_RESPONSE_CODE, 400);
             POProcessingProblem fault= new POProcessingProblem();
             fault.setMessage("Unable to retrieve the order associated with the orderid you specified");
             return new JAXBSource(jc, new ObjectFactory().createPOProcessingFault(fault));
                                }

                // demonstrates verb in path strategy
        if (path != null && path.lastIndexOf("/acceptPO")!=-1) {
            try{
          String xml= java.net.URLDecoder.decode(path.substring(10,path.length()),"UTF-8");
                  String replacedstr=xml.replace("http:/","http://");

                        Unmarshaller u = jc.createUnmarshaller();
                        JAXBElement o = (JAXBElement)u.unmarshal(new StringReader(xml.trim()));
                        PurchaseOrder request = (PurchaseOrder)o.getValue();
                        PurchaseOrderStatus response= acceptPO(request);
                     return new JAXBSource(jc, new ObjectFactory().createStatus(response));
                        }catch(java.io.UnsupportedEncodingException e){}
                }
                else
                {               path.replace("/","");
                                        PurchaseOrder order= retreivePO(path);
                                        return new JAXBSource(jc, new ObjectFactory().createPurchaseOrderDocument(order));

                }
                throw new WebServiceException("Webservice does not understand the operation you invoked="+path);
    }
}

Web XML :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>PurchaseOrder Service</display-name>
  <listener>
    <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
  </listener>
  <servlet>
    <display-name>POServiceImpl</display-name>
    <servlet-name>POServiceImpl</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>POServiceImpl</servlet-name>
    <url-pattern>/poservice/*</url-pattern>
  </servlet-mapping>
</web-app>

sun-jaxws.xml :
<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
    <endpoint name="RESTfulWebService"
        implementation="com.sun.examples.rest.PurchaseOrderService" 
        binding="http://www.w3.org/2004/08/wsdl/http"
          url-pattern='/poservice/*'/>
</endpoints>



Back to top

------------------------- We hope you got necessary Info On -----------------------------------------

Jax Ws RestFul Service Example


Jax Ws RestFul Service Example

-------------------------------------------------------------------------------------------------------



Face Book
Request for a Mock Interview/Training

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free