Skip to main content

JAXB - Java Architecture for XML Binding


Introduction

Allows mapping xml files to java classes.

 

Example


Sample schema file:
<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:sx="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified">

    <xs:element name="item-configuration" type="itemConfigurationType"/>

    <xs:complexType name="itemConfigurationType">
        <xs:sequence>
            <xs:element name="item-id" type="StringT"/>
            <xs:element name="enabled" type="xs:boolean"/>
            <xs:element name="item-type">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="item-type-name" type="itemTypeNameT"/>
                        <xs:element name="item-type-value" type="Base_item_Type"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            <xs:element name="retry-count" type="xs:integer" minOccurs="0" default="-1"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="ITEM_1">
        <xs:complexContent>
            <xs:extension base="Base_item_Type">
                <xs:sequence>
                    <xs:element name="dst-model" type="ModelT"/>
                    <xs:element name="dst-model-key" type="StringT"/>
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
    <xs:complexType name="ITEM_2">
        <xs:complexContent>
            <xs:extension base="Base_item_Type">
                <xs:sequence>
                    <xs:element name="dst-model" type="ModelT"/>
                    <xs:element name="dst-model-key" type="StringT"/>
                    <xs:element name="dst-dao" type="DaoT"/>
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>

    <xs:complexType name="Base_item_Type" abstract="true">
        <xs:sequence>
            <xs:element name="src-filter" type="StringT"/>
        </xs:sequence>
  <xs:attribute name="apply" type="ApplyType" default="ALWAYS"/>
    </xs:complexType>
 
 
    <xs:simpleType name="ApplyType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="ALWAYS"/>
            <xs:enumeration value="IFEMPTY"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="ModelT">
        <xs:restriction base="xs:string">
            <xs:pattern value="(\[int\]|\[ext\])\..+"/>
            <xs:pattern value="NONE"/>
        </xs:restriction>
    </xs:simpleType>
 
    <xs:simpleType name="DaoT">
        <xs:restriction base="xs:string">
            <xs:pattern value="(\[int\]|\[ext\])\..+DaoImpl"/>
            <xs:pattern value="NONE"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="StringT">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="itemTypeNameT">
        <xs:restriction base="xs:string">
            <xs:enumeration value="ITEM_TYPE_1"/>
            <xs:enumeration value="ITEM_TYPE_2"/>
        </xs:restriction>
    </xs:simpleType>

</xs:schema>



Sample XML file: Sample is to show possible content of xml file having the item.configuration schema.
<?xml version="1.0" ?>
<item-configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:noNamespaceSchemaLocation="item.configuration.xsd"> <!-- specify schema file -->

    <item>
        <item-id>item-id-1</item-id>
        <enabled>true</enabled>
        <item-type>
            <item-type-name>ITEM_TYPE_1</item-type-name>
            <item-type-value xsi:type="ITEM_1" apply="IFEMPTY"><!-- optional attribute -->
                <src-filter>asd</src-filter>
                <dst-model>[int].Item1Model</dst-model>
                <dst-model-key>key</dst-model-key>
            </item-type-value>
        </item-type>

        <retry-count>1</retry-count> <!-- optional -->
    </item>

    <item>
        <item-id>item-id-2</item-id>
        <enabled>false</enabled>
        <item-type>
            <item-type-name>ITEM_TYPE_2</item-type-name>
            <item-type-value xsi:type="ITEM_2">
                <src-filter>asd</src-filter>
                <dst-model>[int].Item2Model</dst-model>
                <dst-model-key>key</dst-model-key>
                <dst-dao>[int].Item2Impl</dst-dao>
            </item-type-value>
        </item-type>

    </item>


</item-configuration>


Creating Java Files: As simple as typing the following command.
xjc item.configuration.xsd
Java files will be generated into a folder called “generated”. Sample test method can something like below. Following code reads items.xml file, parses according to item.configuration.xsd and maps toItemConfiguration object.
public class Main{

    private static final String ITEM_CONFIGURATION_SCHEMA_LOCATION_FILE = "item.configuration.xsd";
 
 public static void main(String[] args){
 
   try {
   File file = new File("items.xml");
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(ClassLoader.getSystemResource(ITEM_CONFIGURATION_SCHEMA_LOCATION_FILE));

            JAXBContext jaxbContext = JAXBContext.newInstance(ItemConfigurationType.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();// create unmarshaller
            jaxbUnmarshaller.setSchema(schema); // set schema file

            JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(file);// unmarshal file
            ItemConfigurationType itemConfiguration = element.getValue();
   
   //work on itemConfiguration object
   // ....
   // ....
   
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
 
 }
}



Example Cases:



Inheritance Relationship

XML:
<item-type>
            <item-type-name>ITEM_TYPE_1</item-type-name>
            <item-type-value xsi:type="ITEM_1" apply="IFEMPTY"><!-- optional attribute -->
                <src-filter>asd</src-filter>


XSD:

    <xs:complexType name="Base_item_Type" abstract="true">
        <xs:sequence>
            <xs:element name="src-filter" type="StringT"/>
        </xs:sequence>
        <xs:attribute name="apply" type="ApplyType" default="ALWAYS"/>
    </xs:complexType>
               
    <xs:complexType name="ITEM_1">
        <xs:complexContent>
            <xs:extension base="Base_item_Type">
                <xs:sequence>


Java File:
BaseItemType.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Base_item_Type", propOrder = {
    "srcFilter"
})
@XmlSeeAlso({
    ITEM1 .class,
    ITEM2 .class
})
public abstract class BaseItemType {

