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.

StringToShortConverter.java 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  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
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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
  14. * the License.
  15. */
  16. package com.vaadin.data.util.converter;
  17. import java.text.NumberFormat;
  18. import java.util.Locale;
  19. /**
  20. * A converter that converts from {@link String} to {@link Short} and back. Uses
  21. * the given locale and a {@link NumberFormat} instance for formatting and
  22. * parsing.
  23. * <p>
  24. * Override and overwrite {@link #getFormat(Locale)} to use a different format.
  25. * </p>
  26. *
  27. * @author Vaadin Ltd
  28. * @since 7.4
  29. */
  30. public class StringToShortConverter extends
  31. AbstractStringToNumberConverter<Short> {
  32. /**
  33. * Returns the format used by
  34. * {@link #convertToPresentation(Short, Class, Locale)} and
  35. * {@link #convertToModel(String, Class, Locale)}
  36. *
  37. * @param locale
  38. * The locale to use
  39. * @return A NumberFormat instance
  40. */
  41. @Override
  42. protected NumberFormat getFormat(Locale locale) {
  43. if (locale == null) {
  44. locale = Locale.getDefault();
  45. }
  46. return NumberFormat.getIntegerInstance(locale);
  47. }
  48. /*
  49. * (non-Javadoc)
  50. *
  51. * @see
  52. * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
  53. * java.lang.Class, java.util.Locale)
  54. */
  55. @Override
  56. public Short convertToModel(String value,
  57. Class<? extends Short> targetType, Locale locale)
  58. throws ConversionException {
  59. Number n = convertToNumber(value, targetType, locale);
  60. if (n == null) {
  61. return null;
  62. }
  63. short shortValue = n.shortValue();
  64. if (shortValue == n.longValue()) {
  65. return shortValue;
  66. }
  67. throw new ConversionException("Could not convert '" + value + "' to "
  68. + Short.class.getName() + ": value out of range");
  69. }
  70. /*
  71. * (non-Javadoc)
  72. *
  73. * @see com.vaadin.data.util.converter.Converter#getModelType()
  74. */
  75. @Override
  76. public Class<Short> getModelType() {
  77. return Short.class;
  78. }
  79. }