Monday 16 December 2013

JAX-RS


JAX-RS

Hello Friends hope you All are aware of Restful web services.if not than let me put something about Restful web service.There are two ways using which Client can access web service
(1) SOAP
(2) Restful

The key Difference between Soap web service and Restful web service is using Restful web service is in Restful web service client can access resource using its Uri.in soap web service client have to go through WSDL(WebService Description Language) in order to access web service.here i am using jetty plugin which is http server inorder to handle http request initiated by client .you need to add this plugin into project.


i am defining university Resource which consist of various web methods.getData(),getHTMLUniversityInfo(),getStudentInfo() etc.note that i am pulling out data using jdbc API that means is i am integrating jdbc with restful web services.

Restful web service architecture will look like given below:



in order to deploy web application i need to have one jsp page to make sure that application is successfully deployed on web server.even if it is of no use.


//Static Connection Class
package org.demo.jaxrs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionUtil
{
   
   
    private static Connection conn;

    public static Connection getConn()
    {
        return conn;
    }

    public static void setConn(Connection conn) {
        ConnectionUtil.conn = conn;
    }
   
    public static Connection  getConnection()
    {
       
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            conn=DriverManager.getConnection("jdbc:derby://localhost:1527/sample,create=true","app","app");
           
           
        }
        catch(ClassNotFoundException cn){cn.printStackTrace();}
        catch (InstantiationException e) {e.printStackTrace();}
        catch (IllegalAccessException e) {e.printStackTrace();}
        catch (SQLException e) {e.printStackTrace();}
       
       
        return conn;
       
    }
   
}
//University Resource ,can be pulled up as a Restful web service
package org.demo.jaxrs;




import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.PreparedStatement;
//import javax.enterprise.inject.Produces;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;


//using jax-rs ,the resource can be accessed using uri where as in jax-ws ,client have to go through wsdl
@Path("/university")
//university is resource that client can access

public class University
{

      
//i am using precompiled version of query
    ResultSet rs;
    PreparedStatement ps;
   
   
    @GET
   
    @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
   
    public String getData()
    {
        String rollno="";
        String name="";
        try
        {
            ps=ConnectionUtil.getConnection().prepareStatement("select * from university");
            rs=ps.executeQuery();
          
            while(rs.next())
            {
                  rollno = rs.getString("Rollno");
                    name = rs.getString("name");
                  
                  
            }
          
        } catch (SQLException e){e.printStackTrace();}
      
      
      
        return  rollno.toString()+name.toString();
    }
        @GET
      
        @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
      
        public String getHTMLUniversityInfo()
        {
            return "<html>" +"<title>"+"University information"+"</title>"+"<body><h1>"+"Name -Indian University"+"</body></h1>"+"</html>";
          
        }
      
        @GET
        @Path("{studentrollno1}/{name}")

      
        //you can also use return type as a responsebuilder which returns status code if it successfully compiles
        @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
        public String getStudentInfo(@PathParam("studentrollno1") String roll1,@PathParam("name") String name)
        {
            int count =0;
          
          
            try
            {
                ps=ConnectionUtil.getConnection().prepareStatement("select * from university where (first_name = ? or last_name = ?) and address = ?");
                rs=ps.executeQuery("select * from university ");
              
                ps.setString(1, roll1);
                ps.setString(2, name);
              
                 count=ps.executeUpdate();
              
              
            }
            catch (SQLException e) {e.printStackTrace();}
          
          
          
          
            return "you sent me  roll number & name  using path param annotation : "+roll1+"roll no: 2"+name+"with Update is :"+count;
        }
      
        @GET
        @Path("{filename}")
      
      
        @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
        public Response getFileInTextFormat(@PathParam("fileName") String fileName)
        {
          
                System.out.println("File Requested is :  "+fileName);
      
              
                if(fileName==null || fileName.isEmpty())
                {
                    ResponseBuilder response=Response.status(Status.BAD_REQUEST);
                  
                    return response.build();
                  
                }
                File file=new File("D:/demoTxtFile.txt");
              
              
                ResponseBuilder response=Response.ok((Object)file);
                    response.header("Content-Disposition","attatchment;filename=\"howtodoinjava.txt\"");
      
                return response.build();
              
        }
        @GET
        @Path("{fileName}")
          
      
        @javax.ws.rs.Produces("image/jpeg")

            public Response getFileInJpegFormat(@javax.ws.rs.PathParam("fileName") String fileName)
            {
                System.out.println("File Requested is : "+fileName);
              
                if(fileName.isEmpty() || fileName==null)
                {
                    ResponseBuilder response=Response.status(Status.BAD_REQUEST);
                    return response.build();
                }
                File file= new File("d:/demoJpegFile.jpeg");
                ResponseBuilder response=Response.ok((Object)file);
              
                response.header("Content-Disposition","attatchment;filename=\"sample.jpeg\"");
                return response.build();
              
            }

}


web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app 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"
    version="2.4">

    <display-name>HelloWorld Application</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

    <servlet>
        <servlet-name>Jersey Rest Services </servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey Rest Services</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>    

i can use restului-client in order to test restful url's .i will write how to test restful web service into the next session.

for any query or improvement in blog ping me on pathak.nisarg@yahoo.com


Thanks













No comments:

Post a Comment

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...