You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StringToIntegerConverter.java 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.data.util.converter;
  5. import java.text.NumberFormat;
  6. import java.text.ParsePosition;
  7. import java.util.Locale;
  8. /**
  9. * A converter that converts from {@link String} to {@link Integer} and back.
  10. * Uses the given locale and a {@link NumberFormat} instance for formatting and
  11. * parsing.
  12. * <p>
  13. * Override and overwrite {@link #getFormat(Locale)} to use a different format.
  14. * </p>
  15. *
  16. * @author Vaadin Ltd
  17. * @since 7.0
  18. */
  19. public class StringToIntegerConverter implements Converter<String, Integer> {
  20. /**
  21. * Returns the format used by
  22. * {@link #convertToPresentation(Integer, Locale)} and
  23. * {@link #convertToModel(String, Locale)}.
  24. *
  25. * @param locale
  26. * The locale to use
  27. * @return A NumberFormat instance
  28. */
  29. protected NumberFormat getFormat(Locale locale) {
  30. if (locale == null) {
  31. locale = Locale.getDefault();
  32. }
  33. return NumberFormat.getIntegerInstance(locale);
  34. }
  35. @Override
  36. public Integer convertToModel(String value, Locale locale)
  37. throws ConversionException {
  38. if (value == null) {
  39. return null;
  40. }
  41. // Remove leading and trailing white space
  42. value = value.trim();
  43. // Parse and detect errors. If the full string was not used, it is
  44. // an error.
  45. ParsePosition parsePosition = new ParsePosition(0);
  46. Number parsedValue = getFormat(locale).parse(value, parsePosition);
  47. if (parsePosition.getIndex() != value.length()) {
  48. throw new ConversionException("Could not convert '" + value
  49. + "' to " + getModelType().getName());
  50. }
  51. if (parsedValue == null) {
  52. // Convert "" to null
  53. return null;
  54. }
  55. return parsedValue.intValue();
  56. }
  57. @Override
  58. public String convertToPresentation(Integer value, Locale locale)
  59. throws ConversionException {
  60. if (value == null) {
  61. return null;
  62. }
  63. return getFormat(locale).format(value);
  64. }
  65. @Override
  66. public Class<Integer> getModelType() {
  67. return Integer.class;
  68. }
  69. @Override
  70. public Class<String> getPresentationType() {
  71. return String.class;
  72. }
  73. }