Monday, April 11, 2016

JAX - RS / Jersey application development and Testing

JAX - RS / Jersey application development and Testing


WEB.XML example


<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.sudas.study.glassfish.StudyProject.examples</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

This is a car model/ POJO class which is used for returning car objects as list in REST @GET method

package com.sudas.study.glassfish.StudyProject.examples;

public class CarModel {
 public CarModel() {
  // TODO Auto-generated constructor stub
 }
 String brand;
 String model;
 String colour;
 public CarModel(String brand, String model, String colour) {
  super();
  this.brand = brand;
  this.model = model;
  this.colour = colour;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }

 public void setModel(String model) {
  this.model = model;
 }

 public void setColour(String colour) {
  this.colour = colour;
 }

 public String getBrand() {
  return brand;
 }
 public String getModel() {
  return model;
 }
 public String getColour() {
  return colour;
 }
 

}


  • Example of a simple @GET method which produces JSON content



package com.sudas.study.glassfish.StudyProject.examples;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/cars")
public class JaxRSexample1 {

 static List<CarModel> cars = new ArrayList<>();

 // add few cars
 public static void addCars() {
  cars.add(new CarModel("BMW", "x1", "black"));
  cars.add(new CarModel("BMW", "x2", "black"));
  cars.add(new CarModel("BMW", "x3", "black"));

 }

 /***
  * A simple get example which uses content type as application/ JSON in
  * header
  * 
  * @return
  */

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public static List<CarModel> getJSONexample() {
  addCars();
  return cars;
 }

}

As you can see in the above xml the resource URL is formed upto /webapi, any url-pattern called after the /webapi will result in execution of any rest methods. In the above example the class JaxRSExample1 has a @Path annotation with url-pattern cars. so when ever the url-pattern cars is put after the resource url which is http://localhost:9090/StudyProject/webapi/cars will result in calling the getJSONexample method. 

  • Testing the getJSONexample method using postman

  • Testing the getJSONexample method using custom client


package com.sudas.study.glassfish.StudyProject.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Example1Client {
 public static void main(String[] args) {
  testClient();
 }

 public static void testClient() {

  HttpURLConnection conn = null;
  try {
   URL url = new URL("http://localhost:9090/StudyProject/webapi/cars");
   // creating connection object
   conn = (HttpURLConnection) url.openConnection();
   // setting the connection as GET it can be POST/ PUT / DELETE etc
   conn.setRequestMethod("GET");

   // I am accepting the media type as JSON you can do XML .
   conn.setRequestProperty("Accept", "application/json");
   // If the response has no error read the response
   if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
    System.out.println(conn.getResponseCode());
   }
   BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
   while (bis.available() > 0) {
    System.out.print((char) bis.read());
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  conn.disconnect();
 }
}

OUTPUT:

[{"brand":"BMW","colour":"black","model":"x1"},{"brand":"BMW","colour":"black","model":"x2"},{"brand":"BMW","colour":"black","model":"x3"}]

  • Example of a simple @POST using @FormParam method which produces media type as plain text and consumes media type as x-www-form-urlencoded



package com.sudas.study.glassfish.StudyProject.examples;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/cars2")
public class JaxRSexample2 {

 // a post method which uses @FormParam
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Produces(MediaType.TEXT_PLAIN)
 public static String postMethod(@FormParam("userName") String userName, @FormParam(" ") String password) 
 {
  return "You have successfully logged in as " + userName;
 }

}

  • Testing the method using postman

  • Testing the method using custom client

package com.sudas.study.glassfish.StudyProject.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;

public class Example2Client {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
try {
 POSTclientForm();
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
 }

 public static void POSTclientForm() throws IOException {
  URL url = new URL("http://localhost:9090/StudyProject/webapi/cars2");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  // Create a list of type NameValuePair (interface)
  List<NameValuePair> nvList = new ArrayList<>();
  // BasicNameValuePair class implements NameValuePair interface
  // passing username and password to POST body as name value pairs
  nvList.add(new BasicNameValuePair("userName", "Demo"));
  nvList.add(new BasicNameValuePair("password", "Tester01"));

  URIBuilder newUri = new URIBuilder().setParameters(nvList);
  System.out.println(newUri.toString());

  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  // "ContentType.APPLICATION_FORM_URLENCODED" gives me
  // x-www-form-urlencoded
  connection.setRequestProperty("content-type", ContentType.APPLICATION_FORM_URLENCODED.toString());

  OutputStream os = connection.getOutputStream();
  // removing the ?
  String newString = newUri.toString().substring(1);
  System.out.println(newString);
  os.write(newString.getBytes());
  os.flush();
  InputStream inputStream = connection.getInputStream();
  BufferedInputStream bis = new BufferedInputStream(inputStream);
  while (bis.available() > 0) {
   char c = (char) bis.read();
   System.out.print(c);
  }

 }
}

OUTPUT

You have successfully logged in as Demo using Tester01


  • Example of simple @GET method using @QueryParam 


package com.sudas.study.glassfish.StudyProject.examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("/cars3")
public class JaxRSexample3 {
 // use of @QueryParam for @GET method

 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public static String getQueryParamExample(@QueryParam("userName") String userName,
   @QueryParam("password") String password) {
  System.out.println("You have logged in as " + userName + " " + "using password " + password);
  return "You have logged in as " + userName + " " + "using password " + password;
 }

}

  • Test the method using postman


  • Test the method using custom client

package com.sudas.study.glassfish.StudyProject.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;

public class Example3Client {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GETqueryString();

 }
 public static void GETqueryString() {
  List<NameValuePair> nvList = new ArrayList<>();
  nvList.add(new BasicNameValuePair("userName", "sudas"));
  nvList.add(new BasicNameValuePair("password", "password"));

  try {
   URIBuilder builder = new URIBuilder("http://localhost:9090/StudyProject/webapi/cars3");
   builder.addParameters(nvList);

   System.out.println(builder.toString());
   final String URI = builder.toString();

   try {
    URL url = new URL(URI);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.setRequestProperty("accept", ContentType.TEXT_PLAIN.toString());
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);

    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
    while (bis.available() > 0) {
     char c = (char) bis.read();
     System.out.print(c);
    }

   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  } catch (URISyntaxException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
 
}

OUTPUT

You have logged in as sudas using password password
  • For a complete list of MIME ("Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format) click here

This example illustrates sending JSON in body of @POST request 

  • Example -- method using @PathParam Jersey annotation



Example URI
http://localhost:9090/StudyProject/webapi/query/hello,world 

  • Example -- method using @MatrixParam Jersey annotation

Example URI
http://localhost:9090/StudyProject/webapi/query;name=sss;age=22



No comments:

Post a Comment