2 * Copyright 2000-2016 Vaadin Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
17 package com.vaadin.v7.data.util.converter;
19 import java.text.NumberFormat;
20 import java.text.ParsePosition;
21 import java.util.Locale;
24 * A converter that converts from the number type T to {@link String} and back.
25 * Uses the given locale and {@link NumberFormat} for formatting and parsing.
26 * Automatically trims the input string, removing any leading and trailing white
29 * Override and overwrite {@link #getFormat(Locale)} to use a different format.
35 public abstract class AbstractStringToNumberConverter<T>
36 implements Converter<String, T> {
39 * Returns the format used by {@link #convertToPresentation(Object, Locale)}
40 * and {@link #convertToModel(Object, Locale)}.
44 * @return A NumberFormat instance
47 protected NumberFormat getFormat(Locale locale) {
49 locale = Locale.getDefault();
52 return NumberFormat.getNumberInstance(locale);
56 * Convert the value to a Number using the given locale and
57 * {@link #getFormat(Locale)}.
60 * The value to convert
62 * The locale to use for conversion
63 * @return The converted value
64 * @throws ConversionException
65 * If there was a problem converting the value
68 protected Number convertToNumber(String value,
69 Class<? extends Number> targetType, Locale locale)
70 throws ConversionException {
75 // Remove leading and trailing white space
78 // Parse and detect errors. If the full string was not used, it is
80 ParsePosition parsePosition = new ParsePosition(0);
81 Number parsedValue = getFormat(locale).parse(value, parsePosition);
82 if (parsePosition.getIndex() != value.length()) {
83 throw new ConversionException("Could not convert '" + value
84 + "' to " + getModelType().getName());
87 if (parsedValue == null) {
99 * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
100 * .Object, java.util.Locale)
103 public String convertToPresentation(T value,
104 Class<? extends String> targetType, Locale locale)
105 throws ConversionException {
110 return getFormat(locale).format(value);
116 * @see com.vaadin.data.util.converter.Converter#getPresentationType()
119 public Class<String> getPresentationType() {