WELCOME Abdennour : Software engineer

May 19, 2012

CRUD RESTful webservice : Part2





1.CRUD RESTful webservice :
2.Create Client :




1.CRUD RESTful webservice

1.1.  Project

Create a new dynamic project "crudJaxRs" and add the jersey libs.





 Modify "web.xml" to the following.
    
<?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>crudJaxRs</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>slm.abdennour.jersey.soura.resources</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>

   
Create the following :
  >> data model (Bean)and 
  >>a Dummy DB which serves as the data provider for the model.( via enumeration).

package slm.abdennour.jersey.soura.model; import javax.xml.bind.annotation.XmlRootElement; /** * * @author عبد النور Abdennour Soura=السورة * @since 18 mai 2012 */ @XmlRootElement public class Soura { /** * رقم السورة في القرآن الكريم */ String id; /** * اسم السورة */ String name; /** * تفسير السورة */ String tfsir; public Soura() { } public Soura(String id, String name) { super(); this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTfsir() { return tfsir; } public void setTfsir(String tfsir) { this.tfsir = tfsir; } }
    
package slm.abdennour.jersey.soura.dao;

import java.util.HashMap;
import java.util.Map;

import slm.abdennour.jersey.soura.model.Soura;
//Virtual Data Base
public enum SouraDao { instance; private Map<String, Soura> contentProvider = new HashMap<String, Soura>(); private SouraDao() { //سورة الفاتحة Soura soura=new Soura
("1","الفاتحة"); soura.setTfsir("Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml"); contentProvider.put("1", soura); //سورة الإخلاص soura=new Soura("112","الإخلاص"); soura.setTfsir("Read http://www.ibnothaimeen.com/all/books/article_17898.shtml"); contentProvider.put("2", soura); } public Map<String, Soura> getModel() { return contentProvider; } }

1.2.  Create a simple HTML form

The following HTML form will allow to post new data to the service. 
==¦Create the following page "save_soura.html" in the folder "WEB-INF".
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

 <form action="../crudJaxRs/rest/souwar" method="POST">
 <label for="id">رقم السورة</label>
 <input name="id" />
 <br/>
 <label for="name">اسم السورة</label>
 <input name="name" />
 <br/>
 رابط تفسير السورة
 <TEXTAREA NAME="tfsir" COLS=40 ROWS=6></TEXTAREA>
 <br/>
 <input type="submit" value="Submit" />
 </form>
</body>
</html>   

 1.3.  Rest Service

Create the following classes which will be used as REST resources.
    
package slm.abdennour.jersey.soura.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import slm.abdennour.jersey.soura.dao.SouraDao;
import slm.abdennour.jersey.soura.model.Soura;

public class SouraResource {
 @Context
 UriInfo uriInfo;
 @Context
 Request request;
 String id;

 public SouraResource(UriInfo uriInfo, Request request, String id) {
  this.uriInfo = uriInfo;
  this.request = request;
  this.id = id;
 }

 // Application integration
 @GET
 @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
 public Soura getSoura() {
  Soura soura = SouraDao.instance.getModel().get(id);
  if (soura == null)
   throw new RuntimeException("Get: Todo with " + id
     + " not saved yet or not soura ");

  return soura;
 }
 // For the browser
 @GET
 @Produces(MediaType.TEXT_XML)
 public Soura getSouraHTML() {
  Soura soura = SouraDao.instance.getModel().get(id);
  if(soura==null)
   throw new RuntimeException("Get: Soura with numero " + id +  " not saved");
  return soura;
 }
 
 @PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response putSoura(JAXBElement<Soura> soura) {
  Soura c = soura.getValue();
  return putAndGetResponse(c);
 }
 
 @DELETE
 public void deleteSoura() {
  Soura c = SouraDao.instance.getModel().remove(id);
  if(c==null)
   throw new RuntimeException("Delete: Soura with numero" + id +  " not saved");
 }
 
 private Response putAndGetResponse(Soura soura) {
  Response res;
  if(SouraDao.instance.getModel().containsKey(soura.getId())) {
   res = Response.noContent().build();
  } else {
   res = Response.created(uriInfo.getAbsolutePath()).build();
  }
  SouraDao.instance.getModel().put(soura.getId(), soura);
  return res;
 }
}

   
    
package slm.abdennour.jersey.soura.resources;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import slm.abdennour.jersey.soura.dao.SouraDao;
import slm.abdennour.jersey.soura.model.Soura;
@Path("/souwar")
public class SouwarResource {

 // Allows to insert contextual objects into the class, 
 // e.g. ServletContext, Request, Response, UriInfo
 @Context
 UriInfo uriInfo;
 @Context
 Request request;


 // Return the list of souwar to the user in the browser
 @GET
 @Produces(MediaType.TEXT_XML)
 public List<Soura> getSouwarBrowser() {
  List<Soura> souwar = new ArrayList<Soura>();
  souwar.addAll( SouraDao.instance.getModel().values() );
  return souwar; 
 }
 
 // Return the list of souwar for applications
 @GET
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 public List<Soura> getSouwar() {
  List<Soura> souwar = new ArrayList<Soura>();
  souwar.addAll( SouraDao.instance.getModel().values() );
  return souwar; 
 }
 
 
 // retuns the number of souwar
 // Use http://localhost:8080/crudJaxRs/rest/souwar/count
 // to get the total number of records
 @GET
 @Path("count")
 @Produces(MediaType.TEXT_PLAIN)
 public String getCount() {
  int count = SouraDao.instance.getModel().size();
  return String.valueOf(count);
 }
 
 @POST
 @Produces(MediaType.TEXT_HTML)
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public void newSoura(
   @FormParam("id") String id,
   @FormParam("name") String name,
   @FormParam("tfsir") String tfsir,
   @Context HttpServletResponse servletResponse
 ) throws IOException {
  Soura soura = new Soura(id,name);
  if (tfsir!=null){
   soura.setTfsir(tfsir);
  }
  SouraDao.instance.getModel().put(id, soura);
  
  servletResponse.sendRedirect("../save_soura.html");
 }
 
 
 // Defines that the next path parameter after souwar is
 // treated as a parameter and passed to the SouraResources
 // Allows to type http://localhost:8080/crudJaxRs/rest/souwar/1
 // 1 will be treaded as parameter soura and passed to SouraResource
 @Path("{soura}")
 public SouraResource getSoura(
   @PathParam("soura") String id) {
  return new SouraResource(uriInfo, request, id);
 }

}

   
This TodosResource uses "@PathParam" annotation to use the parameter "id" to forward the request to the class "TodoResource".

1.4.  Run

Run you web application in Eclipse and test the availability of your REST service under: "http://localhost:8080/crudJaxRs/rest/souwar". You should see the XML representation of your Todo items.


1.5. Source Code : 
2.Create Client:

1.1.Client REST Code : 
>>Create a Java project "clientCrudRS". 
>>Create a folder "lib",
 >>place all jersey libs there and add then to your classpath. 
>>Create the following class.
    

package slm.abdennour.jersey.soura.client;
import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import slm.abdennour.jersey.soura.model.Soura;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;
public class Tester {
 public static void main(String[] args) {
  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  WebResource service = client.resource(getBaseURI());
  // Create one soura
  Soura soura = new Soura("114", "الناس" );
  ClientResponse response = service.path("rest").path("souwar").path(soura.getId()).accept(MediaType.APPLICATION_XML).put(ClientResponse.class, soura);
  // Return code should be 201 == created resource
  System.out.println(response.getStatus());
  // Get the Souras
  System.out.println(service.path("rest").path("souwar").accept(
    MediaType.TEXT_XML).get(String.class));
  // Get XML for application
  System.out.println(service.path("rest").path("souwar").accept(
    MediaType.APPLICATION_JSON).get(String.class));
  // Get JSON for application
  System.out.println(service.path("rest").path("souwar").accept(
    MediaType.APPLICATION_XML).get(String.class));
  
  // Get the  Soura with id 1
  System.out.println(service.path("rest").path("souwar/1").accept(
    MediaType.APPLICATION_XML).get(String.class));
  // get Soura with id 114 
  service.path("rest").path("souwar/114").delete();
  // Get the all souwar, id 1 should be deleted
  System.out.println(service.path("rest").path("souwar").accept(
    MediaType.APPLICATION_XML).get(String.class));
  
  
  // Create a Soura
  Form form = new Form();
  form.add("id", "113");
  form.add("name", "الفلق");
  response = service.path("rest").path("souwar").type(MediaType.APPLICATION_FORM_URLENCODED)
           .post(ClientResponse.class, form);
  System.out.println("Form response " + response.getEntity(String.class));
  // Get the all souwar, id 113 should be created
  System.out.println(service.path("rest").path("souwar").accept(
    MediaType.APPLICATION_XML).get(String.class));
  
 }
 private static URI getBaseURI() {
  return UriBuilder.fromUri(
    "http://localhost:8080/crudJaxRs").build();
 }
}





2.2.Consol RESULT :


201
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><souras><soura><id>112</id><name>الإخلاص</name><tfsir>Read http://www.ibnothaimeen.com/all/books/article_17898.shtml</tfsir></soura><soura><id>114</id><name>الناس</name></soura><soura><id>1</id><name>الفاتحة</name><tfsir>Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml</tfsir></soura></souras>
{"soura":[{"id":"112","name":"الإخلاص","tfsir":"Read http://www.ibnothaimeen.com/all/books/article_17898.shtml"},{"id":"114","name":"الناس"},{"id":"1","name":"الفاتحة","tfsir":"Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml"}]}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><souras><soura><id>112</id><name>الإخلاص</name><tfsir>Read http://www.ibnothaimeen.com/all/books/article_17898.shtml</tfsir></soura><soura><id>114</id><name>الناس</name></soura><soura><id>1</id><name>الفاتحة</name><tfsir>Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml</tfsir></soura></souras>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><soura><id>1</id><name>الفاتحة</name><tfsir>Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml</tfsir></soura>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><souras><soura><id>112</id><name>الإخلاص</name><tfsir>Read http://www.ibnothaimeen.com/all/books/article_17898.shtml</tfsir></soura><soura><id>1</id><name>الفاتحة</name><tfsir>Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml</tfsir></soura></souras>
Form response <html><head><title>Apache Tomcat/7.0.12 - Rapport d''erreur</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>Etat HTTP 404 - /crudJaxRs/rest/../save_soura.html</h1><HR size="1" noshade="noshade"><p><b>type</b> Rapport d''état</p><p><b>message</b> <u>/crudJaxRs/rest/../save_soura.html</u></p><p><b>description</b> <u>La ressource demandée (/crudJaxRs/rest/../save_soura.html) n'est pas disponible.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.12</h3></body></html>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><souras><soura><id>112</id><name>الإخلاص</name><tfsir>Read http://www.ibnothaimeen.com/all/books/article_17898.shtml</tfsir></soura><soura><id>1</id><name>الفاتحة</name><tfsir>Read http://www.ibnothaimeen.com/all/books/printer_16805.shtml</tfsir></soura><soura><id>113</id><name>سورة الفلق</name></soura></souras>




Reference : 










No comments:

Post a Comment