MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to use REST service with Websphere 8.5 application server and send JSON data

In this article, we will learn about the process of sending and receiving JSON data between REST client and RESTful web service deployed on Websphere 8.5 application server.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Before proceeding ahead, we need the following jars (for creating a REST service) on Websphere application:

  • ibm-wink-jaxrs.jar
  • JSON4J.jar
  • jsr311-api.jar
  • slf4j-api.jar
  • slf4j-jdk14.jar

These jars are available as part of WebSphere Application Server Feature Pack for Web 2.0 and Mobile

We will be using eclipse for developing a sample web project which will be exported as WAR file and deployed on Websphere Application Server. Testing will be done using a standalone Java client which will invoke the resource and display the results. The sample REST service that we will be creating is used to add 2 numbers and output returned is the added result.

The complete process is carried out in following steps:

Step 1: In this step, we will create the RESTful web service using JAX-RS (JSR-311) on Java EE environment.

Listing 1: Shows the code to perform step 1

package adv.rs;

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

import com.ibm.json.java.JSONObject;



/**
 * Service interface to add number.
 */
@Path("/AddNumber") 
public class AddNumberRS 
{
   
   public static final String RESP_CD_OK = "200";
   public static final String RESP_CD_ACCEPTED = "202";
   public static final String RESP_CD_ERROR = "500";
   public static final String RESP_CD_SERVER_ERROR = "503";

   public static final String RESPONSE_CD = "response_cd";
   public static final String RESPONSE_MESSAGE = "response_msg";


   /**
    * Default constructor.
    */
   public AddNumberRS()
   {
   }

   /**
    * 
    * @param foJSONObject
    * @return
    */
   @POST
   @Produces(MediaType.APPLICATION_JSON)
   @Consumes(MediaType.APPLICATION_JSON)
   @Path("/add")
   public JSONObject addNumbers(JSONObject foJSONObject)
   {
      long llNo1;
      long llNo2;

      JSONObject loResJSONObject = new JSONObject();

      try
      {

         llNo1 = (Long) foJSONObject.get("Number1");
         llNo2 = (Long) foJSONObject.get("Number2");

         long llResult = llNo1 + llNo2;

         loResJSONObject.put(RESPONSE_CD, RESP_CD_OK);
         loResJSONObject.put("Result", llResult);
         loResJSONObject.put(RESPONSE_MESSAGE, "Numbers added successfully");

      }
      catch (Exception loException)
      {

         loException.printStackTrace();

         loResJSONObject.put(RESPONSE_CD, RESP_CD_ERROR);
         loResJSONObject.put("Result", "-1");
         loResJSONObject.put(RESPONSE_MESSAGE, "Error: While adding numbers: "
               + loException.getMessage());
      }
      return loResJSONObject;

   }

}
/** End Class AddNumberRS */

In the above code, we have created a java class which is a root resource having @Path annotation. The Path annotation specifies that it is the path at which the resource is available. Path annotation added for method addNumbers is a sub resource method. It handles HTTP Post request and produces/consumes JSON which means JSON is taken as input and JSON is returned as output.

Step 2: In this step, we will need to create another Java class which extends javax.ws.rs.core.Application as per the requirement of JSR 311 and add the above created Service

Listing 2: Shows the code to perform step 2

package adv.rs;


import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import com.ibm.websphere.jaxrs.providers.json4j.JSON4JObjectProvider;


public class AddNumberApplication extends Application
{
   @Override
   public Set<Class<?>> getClasses() {
       Set<Class<?>> classes = new HashSet<Class<?>>();
       classes.add(AddNumberRS.class);
       classes.add(JSON4JObjectProvider.class);
       
       System.out.println("Classes:"+classes);
       return classes;
   }


}

Step 3: web.xml entry

Listing 3: Shows the code to perform step 3

