Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

StringToIntegerConverter.java 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * @version
  18. * @VERSION@
  19. * @since 7.0
  20. */
  21. public class StringToIntegerConverter implements Converter<String, Integer> {
  22. /**
  23. * Returns the format used by
  24. * {@link #convertToPresentation(Integer, Locale)} and
  25. * {@link #convertToModel(String, Locale)}.
  26. *
  27. * @param locale
  28. * The locale to use
  29. * @return A NumberFormat instance
  30. */
  31. protected NumberFormat getFormat(Locale locale) {
  32. if (locale == null) {
  33. locale = Locale.getDefault();
  34. }
  35. return NumberFormat.getIntegerInstance(locale);
  36. }
  37. @Override
  38. public Integer convertToModel(String value, Locale locale)
  39. throws ConversionException {
  40. if (value == null) {
  41. return null;
  42. }
  43. // Remove leading and trailing white space
  44. value = value.trim();
  45. // Parse and detect errors. If the full string was not used, it is
  46. // an error.
  47. ParsePosition parsePosition = new ParsePosition(0);
  48. Number parsedValue = getFormat(locale).parse(value, parsePosition);
  49. if (parsePosition.getIndex() != value.length()) {
  50. throw new ConversionException("Could not convert '" + value
  51. + "' to " + getModelType().getName());
  52. }
  53. if (parsedValue == null) {
  54. // Convert "" to null
  55. return null;
  56. }
  57. return parsedValue.intValue();
  58. }
  59. @Override
  60. public String convertToPresentation(Integer value, Locale locale)
  61. throws ConversionException {
  62. if (value == null) {
  63. return null;
  64. }
  65. return getFormat(locale).format(value);
  66. }
  67. @Override
  68. public Class<Integer> getModelType() {
  69. return Integer.class;
  70. }
  71. @Override
  72. public Class<String> getPresentationType() {
  73. return String.class;
  74. }
  75. }