org.milyn.javabean.decoders.XMLGregorianCalendarDecoder Maven / Gradle / Ivy
The newest version!
/*
Milyn - Copyright (C) 2006 - 2010
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software
Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details:
http://www.gnu.org/licenses/lgpl.txt
*/
package org.milyn.javabean.decoders;
import org.milyn.javabean.DataDecodeException;
import org.milyn.javabean.DecodeType;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* {@link javax.xml.datatype.XMLGregorianCalendar} data decoder.
*
* Decodes the supplied string into a {@link javax.xml.datatype.XMLGregorianCalendar} value based on the supplied "
* {@link java.text.SimpleDateFormat format}" parameter, or the default (see below).
*
* The default date format used is "yyyy-MM-dd'T'HH:mm:ss" (see {@link java.text.SimpleDateFormat}). This format is based on the ISO 8601 standard as used by the XML Schema type "dateTime".
*
* This decoder is synchronized on its underlying {@link java.text.SimpleDateFormat} instance.
*
* @author [email protected]
*/
@DecodeType(XMLGregorianCalendar.class)
public class XMLGregorianCalendarDecoder extends DateDecoder {
@Override
public Object decode(String data) throws DataDecodeException {
Date date = (Date) super.decode(data);
try {
GregorianCalendar gregCal = new GregorianCalendar();
gregCal.setTime(date);
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregCal);
} catch (DatatypeConfigurationException e) {
throw new DataDecodeException("Error decoding XMLGregorianCalendar data value '" + data + "' with decode format '" + format + "'.", e);
}
}
@Override
public String encode(Object date) throws DataDecodeException {
if(!(date instanceof XMLGregorianCalendar)) {
throw new DataDecodeException("Cannot encode Object type '" + date.getClass().getName() + "'. Must be type '" + XMLGregorianCalendar.class.getName() + "'.");
}
return super.encode(((XMLGregorianCalendar)date).toGregorianCalendar().getTime());
}
}