Friday, January 15, 2010

JAXB

Data representation is a core component of communication between enterprise applications. There are a number of formats for data exchange - XML, CSV, JSON, proprietary to name a few. XML is a common format when working with web services and is also fundamental to SOA. Working with XML in Java applications often requires transformation between Java objects and XML documents. There are many open source tools (JAXB,  XMLBeans, Xstreme, JiBX, Zeus, etc.)  to achieve this transformation .  This post explores JAXB. JAXB API is part of J2SE 1.6,

Convert XML Document into Java Objects (Unmarshal)

Converting a XML document into Java objects is a common use case. XML document that is being transformed to Java objects is required to have a XML Schema to produce bindings.  Following steps will achieve the transformation .  As you go through these steps you will notice use of auto generated classes to get XML data, you do not have to write XML parsing code using DOM or SAX.  In some cases your application may already have predefined domain classes which closely match the XML schema representation or somewhat match XML representation and you may not not like using of auto generated classes,  for these cases there are ways to minimize use of auto generated classes, using some mapping libraries or using JAXB Customizations.

  • Step 1:  At compile time, use XML Schema associated with XML document and JAXB tool auto generate Java classes, this is called binding (Tool lets you specify a package name and generates java Interface and Implementation source file and an ObjectFactory class which provides methods to create generated types.


Use following command..(for generating code using Maven scroll down)


jdk\bin\xjc.exe -p com.mypkgname appscheama.xsd


INPUT Schema



I have used following XML Schema to model NFL scores



xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/SportsSchema"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:nfl="http://www.example.org/SportsSchema"
elementFormDefault="qualified">

<xs:complexType name="TeamType">
<xs:attribute name="name" type="xs:string"/>
<xs:attribute name="location" type="xs:string" />
<!--xs:complexType>

<xs:complexType name="FootballScoreType">
<xs:sequence>
<xs:element name="firstTeam" type="nfl:TeamType" />
<xs:element name="secondTeam" type="nfl:TeamType" />
<xs:element name="firstTeamPoints" type="xs:int"  />
<xs:element name="secondTeamPoints" type="xs:int" />
<!--xs:sequence
<!--xs:complexType>

<xs:element name="scores">
<xs:complexType>
<xs:sequence>
<xs:element name="score" type="nfl:FootballScoreType" maxOccurs="unbounded" />
<!--xs:sequence>
<!--xs:complexType>
<!--xs:element>
</schema>

AUTO GENERATED CODE



Upon running the xjc tool,  various Java classes representing XML schema are generated. Following is an example of generated for one of the element in schema. Notice the annotations on Java classes, this what make the binding work. Generated code also a ObjectFactory which is used to create instances of various auto generated types.



//

// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs 
// See xml/jaxb">http://java.sun.com/xml/jaxb

// Any modifications to this file will be lost upon recompilation of the source schema.

// Generated on: 2010.01.08 at 02:37:52 PM EST
//

package com.spag.dataxchange.generated;

import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlType;

/**
*
Java class for FootballScoreType complex type. *

* <p>The following schema fragment specifies the expected content contained within this class.
*/

        @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FootballScoreType", propOrder = {
"firstTeam", "secondTeam", "firstTeamPoints", "secondTeamPoints"})

public class FootballScoreType {

 @XmlElement(required = true)
 protected TeamType firstTeam;

 @XmlElement(required = true)
 protected TeamType secondTeam;

 @XmlElement(required = true)
 protected BigInteger firstTeamPoints;

 @XmlElement(required = true)
 protected BigInteger secondTeamPoints;

 public TeamType getFirstTeam() {return firstTeam;}
 public void setFirstTeam(TeamType value) {this.firstTeam = value;}

public TeamType getSecondTeam() {return secondTeam;}
public void setSecondTeam(TeamType value) {this.secondTeam = value;}
public BigInteger getFirstTeamPoints() { return firstTeamPoints; }
public void setFirstTeamPoints(BigInteger value) {this.firstTeamPoints = value;}
public BigInteger getSecondTeamPoints() {return secondTeamPoints;}
public void setSecondTeamPoints(BigInteger value) {this.secondTeamPoints = value;}


}

Step 2: Now that we jave java XML bindings in place. We can use these classes to convert XML document into Java objects, aka unmarshaling.  Unmarshaling is performed using JAXB API and auto generated classes from step 1. Following is sample code.
package com.spag.dataxchange;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Validator;
import com.spag.dataxchange.generated.*;

public class ScoreReader {

public static void main(String [] args) {
try {
JAXBContext jaxbCtx = JAXBContext.newInstance("com.spag.dataxchange.generated") ;
Unmarshaller reader = jaxbCtx.createUnmarshaller();
Scores obj = (Scores)reader.unmarshal(new File("src/main/resources/data/scores.xml"));
List list = obj.getScore();
Iterator iter = list.iterator();
int i = 0;
while(iter.hasNext()) {
i++;
FootballScoreType score = iter.next();
System.out.println("Game " + i );
System.out.println( score.getFirstTeam().getLocation() + " - " + score.getFirstTeam().getName() + ": " +                 score.getFirstTeamPoints());
System.out.println( score.getSecondTeam().getLocation() + " - " + score.getSecondTeam().getName() + ": " +      score.getSecondTeamPoints());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
}


Consider the scenario where we already have domain classes defined, the challenge here is to either map the auto generated to classes to domain classes or to eliminate use of auto generated classes and go straight to domain classes. One way to eliminate/reduce use of auto generated classes  is to use JAXB Customization.  JAXB Customization tags lets you map XML schema to classes of your liking. Customizations can be specified inline with XML Schema code, however in most cases you won't be entitled to modifying the schema of XML document that being published by other application, that too referencing domain classes specific to your application.  Thanks goodness customizations can be specified in external binding file (binding.xjb).

bindings.xjb allows you to map existing classes to domain classes, when invoking the xjc comipler specify the binding file that is being used. Binding customizations can be done at various xml schema element to class mapping,

<jxb:bindings version="2.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:bindings schemaLocation="GolfSchema.xsd" node="/xs:schema"  >
<jxb:bindings node="//xs:complexType[@name='golfRound']">
<jxb:class ref="com.spag.dataxchange.golf.GolfRound"/>
<!--jxb:bindings>
<jxb:bindings node="//xs:complexType[@name='golfer']">
<jxb:class ref="com.spag.dataxchange.golf.Golfer"/>
<!--jxb:bindings>
<!--jxb:bindings>
 <!--jxb:bindings>

Binding file could get unwieldy, there are other options to  map auto generated class objects to domain class objects. Dozer is such a library that provides mapping from one JavaBean to other. This library could be utilized to convert between auto generated JAXB classes and your domain model.

Maven configuration for working with JAXB, including use of mapping files.



<dependency>
 <groupId>javax.xml.bind</groupId>

<artifactId>jaxb-api</artifactId>
<version>2.2</version>
</dependency>
 
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<id>1</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
  <outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
src/main/resources/schema/nfl
<schemaFiles>SportsSchema.xsd</schemaFiles>
<packageName>com.spag.dataxchange.generated</packageName> <!-- The name of your generated source package -->
</configuration>
</execution>
<execution>
<id>2</id>
<goals>
<goal>xjc</goal>
</goals> 
<configuration>
<clearOutputDir>false</clearOutputDir>
<outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
src/main/resources/schema/golf
<schemaFiles>GolfSchema.xsd</schemaFiles>
<packageName>com.spag.dataxchange.golf</packageName> <!-- The name of your generated source package -->
src/main/resources/schema/golf
<bindingFiles>bindings.xjb</bindingFiles>
</configuration> 
</execution>
</executions>
  </plugin>
 
 

Convert Java Objects into XML document (Marshal)


To convert  Java object into XML document,  JAXB has schemagen tool which lets you create a Schema from your domain classes. Using Objects instances, generated XML schema and JAXB API you could generate the XML document easily. Here are some code snippets and maven configurations to ease your development.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<goals>
<goal>schemagen</goal>
</goals>
</execution>
</executions>
<configuration>
<outputDirectory>${project.build.directory}/generated-schema</outputDirectory>
<includes>
<include>com/spag/dataxchange/golf/*.java</include>
</includes> <!-- The name of your generated source package -->
</configuration>
</plugin>

Further Pondering

JAXB is primarily used in webservices developed using existing Java classes.

What happens when the the schema changes / domain model changes ?


Explore of JAXB annotations.

Java to XML(WSDL)nges ?

Ref: https://jaxb.dev.java.net/tutorial/

http://blogs.sun.com/CoreJavaTechTips/entry/exchanging_data_with_xml_and1

58 comments:

Anonymous said...

advertising and ***********

with Adwords. Well I’m adding this RSS to my email and can glance out

for much extra of your respective intriguing content.
Make sure you update this again very soon..



Feel free to visit my webpage ... lpedia.org

Anonymous said...

Thanks on your marvelous posting! I truly enjoyed reading it, you can be a great author.
I will remember to bookmark your blog and will come back sometime soon.

I want to encourage you continue your great work, have a nice afternoon!
my site - Illegalvillasspain.Com

Anonymous said...

Hello my friend! I want to say that this post is awesome, nice written and include

approximately all important infos. I would like to see
more posts like this.
my page > blogspot.com

Anonymous said...

It's a shame you don't have a donate button!
I'd definitely donate to

this brilliant blog! I suppose for now i'll settle for
book-marking and adding your RSS feed to my Google account.
I look forward to new updates and will talk

about this site with my Facebook group. Talk soon!
my website - metalgearsoliduk.blogspot.ru

Anonymous said...

Valuable information. Fortunate me I found your website


by accident, and I am surprised why this twist of fate
didn't happened earlier! I bookmarked it.
Here is my blog ; http://365-days-of-love.blogspot.fi/2006/08/august-3-2006bubble-bath.html

Anonymous said...

Do you have a spam issue on this blog; I also am a blogger, and I was wondering your situation; we have
created some nice procedures and we

are looking to trade methods with other folks, please shoot me an e-mail if interested.
Check out my blog post ; org.ua

Anonymous said...

Hi there! I'm at work browsing your blog from my new iphone

4! Just wanted to say I love reading your blog and look forward to all your

posts! Keep up the outstanding work!
Feel free to visit my homepage ... dolores umbridge inquisitorial squad

Anonymous said...

of course like your website but you have to check
the

spelling on quite a few of your posts. Many of them are rife with spelling
issues

and I find it very troublesome to tell the truth nevertheless I will definitely come

back again.
Here is my web site : http://sawit.cammad.net/

Anonymous said...

whoah this blog is excellent i love reading your posts.
Keep up the

great work! You know, lots of people are hunting around for this

information, you can help them greatly.
Feel free to surf my website ... arabxoops.com

Anonymous said...

I’ve recently started a blog, the information you provide on this web

site has helped me greatly. Thanks for all of your time
& work.
Feel free to visit my blog Pitfalls of buying property in france

Anonymous said...

Hey! I just wish to give an

enormous thumbs up for the good information you've gotten right here on this post. I

might be coming back to your blog for more soon.
Visit my blog - aag tv on sky

Anonymous said...

I am continuously invstigating online for articles that can help me.

Thanks!
Also see my website > ancientshores.com

Anonymous said...

I think this is among the most vital information for me. And i am glad

reading your article. But want to remark on some general things, The site style is

great, the articles is really nice : D. Good job, cheers
my web page > http://www.diysolarheatingspain.com/diy-solar-swimming-pool-water-heater-plans.html

Anonymous said...

Wonderful blog! I found it while surfing around on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I've been trying for a while but I never seem to get there! Thanks
Visit my page ; http://cybercommune.bretagne.fr/

Anonymous said...

Excellent items from you, man. I have be aware your stuff

prior to and you are simply too great. I really like what you have acquired right here,

certainly like what you are saying and the best way through which you
say it. You're making

it enjoyable and you continue to care for to stay it sensible. I can not wait to learn far more from you. That is really a

tremendous site.
Also see my web page > free classifieds pretoria

Anonymous said...

Good write-up, I am normal visitor of one’s site, maintain up the

nice operate, and It is going to be a regular visitor for a
long time.
Here is my site : bluewing1976.pixnet.net

Anonymous said...

WONDERFUL Post.thanks for share..extra wait .. …
Also visit my website :: dxinternational.blogspot.ru

Anonymous said...

It is appropriate time to make a few plans for the longer term

and it's time to be happy. I have learn this put up and if I

could I want to suggest you some attention-

grabbing issues or suggestions. Perhaps you could write next articles

relating to this article. I wish to learn more

issues about it!
Also visit my weblog - hotel montepiedra costa blanca

Anonymous said...

You are a very capable person!
My website - Get More Info

Anonymous said...

Aw, this was a really nice post. In idea I want to put in writing

like this moreover - taking time and precise effort to make a very good article…

however what can I say… I procrastinate alot and under no
circumstances appear to get something done.
My web page ... Ww.Helsingkrona.se

Anonymous said...

Aw, this was a very nice post. In thought I want to put in writing

like this additionally - taking time and precise effort to make an excellent article…

however what can I say… I procrastinate alot and certainly not appear to get something done.
My page ... la quinta spain

Anonymous said...

It's perfect time to make a few plans for the longer term

and it is time to be happy. I have read this submit and if I may I want to recommend you few interesting issues or suggestions. Maybe you can write subsequent articles

regarding this article. I want to read even more

issues approximately it!
My website :: aemet localidades cantabria

Anonymous said...

I was just looking for this info for some time. After six hours of

continuous Googleing, at last I got it in your site.
I wonder what is the lack of

Google strategy that don't rank this type of informative websites in top of the list.

Generally the top web sites are full of garbage.
My webpage > property lochardil inverness

Anonymous said...

Whoa! This blog looks just like my old one! It's on a totally

different topic but it has pretty much the same layout and design. Excellent choice of colors!
Review my blog : http://la-belleza-del-caos.blogspot.fr/2011/06/berluscony-masas-negras.html

Anonymous said...

Can I just say what a aid to find somebody who

truly knows what theyre talking about on the internet. You positively know the way to carry a problem to

gentle and make it important. Extra folks have to read this

and perceive this facet of the story. I cant believe youre no more

popular since you definitely have the gift.
My web-site :: mr-laluna.blogspot.com

Anonymous said...

My brother suggested I would possibly like this web site.
He was

once totally right. This put up truly made my day. You
cann't

consider just how so much time I had spent for this information! Thank

you!
Also see my web page > torrevieja Historia

Anonymous said...

You completed several nice points there. I did a search on the

topic and found nearly all

persons will agree with your blog.
my page: wiki.acerenza.info

Anonymous said...

Howdy! I just want to give a huge thumbs up for the good information you've right here on this post. I will probably be coming back to your weblog for more soon.
Stop by my web site : gnb property management

Anonymous said...

Very nice info and straight to the point. I am not sure if this is

really the best place to ask but do you guys have any thoughts
on where

to get some professional writers? Thank you :)
Feel free to visit my weblog wiki.wc3mods.net

Anonymous said...

I am typically to blogging and i actually respect your content.

The article has actually peaks my interest. I am going to bookmark your web site and hold checking for new information.
Review my web site ... news culture

Anonymous said...

Hey there, You have performed an incredible job.



I’ll definitely digg it and personally recommend

to my friends. I'm sure they'll be benefited from this web site.
Stop by my web-site :: essentialweb.asia

Anonymous said...

Does your blog have a contact page? I'm having trouble locating it but, I'd like to

send you an e-mail. I've got some suggestions for your blog you

might be interested in hearing. Either way, great blog and I look forward to seeing it

expand over time.
My weblog xuhfiu.bbs.mythem.es

Anonymous said...

I am extremely impressed with your writing skills as well as with the layout
on your blog. Is this a paid theme or did you customize it
yourself? Either way keep up the nice

quality writing, it is rare to see a nice blog like this one these days.
.
Here is my blog post :: http://fudubbnqt.twbqzvwhko.czpwvcqq.wfka.forum.mythem.es/

Anonymous said...

Undeniably imagine that which you said. Your

favorite reason seemed to be at the web the

easiest thing to be mindful of. I say to you, I certainly get irked at

the same time as folks consider

issues that they just do not recognize about. You controlled to hit the nail upon the
highest as well as outlined out the

whole thing with no need side-effects , folks can take a signal.
Will probably be back to get more. Thanks
Look at my web-site ... www.na-tali.com

Anonymous said...

I am curious to find out what blog platform you happen to be

utilizing? I'm having some small security issues with my latest

blog and I'd like to find something more safe. Do you have any

suggestions?
Feel free to visit my page :: android-optimus.Blogspot.com

Anonymous said...

Attractive part of content. I just stumbled


upon your web site and in accession capital to assert that I acquire in

fact enjoyed account your blog posts. Anyway I will be subscribing for your augment and even I achievement you get


right of entry to consistently fast.
Take a look at my page :: www.authenticlinks.com

Anonymous said...

I've been browsing online more than three hours today, yet I never found any interesting article

like yours. It’s pretty worth enough for me. In my opinion, if all web owners and bloggers made good content as you did, the internet will be much more useful than ever before.
Look into my blog : marcosweb.com.ar

Anonymous said...

Hmm is anyone else encountering problems with the images
on this blog loading? I'm trying

to determine if its a problem on my end or if it's the blog.
Any feed-back would be greatly appreciated.
My weblog - die-kostenlose.de

Anonymous said...

I have been exploring for a little bit for any high-quality articles or blog posts on this kind of space .
Exploring in Yahoo I eventually stumbled upon this website.
Studying this information So i am

glad to exhibit that I've a very good uncanny feeling I discovered just what I needed. I so much

indisputably will

make certain to do not disregard this web

site and give it a glance on a continuing basis.
Look at my web site :: essentialweb.asia

Anonymous said...

Hi there just wanted to give you a quick heads up.
The words in your

article seem to be running off the screen in Safari.
I'm not sure if this is a

formatting issue or something to do with web browser compatibility but I

figured I'd post to let you know. The design look great though!
Hope you get

the issue resolved soon. Cheers
Also visit my website : http://wiki.idebate.org/

Anonymous said...

I'm not sure exactly why but this website is loading very slow for

me. Is anyone else having this issue or is it a problem on my end? I'll check back later and

see if the problem still exists.
Feel free to visit my web page :: forum.mythem.es

Anonymous said...

Does your website have a contact page? I'm having a tough time locating it but, I'd like to

shoot you an email. I've got some suggestions for your blog you

might be interested in hearing. Either way, great site and I look forward to seeing it

expand over time.
My web site - http://www.stadt-geislingen.de/

Anonymous said...

Good day! Do you know if they make any plugins to protect

against hackers? I'm kinda paranoid about losing everything I've worked hard on.
Any suggestions?
my website: Valencia Vrs Barcelona

Anonymous said...

There are some attention-grabbing time limits in this article however I don’t know if I see all of them center
to heart. There's some validity but I'll take hold opinion till I look into it

further. Good article , thanks and we would like extra!
Added to FeedBurner as well
Also visit my web blog :: spain photographs

Anonymous said...

Thank you for another magnificent post. Where else could

anybody get that type of info in such an ideal way of writing?

I've a

presentation next week, and I'm on the look for such info.


Feel free to visit my web page http://thefriendshipsite.com/RussellLewis82

Anonymous said...

Thank you for the sensible critique. Me & my neighbor were just preparing
to do a little research

about this. We got a grab a book from our local library
but I think I learned more from this post.

I'm very glad to see such magnificent info being shared freely

out there.

Here is my weblog HTTP://Dvdcoverlinks.com/

Anonymous said...

Hey! This post could not be written any better!

Reading through this post reminds me of my previous room mate!
He always kept talking

about this. I will forward this write-up to him. Fairly certain he will have a good read.


Thank you for sharing!

Feel free to visit my web page; http://creativecommunity.altervista.org/

Anonymous said...

I am really impressed with your writing skills as well as with the format in your

weblog. Is that this a paid topic or did you customize it

your self? Either way stay up the nice quality writing, it is

rare to look a great blog like this one today..

Stop by my blog ... ndsassn.com

Anonymous said...

Thank you for another informative website. The

place else may I am getting that type of info written in such an ideal means?
I have a undertaking that

I am just now running on, and I've been on the glance out for

such info.

My page; http://www.bandcircle.net/honbu/groups/the-just-good-shark-is-a-dead-shark/

Anonymous said...

Great write-up, I’m regular visitor of one’s website, maintain
up the

excellent operate, and It's going to be a regular visitor for a lengthy time.

Here is my site; http://gratis-community.at/story.php?id=891127

Anonymous said...

Hi! I'm at work browsing your blog from my new iphone! Just wanted to say I love reading through your blog and look forward to all your

posts! Keep up the excellent work!

Feel free to visit my weblog: http://www.vikstyle.com.ua

Anonymous said...

Attractive component of content. I just stumbled

upon your weblog and in accession capital to say that I acquire in

fact loved account your blog posts. Any way I’ll be subscribing in your augment and
even I fulfillment you get

right of entry to constantly rapidly.

Have a look at my weblog :: http://www.seolinkads.com/tag/adventure+golf+costa+blanca,+twin+falls

Anonymous said...

Please let me know if you're looking for a article writer for your weblog. You

have some really great articles and I believe I would be a good asset. If you ever want to take

some of the load off, I'd absolutely love to write
some articles for your blog in

exchange for a link back to mine. Please blast me an email if interested.
Kudos!

Stop by my site; authenticlinks.com

Anonymous said...

Does your website have a contact page? I'm having a tough time locating it but, I'd like to

send you an e-mail. I've got some ideas for your blog you

might be interested in hearing. Either way, great site and I look forward to seeing it

expand over time.

Look at my homepage ... the3rdgoal.org

Anonymous said...

I do agree with all of the ideas you have

introduced to your post. They are very convincing and

will certainly work. Still, the posts are very brief for
novices. May just you please extend them a little from

subsequent time? Thank you for the post.

Also visit my blog :: Www.Barknetwork.com

Anonymous said...

You made some good points there. I did a search on the issue and found most individuals will approve with


your blog.

Also visit my web site - www.ncsfd1.com

Anonymous said...

Hello this is kinda of off topic but I was

wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML.
I'm starting a blog soon but have

no coding expertise so I wanted to get advice from someone with

experience. Any help would be enormously appreciated!

Check out my webpage :: http://motion.mediadeling.com

Anonymous said...

You are a very capable individual!

my webpage; Groovaz.com