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.

BeanBinderPropertySet.java 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. * Copyright 2000-2016 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;
  17. import java.beans.IntrospectionException;
  18. import java.beans.PropertyDescriptor;
  19. import java.io.IOException;
  20. import java.io.Serializable;
  21. import java.lang.reflect.InvocationTargetException;
  22. import java.lang.reflect.Method;
  23. import java.util.Map;
  24. import java.util.Objects;
  25. import java.util.Optional;
  26. import java.util.concurrent.ConcurrentHashMap;
  27. import java.util.concurrent.ConcurrentMap;
  28. import java.util.function.Function;
  29. import java.util.stream.Collectors;
  30. import java.util.stream.Stream;
  31. import com.vaadin.data.util.BeanUtil;
  32. import com.vaadin.server.Setter;
  33. import com.vaadin.util.ReflectTools;
  34. /**
  35. * A {@link BinderPropertySet} that uses reflection to find bean properties.
  36. *
  37. * @author Vaadin Ltd
  38. *
  39. * @since
  40. *
  41. * @param <T>
  42. * the type of the bean
  43. */
  44. public class BeanBinderPropertySet<T> implements BinderPropertySet<T> {
  45. /**
  46. * Serialized form of a property set. When deserialized, the property set
  47. * for the corresponding bean type is requested, which either returns the
  48. * existing cached instance or creates a new one.
  49. *
  50. * @see #readResolve()
  51. * @see BeanBinderPropertyDefinition#writeReplace()
  52. */
  53. private static class SerializedPropertySet implements Serializable {
  54. private final Class<?> beanType;
  55. private SerializedPropertySet(Class<?> beanType) {
  56. this.beanType = beanType;
  57. }
  58. private Object readResolve() {
  59. /*
  60. * When this instance is deserialized, it will be replaced with a
  61. * property set for the corresponding bean type and property name.
  62. */
  63. return get(beanType);
  64. }
  65. }
  66. /**
  67. * Serialized form of a property definition. When deserialized, the property
  68. * set for the corresponding bean type is requested, which either returns
  69. * the existing cached instance or creates a new one. The right property
  70. * definition is then fetched from the property set.
  71. *
  72. * @see #readResolve()
  73. * @see BeanBinderPropertySet#writeReplace()
  74. */
  75. private static class SerializedPropertyDefinition implements Serializable {
  76. private final Class<?> beanType;
  77. private final String propertyName;
  78. private SerializedPropertyDefinition(Class<?> beanType,
  79. String propertyName) {
  80. this.beanType = beanType;
  81. this.propertyName = propertyName;
  82. }
  83. private Object readResolve() throws IOException {
  84. /*
  85. * When this instance is deserialized, it will be replaced with a
  86. * property definition for the corresponding bean type and property
  87. * name.
  88. */
  89. return get(beanType).getProperty(propertyName)
  90. .orElseThrow(() -> new IOException(
  91. beanType + " no longer has a property named "
  92. + propertyName));
  93. }
  94. }
  95. private static class BeanBinderPropertyDefinition<T, V>
  96. implements BinderPropertyDefinition<T, V> {
  97. private final PropertyDescriptor descriptor;
  98. private final BeanBinderPropertySet<T> propertySet;
  99. public BeanBinderPropertyDefinition(
  100. BeanBinderPropertySet<T> propertySet,
  101. PropertyDescriptor descriptor) {
  102. this.propertySet = propertySet;
  103. this.descriptor = descriptor;
  104. if (descriptor.getReadMethod() == null) {
  105. throw new IllegalArgumentException(
  106. "Bean property has no accessible getter: "
  107. + propertySet.beanType + "."
  108. + descriptor.getName());
  109. }
  110. }
  111. @Override
  112. public ValueProvider<T, V> getGetter() {
  113. return bean -> {
  114. Method readMethod = descriptor.getReadMethod();
  115. Object value = invokeWrapExceptions(readMethod, bean);
  116. return getType().cast(value);
  117. };
  118. }
  119. @Override
  120. public Optional<Setter<T, V>> getSetter() {
  121. Method setter = descriptor.getWriteMethod();
  122. if (setter == null) {
  123. return Optional.empty();
  124. }
  125. return Optional.of(
  126. (bean, value) -> invokeWrapExceptions(setter, bean, value));
  127. }
  128. @SuppressWarnings("unchecked")
  129. @Override
  130. public Class<V> getType() {
  131. return (Class<V>) ReflectTools
  132. .convertPrimitiveType(descriptor.getPropertyType());
  133. }
  134. @Override
  135. public String getName() {
  136. return descriptor.getName();
  137. }
  138. @Override
  139. public BeanBinderPropertySet<T> getPropertySet() {
  140. return propertySet;
  141. }
  142. private Object writeReplace() {
  143. /*
  144. * Instead of serializing this actual property definition, only
  145. * serialize a DTO that when deserialized will get the corresponding
  146. * property definition from the cache.
  147. */
  148. return new SerializedPropertyDefinition(getPropertySet().beanType,
  149. getName());
  150. }
  151. }
  152. private static final ConcurrentMap<Class<?>, BeanBinderPropertySet<?>> instances = new ConcurrentHashMap<>();
  153. private final Class<T> beanType;
  154. private final Map<String, BinderPropertyDefinition<T, ?>> definitions;
  155. private BeanBinderPropertySet(Class<T> beanType) {
  156. this.beanType = beanType;
  157. try {
  158. definitions = BeanUtil.getBeanPropertyDescriptors(beanType).stream()
  159. .filter(BeanBinderPropertySet::hasNonObjectReadMethod)
  160. .map(descriptor -> new BeanBinderPropertyDefinition<>(this,
  161. descriptor))
  162. .collect(Collectors.toMap(BinderPropertyDefinition::getName,
  163. Function.identity()));
  164. } catch (IntrospectionException e) {
  165. throw new IllegalArgumentException(
  166. "Cannot find property descriptors for "
  167. + beanType.getName(),
  168. e);
  169. }
  170. }
  171. /**
  172. * Gets a {@link BeanBinderPropertySet} for the given bean type.
  173. *
  174. * @param beanType
  175. * the bean type to get a property set for, not <code>null</code>
  176. * @return the bean binder property set, not <code>null</code>
  177. */
  178. @SuppressWarnings("unchecked")
  179. public static <T> BinderPropertySet<T> get(Class<? extends T> beanType) {
  180. Objects.requireNonNull(beanType, "Bean type cannot be null");
  181. // Cache the reflection results
  182. return (BinderPropertySet<T>) instances.computeIfAbsent(beanType,
  183. BeanBinderPropertySet::new);
  184. }
  185. @Override
  186. public Stream<BinderPropertyDefinition<T, ?>> getProperties() {
  187. return definitions.values().stream();
  188. }
  189. @Override
  190. public Optional<BinderPropertyDefinition<T, ?>> getProperty(String name) {
  191. return Optional.ofNullable(definitions.get(name));
  192. }
  193. private static boolean hasNonObjectReadMethod(
  194. PropertyDescriptor descriptor) {
  195. Method readMethod = descriptor.getReadMethod();
  196. return readMethod != null
  197. && readMethod.getDeclaringClass() != Object.class;
  198. }
  199. private static Object invokeWrapExceptions(Method method, Object target,
  200. Object... parameters) {
  201. try {
  202. return method.invoke(target, parameters);
  203. } catch (IllegalAccessException | InvocationTargetException e) {
  204. throw new RuntimeException(e);
  205. }
  206. }
  207. @Override
  208. public String toString() {
  209. return "Property set for bean " + beanType.getName();
  210. }
  211. private Object writeReplace() {
  212. /*
  213. * Instead of serializing this actual property set, only serialize a DTO
  214. * that when deserialized will get the corresponding property set from
  215. * the cache.
  216. */
  217. return new SerializedPropertySet(beanType);
  218. }
  219. }