Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MOXy and JSON with Padding

DZone's Guide to

MOXy and JSON with Padding

· Integration Zone ·
Free Resource

The new Gartner Critical Capabilities report explains how APIs and microservices enable digital leaders to deliver better B2B, open banking and mobile projects.

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:


The new Gartner Critical Capabilities for Full Lifecycle API Management report shows how CA Technologies helps digital leaders with their B2B, open banking, and mobile initiatives. Get your copy from CA Technologies.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}