Thursday, March 12, 2015

REST Using Apache Wink (XML/JSON)

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-hochiminh



As mentioned earlier, this is  the second in series on REST Using Apache Wink. You can understand how to use complex return types, such as XML using JAXB and Json using Jackson as the stream reader or stream writer.

Firstly, setup the REST project as described in REST Using Apache Wink

1. Returning XML using JAXB
The class whose object that has to be returned to the client has to be first annotated using the following annotations:

1. XMLRootElement
The root element of the xml that has to be returned, at the class level

2. XMLAttribute
An attribute of the root element that has to be returned

3. XMLElement
An element contained within the root element

This can be used in a nested way to allow multiple levels of nested objects to be returned to the invoker.
 package me.sumithpuri.rest.vo;  
 import javax.xml.bind.annotation.XmlAttribute;  
 /**  
  * @author sumith_puri  
  *  
  */  
 @XmlRootElement(name="product")  
 public class Product {  
      long id;  
      String name;  
      @XmlAttribute  
      public long getId() {  
           return id;  
      }  
      public void setId(long id) {  
           this.id = id;  
      }  
      @XmlElement(name="name")  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String toString() {  
           String productStr="ID:" + this.id + ", NAME: " + this.name;  
           return productStr;  
      }  
 }  

The respective method(s) now need to annotated to return XML using @Produces.
      @GET  
      @Path("/{id}")  
      @Produces(MediaType.APPLICATION_XML)  
      public Product getProductById(@PathParam(value="id") long id) {  
           Product product = persistenceManager.getProduct(id);  
           return product;  
      }  

We can access this method now using a REST Client
      public void invokeJAXBGET(long id) {  
           System.out.println("Testing JAXB GET command....");       
           RestClient restClient = new RestClient(clientConfig);  
           Resource resource = restClient.resource(REST_WEB_SERVICE+"/"+id);  
           ClientResponse response=resource.accept(MediaType.APPLICATION_XML).get();  
           System.out.println("...JAXB GET command is successful");  
      }  

On the browser, type the url : http://localhost:8080/products/rest/product/3
<product id="3">
<name>Sumith Puri</name>
</product> 

2. Returning JSON using Jackson
Jackson is an extension over JAXB to return JSON from REST web service. It can be used as the mapper to convert from JAXB. First, include the relevant Jackson JARs:

We also have to write an application class, to register the mapper.
 package me.sumithpuri.rest.app;  

 import java.util.HashSet;  
 import java.util.Set;  
 import javax.ws.rs.core.Application;  
 import me.sumithpuri.rest.webservice.ProductWebService;  
 import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;  
 import org.codehaus.jackson.map.AnnotationIntrospector;  
 import org.codehaus.jackson.map.ObjectMapper;  
 import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;  

 public class ProductApplication extends Application {  
      @Override  
      public Set<Class<?>> getClasses() {  
           Set<Class<?>> classes = new HashSet<Class<?>>();  
           classes.add(ProductWebService.class);  
           return classes;  
      }  
      @Override  
      public Set<Object> getSingletons() {  
           Set<Object> s = new HashSet<>();  
           ObjectMapper objMapper = new ObjectMapper();  
           AnnotationIntrospector primary = new JaxbAnnotationIntrospector();  
           AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();  
           AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);  
           objMapper.getDeserializationConfig().withAnnotationIntrospector(pair);  
           objMapper.getSerializationConfig().withAnnotationIntrospector(pair);  
           JacksonJaxbJsonProvider jaxbProvider = new JacksonJaxbJsonProvider();  
           jaxbProvider.setMapper(objMapper);  
           s.add(jaxbProvider);  
           return s;  
      }  
 }  

Next, change the Apache Wink configuration in your web.xml as follows:
 <?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" id="WebApp_ID" version="3.0">  
  <display-name>products</display-name>  
  <servlet>  
   <servlet-name>restService</servlet-name>  
   <servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>  
   <init-param>  
    <!-- <param-name>applicationConfigLocation</param-name> -->  
    <!-- <param-value>/WEB-INF/application</param-value> -->  
    <param-name>javax.ws.rs.Application</param-name>  
    <param-value>me.sumithpuri.rest.app.ProductApplication</param-value>  
   </init-param>  
  </servlet>  
  <servlet-mapping>  
   <servlet-name>restService</servlet-name>  
   <url-pattern>/rest/*</url-pattern>  
  </servlet-mapping>  
 </web-app>  

The next is to add the relevant method to the service, and mark that it returns JSON. 
      @GET  
      @Path("/json/{id}")  
      @Produces(MediaType.APPLICATION_JSON)  
      public Product getProductJsonById(@PathParam(value="id") long id) {  
           Product product = persistenceManager.getProduct(id);  
           return product;  
      }  

Now, add the method to the client to test out the method.
      public void invokeJSONGET(long id) {  
           System.out.println("Testing JSON GET command....");       
           RestClient restClient = new RestClient(clientConfig);  
           Resource resource = restClient.resource(REST_WEB_SERVICE+"/json/"+id);  
           ClientResponse response=resource.accept(MediaType.APPLICATION_JSON).get();  
           System.out.println("...JSON GET command is successful");  
      }  

On the browser, type the url : http://localhost:8080/products/rest/product/json/3 
{"id":3,"name":"Sumith Puri"}

You may download the war, including source, for reference from here.


[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-hochiminh

15 comments:

Unknown said...

Hi, I am new to apache win and REST, can you please let me know how can i read the result in standalone java instead of browser

Sumith Kumar Puri said...

hi mohammed, actually with apache wink - the restclient is packaged into the client jar of the distribution.

you may check the javadoc here: https://wink.apache.org/documentation/1.0/api/org/apache/wink/client/RestClient.html

if you are using maven, this may do the trick for dependencies, as provided for the clients: https://wink.apache.org/downloads.html

Extensiya said...

Awesome blog thankks for sharing 100% virgin Remy Hair Extension in USA, importing from India. Premium and original human hair without joints and bondings. Available in Wigs, Frontal, Wavy, Closure, Bundle, Curly, straight and customized color hairstyles Extensions.

Indpac said...

Very useful blog thanks for sharing IndPac India the German technology Packaging and sealing machines in India is the leading manufacturer and exporter of Packing Machines in India.

priya said...

Have a nice blog
Thank for sharing Information
php online training in chennai
php programming center in chennai
php class in chennnai
php certification course
php developer training institution chennai
php training in chennnai
php mysql course in chennai
php institute in chennnai
php course in chennnai
php training with placement in chennnai
php developer course

priya said...

Great work!
NIce Blog
appium online training
appium training centres in chennai
best appium training institute in chennnai
apppium course
mobile appium in chennnai
mobile training in chennnai
appium training institute in chennnai

mindreader said...

Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
Java Training in Chennai
Java Training Institute in Chennai
Java course in chennai
Java Training classes
Java Training
Java programming classes
core Java course

sureshshetty said...

7 tips to start a career in digital marketing

“Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

we have offered to the advanced syllabus course digital marketing for available join now

more details click the link now

[url]https://www.webdschool.com/digital-marketing-course-in-chennai.html[/url]

sureshshetty said...

Web designing trends in 2020

When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

we have offered to the advanced syllabus course web design and development for available join no

more details click the link now

[url]https://www.webdschool.com/web-development-course-in-chennai.html[/url]

w3webschool said...

Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
Digital Marketing Course In Kolkata
Web Design Course In Kolkata

chandhran m said...

Nice blog, I am really happy to read your blog. Thanks for sharing your blog.
AWS Training in Bangalore
AWS Training in Chennai
AWS Course in Bangalore
Best AWS Training in Bangalore
AWS Training Institutes in Bangalore
AWS Certification Training in Bangalore
Data Science Courses in Bangalore
DevOps Training in Bangalore
PHP Training in Bangalore
DOT NET Training in Bangalore

shreekavi said...

Wonderful blog. It is really informative to all.keep update more information about this
IELTS Coaching in Chennai
IELTS Coaching in Bangalore
IELTS Coaching centre in coimbatore
IELTS Coaching in madurai
IELTS Coaching in Hyderabad
ielts training in marathahalli
IELTS Classes in Bangalore
IELTS Coaching in BTM
German Classes in Bangalore
Selenium Training in Bangalore

sasi said...

Great experience for me by reading this blog. Thank you for the wonderful article.
Angularjs course in Chennai
Angularjs Training in Bangalore
angular training in bangalore
Angular Training in hyderabad
angular course in bangalore
angularjs training in marathahalli
Web Designing Course in bangalore
python training in Bangalore
angularjs training institute in bangalore
best angularjs training in bangalore


Unknown said...

Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
Mobile app development training
App development training
Mobile app development course
Mobile development course
Mobile application development course
Learn mobile application development

w3webschool said...

Thanks for sharing this valuable information to our vision. You have posted a worthy blog keep sharing.
Digital Marketing Course In Kolkata
Web Design Course In Kolkata
SEO Course In Kolkata