Saturday 2 March 2013

How to create a Restful Web service

How to create a Restful Web service?

This example help you all to understand the basics of Restful Webservice creation without any plugin

You  need to do the following things to do
1)Create a Dynamic Web Project
2)Put the following jar files into the WEB-INF/lib folder
asm-x.x.jar
jersey-core-x.x.jar
jersey-json-x.x.jar
jersey-server-x.x.jar
jersey-servlet-x.x.jar
jersey-bundle-x.x.jar
jsr311-api.jar

3)Configure the web.xml.The code is given below

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Rest WS Test</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.test</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>


4)Write a Class which extends the Application.This class  we need to override the classes which need to publish the web service methods

package com.test;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;



public class TestApplication extends Application{
    @Override
    public Set<Class<?>> getClasses(){
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(TestRestWebService.class);
        return classes;
    }

}

5)Web service classes in which we actually define the web methods(Ideompotent methods) like GET,POST,PUT,DELETE etc.

package com.test;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

@Path("/testrs")

public class TestRestWebService {

    @GET
    public String getInfo(@QueryParam("name") String name) {
        Date dt=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat();
        
        String str="Hello Mr "+ name+" Today is "+ dt.getDate() +"-"+dt.getMonth()+"-"+(Integer.valueOf(dt.getYear())+1900);
        return str;
    }
    @POST
    public String postInfo(@QueryParam("name") String name) {
        Date dt=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat();
        
        String str="Hello Mr post "+ name+" Today is "+ dt.getDate() +"-"+dt.getMonth()+"-"+(Integer.valueOf(dt.getYear())+1900);
        return str;
    }
    
    @PUT
    public String putInfo(@QueryParam("name") String name) {
        Date dt=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat();
        
        String str="Hello Mr put "+ name+" Today is "+ dt.getDate() +"-"+dt.getMonth()+"-"+(Integer.valueOf(dt.getYear())+1900);
        return str;
    }
    
}


6)Create war file and deploy it in server.
I assume you are using a tomcat server then

your request for rest call looks like

http://localhost:8080/<ProjectName>/rest/testrs?name=xxxx

Monday 26 November 2012

Simple Web Service Creation Example Using CXF Framework and SOAP in Eclips

Simple Web Service Development Example Using CXF Framework:---

Required Configuration :
1)JDK 1.5 and above
2)Eclipse
3)CXF 2+

Plug CXF  with the eclipse:

1)Open the eclipse IDE
2)Go to Window menu then click on the Preference
3)Then go to Web service link and select CXF
4)A window will  open where you will add the CXF home path

5)Then click ok

Create a simple web service using cxf:
For this example iam follow a bottum up approach

1)Creat a simple dynamic web project

2)Create a Class SimpleWebServiceImpl

package com.nik.test;

public class SimpleWebServiceImpl {
   
    public  String addMethod(int a,int b){
        return "Your sum is ="+(a+b);
    }

}

3)Right click on the class and go to New->Other -> Web Service link and select Web service from the populated links
4)
Select the web service type ->
Browse the service Implementation Class ->
Edit the configuration by --Selecting the server runtime, Web Service runtime
Select Client Type as Java Proxy ->
Check in the options if You want to publish and moniter the web services..
Clic Next


5)Select the method to publish as a web service and click next


6)Click next
 7)Click next
 8)Start server
9)Click next
 10)Click Finish
 11)The Web Serviice Explorer window open
 12)Click on the method link and add the parameter value and click ok
13)This shows that your web service method is successfully published

Wednesday 3 October 2012

How to access REST web services as a client

What is REST?
Representational State Transfer (REST)is the method used to create and in order to communicate with the web services. It is primarily used to build Web services that are lightweight, maintainable, and scalable.REST web service used HTTP protocol  in order to perform the four operations  create, read, update and delete by calling the methods post,get,put and delete respectively.

HTTP request includes VERB,URI,HTTP VERSION,Request Header and Request Body 
VERB is one of the HTTP methods like GET, PUT, POST, DELETE, OPTIONS, etc
URI is the URI of the resource on which the operation is going to be performed
HTTP Version is the version of HTTP, generally "HTTP v1.1" .
Request Header contains the metadata as a collection of key-value pairs of headers and their values. These settings contain information about the message and its sender like client type, the formats client supports, format type of the message body, cache settings for the response, and a lot more information.
Request Body is the actual message content. In a RESTful service, that's where the representations of resources sit in a message.

How to access rest web services from client site ?

The example for a get request is given below...

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class RESTWebServiceGet {   
   
    public static void main(String[] args) throws Exception {
        String request = "http://twitter.com/statuses/user_timeline.xml?id=xxx";
    
       //Create http client
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(request);
       
        // Send GET request
        int statusCode = client.executeMethod(method);
       
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        InputStream rstream = null;
       
        // Get the response body
        rstream = method.getResponseBodyAsStream();
       
        // Process the response from Yahoo! Web Services
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line+"------");
        }
        br.close();
    }

}