01: package org.vraptor.converter;
02:
03: import java.text.NumberFormat;
04: import java.text.ParseException;
05: import java.util.Locale;
06:
07: import org.apache.log4j.Logger;
08: import org.vraptor.LogicRequest;
09: import org.vraptor.i18n.JstlWrapper;
10:
11: /**
12: * Locale based float converter. Uses the error key invalid_value if unable to
13: * parse its information.
14: *
15: * @author Nico Steppat
16: */
17: public class LocalePrimitiveFloatConverter implements Converter {
18:
19: private final JstlWrapper jstlWrapper = new JstlWrapper();
20:
21: private static final Logger LOG = Logger
22: .getLogger(LocalePrimitiveFloatConverter.class);
23:
24: public Object convert(String value, Class<?> type,
25: LogicRequest context) throws ConversionException {
26:
27: if (value == null || value.equals("")) {
28: throw new ConversionException("invalid_value",
29: "Unable to parse string " + value);
30: }
31:
32: Locale locale = jstlWrapper.findLocale((LogicRequest) context);
33: if (locale == null) {
34: locale = Locale.getDefault();
35: }
36:
37: try {
38: Number number = NumberFormat.getInstance(locale).parse(
39: value);
40: return number.floatValue();
41: } catch (ParseException e) {
42: LOG.error("Unable to parse string " + value, e);
43: throw new ConversionException("invalid_value",
44: "Unable to parse string " + value, e);
45: }
46: }
47:
48: /**
49: * Returns the list of supported types
50: *
51: * @see org.vraptor.converter.Converter#getSupportedTypes()
52: */
53: public Class<?>[] getSupportedTypes() {
54: return new Class[] { float.class };
55: }
56: }
|