1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.exolab.castor.mapping.GeneralizedFieldHandler;
import org.exolab.castor.mapping.ValidityException;
public class CustomDateFieldHandler extends GeneralizedFieldHandler {
private SimpleDateFormat formatter;
public CustomDateFieldHandler() {
//
}
public Object convertUponGet(Object value) {
if (value == null) return null;
Date date = (Date)value;
return formatter.format(date);
}
public Object convertUponSet(Object value) {
Date date = null;
try {
date = formatter.parse((String)value);
}
catch(ParseException px) {
throw new IllegalArgumentException(px.getMessage());
}
return date;
}
public Class getFieldType() {
return Date.class;
}
public Object newInstance( Object parent )
throws IllegalStateException
{
//-- Since it's marked as a string...just return null,
//-- it's not needed.
return null;
}
public void setConfiguration(Properties config) throws ValidityException {
String pattern = config.getProperty("date-format");
if (pattern == null) {
throw new ValidityException("Required parameter \"date-format\" is missing for CustomDateFieldHandler.");
}
try {
formatter = new SimpleDateFormat(pattern);
} catch (IllegalArgumentException e) {
throw new ValidityException("Pattern \""+pattern+"\" is not a valid date format.");
}
}
}
|