Enterprise Integration Zone is brought to you in partnership with:

Team lead for the TopLink/EclipseLink JAXB & SDO implementations, and the Oracle representative on those specifications. Blaise is a DZone MVB and is not an employee of DZone and has posted 44 posts at DZone. You can read more from them at their website. View Full User Profile

MOXy and JSON with Padding

04.06.2013
| 3085 views |
  • submit to reddit

JSON with padding is a communication mechanism used in JavaScript to overcome restrictions due to the same origin policy (for more information see: http://en.wikipedia.org/wiki/JSONP).  In this post I will demonstrate how to leverage JSON with padding when using MOXy as your JSON provider.

This functionality is new in EclipseLink 2.5.0 (and 2.4.2), you can try it out today using a nightly build available from:


Web Application (foo.html)
The data that we are requesting (to populate the div with id="message") via HTTP comes from a different server than the one hosting our application.  We will utilize JSON with padding to get the data.  The response from the URL will be a call to our foo function.  We will supply the function name via the callback query parameter.


Below is the response from making the HTTP call.  See how the JSON data is wrapped in a call to our foo function.

RESTful Service (FooResource)
Below is the RESTful service implemented with JAX-RS.  Our GET method returns an instance of the MOXy class JSONWithPadding parameterized with the domain class Foo.  When instantiating this class we give it the callback function name (default is callback) and an instance of the domain class.  We will use the callback function name from the query parameters if one was provided.

Java Model (Foo)
Below is the Java model that we will use for this example.

package org.example.padding;
 
public class Foo {
 
    private String bar;
 
    public String getBar() {
        return bar;
    }
 
    public void setBar(String bar) {
        this.bar = bar;
    }
 
}

Handling the application/x-javascript Media Type  (MyProvider)
Due to a bug (see:  http://bugs.eclipse.org/404927) that we will fix in EclipseLink 2.5.1 you will need to subclass MOXyJsonProvider to override @Produces and the isWritable method in order to utilize JSON with padding.

Further Reading
If you enjoyed this post then you may also be interested in:


Published at DZone with permission of Blaise Doughan, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)