01: /*
02: * $Id: AbstractConverter.java 456296 2005-03-23 16:32:59Z jonl $ $Revision:
03: * 1.9 $ $Date: 2005-03-23 17:32:59 +0100 (Wed, 23 Mar 2005) $
04: *
05: * ==============================================================================
06: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
07: * use this file except in compliance with the License. You may obtain a copy of
08: * the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15: * License for the specific language governing permissions and limitations under
16: * the License.
17: */
18: package wicket.util.convert.converters;
19:
20: import java.text.Format;
21: import java.text.ParsePosition;
22: import java.util.Locale;
23:
24: import wicket.util.convert.ConversionException;
25: import wicket.util.convert.ITypeConverter;
26:
27: /**
28: * Base class for locale aware type converters.
29: *
30: * @author Eelco Hillenius
31: */
32: public abstract class AbstractConverter implements ITypeConverter {
33: /**
34: * Parses a value using one of the java.util.text format classes.
35: *
36: * @param format
37: * The format to use
38: * @param value
39: * The object to parse
40: * @return The object
41: * @throws ConversionException
42: * Thrown if parsing fails
43: */
44: protected Object parse(final Format format, final Object value) {
45: final ParsePosition position = new ParsePosition(0);
46: final String stringValue = value.toString();
47: final Object result = format.parseObject(stringValue, position);
48: if (position.getIndex() != stringValue.length()) {
49: throw newConversionException(
50: "Cannot parse '" + value + "' using format "
51: + format, value, null).setFormat(format);
52: }
53: return result;
54: }
55:
56: /**
57: * Creates a conversion exception for throwing
58: *
59: * @param message
60: * The message
61: * @param value
62: * The value that didn't convert
63: * @param locale
64: * The locale
65: * @return The ConversionException
66: */
67: protected ConversionException newConversionException(
68: final String message, final Object value,
69: final Locale locale) {
70: return new ConversionException(message).setSourceValue(value)
71: .setTargetType(getTargetType()).setTypeConverter(this )
72: .setLocale(locale);
73: }
74:
75: /**
76: * @return The target type of this type converter
77: */
78: protected abstract Class getTargetType();
79: }
|