Convert JAXB Object to XML in Mule ESB

In this tutorial I am going to show you how we can convert JAXB object into XML data in Mule ESB. We will use File Connector to take an XML file as input then we will map it to an appropriate JAXB object, then finally we will convert the JAXB object back into XML data.

You can see also Convert XML to JAXB Object in Mule ESB

The JAXB transformers allow objects to be serialized to XML and back again using the JAXB binding framework.

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program’s class structure.

Mule support binding frameworks such as JAXB and Jackson. These frameworks use annotations to describe how data is mapped to a Java object model. Reference https://docs.mulesoft.com/mule-user-guide/v/3.7/jaxb-transformers

Prerequisites

Mule Studio 3.x(Anypoint Studio) (Download from https://www.mulesoft.com/platform/studio)
Maven 3.2.1 (Download from https://maven.apache.org/download.cgi?Preferred=ftp://mirror.reverse.net/pub/apache/)
JDK 1.7 (Download from http://www.oracle.com/technetwork/java/javase/downloads/index.html)
Configure JDK, Maven and Mule Studio

Step 1. First install JDK
Step 2. Add the Java_Home/bin directory to your system’s PATH.
Step 3. After downloading Maven, extract it to a drive
Step 4. Add the M2_Home/bin directory to your system’s PATH.
Step 5. Download and extract Mule Studio to a drive
Step 6. Now start Mule Studio by clicking on AnypointStudio exe icon in the folder <physical drive>/AnypointStudio
Step 7. Once started, close the startup page
Step 8. In Mule Studio, go to Window -> Preferences. Expand Java, then click on Installed JREs. Add JDK 1.7 and select it. In expanded Java, click on Compiler and select the compiler level as 1.7
Step 9. Now expand Anypoint Studio and click on Maven Settings. Then select appropriate Maven installation home directory using Browse button.
Step 10. If you want you can input Default groupId for new projects, it will save your time every time when you want to create a new project.

Create Mule project in Mule Studio
Now we will see how to create a new project in Mule Studio(Anypoint Studio).

Step 1. In Anypoint Studio, go to File -> New -> Mule Project
Step 2. Input Project Name: mule-xml-java, Runtime is by default selected, tick on Use Maven; here the artifactId is automatically picked up from the Project Name:, the Group Id is picked up from the Default groupId for new projects and version is also a default value.
Step 3. Click Next and verify the JDK, mainly select Use default JRE(currently ‘jdk1.7.0_x’)
Step 4. Click on Next and click on Finish.

So when the project mule-xml-java is created in the Anypoint Studio, the project structure looks like below

mule xml to object

Convert XML file to JAXB object and JAXB object into XML data

mule jaxb to xml

Step 1. Open the mule-xml-java.xml file and click on Configuration XML view in the Editor
Step 2. Modify the mule-xml-java.xml file as shown below

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml"
	xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns="http://www.mulesoft.org/schema/mule/core"
	xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
	xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.5.1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
	<spring:beans>
		<spring:bean name="JAXB_Context" class="javax.xml.bind.JAXBContext"
			factory-method="newInstance">
			<spring:constructor-arg value="com.roytuts.jaxb.model" />
		</spring:bean>
	</spring:beans>
	<!--or use below configuration for JAXB_Context-->
	<!-- <mulexml:jaxb-context name="JAXB_Context" packageNames="com.roytuts.model"
		doc:name="JAXB Context" /> -->
	<flow name="xmlToObjectFlow" doc:name="xmlToObjectFlow">
		<file:inbound-endpoint path="D:AnypointWorkspace"
			responseTimeout="10000" doc:name="File">
			<file:filename-wildcard-filter pattern="catalog.xml" />
		</file:inbound-endpoint>
		<file:file-to-string-transformer
			doc:name="File to String" />
		<mulexml:jaxb-xml-to-object-transformer
			name="XmlToCatalog" jaxbContext-ref="JAXB_Context" returnClass="com.roytuts.jaxb.model.Catalog"
			doc:name="XML to JAXB Object" />
                <logger message="#[message.payload]" level="INFO" doc:name="Logger"/>
		<mulexml:jaxb-object-to-xml-transformer jaxbContext-ref="JAXB_Context"
			doc:name="JAXB Object to XML" />
		<logger message="#[message.payload]" level="INFO" doc:name="Logger" />
	</flow>
</mule>

In the above configuration we have first created the JAXB_Context using either spring:bean or mulexml:jaxb-context that is used later in mulexml:jaxb-xml-to-object-transformer.

Then we have <file:inbound-endpoint/> for taking an XML file as an input. Then we transform the file content or payload to string value using <file:file-to-string-transformer/>. We log the file content using <logger/>.

Next we transform the XML file data into JAXB Java object – we specify here the JAXB_Context to use for transforming and returnClass to what type of Java object it has to convert.

Then again we use <logger/> for logging message into the Console.

Next we have <mulexml:jaxb-object-to-xml-transformer/> for transforming the JAXB object into XML.

Finally we use <logger/> for logging the XML data into the Console.

Step 3. Create catalog.xsd file in src/main/resources/xsd directory with below content

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified"
	elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
	<xs:element name="Catalog">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="Book" maxOccurs="unbounded" minOccurs="0">
					<xs:complexType>
						<xs:sequence>
							<xs:element type="xs:string" name="Author" />
							<xs:element type="xs:string" name="Title" />
							<xs:element type="xs:string" name="Genre" />
							<xs:element type="xs:float" name="Price" />
							<xs:element type="xs:date" name="PublishDate" />
							<xs:element type="xs:string" name="Description" />
						</xs:sequence>
						<xs:attribute type="xs:string" name="id" use="optional" />
					</xs:complexType>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>

Step 4. Add XJC plugin to the pom.xml file for generating Java object from XSD

<plugins>
...
<!-- JAXB xjc plugin that invokes the xjc compiler to compile XML schema
				into Java classes. -->
<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>jaxb2-maven-plugin</artifactId>
	<version>1.6</version>
	<executions>
		<execution>
			<id>xjc</id>
			<goals>
				<goal>xjc</goal>
			</goals>
		</execution>
	</executions>
	<configuration>
		<!-- The schema directory or xsd files. -->
		<schemaDirectory>${project.basedir}/src/main/resources/xsd</schemaDirectory>
		<!-- The package in which the java source files will be generated. -->
		<packageName>com.roytuts.jaxb.model</packageName>
		<!-- The working directory to create the generated java source files. -->
		<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
	</configuration>
</plugin>
...
</plugins>

Step 5. Now build the project, you will Catalog.java and ObjectFactory.java have been generated in com.roytuts.jaxb.model package
Catalog.java

package com.roytuts.jaxb.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
 * <p>
 * Java class for anonymous complex type.
 *
 * <p>
 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 * <pre>
 * &lt;complexType>
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="Book" maxOccurs="unbounded" minOccurs="0">
 *           &lt;complexType>
 *             &lt;complexContent>
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 &lt;sequence>
 *                   &lt;element name="Author" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                   &lt;element name="Title" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                   &lt;element name="Genre" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                   &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
 *                   &lt;element name="PublishDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
 *                   &lt;element name="Description" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                 &lt;/sequence>
 *                 &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
 *               &lt;/restriction>
 *             &lt;/complexContent>
 *           &lt;/complexType>
 *         &lt;/element>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "book" })
@XmlRootElement(name = "Catalog")
public class Catalog {
	@XmlElement(name = "Book")
	protected List<Catalog.Book> book;
	/**
	 * Gets the value of the book property.
	 *
	 * <p>
	 * This accessor method returns a reference to the live list, not a
	 * snapshot. Therefore any modification you make to the returned list will
	 * be present inside the JAXB object. This is why there is not a
	 * <CODE>set</CODE> method for the book property.
	 *
	 * <p>
	 * For example, to add a new item, do as follows:
	 *
	 * <pre>
	 * getBook().add(newItem);
	 * </pre>
	 *
	 *
	 * <p>
	 * Objects of the following type(s) are allowed in the list
	 * {@link Catalog.Book }
	 *
	 *
	 */
	public List<Catalog.Book> getBook() {
		if (book == null) {
			book = new ArrayList<Catalog.Book>();
		}
		return this.book;
	}
	/**
	 * <p>
	 * Java class for anonymous complex type.
	 *
	 * <p>
	 * The following schema fragment specifies the expected content contained
	 * within this class.
	 *
	 * <pre>
	 * &lt;complexType>
	 *   &lt;complexContent>
	 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
	 *       &lt;sequence>
	 *         &lt;element name="Author" type="{http://www.w3.org/2001/XMLSchema}string"/>
	 *         &lt;element name="Title" type="{http://www.w3.org/2001/XMLSchema}string"/>
	 *         &lt;element name="Genre" type="{http://www.w3.org/2001/XMLSchema}string"/>
	 *         &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
	 *         &lt;element name="PublishDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
	 *         &lt;element name="Description" type="{http://www.w3.org/2001/XMLSchema}string"/>
	 *       &lt;/sequence>
	 *       &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
	 *     &lt;/restriction>
	 *   &lt;/complexContent>
	 * &lt;/complexType>
	 * </pre>
	 *
	 *
	 */
	@XmlAccessorType(XmlAccessType.FIELD)
	@XmlType(name = "", propOrder = { "author", "title", "genre", "price",
			"publishDate", "description" })
	public static class Book {
		@XmlElement(name = "Author", required = true)
		protected String author;
		@XmlElement(name = "Title", required = true)
		protected String title;
		@XmlElement(name = "Genre", required = true)
		protected String genre;
		@XmlElement(name = "Price")
		protected float price;
		@XmlElement(name = "PublishDate", required = true)
		@XmlSchemaType(name = "date")
		protected XMLGregorianCalendar publishDate;
		@XmlElement(name = "Description", required = true)
		protected String description;
		@XmlAttribute(name = "id")
		protected String id;
		/**
		 * Gets the value of the author property.
		 *
		 * @return possible object is {@link String }
		 *
		 */
		public String getAuthor() {
			return author;
		}
		/**
		 * Sets the value of the author property.
		 *
		 * @param value
		 *            allowed object is {@link String }
		 *
		 */
		public void setAuthor(String value) {
			this.author = value;
		}
		/**
		 * Gets the value of the title property.
		 *
		 * @return possible object is {@link String }
		 *
		 */
		public String getTitle() {
			return title;
		}
		/**
		 * Sets the value of the title property.
		 *
		 * @param value
		 *            allowed object is {@link String }
		 *
		 */
		public void setTitle(String value) {
			this.title = value;
		}
		/**
		 * Gets the value of the genre property.
		 *
		 * @return possible object is {@link String }
		 *
		 */
		public String getGenre() {
			return genre;
		}
		/**
		 * Sets the value of the genre property.
		 *
		 * @param value
		 *            allowed object is {@link String }
		 *
		 */
		public void setGenre(String value) {
			this.genre = value;
		}
		/**
		 * Gets the value of the price property.
		 *
		 */
		public float getPrice() {
			return price;
		}
		/**
		 * Sets the value of the price property.
		 *
		 */
		public void setPrice(float value) {
			this.price = value;
		}
		/**
		 * Gets the value of the publishDate property.
		 *
		 * @return possible object is {@link XMLGregorianCalendar }
		 *
		 */
		public XMLGregorianCalendar getPublishDate() {
			return publishDate;
		}
		/**
		 * Sets the value of the publishDate property.
		 *
		 * @param value
		 *            allowed object is {@link XMLGregorianCalendar }
		 *
		 */
		public void setPublishDate(XMLGregorianCalendar value) {
			this.publishDate = value;
		}
		/**
		 * Gets the value of the description property.
		 *
		 * @return possible object is {@link String }
		 *
		 */
		public String getDescription() {
			return description;
		}
		/**
		 * Sets the value of the description property.
		 *
		 * @param value
		 *            allowed object is {@link String }
		 *
		 */
		public void setDescription(String value) {
			this.description = value;
		}
		/**
		 * Gets the value of the id property.
		 *
		 * @return possible object is {@link String }
		 *
		 */
		public String getId() {
			return id;
		}
		/**
		 * Sets the value of the id property.
		 *
		 * @param value
		 *            allowed object is {@link String }
		 *
		 */
		public void setId(String value) {
			this.id = value;
		}
	}
}

ObjectFactory.java

package com.roytuts.jaxb.model;
import javax.xml.bind.annotation.XmlRegistry;
/**
 * This object contains factory methods for each Java content interface and Java
 * element interface generated in the com.roytuts.jaxb.model package.
 * <p>
 * An ObjectFactory allows you to programatically construct new instances of the
 * Java representation for XML content. The Java representation of XML content
 * can consist of schema derived interfaces and classes representing the binding
 * of schema type definitions, element declarations and model groups. Factory
 * methods for each of these are provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {
	/**
	 * Create a new ObjectFactory that can be used to create new instances of
	 * schema derived classes for package: com.roytuts.jaxb.model
	 *
	 */
	public ObjectFactory() {
	}
	/**
	 * Create an instance of {@link Catalog }
	 *
	 */
	public Catalog createCatalog() {
		return new Catalog();
	}
	/**
	 * Create an instance of {@link Catalog.Book }
	 *
	 */
	public Catalog.Book createCatalogBook() {
		return new Catalog.Book();
	}
}

