Code, JavaEE, Technical

JAXB Solution for Custom Date Format

OVERVIEW

Working on a recent project, there was a need to support XML validation against an XML Schema based on a date in the format:

yyyy-MM-dd hh:mm:ss

The problem was this format does not align with the XML Schema definition for xs:dateTime. The proper format would include a T in between the date and time as follows:

yyyy-MM-ddThh:mm:ss

Unfortunately, this was not supported. So after trying a number of things including writing a custom javax.xml.bind.annotation.adapters.XmlAdapter subclass and annotating the getters for the date properties of the JAXB POJO, it still didn’t work.

SOLUTION

The solution was to define the date time elements in the XML Schema:


<xs:element name="BeginningDate" minOccurs="0">
 <xs:simpleType>
 <xs:restriction base="xs:string">
 <xs:pattern value="\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d" />
 </xs:restriction>
 </xs:simpleType>
 </xs:element>

If any other format comes in other than what is defined in the XML Schema the parsing/validation will fail and exception will be thrown.

Happy thinking and coding!

TOOLS AND TECHNOLOGIES REFERENCE

  • Java 7 Standard Edition
  • Java EE API
  • Spring Framework
    • Spring Core
    • Spring JMS
    • Spring JDBC
    • Spring Test
  • Active MQ
  • Google Gson
  • SLF4J Logging Library
  • JUnit Testing Framework
  • MySQL Connector Driver
  • Oracle Database Driver
  • Apache Maven
  • RedHat JBoss Application Server
  • Oracle GlassFish Application Server
  • Git – Source Control Management
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s