Skip to main content
Jump to: navigation, search


< EclipseLink‎ | Examples‎ | MOXy‎ | Dynamic

Dynamic MOXy: Flickr Example

This example will demonstrate how to use MOXy's Dynamic JAXB features to work with public JSON and XML feeds, without having to create concrete Java classes. The following concepts are demonstrated:

  • Mapping to JSON and XML data without writing or generating concrete Java classes
  • Using multiple MOXy metadata files to modularize your metadata
  • Bootstrapping a DynamicJAXBContext from multiple MOXy metadata files
  • Using a single DynamicJAXBContext to read both JSON and XML data
  • Using DynamicEntity APIs to interact with mapped data
  • Using XPath Predicates to map to an attribute based on another attribute value
  • Using UnmarshallerProperties.JSON_INCLUDE_ROOT to read JSON that does not have a root element
  • Using Marshaller.JAXB_FRAGMENT to omit the XML preamble when writing

The example application uses Dynamic MOXy to read a JSON stream from Reddit, an XML stream from Flickr, and uses the data from both to create an HTML file.

Running the Example

The full code for this example is available under moxy/dynamic/flickr in the EclipseLink Examples Git repository. To clone the complete Examples repository, use the following Git command:

git clone git://

To run the example, just execute Maven:

$ mvn

This will connect to the Internet to read the JSON and XML feeds, and will launch the system browser on the generated HTML file.

Proxy Connections
If you require a proxy server to access the Internet, check the <systemProperties> section of pom.xml.

Background: DynamicEntities

Instead of using actual Java classes (such as Customer.class or Address.class), Dynamic MOXy generates (in-memory) DynamicTypes defined by the metadata provided. An "instance" of a DynamicType is called a DynamicEntity, which provides a simple get(propertyName) / set(propertyName, propertyValue) API to manipulate data.

For more information, and to learn about other ways that Dynamic MOXy can be used, see Using Dynamic JAXB in the EclipseLink documentation.

Getting JSON from Reddit

Reddit provides a public JSON feed using the following URL format:

This will return us JSON in the following format. For this example, we are primarily interested in the title and url fields of data/children/data.

Mapping to Reddit JSON

The MOXy metadata that defines our mappings to the JSON output is stored in the bindings-reddit.xml file. We define a RedditResults class that will hold a collection of RedditPost objects. Each RedditPost maps to the title and url returned by Reddit. Here, we are essentially designing virtual "classes" that will be mapped to the information we are interested in.

    <java-type name="">
            <xml-element java-attribute="posts" xml-path="data/children" container-type="java.util.ArrayList"
                         type="" />
    <java-type name="">
            <xml-element java-attribute="title" xml-path="data/title/text()" type="java.lang.String"/>
            <xml-element java-attribute="url" xml-path="data/url/text()" type="java.lang.String"/>

Getting XML from Flickr

Flickr provides a public XML feed using the following URL format:

This will return us XML in the following format. For each entry, we want to locate two link elements, based on their attributes:

  • link with @type='image/jpeg' : the @href attribute points to the actual image
  • link with @rel='alternate' : the @href attribute points to the corresponding Flickr page

Mapping to Flickr XML