Step 6. Create sample XML file catalog.xml with below data

<?xml version="1.0" encoding="UTF-8"?>
<Catalog>
	<Book id="bk101">
		<Author>Garghentini, Davide</Author>
		<Title>XML Developer's Guide</Title>
		<Genre>Computer</Genre>
		<Price>44.95</Price>
		<PublishDate>2000-10-01</PublishDate>
		<Description>An in-depth look at creating applications
			with XML.</Description>
	</Book>
	<Book id="bk102">
		<Author>Garcia, Debra</Author>
		<Title>Midnight Rain</Title>
		<Genre>Fantasy</Genre>
		<Price>5.95</Price>
		<PublishDate>2000-12-16</PublishDate>
		<Description>A former architect battles corporate zombies,
			an evil sorceress, and her own childhood to become queen
			of the world.</Description>
	</Book>
</Catalog>

Running the application

Now do a right-click on the mule-xml-java project and click on Run As -> Mule Application. Then you will see something like below in Console when the application runs

**********************************************************************
* Application: mule-3                                                *
* OS encoding: Cp1252, Mule encoding: UTF-8                          *
*                                                                    *
* Agents Running:                                                    *
*   DevKit Extension Information                                     *
*   Batch module default engine                                      *
*   Clustering Agent                                                 *
*   JMX Agent                                                        *
**********************************************************************

Once the application is up and running put the catalog.xml file under D:AnypointWorkspace.

Console output

INFO  2016-07-08 07:28:57,852 [[mule-xml-java].connector.file.mule.default.receiver.01] org.mule.transport.file.FileMessageReceiver: Lock obtained on file: D:AnypointWorkspacecatalog.xml
INFO  2016-07-08 07:28:58,113 [[mule-xml-java].xmlToObjectFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: com.roytuts.jaxb.model.Catalog@12d16a5
INFO  2016-07-08 07:28:58,156 [[mule-xml-java].xmlToObjectFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Catalog><Book id="bk101"><Author>Garghentini, Davide</Author><Title>XML Developer's Guide</Title><Genre>Computer</Genre><Price>44.95</Price><PublishDate>2000-10-01</PublishDate><Description>An in-depth look at creating applications
			with XML.</Description></Book><Book id="bk102"><Author>Garcia, Debra</Author><Title>Midnight Rain</Title><Genre>Fantasy</Genre><Price>5.95</Price><PublishDate>2000-12-16</PublishDate><Description>A former architect battles corporate zombies,
			an evil sorceress, and her own childhood to become queen
			of the world.</Description></Book></Catalog>

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *