Thursday, 23 May 2013

JAXB with an adapter: Date formatting example

So, moving along from the absolute basics, I will now demonstrate how to add an adapter for formatting.

We had a kennel class which contained a list of puppies.  Each puppy has a birthday and a timestamp when it arrived in the kennel.  These are both of the type XMLGregorianCalendar but I would rather have use Joda LocalDate and LocalDateTime. Therefore I add an adapter which is called when the contents of the <birthday> and <timestamp> tags are unmarshalled.

The DateAdapter.java has two static methods, unmarshal and marshal, which convert a string to a LocalDate and vice versa respectively.

package com.ojha.jaxb.kennel.generated;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateAdapter {
private static DateTimeFormatter dateFormatter = DateTimeFormat
.forPattern("dd-MM-yyyy");
public static LocalDate unmarshal(final String date) {
return dateFormatter.parseLocalDate(date);
}
public static String marshal(LocalDate date) {
return date.toString("yyyy-MM-dd");
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Run it to generate the code:

xjc ../resources/puppy/kennel.xsd -p com.ojha.jaxb.kennel.generated


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema version="1.0" attributeFormDefault="unqualified"
elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.1">
<xs:annotation>
<xs:appinfo>
<jaxb:globalBindings>
<jaxb:javaType name="org.joda.time.LocalDate" xmlType="xs:date"
parseMethod="DateAdapter.unmarshal" printMethod="DateAdapter.marshal" />
<jaxb:javaType name="org.joda.time.LocalDateTime"
xmlType="xs:dateTime" parseMethod="DateTimeAdapter.unmarshal"
printMethod="DateTimeAdapter.marshal" />
</jaxb:globalBindings>
</xs:appinfo>
</xs:annotation>
<xs:element name="kennel" type="kennel" />
<xs:complexType name="kennel">
<xs:sequence>
<xs:element name="puppy" type="puppy" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="puppy">
<xs:sequence>
<xs:element type="xs:string" name="puppyName" />
<xs:element type="xs:date" name="puppyBirthday" />
<xs:element type="xs:dateTime" name="timeStamp" />
</xs:sequence>
</xs:complexType>
</xs:schema>
view raw gistfile1.xml hosted with ❤ by GitHub
The DateAdapter generates an Adapter1.java

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning...