Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

DesignFormatter.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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.ui.declarative;
  17. import java.io.Serializable;
  18. import java.math.BigDecimal;
  19. import java.text.DecimalFormat;
  20. import java.text.DecimalFormatSymbols;
  21. import java.text.NumberFormat;
  22. import java.util.Collections;
  23. import java.util.Date;
  24. import java.util.Locale;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.TimeZone;
  28. import java.util.concurrent.ConcurrentHashMap;
  29. import com.vaadin.data.util.converter.Converter;
  30. import com.vaadin.data.util.converter.StringToBigDecimalConverter;
  31. import com.vaadin.data.util.converter.StringToDoubleConverter;
  32. import com.vaadin.data.util.converter.StringToFloatConverter;
  33. import com.vaadin.event.ShortcutAction;
  34. import com.vaadin.server.Resource;
  35. import com.vaadin.ui.declarative.converters.DesignDateConverter;
  36. import com.vaadin.ui.declarative.converters.DesignEnumConverter;
  37. import com.vaadin.ui.declarative.converters.DesignObjectConverter;
  38. import com.vaadin.ui.declarative.converters.DesignResourceConverter;
  39. import com.vaadin.ui.declarative.converters.DesignShortcutActionConverter;
  40. import com.vaadin.ui.declarative.converters.DesignTimeZoneConverter;
  41. import com.vaadin.ui.declarative.converters.DesignToStringConverter;
  42. /**
  43. * Class focused on flexible and consistent formatting and parsing of different
  44. * values throughout reading and writing {@link Design}. An instance of this
  45. * class is used by {@link DesignAttributeHandler}.
  46. *
  47. * @since 7.4
  48. * @author Vaadin Ltd
  49. */
  50. public class DesignFormatter implements Serializable {
  51. private final Map<Class<?>, Converter<String, ?>> converterMap = new ConcurrentHashMap<Class<?>, Converter<String, ?>>();
  52. private final Converter<String, Enum> stringEnumConverter = new DesignEnumConverter();
  53. private final Converter<String, Object> stringObjectConverter = new DesignObjectConverter();
  54. /**
  55. * Creates the formatter with default types already mapped.
  56. */
  57. public DesignFormatter() {
  58. mapDefaultTypes();
  59. }
  60. /**
  61. * Maps default types to their converters.
  62. *
  63. */
  64. protected void mapDefaultTypes() {
  65. // numbers use standard toString/valueOf approach
  66. for (Class<?> c : new Class<?>[] { Byte.class, Short.class,
  67. Integer.class, Long.class }) {
  68. DesignToStringConverter<?> conv = new DesignToStringConverter(c);
  69. converterMap.put(c, conv);
  70. try {
  71. converterMap.put((Class<?>) c.getField("TYPE").get(null), conv);
  72. } catch (Exception e) {
  73. ; // this will never happen
  74. }
  75. }
  76. // booleans use a bit different converter than the standard one
  77. // "false" is boolean false, everything else is boolean true
  78. Converter<String, Boolean> booleanConverter = new Converter<String, Boolean>() {
  79. @Override
  80. public Boolean convertToModel(String value,
  81. Class<? extends Boolean> targetType, Locale locale)
  82. throws Converter.ConversionException {
  83. return !value.equalsIgnoreCase("false");
  84. }
  85. @Override
  86. public String convertToPresentation(Boolean value,
  87. Class<? extends String> targetType, Locale locale)
  88. throws Converter.ConversionException {
  89. if (value.booleanValue()) {
  90. return "";
  91. } else {
  92. return "false";
  93. }
  94. }
  95. @Override
  96. public Class<Boolean> getModelType() {
  97. return Boolean.class;
  98. }
  99. @Override
  100. public Class<String> getPresentationType() {
  101. return String.class;
  102. }
  103. };
  104. converterMap.put(Boolean.class, booleanConverter);
  105. converterMap.put(boolean.class, booleanConverter);
  106. // floats and doubles use formatters
  107. final DecimalFormatSymbols symbols = new DecimalFormatSymbols(
  108. new Locale("en_US"));
  109. final DecimalFormat fmt = new DecimalFormat("0.###", symbols);
  110. fmt.setGroupingUsed(false);
  111. Converter<String, ?> floatConverter = new StringToFloatConverter() {
  112. @Override
  113. protected NumberFormat getFormat(Locale locale) {
  114. return fmt;
  115. };
  116. };
  117. converterMap.put(Float.class, floatConverter);
  118. converterMap.put(float.class, floatConverter);
  119. Converter<String, ?> doubleConverter = new StringToDoubleConverter() {
  120. @Override
  121. protected NumberFormat getFormat(Locale locale) {
  122. return fmt;
  123. };
  124. };
  125. converterMap.put(Double.class, doubleConverter);
  126. converterMap.put(double.class, doubleConverter);
  127. final DecimalFormat bigDecimalFmt = new DecimalFormat("0.###", symbols);
  128. bigDecimalFmt.setGroupingUsed(false);
  129. bigDecimalFmt.setParseBigDecimal(true);
  130. converterMap.put(BigDecimal.class, new StringToBigDecimalConverter() {
  131. @Override
  132. protected NumberFormat getFormat(Locale locale) {
  133. return bigDecimalFmt;
  134. };
  135. });
  136. // strings do nothing
  137. converterMap.put(String.class, new Converter<String, String>() {
  138. @Override
  139. public String convertToModel(String value,
  140. Class<? extends String> targetType, Locale locale)
  141. throws Converter.ConversionException {
  142. return value;
  143. }
  144. @Override
  145. public String convertToPresentation(String value,
  146. Class<? extends String> targetType, Locale locale)
  147. throws Converter.ConversionException {
  148. return value;
  149. }
  150. @Override
  151. public Class<String> getModelType() {
  152. return String.class;
  153. }
  154. @Override
  155. public Class<String> getPresentationType() {
  156. return String.class;
  157. }
  158. });
  159. // char takes the first character from the string
  160. Converter<String, Character> charConverter = new DesignToStringConverter<Character>(
  161. Character.class) {
  162. @Override
  163. public Character convertToModel(String value,
  164. Class<? extends Character> targetType, Locale locale)
  165. throws Converter.ConversionException {
  166. return value.charAt(0);
  167. }
  168. };
  169. converterMap.put(Character.class, charConverter);
  170. converterMap.put(char.class, charConverter);
  171. converterMap.put(Date.class, new DesignDateConverter());
  172. converterMap.put(ShortcutAction.class,
  173. new DesignShortcutActionConverter());
  174. converterMap.put(Resource.class, new DesignResourceConverter());
  175. converterMap.put(TimeZone.class, new DesignTimeZoneConverter());
  176. }
  177. /**
  178. * Adds a converter for a new type.
  179. *
  180. * @param converter
  181. * Converter to add.
  182. */
  183. protected <T> void addConverter(Converter<String, T> converter) {
  184. converterMap.put(converter.getModelType(), converter);
  185. }
  186. /**
  187. * Adds a converter for a given type.
  188. *
  189. * @param type
  190. * Type to convert to/from.
  191. * @param converter
  192. * Converter.
  193. */
  194. protected <T> void addConverter(Class<?> type,
  195. Converter<String, ?> converter) {
  196. converterMap.put(type, converter);
  197. }
  198. /**
  199. * Removes the converter for given type, if it was present.
  200. *
  201. * @param type
  202. * Type to remove converter for.
  203. */
  204. protected void removeConverter(Class<?> type) {
  205. converterMap.remove(type);
  206. }
  207. /**
  208. * Returns a set of classes that have a converter registered. This is <b>not
  209. * the same</b> as the list of supported classes - subclasses of classes in
  210. * this set are also supported.
  211. *
  212. * @return An unmodifiable set of classes that have a converter registered.
  213. */
  214. protected Set<Class<?>> getRegisteredClasses() {
  215. return Collections.unmodifiableSet(converterMap.keySet());
  216. }
  217. /**
  218. * Parses a given string as a value of given type
  219. *
  220. * @param value
  221. * String value to convert.
  222. * @param type
  223. * Expected result type.
  224. * @return String converted to the expected result type using a registered
  225. * converter for that type.
  226. */
  227. public <T> T parse(String value, Class<? extends T> type) {
  228. Converter<String, T> converter = findConverterFor(type);
  229. if (converter != null) {
  230. return converter.convertToModel(value, type, null);
  231. } else {
  232. return null;
  233. }
  234. }
  235. /**
  236. * Finds a formatter for a given object and attempts to format it.
  237. *
  238. * @param object
  239. * Object to format.
  240. * @return String representation of the object, as returned by the
  241. * registered converter.
  242. */
  243. public String format(Object object) {
  244. return format(object, object == null ? Object.class : object.getClass());
  245. }
  246. /**
  247. * Formats an object according to a converter suitable for a given type.
  248. *
  249. * @param object
  250. * Object to format.
  251. * @param type
  252. * Type of the object.
  253. * @return String representation of the object, as returned by the
  254. * registered converter.
  255. */
  256. public <T> String format(T object, Class<? extends T> type) {
  257. if (object == null) {
  258. return null;
  259. } else {
  260. return findConverterFor(object.getClass()).convertToPresentation(
  261. object, String.class, null);
  262. }
  263. }
  264. /**
  265. * Checks whether or not a value of a given type can be converted. If a
  266. * converter for a superclass is found, this will return true.
  267. *
  268. * @param type
  269. * Type to check.
  270. * @return <b>true</b> when either a given type or its supertype has a
  271. * converter, <b>false</b> otherwise.
  272. */
  273. public boolean canConvert(Class<?> type) {
  274. return findConverterFor(type) != null;
  275. }
  276. /**
  277. * Finds a converter for a given type. May return a converter for a
  278. * superclass instead, if one is found and {@code strict} is false.
  279. *
  280. * @param sourceType
  281. * Type to find a converter for.
  282. * @param strict
  283. * Whether or not search should be strict. When this is
  284. * <b>false</b>, a converter for a superclass of given type may
  285. * be returned.
  286. * @return A valid converter for a given type or its supertype, <b>null</b>
  287. * if it was not found.
  288. */
  289. @SuppressWarnings("unchecked")
  290. protected <T> Converter<String, T> findConverterFor(
  291. Class<? extends T> sourceType, boolean strict) {
  292. if (sourceType == Object.class) {
  293. // Use for propertyIds, itemIds and such. Only string type objects
  294. // are really supported if no special logic is implemented in the
  295. // component.
  296. return (Converter<String, T>) stringObjectConverter;
  297. }
  298. if (converterMap.containsKey(sourceType)) {
  299. return ((Converter<String, T>) converterMap.get(sourceType));
  300. } else if (!strict) {
  301. for (Class<?> supported : converterMap.keySet()) {
  302. if (supported.isAssignableFrom(sourceType)) {
  303. return ((Converter<String, T>) converterMap.get(supported));
  304. }
  305. }
  306. }
  307. if (sourceType.isEnum()) {
  308. return (Converter<String, T>) stringEnumConverter;
  309. }
  310. return null;
  311. }
  312. /**
  313. * Finds a converter for a given type. May return a converter for a
  314. * superclass instead, if one is found.
  315. *
  316. * @param sourceType
  317. * Type to find a converter for.
  318. * @return A valid converter for a given type or its subtype, <b>null</b> if
  319. * it was not found.
  320. */
  321. protected <T> Converter<String, T> findConverterFor(
  322. Class<? extends T> sourceType) {
  323. return findConverterFor(sourceType, false);
  324. }
  325. }