This is just a little post that comes about from my frustration in working with dates in Java. I say in Java, generally speaking, because it still bugs me that sometimes you end up with a java.util.Date object and sometimes with a java.util.Calendar and I constantly seem to have to convert between them to end up with the one that I actually want. To add to that in my GWT projects Calendar is not supported client side so I usually use Date which is not my preference.

Anyway, to end my little rant, the motivation for this post is actually javax.xml.datatype.XMLGregorianCalendar, all I could think of was not another one! I noticed in one of my web service projects that JAXB was binding <xsd:dateTime> to XMLGregorianCalendar when what I really wanted was a Calendar. I could have written a conversion method but that seemed stupid and I found a better solution in the form of JAXB binding declarations.

All you do is take your WSDL or XML schema and add the following annotation block below the <xsd:schema> element:

<xsd:schema

     targetNamespace="com.codenes"

     xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"

     xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"

     xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

     xmlns:xsd="http://www.w3.org/2001/XMLSchema"

     xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.0">

     <xsd:annotation>

          <xsd:appinfo>

               <jaxb:globalBindings>

                    <jaxb:javaType name="java.util.Calendar" xmlType="xsd:dateTime" parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime" printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />

               </jaxb:globalBindings>

          </xsd:appinfo>

     </xsd:annotation>

     ...

Note. The JAXB namespace and version are specified as attributes of the <xsd:schema> element.

After modifying my WSDL as above in NetBeans I then just refreshed the web service and did a build, and the xjc (JAXB Binding Compiler) generates source with Calendar objects in place of the default XMLGregorianCalendar.