MOXy metadata can also be provided in a JSON file, which can be more compact than XML. The metadata that defines our mappings to Flickr's XML output is stored in the bindings-flickr.json file. We define a FlickrResults class that will hold a collection of FlickrItem objects, as well as a description of the search being performed. Each FlickrItem contains two URLs: one to the actual image, and one to the Flickr page for that image..

   "package-name" : "",
   "xml-schema" : {
      "element-form-default" : "QUALIFIED",
      "namespace" : ""
   "java-types" : {
      "java-type" : [ {
         "name" : "",
         "xml-root-element" : {
            "name" : "feed"
         "java-attributes" : {
            "xml-element" : [ {
               "java-attribute" : "description",
               "type" : "java.lang.String",
               "xml-path" : "title/text()"
            }, {
               "java-attribute" : "items",
               "container-type" : "java.util.ArrayList",
               "type" : "",
               "xml-path" : "entry"
            } ]
      }, {
         "name" : "",
         "java-attributes" : {
            "xml-attribute" : [ {
               "java-attribute" : "flickrPage",
               "type" : "java.lang.String",
               "xml-path" : "link[@rel='alternate']/@href"
            }, {
               "java-attribute" : "imageUrl",
               "type" : "java.lang.String",
               "xml-path" : "link[@type='image/jpeg']/@href"
            } ]
      } ]
MOXy Metadata in JSON Format
The following code can be used to convert an EclipseLink bindings file in XML format, to the same bindings in JSON format.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream bindingsXml = loader.getResourceAsStream("META-INF/bindings-flickr.xml");
JAXBContext ctx = JAXBContext.newInstance("org.eclipse.persistence.jaxb.xmlmodel");
Object bindings = ctx.createUnmarshaller().unmarshal(bindingsXml);
Marshaller m = ctx.createMarshaller();
m.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
m.marshal(bindings, System.out);


At startup, we gather our three metadata files and pass them to DynamicJAXBContextFactory to create the DynamicJAXBContext.

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream redditBindings = loader.getResourceAsStream("META-INF/bindings-reddit.xml");
InputStream flickrBindings = loader.getResourceAsStream("META-INF/bindings-flickr.json");
InputStream htmlBindings = loader.getResourceAsStream("META-INF/bindings-html.xml");
ArrayList<InputStream> dataBindings = new ArrayList<InputStream>(3);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, dataBindings);
context = DynamicJAXBContextFactory.createContextFromOXM(null, properties);


To unmarshal Reddit's JSON, we create a new Unmarshaller, and specify that our media type is JSON.

We also specify (JSON_INCLUDE_ROOT, false), because there is no root element in this JSON format. Because of this, we need to use an unmarshal() method that takes a Class parameter, indicating the type of object we are unmarshalling. We can obtain our "virtual" class by creating a new DynamicEntity of type RedditResults.

Unmarshaller u = context.createUnmarshaller();
u.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
u.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
Class<? extends DynamicEntity> redditResultsClass = context.newDynamicEntity("").getClass();
DynamicEntity redditResults = u.unmarshal(new StreamSource(REDDIT_URL), redditResultsClass).getValue();


Now that we have RedditResults, we will iterate over its RedditPosts and construct a Flickr query URL for each one, using keywords from the post's title. We'll then unmarshal from the query URL to get an instance of our FlickrResults. Because Flickr is providing a standard XML format, a simple default Unmarshaller is all that is necessary.

DynamicEntity redditPost = ...;
String keywords = extractKeywords(post.get("title").toString());
String flickrUrlString = FLICKR_URL + keywords;
InputStream flickrStream = new URL(flickrUrlString).openConnection().getInputStream();
Unmarshaller u = context.createUnmarshaller();
DynamicEntity flickrResults = (DynamicEntity) u.unmarshal(flickrStream);


Finally, we take the information from our RedditResults and FlickerResults and put it together into an HtmlPage object, defined in bindings-html.xml. We then marshal this to a File. In addition to specifying that our Marshaller should use formatted output, we also use (Marshaller.JAXB_FRAGMENT, true), to omit the <?xml ... preamble from our HTML file.

DynamicEntity html = context.newDynamicEntity("");
html.set("title", "TopLink MOXy - Dynamic JAXB");
html.set("css", "style.css");
DynamicEntity body = context.newDynamicEntity("");
body.set("title", "Reddit /" + SUBREDDIT + " - Today's Top Posts");
DynamicEntity redditLink = context.newDynamicEntity("");
redditLink.set("url", redditPost.get("url"));
redditLink.set("title", redditPost.get("title"));
DynamicEntity flickrDescription = context.newDynamicEntity("");
flickrDescription.set("text", flickrResults.get("description"));
DynamicEntity flickrImageLink = context.newDynamicEntity("");
flickrImageLink.set("url", flickrItem.get("imageUrl"));
flickrImageLink.set("image", flickrItem.get("imageUrl"));
flickrImageLink.set("height", Integer.valueOf(80));
html.set("body", body);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
m.marshal(html, outputFile);



The following metadata is used to generate an HTML structure programatically. The HtmlBody object contains a collection of HtmlDiv, which in turn has a collection of HtmlItem. Inheritance is used to model HtmlItem and its sub-types HtmlText, HtmlLink, HtmlTextLink and HtmlImageLink.

<?xml version="1.0" encoding="UTF-8"?>
<xml-bindings xmlns="" package-name="">
    <java-type name="">
      <xml-root-element name="html" />
        <xml-element java-attribute="title" xml-path="head/title/text()" type="java.lang.String" />
        <xml-attribute java-attribute="css" xml-path="head/link/@href" type="java.lang.String" />
        <xml-attribute java-attribute="rel" xml-path="head/link/@rel" type="java.lang.String" />
        <xml-attribute java-attribute="type" xml-path="head/link/@type" type="java.lang.String" />
        <xml-attribute java-attribute="media" xml-path="head/link/@media" type="java.lang.String" />
        <xml-element java-attribute="body" xml-path="body" type="" />
    <java-type name="">
        <xml-element java-attribute="title" xml-path="p/h1/text()" type="java.lang.String" />
        <xml-element java-attribute="divs" xml-path="p/p" type="" container-type="java.util.ArrayList" />
    <java-type name="">
        <xml-attribute java-attribute="id" xml-path="div/@id" type="java.lang.String" />
        <xml-element java-attribute="span" type="" container-type="java.util.ArrayList">
          <xml-element-wrapper name="div" />
    <java-type name="" />
    <java-type name="" super-type="">
        <xml-element java-attribute="text" xml-path="p/small/text()" type="java.lang.String" />
    <java-type name="" super-type="">
        <xml-attribute java-attribute="url" xml-path="a/@href" type="java.lang.String" />
    <java-type name="" super-type="">
        <xml-element java-attribute="title" xml-path="a/text()" type="java.lang.String" />
    <java-type name="" super-type="">
        <xml-attribute java-attribute="image" xml-path="a/img/@src" type="java.lang.String" />
        <xml-attribute java-attribute="width" xml-path="a/img/@width" type="java.lang.Integer" />
        <xml-attribute java-attribute="height" xml-path="a/img/@height" type="java.lang.Integer" />

Reddit JSON Format

          "title":"Plants re-grow after 500 years under the ice",

Flickr XML Format

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="" xmlns:dc="" xmlns:flickr="urn:flickr:user">
  <title>Recent Uploads tagged science</title>
  <link rel="self" href="" />
  <link rel="alternate" type="text/html" href="" />
  <subtitle />
  <generator uri="">Flickr</generator>
    <title>Space Shuttle Endeavour</title>
    <link rel="alternate" type="text/html" href="" />
    <content type="html">&lt;p&gt;&lt;a href=""&gt;Jason Scheier&lt;/a&gt; posted a photo:</content>
      <name>Jason Scheier</name>
    <link rel="enclosure" type="image/jpeg" href="" />
    <category term="park" scheme="" />
    <category term="love" scheme="" />
    <category term="los" scheme="" />
    <category term="memorial" scheme="" />
    <category term="day" scheme="" />
    <category term="control" scheme="" />
    <category term="angeles" scheme="" />
    <category term="space" scheme="" />
    <category term="engineering" scheme="" />
    <category term="center" scheme="" />
    <category term="science" scheme="" />
    <category term="nasa" scheme="" />
    <category term="exposition" scheme="" />
    <category term="shuttle" scheme="" />
    <category term="mission" scheme="" />
    <category term="jpl" scheme="" />
    <category term="starship" scheme="" />
    <category term="endeavour" scheme="" />

Back to the top