summaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/data/util/converter/IntegerToStringConverter.java
blob: c73f31a5274cfd285df2c526aacfbe1460b03b5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
@VaadinApache2LicenseForJavaFiles@
 */

package com.vaadin.data.util.converter;

import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;

public class IntegerToStringConverter implements Converter<Integer, String> {

    protected NumberFormat getFormatter(Locale locale) {
        if (locale == null) {
            return NumberFormat.getIntegerInstance();
        } else {
            return NumberFormat.getIntegerInstance(locale);
        }
    }

    public Integer convertFromTargetToSource(String value, Locale locale) {
        if (value == null) {
            return null;
        }

        // Remove extra spaces
        value = value.trim();

        // Parse and detect errors. If the full string was not used, it is
        // an error.
        ParsePosition parsePosition = new ParsePosition(0);
        Number parsedValue = getFormatter(locale).parse(value, parsePosition);
        if (parsePosition.getIndex() != value.length()) {
            throw new ConversionException("Could not convert '" + value
                    + "' to " + getTargetType().getName());
        }

        if (parsedValue == null) {
            // Convert "" to null
            return null;
        }
        return parsedValue.intValue();
    }

    public String convertFromSourceToTarget(Integer value, Locale locale) {
        if (value == null) {
            return null;
        }

        return getFormatter(locale).format(value);
    }

    public Class<Integer> getSourceType() {
        return Integer.class;
    }

    public Class<String> getTargetType() {
        return String.class;
    }

}