Friday, July 5, 2013

Integrate Jersey RESTful with portlet project

Hello All Friends...

Recently I have succssfully integrate Jersey Framework with my existing portlet project.

It is very easy and very useful..

For this, you have to follow following steps..

1) Add following dependency if you are using maven, otherwise add this jars to your classpat.

<!-- Jersey -->



2) Edit in web.xml

                  <!-- Here, you have to mention package name where toy are implementd service(web service)-->


3) Look out Web service class.

public class MyWebServiceClass
      public Message myMethod()
             MyMessage msg = new MyMessage();
             msg.setName("Good Day!!!");

            return msg;

-> here, we can define @Path at two level. 1) class level 2) path level.
-> so Here, i provide both ultimately url become... <...>/mymessage/hello
-> @Produces(MediaType.APPLICATION_JSON) defines that this method returns data in JSON format.

This is web service class where we implelent service.

4) Now we have to create client which call this service.


I am using GSON. So..

<!-- GSON -->

5) Client program

public class MyClient {

      Logger log = Logger.getLogger(MyClient.class);

      public String createClient(String url) {
      try {
                    Client client = Client.create();
                    String baseURL = "http://localhost:8080/admin-0.0.1/rest";
                    WebResource webResource = client.resource(baseURL + url);
                    ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class);

                    if (clientResponse.getStatus() != 200) {
                                       throw new RuntimeException("Failed...... HTTP Error Code :"
                                                        + clientResponse.getStatus());

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

                    System.out.println("Output from Server :");


                    return output;
                   } catch (Exception e) {
                       return "ERROR";

--> Here... http://localhost:8080/admin-0.0.1/rest define as a Base URL. and at the time of calling any service we have to pass remaining parameter in it.


       MyClient client = new MyClient();
      String result = client.createClient("/mymessage/hello");

So... It will return MyMessage object in JSON format.


No comments: