01: /*
02: * Copyright 2005-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
05: * in compliance with the License. You may obtain a copy of the License at
06: *
07: * http://www.apache.org/licenses/LICENSE-2.0
08: *
09: * Unless required by applicable law or agreed to in writing, software distributed under the License
10: * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11: * or implied. See the License for the specific language governing permissions and limitations under
12: * the License.
13: */
14:
15: package org.strecks.converter;
16:
17: import java.text.ParseException;
18: import java.text.SimpleDateFormat;
19: import java.util.Date;
20:
21: import org.strecks.exceptions.ConversionException;
22:
23: /**
24: * Provides logic for converting to and from dates using the SimpleDateFormat class. The subclasses of this abstract
25: * class must provide the pattern to be used
26: *
27: * @author Phil Zoio
28: */
29: public abstract class SimpleDateFormatConverter implements
30: Converter<String, Date> {
31:
32: public SimpleDateFormatConverter() {
33: super ();
34: }
35:
36: public void setTargetClass(Class clazz) {
37: if (!clazz.equals(Date.class)) {
38: throw new IllegalArgumentException(
39: "Converter will only convert to and from java.util.Date instances");
40: }
41: }
42:
43: public Date toTargetType(String toConvert)
44: throws ConversionException {
45:
46: SimpleDateFormat formatter = getDateFormat();
47:
48: if (toConvert == null || toConvert.length() == 0)
49: return null;
50:
51: try {
52: return formatter.parse(toConvert);
53: } catch (ParseException e) {
54: // should have already been validated so this is not recoverable
55: throw new ConversionException("Unable to convert value "
56: + toConvert + " to Date using pattern "
57: + getDatePattern());
58: }
59: }
60:
61: public String toSourceType(Date toConvert) {
62: if (toConvert == null)
63: return null;
64: return getDateFormat().format(toConvert);
65: }
66:
67: private SimpleDateFormat getDateFormat() {
68: SimpleDateFormat formatter = new SimpleDateFormat(
69: getDatePattern());
70: formatter.setLenient(false);
71: return formatter;
72: }
73:
74: protected abstract String getDatePattern();
75:
76: }
|