Saturday, April 12, 2014

ReST Web Service Implementation step by step.

www.javabykiran.com

Below are steps should be followed to make simple application for REST full Web service implementation.


First create server (Host web service) -- Create web application [Web Project in eclipse]


Add below Jars






Web.xml


<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--  Auto scan REST service  -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

Create Model Class



import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "user")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@XmlAttribute(name = "id" )
private int id;

@XmlElement(name = "firstName")
private String firstName;

@XmlElement(name = "lastName")
private String lastName;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

}


Create Service Class




import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/user-management")
public class UserManagementModule {
@GET
@Path("/users")
public Response getAllUsers() {
String result = "First demo ";
System.out.println(result);
return Response.status(200).entity(result).build();
}

@GET
@Path("/users/{id}")
public Response getUserById(@PathParam("id")
Integer id) {
String result = "<user id=\"10\"><firstName>demo</firstName>"
+ "<lastName>user</lastName></user>";
return Response.status(200).entity(result).build();

}

/*
* @GET @Path("retrieve/{uuid}") public Response
* retrieveSomething(@PathParam("uuid") String uuid) { if(uuid == null ||
* uuid.trim().length() == 0) { return Response.serverError().entity("UUID
* cannot be blank").build(); } // Entity entity = service.getById(uuid);
* if(entity == null) { return
* Response.status(Response.Status.NOT_FOUND).entity("Entity not found for
* UUID: " + uuid).build(); } String json = //convert entity to json return
* Response.ok(json, MediaType.APPLICATION_JSON).build(); }
*/
@POST
@Path("/users123")
public Response createUser(String dd) {
System.out.println(dd);
String result = "<user id=\"10\"><firstName>demo</firstName><lastName>user</lastName></user>";
return Response.status(200).entity(result).build();

}

/*@Path("/hello")
public class Hello {

@POST
@Produces(MediaType.APPLICATION_ATOM_XML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj)
throws Exception {

String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);

return outputJsonObj;
}
}
*/
}




Client Code not to be deployed on server



import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.howtodoinjava.model.User;

public class DemoHttpRESTfulClient
{
public static void main(String[] args) throws Exception
{
//Demo Get request
//demoGetRESTAPI();

//Demo Post request
demoPostRESTAPI();
}


public static void demoGetRESTAPI() throws Exception
{
DefaultHttpClient httpClient = new DefaultHttpClient();
try
{
//Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also.
//Choice depends on type of method you will be invoking.
//HttpGet getRequest = new HttpGet("http://localhost:8090/RestSer/user-management/users/10");
//HttpGet getRequest = new HttpGet("http://localhost:8090/RestSer/user-management-service/user1");
HttpGet getRequest = new HttpGet("http://localhost:8090/RestSer/user-management-service/user2XML");

//Set the API media type in http accept header
getRequest.addHeader("accept", "application/xml");

//Send the request; It will immediately return the response in HttpResponse object
HttpResponse response = httpClient.execute(getRequest);

//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200)
{
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}

//Now pull back the response object
HttpEntity httpEntity = response.getEntity();
String apiOutput = EntityUtils.toString(httpEntity);

//Lets see what we got from API
System.out.println(apiOutput); //<user id="10"><firstName>demo</firstName><lastName>user</lastName></user>

//In realtime programming, you will need to convert this http response to some java object to re-use it.
//Lets see how to jaxb unmarshal the api response content
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
       Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
       User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
     
     
     
     
     
       //Verify the populated object
       System.out.println(user.getId());
       System.out.println(user.getFirstName());
       System.out.println(user.getLastName());
}
finally
{
//Important: Close the connect
httpClient.getConnectionManager().shutdown();
}
}

public static void demoPostRESTAPI() throws Exception
{
DefaultHttpClient httpClient = new DefaultHttpClient();

User user = new User();
user.setId(100);
user.setFirstName("jbk");
user.setLastName("javabykiran");

StringWriter writer = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.marshal(user, writer);
     
try
{
//Define a postRequest request
HttpPost postRequest = new HttpPost("http://localhost:8090/RestSer/user-management/users123");

//Set the API media type in http content-type header
postRequest.addHeader("content-type", "application/xml");

//Set the request post body
StringEntity userEntity = new StringEntity(writer.getBuffer().toString());
postRequest.setEntity(userEntity);

//Send the request; It will immediately return the response in HttpResponse object if any
HttpResponse response = httpClient.execute(postRequest);

//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200)
{
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
}
finally
{
//Important: Close the connect
httpClient.getConnectionManager().shutdown();
}
}

public static void demoPostJsonRESTAPI() throws Exception
{/*
DefaultHttpClient httpClient = new DefaultHttpClient();

User user = new User();
user.setId(100);
user.setFirstName("jbk");
user.setLastName("javabykiran");

StringWriter writer = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.marshal(user, writer);
     
try
{
 ClientConfig config = new DefaultClientConfig();
 Client client = Client.create(config);
 client.addFilter(new LoggingFilter());
 WebResource service = client.resource(getBaseURI());
 JSONObject inputJsonObj = new JSONObject();
 inputJsonObj.put("input", "Value");
 System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));}
finally
{
//Important: Close the connect
httpClient.getConnectionManager().shutdown();
}*/
}


}


No comments: