From Eclipsepedia

Jump to: navigation, search

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 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
  • Using XPath Predicate mapping to map to an element based on an attribute value

This example 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:

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 see 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', and extract the href attribute, pointing to the actual image
  • link with @rel='alternate', and extract the href attribute, pointing to the corresponding Flickr page

Mapping to Flickr XML

The MOXy metadata that defines our mappings to Flickr's XML output is stored in the bindings-flickr.xml 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..

<xml-schema element-form-default="QUALIFIED" namespace=""/>
    <java-type name="">
        <xml-root-element name="feed"/>
            <xml-element java-attribute="description" xml-path="title/text()" type="java.lang.String"/>
            <xml-element java-attribute="items" xml-path="entry" container-type="java.util.ArrayList"
    <java-type name="">
            <xml-attribute java-attribute="flickrPage" xml-path="link[@rel='alternate']/@href" type="java.lang.String"/>
            <xml-attribute java-attribute="imageUrl" xml-path="link[@type='image/jpeg']/@href" type="java.lang.String"/>


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.xml");
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("width", Integer.valueOf(80));
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);



<?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="" />