Wednesday 8 January 2014

Spring Object XML mapping example

converting Object to XML or vice verse. This process is also known as
  • XML Marshalling – Convert Object to XML.
  • XML UnMarshalling – Convert XML to Object.

Example show you how to use Spring’s oxm to do the conversion, Object <--> XML.

Spring’s oxm itself doesn’t handle the XML marshalling or UnMarshalling, it depends developer to inject their prefer XML binding framework. In this case, you will use Castor binding framework.



pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mahesh.core</groupId>
    <artifactId>SpringOXM</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringOXM</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Uses Castor for XML -->
        <dependency>
            <groupId>org.codehaus.castor</groupId>
            <artifactId>castor</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Castor need this -->
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.8.1</version>
        </dependency>

    </dependencies>
</project>


Here is the content for simple Customer.java


package com.mahesh.core.model;

public class Customer {

    String name;
    int age;
    boolean flag;
    String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", age=" + age + ", flag=" + flag
                + ", address=" + address + "]";
    }

}

Here is the content for Marshaller and Unmarshaller logic XMLConverter.java


package com.mahesh.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class XMLConverter {

    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public Marshaller getMarshaller() {
        return marshaller;
    }

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public Unmarshaller getUnmarshaller() {
        return unmarshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }

    public void convertFromObjectToXML(Object object, String filepath)
            throws IOException {

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filepath);
            getMarshaller().marshal(object, new StreamResult(os));
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    public Object convertFromXMLToObject(String xmlfile) throws IOException {
        FileInputStream is = null;
        try {
            is = new FileInputStream(xmlfile);
            return getUnmarshaller().unmarshal(new StreamSource(is));
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

}

Here is the content for bean configuration file beans.xml



<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="XMLConverter" class="com.mahesh.core.XMLConverter">
        <property name="marshaller" ref="castorMarshaller" />
        <property name="unmarshaller" ref="castorMarshaller" />
    </bean>
    <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" >
        <property name="mappingLocation" value="classpath:mapping.xml" />
    </bean>

</beans>

Here is the content for Castor XML Mapping mapping.xml to define the relationship between Object and XML


<mapping>
    <class name="com.mahesh.core.model.Customer">

        <map-to xml="customer" />

        <field name="age" type="integer">
            <bind-xml name="age" node="attribute" />
        </field>

        <field name="flag" type="boolean">
            <bind-xml name="flag" node="element" />
        </field>

        <field name="name" type="string">
            <bind-xml name="name" node="element" />
        </field>

        <field name="address" type="string">
            <bind-xml name="address" node="element" />
        </field>
    </class>
</mapping>


Here is the content for App.java to test



package com.mahesh.core;

import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mahesh.core.model.Customer;

public class App {
    private static final String XML_FILE_NAME = "customer.xml";
   
    public static void main(String[] args) throws IOException {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("App.xml");
        XMLConverter converter = (XMLConverter) appContext.getBean("XMLConverter");
       
        Customer customer = new Customer();
        customer.setName("mahesh");
        customer.setAge(30);
        customer.setFlag(true);
        customer.setAddress("This is address");
       
        System.out.println("Convert Object to XML!");
        //from object to XML file
        converter.convertFromObjectToXML(customer, XML_FILE_NAME);
        System.out.println("Done \n");
       
        System.out.println("Convert XML back to Object!");
        //from XML to object
        Customer customer2 = (Customer)converter.convertFromXMLToObject(XML_FILE_NAME);
        System.out.println(customer2);
        System.out.println("Done");
       
    }
}


Output


Convert Object to XML!
Done

Convert XML back to Object!
Customer [name=mahesh, age=30, flag=true, address=This is address]
Done


The following XML file “customer.xml” is generated in your project root folder.

<?xml version="1.0" encoding="UTF-8"?>
   <customer age="30">
   <flag>true</flag>
   <name>mahesh</name>
   <address>This is address</address>
</customer>


No comments:

Post a Comment