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.

StringToByteConverter.java 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 Byte} 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 StringToByteConverter extends
  31. AbstractStringToNumberConverter<Byte> {
  32. /**
  33. * Returns the format used by
  34. * {@link #convertToPresentation(Byte, 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 Byte convertToModel(String value, Class<? extends Byte> targetType,
  57. Locale locale) throws ConversionException {
  58. Number n = convertToNumber(value, targetType, locale);
  59. if (n == null) {
  60. return null;
  61. }
  62. byte byteValue = n.byteValue();
  63. if (byteValue == n.longValue()) {
  64. return byteValue;
  65. }
  66. throw new ConversionException("Could not convert '" + value + "' to "
  67. + Byte.class.getName() + ": value out of range");
  68. }
  69. /*
  70. * (non-Javadoc)
  71. *
  72. * @see com.vaadin.data.util.converter.Converter#getModelType()
  73. */
  74. @Override
  75. public Class<Byte> getModelType() {
  76. return Byte.class;
  77. }
  78. }