<?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_3_0.xsd" version="3.0">
  <display-name>AddNumberRS</display-name>
  <servlet>
    <description>JAX-RS Tools Generated - Do not modify</description>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>adv.rs.AddNumberApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <url-pattern>/AddNumberService/*</url-pattern>
  </servlet-mapping>
</web-app>

Servlet mapping is done to handle requests directed towards url-pattern having /AddNumberService/

We will see more on url formation in the later part of this article.

Step 4: In this step, we will write the client to test the RESTful webservice that will be deployed on Websphere .

Listing 4: Shows the code to perform step 4

package adv.rs;

import javax.ws.rs.core.MediaType;

import org.apache.wink.client.ClientWebException;
import org.apache.wink.client.Resource;
import org.apache.wink.client.RestClient;

import com.ibm.json.java.JSONObject;

public class TestClient
{

   public static void main(String args[])
   {
      try
      {
         testAddNumber();
      }
      catch (ClientWebException loClientWebEx)
      {
         loClientWebEx.printStackTrace();
         System.out.println("Response Status :- "
               + loClientWebEx.getResponse().getStatusCode());
         System.out.println("Response Message :- "
               + loClientWebEx.getResponse().getMessage());
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }

   }

   private static void testAddNumber()
   {
      try
      {
         String lsUrl = "http:////162.70.25.250:9080//Add//AddNumberService//AddNumber//add";

         RestClient client = new RestClient();
         System.out.println("URL is : " + lsUrl);
         Resource resource = client.resource(lsUrl);

         JSONObject loJSON = new JSONObject();

         loJSON.put("Number1", 54321);
         loJSON.put("Number2", 12345);
         
         System.out.println("JSON input::"+loJSON);

         String response = (String) resource.contentType(MediaType.APPLICATION_JSON)
               .post(String.class, loJSON);
         System.out.println("The response is:");
         System.out.println(response);
      }
      catch (ClientWebException loClientWebEx)
      {
         loClientWebEx.printStackTrace();
         System.out.println("Response Status :- "
               + loClientWebEx.getResponse().getStatusCode());
         System.out.println("Response Message :- "
               + loClientWebEx.getResponse().getMessage());
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }

   }

}

Step 5: Below is the complete project as seen in eclipse

Complete web project as seen from eclipse

Figure 1: Complete web project as seen from eclipse

Step 6: Export Web project as a war file from eclipse and deploy it on WAS 8.5 application Context root set for the deployed application in Websphere Application Server

Figure 2: Context root set for the deployed application in Websphere Application Server

Now, let’s go back to the Test service and try to understand the url formation which is very important:

http://162.70.25.250:9080/Add/AddNumberService/AddNumber/add

http://<hostname:port>/<WAS Context Root>/<web.xml url-pattern>/<Resource Path>/<Sub Resource Method Path> Where:

  • hostname - host name or ip of machine where Websphere application server is installed
  • port - WC_defaulthost port under Ports for the server where this application is deployed
  • WAS context root - Context root set for the deployed application
  • web.xml url-pattern - url-pattern as set in Step-3
  • Resource Path - Path annotation used for the Java class which is being used as a resource
  • Sub Resource Method Path - Path annotation used by the method which is to be invoked
Test Service

Figure 3: Test Service

Step 7: In this step, we will execute the REST service from the client that was created in Step 4.

Listing 5: Shows the output after running the Client as a java application

URL is : http:////162.70.25.250:9080//Add//AddNumberService//AddNumber//add
JSON input::{"Number1":54321,"Number2":12345}
Apr 30, 2013 8:37:47 PM org.apache.wink.client.internal.handlers.AcceptHeaderHandler handle
INFO: The accept header is automatically set to the following value: */*
The response is:
{"response_msg":"Numbers added successfully","Result":66666,"response_cd":"200"}

Step 8: Let’s tweak the client to send an incorrect input to the REST service and see what happens:

Listing 6: Shows the part of TestClient which is modified. One of the inputs is changed to a String

         JSONObject loJSON = new JSONObject();

         loJSON.put("Number1", 54321);
         loJSON.put("Number2", "12345");
         

Listing 7: Shows the output after running the Client as a java application

URL is : http:////162.70.25.250:9080//Add//AddNumberService//AddNumber//add
JSON input::{"Number1":54321,"Number2":"12345"}
May 2, 2013 4:20:17 PM org.apache.wink.client.internal.handlers.AcceptHeaderHandler handle
INFO: The accept header is automatically set to the following value: */*
The response is:
{"response_msg":"Error: While adding numbers: java.lang.String incompatible with java.lang.Long","Result":"-1","response_cd":"500"}

As we can see from above output, it gives a response of 500 and returns the reason why it failed.

Conclusion

Finally, in this article, we have learnt sending and receiving JSON messages between a standalone REST client and RESTful web service deployed on Websphere Application Server.



I have done my bachelor in Computer Science and I am well versed with programming languages such as JAVA, C#, html and done courses on Android development.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login