package org.gomba.utils.convert;
import java.util.Date;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.w3c.util.DateParser;
import org.w3c.util.InvalidDateException;
/**
* <p>
* {@link Converter}implementation that converts an incoming String into a
* <code>java.util.Date</code> object according to the ISO 8601 standard,
* optionally using a default value or throwing a {@link ConversionException}if
* a conversion error occurs.
* </p>
*
* <p>
* Supported date formats:
* <ul>
* <li>1997-07-16T19:20:30.45-02:00</li>
* <li>1997-07-16T19:20:30+01:00</li>
* <li>1997-07-16T19:20:30</li>
* <li>1997-07-16T19:20</li>
* <li>1997-07-16</li>
* <li>1997-07</li>
* <li>1997</li>
* </ul>
* </p>
*
* <p>
* This class makes use of <code>org.w3c.util.DateParser</code> to parse
* strings.
* </p>
*
* @author Flavio Tordini
* @version $Id: ISO8601DateConverter.java,v 1.1.1.1 2004/06/16 13:15:12
* flaviotordini Exp $
* @see <a
* href="http://www.w3.org/TR/NOTE-datetime">http://www.w3.org/TR/NOTE-datetime
* </a>
* @see <a
* href="http://dev.w3.org/cvsweb/java/classes/org/w3c/util/">http://dev.w3.org/cvsweb/java/classes/org/w3c/util/
* </a>
*/
public final class ISO8601DateConverter implements Converter {
/**
* Create a {@link Converter}that will throw a {@link ConversionException}
* if a conversion error occurs.
*/
public ISO8601DateConverter() {
this.defaultValue = null;
this.useDefault = false;
}
/**
* Create a {@link Converter}that will return the specified default value
* if a conversion error occurs.
*
* @param defaultValue
* The default value to be returned
*/
public ISO8601DateConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
/**
* The default value specified to our Constructor, if any.
*/
private Object defaultValue = null;
/**
* Should we return the default value on conversion errors?
*/
private boolean useDefault = true;
/**
* Convert the specified input object into an output object of the specified
* type.
*
* @param type
* Data type to which this value should be converted
* @param value
* The input value to be converted
*
* @exception ConversionException
* if conversion cannot be performed successfully
*/
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault) {
return (this.defaultValue);
}
throw new ConversionException("No value specified");
}
if (value instanceof Date) {
return (value);
} else if (value instanceof java.lang.String) {
String valueStr = (String) value;
// w3c DateParser defaults to 1970 for an empty string
if (valueStr.length() == 0) {
throw new ConversionException(
"Cannot convert an empty string to " + Date.class);
}
try {
return DateParser.parse(valueStr);
} catch (InvalidDateException ide) {
throw new ConversionException(ide);
}
}
if (this.useDefault) {
return (this.defaultValue);
}
throw new ConversionException("Cannot convert.");
}
}