Wednesday, 25 June 2014

DOJO Hello world

DOJO is a javascript framework for developing rich UI based web applications. Dojo built using javascript and html. Best part of dojo is its supports AJAX call and ready made UI components called Widgets.

Dojo comes with below packages:

1. Dojo
2. dijit
3. Dojox
4. Util

DOJO simple application to show how dojo can be used.

1. down load Dojo libray from www.dojotoolkit.org
2. extract the zip and keep in project folder as shown below


3. jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet"
href="../dojo-release-1.0.0/dijit/themes/tundra/tundra.css">
<script type="text/javascript" djConfig="parseOnLoad: true"
src="../dojo-release-1.0.0/dojo/dojo.js"></script>

<script type="text/javascript" src="../dojo-release-1.0.0/dojo/dojo.js">

</script>

<script type="text/javascript">
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.ComboBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.DateTextBox");
</script>
</head>
<body class="tundra">
<p>Enter a date below:</p>
<input dojoType="dijit.form.DateTextBox" />
<p>Enter a Name below:</p>
<input dojoType="dijit.form.TextBox" />
<p>Select a Sate below:</p>


<select dojoType="dijit.form.ComboBox" autocomplete="true"
value="Enter a state">
<option selected="selected">Karnataka</option>
<option>AP</option>
<option>Maharastra</option>
<option>Keral</option>
</select>

<p>Check a Name below:</p>
<input dojoType="dijit.form.CheckBox" />

</body>
</html>


4. Run on server in eclipse

Now we can see the features provided by dojo like combo box, date picker etc.





Monday, 9 June 2014

REST Service


Jars Required:


1.        asm-all-3.3.1.jar
2.        commons-codec.jar
3.        commons-httpclient.jar
4.        commons-logging.jar
5.        jersey-bundle-1.14.jar
6.        json-simple.jar

 

Tools Required:
1.        Eclipse
2.        Any webserver/application server

3.     JDK 1.7

References:

http://rest.elkstein.org/

Restful service:

REST (Representational state Transfer) is an architectural style which is based on WEB standards and the HTTP protocol.

It relies on a
a.        Stateless
b.        client-server
c.        Cacheable communications protocol.
As a programming approach REST is light weight alternative to web service (SOAP) and RPC.

Features:
1.        Data which is retrieved from the server is known as resource.
2.        Resources identified over the network by URI.
3.        Bounded by standard protocol HTTP.
4.        It’s a stateless and simple
5.        Request response represented in JSON/XML/TEXT etc.
 

REST sample:

Server side implementation:

Class: WebServices.java

Using annotation @Path (“/WebServices”) in below code we are just saying this is class needs to looked up for the request http://localhost:8080/Restwebservice/webservice. Annotation @Get used for querying the resource. A method level annotation @Path (“hello”) used to identify the resource and URI for this http://localhost:8080/Restwebservice/webservice/hello. Annotation @Produces("application/json") used for specifying the response type. 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; 
@Path("/webservice")
public class WebServices { 
        private static Map<String, Employee> employees = new HashMap<String, Employee>();
        @GET
        @Path("/hello")
        @Produces("application/json")
        public List<Heloo> hello() { 
                Map hellomap = new HashMap();
                Heloo h = new Heloo();
                h.setLname("Savadi");
                h.setName("Prashant");
                hellomap.put("1", h);
                Heloo h1 = new Heloo();
                h1.setLname("Savadi");
                h1.setName("Sushant");
                hellomap.put("2", h1);
                return new ArrayList<Heloo>(hellomap.values());
        }
        @GET
        @Path("/message")
        @Produces("text/plain")
        public String showMsg(@QueryParam("message") String message) {
                return message;
        }
        @GET
        @Path("/employees")
        @Produces("application/xml")
        public List<Employee> listEmployees() {
                return new ArrayList<Employee>(employees.values());
        }
        @GET
        @Path("/employee/{employeeid}")
        @Produces("application/xml")
        public Employee getEmployee(@PathParam("employeeid") String employeeId) {
                return employees.get(employeeId);
        }
        @GET
        @Path("/json/employees/")
        @Produces("application/json")
        public Map listEmployeesJSON() {
                return  employees;
        }
        @GET
        @Path("/json/employee/{employeeid}")
        @Produces("application/json")
        public Employee getEmployeeJSON(@PathParam("employeeid") String employeeId) {
                return employees.get(employeeId);
        } 

}

Class: Heloo.java

This is model class used for returning the data.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "heloo")
public class Heloo {
        private String name;
        private String lname;
        @XmlElement
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        @XmlElement
        public String getLname() {
                return lname;
        }    
        public void setLname(String lname) {
                this.lname = lname;
        }
}

WEB.xml file entry for servlet registration:

REST is implemented by jersey API. Need jersey servlet entry in the server wheel.
<servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>
         com.sun.jersey.spi.container.servlet.ServletContainer
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>jersey-serlvet</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>

 
Client:
 
Using below client we can access the resources from server (cleint/server architecture) using URI :http://localhost:9084/Rest/webservice/hello.

Here response us JSON format and JSON data can be handled by simple-Json API. 

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class RestWebServiceClient { 

       /**

        * @param args

        */

       public static void main(String[] args) {

              RestWebServiceClient restWebServiceClient = new RestWebServiceClient();

              restWebServiceClient.sayHello();

              // restWebServiceClient.getJSONEmployees();

              /*

               * restWebServiceClient.getMessage("Welcome");

               * restWebServiceClient.getXMLEmployees();

               * restWebServiceClient.getXMLEmployee(11111);

               * restWebServiceClient.getJSONEmployees();

               * restWebServiceClient.getJSONEmployee(11111);

               */

       }

       private void sayHello() {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:9084/Rest/webservice/hello");

                     ClientResponse response = webResource.accept("application/json")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     } 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getResponse============");
                     Object p = new JSONParser().parse(output);

                     JSONObject array = (JSONObject) p;

                     JSONArray jarray = (JSONArray) array.get("heloo");

                     Heloo h=null;

                     List list = new ArrayList();                   

                     Iterator it = jarray.iterator();

                     while (it.hasNext()) {

                           h= new Heloo();
                           JSONObject obj=((JSONObject) it.next());
                           System.out.println(obj.get("name"));
                           System.out.println(obj.get("lname"));
                           h.setName(obj.get("name")+"");
                           h.setLname(obj.get("lname")+"");
                           list.add(h);                   

                          

                     }

                      System.out.println(list.toString());

              } catch (Exception e) {
                     e.printStackTrace();

              }
       }


       private void getMessage(String msg) {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/message/"

                                                + msg);

                     ClientResponse response = webResource.accept("text/plain").get(

                                  ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getXMLEmployees() {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/employees");

                     ClientResponse response = webResource.accept("application/xml")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getXMLEmployee(int empid) {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/employee/"

                                                + empid);

                     ClientResponse response = webResource.accept("application/xml")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getJSONEmployees() {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/json/employees/");

                     ClientResponse response = webResource.accept("application/json")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getJSONEmployee(int empid) {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/json/employee/"

                                                + empid);

                     ClientResponse response = webResource.accept("application/json")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

}