| package org.eclipse.osbp.vaaclipse.addons.app.converter; |
| |
| import java.text.DateFormat; |
| import java.text.ParsePosition; |
| import java.util.Date; |
| import java.util.Locale; |
| |
| import com.vaadin.data.util.converter.Converter; |
| |
| @SuppressWarnings("serial") |
| public class VaaclipseDateConverter implements Converter<String, Date> { |
| |
| /** |
| * Returns the format used by |
| * {@link #convertToPresentation(Date, Class,Locale)} and |
| * {@link #convertToModel(String, Class, Locale)}. |
| * |
| * @param locale |
| * The locale to use |
| * @return A DateFormat instance |
| */ |
| protected DateFormat getFormat(Locale locale) { |
| if (locale == null) { |
| locale = Locale.getDefault(); |
| } |
| |
| DateFormat f = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); |
| f.setLenient(false); |
| return f; |
| } |
| |
| /* |
| * (non-Javadoc) |
| * |
| * @see |
| * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object, |
| * java.lang.Class, java.util.Locale) |
| */ |
| @Override |
| public Date convertToModel(String value, Class<? extends Date> targetType, Locale locale) |
| throws com.vaadin.data.util.converter.Converter.ConversionException { |
| if (targetType != getModelType()) { |
| throw new ConversionException("Converter only supports " + getModelType().getName() + " (targetType was " |
| + targetType.getName() + ")"); |
| } |
| |
| if (value == null) { |
| return null; |
| } |
| |
| // Remove leading and trailing white space |
| value = value.trim(); |
| |
| ParsePosition parsePosition = new ParsePosition(0); |
| Date parsedValue = getFormat(locale).parse(value, parsePosition); |
| if (parsePosition.getIndex() != value.length()) { |
| throw new ConversionException("Could not convert '" + value + "' to " + getModelType().getName()); |
| } |
| |
| return parsedValue; |
| } |
| |
| /* |
| * (non-Javadoc) |
| * |
| * @see |
| * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang |
| * .Object, java.lang.Class, java.util.Locale) |
| */ |
| @Override |
| public String convertToPresentation(Date value, Class<? extends String> targetType, Locale locale) |
| throws com.vaadin.data.util.converter.Converter.ConversionException { |
| if (value == null) { |
| return null; |
| } |
| |
| return getFormat(locale).format(value); |
| } |
| |
| /* |
| * (non-Javadoc) |
| * |
| * @see com.vaadin.data.util.converter.Converter#getModelType() |
| */ |
| @Override |
| public Class<Date> getModelType() { |
| return Date.class; |
| } |
| |
| /* |
| * (non-Javadoc) |
| * |
| * @see com.vaadin.data.util.converter.Converter#getPresentationType() |
| */ |
| @Override |
| public Class<String> getPresentationType() { |
| return String.class; |
| } |
| |
| } |