    @XmlElement(name = "src-filter", required = true)
    protected String srcFilter;
    @XmlAttribute(name = "apply")
    protected ApplyType apply;

    

}

ITEM1.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ITEM_1", propOrder = {
    "dstModel",
    "dstModelKey"
})
public class ITEM1
    extends BaseItemType
{

    @XmlElement(name = "dst-model", required = true)
    protected String dstModel;
    @XmlElement(name = "dst-model-key", required = true)
    protected String dstModelKey;

    

}

Attributes

XML:
<item-type-value xsi:type="ITEM_1" apply="IFEMPTY">

XSD:
    <xs:complexType name="Base_item_Type" abstract="true">
        <xs:sequence>
            <xs:element name="src-filter" type="StringT"/>
        </xs:sequence>
        <xs:attribute name="apply" type="ApplyType" default="ALWAYS"/>
    </xs:complexType>

Java File:
@XmlAttribute(name = "apply")
      protected ApplyType apply;



Enumeration Type

XML:
<item-type-name>ITEM_TYPE_2</item-type-name>

XSD:

    <xs:simpleType name="itemTypeNameT">
        <xs:restriction base="xs:string">
            <xs:enumeration value="ITEM_TYPE_1"/>
            <xs:enumeration value="ITEM_TYPE_2"/>
        </xs:restriction>
    </xs:simpleType>

Java File:
ItemTypeNameT.java
@XmlType(name = "itemTypeNameT")
@XmlEnum
public enum ItemTypeNameT {
    ITEM_TYPE_1,
    ITEM_TYPE_2;

    public String value() {
        return name();
    }

    public static ItemTypeNameT fromValue(String v) {
        return valueOf(v);
    }
}


Regular Expression Types

XML:
<xs:element name="dst-dao" type="DaoT"/>

XSD:
   
    <xs:simpleType name="DaoT">
        <xs:restriction base="xs:string">
            <xs:pattern value="(\[int\]|\[ext\])\..+DaoImpl"/>
            <xs:pattern value="NONE"/>
        </xs:restriction>
    </xs:simpleType>


Java File:
    @XmlElement(name = "dst-dao", required = true)
    protected String dstDao;


Summary


JAXB is a great tool while working with XML files. It is easy to use yet powerful. Complete file listing can be download from this link.

Feel free to share your comments to http://el-harezmi.blogspot.com on design and any typos, incorrect or inaccurate expressions you see.

Comments

Popular posts from this blog

Obfuscating Spring Boot Projects Using Maven Proguard Plugin

Introduction Obfuscation is the act of reorganizing bytecode such that it becomes hard to decompile. Many developers rely on obfuscation to save their sensitive code from undesired eyes. Publishing jars without obfuscation may hinder competitiveness because rivals may take advantage of easily decompilable nature of java binaries. Objective Spring Boot applications make use of public interfaces, annotations which makes applications harder to obfuscate. Additionally, maven Spring Boot plugin creates a fat jar which contains all dependent jars. It is not viable to obfuscate the whole fat jar. Thus obfuscating Spring Boot applications is different than obfuscating regular java applications and requires a suitable strategy. Audience Those who use Spring Boot and Maven and wish to obfuscate their application using Proguard are the target audience for this article. Sample Application As the sample application, I will use elastic search synch application from my GitHub repository.

Hadoop Installation Document - Standalone Mode

This document shows my experience on following apache document titled “Hadoop:Setting up a Single Node Cluster”[1] which is for Hadoop version 3.0.0-Alpha2 [2]. A. Prepare the guest environment Install VirtualBox. Create a virtual 64 bit Linux machine. Name it “ubuntul_hadoop_master”. Give it 500MB memory. Create a VMDK disc which is dynamically allocated up to 30GB. In network settings in first tab you should see Adapter 1 enabled and attached to “NAT”. In second table enable adapter 2 and attach to “Host Only Adaptor”. First adapter is required for internet connection. Second one is required for letting outside connect to a guest service. In storage settings, attach a Linux iso file to IDE channel. Use any distribution you like. Because of small installation size, I choose minimal Ubuntu iso [1]. In package selection menu, I only left standard packages selected.  Login to system.  Setup JDK. $ sudo apt-get install openjdk-8-jdk Install ssh and pdsh, if not already i

Java: Cost of Volatile Variables

Introduction Use of volatile variables is common among Java developers as a way of implicit synchronization. JIT compilers may reorder program execution to increase performance. Java memory model[1] constraints reordering of volatile variables. Thus volatile variable access should has a cost which is different than a non-volatile variable access. This article will not discuss technical details on use of volatile variables. Performance impact of volatile variables is explored by using a test application. Objective Exploring volatile variable costs and comparing with alternative approaches. Audience This article is written for developers who seek to have a view about cost of volatile variables. Test Configuration Test application runs read and write actions on java variables. A non volatile primitive integer, a volatile primitive integer and an AtomicInteger is tested. Non-volatile primitive integer access is controlled with ReentrantLock and ReentrantReadWriteLock  to compa