DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. REST - Using Apache Wink (Part 02) [Starting JAX-RS Web Services - 02]

REST - Using Apache Wink (Part 02) [Starting JAX-RS Web Services - 02]

Dive into Apache Wink, where you can return JSON from your REST web services and other complex return types, like XML.

Sumith Puri user avatar by
Sumith Puri
·
Jan. 27, 17 · Tutorial
Like (7)
Save
Tweet
Share
14.03K Views

Join the DZone community and get the full member experience.

Join For Free

GitHub Link (Code Samples from the Article & More)
https://github.com/sumithpuri/skp-code-marathon-hochiminh


As promised in Part One of the Article, here is the second in series on REST using Apache Wink. My earlier article was on JAX-RS (REST Web Services) 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, set up 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 be 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");  
      }  


In your browser, go to 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 services. 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 Step 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");  
      }  


In the Browser, go to: http://localhost:8080/products/rest/product/json/3

{"id":3,"name":"Sumith Puri"}


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

REST Web Protocols Apache Wink Web Service

Published at DZone with permission of Sumith Puri. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • Microservices Discovery With Eureka
  • API Design Patterns Review

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: