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.

BeanPropertySet.java 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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.shared.util.SharedUtil;
  34. import com.vaadin.util.ReflectTools;
  35. /**
  36. * A {@link PropertySet} that uses reflection to find bean properties.
  37. *
  38. * @author Vaadin Ltd
  39. *
  40. * @since
  41. *
  42. * @param <T>
  43. * the type of the bean
  44. */
  45. public class BeanPropertySet<T> implements PropertySet<T> {
  46. /**
  47. * Serialized form of a property set. When deserialized, the property set
  48. * for the corresponding bean type is requested, which either returns the
  49. * existing cached instance or creates a new one.
  50. *
  51. * @see #readResolve()
  52. * @see BeanPropertyDefinition#writeReplace()
  53. */
  54. private static class SerializedPropertySet implements Serializable {
  55. private final Class<?> beanType;
  56. private SerializedPropertySet(Class<?> beanType) {
  57. this.beanType = beanType;
  58. }
  59. private Object readResolve() {
  60. /*
  61. * When this instance is deserialized, it will be replaced with a
  62. * property set for the corresponding bean type and property name.
  63. */
  64. return get(beanType);
  65. }
  66. }
  67. /**
  68. * Serialized form of a property definition. When deserialized, the property
  69. * set for the corresponding bean type is requested, which either returns
  70. * the existing cached instance or creates a new one. The right property
  71. * definition is then fetched from the property set.
  72. *
  73. * @see #readResolve()
  74. * @see BeanPropertySet#writeReplace()
  75. */
  76. private static class SerializedPropertyDefinition implements Serializable {
  77. private final Class<?> beanType;
  78. private final String propertyName;
  79. private SerializedPropertyDefinition(Class<?> beanType,
  80. String propertyName) {
  81. this.beanType = beanType;
  82. this.propertyName = propertyName;
  83. }
  84. private Object readResolve() throws IOException {
  85. /*
  86. * When this instance is deserialized, it will be replaced with a
  87. * property definition for the corresponding bean type and property
  88. * name.
  89. */
  90. return get(beanType).getProperty(propertyName)
  91. .orElseThrow(() -> new IOException(
  92. beanType + " no longer has a property named "
  93. + propertyName));
  94. }
  95. }
  96. private static class BeanPropertyDefinition<T, V>
  97. implements PropertyDefinition<T, V> {
  98. private final PropertyDescriptor descriptor;
  99. private final BeanPropertySet<T> propertySet;
  100. public BeanPropertyDefinition(BeanPropertySet<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 String getCaption() {
  140. return SharedUtil.propertyIdToHumanFriendly(getName());
  141. }
  142. @Override
  143. public BeanPropertySet<T> getPropertySet() {
  144. return propertySet;
  145. }
  146. private Object writeReplace() {
  147. /*
  148. * Instead of serializing this actual property definition, only
  149. * serialize a DTO that when deserialized will get the corresponding
  150. * property definition from the cache.
  151. */
  152. return new SerializedPropertyDefinition(getPropertySet().beanType,
  153. getName());
  154. }
  155. }
  156. private static final ConcurrentMap<Class<?>, BeanPropertySet<?>> instances = new ConcurrentHashMap<>();
  157. private final Class<T> beanType;
  158. private final Map<String, PropertyDefinition<T, ?>> definitions;
  159. private BeanPropertySet(Class<T> beanType) {
  160. this.beanType = beanType;
  161. try {
  162. definitions = BeanUtil.getBeanPropertyDescriptors(beanType).stream()
  163. .filter(BeanPropertySet::hasNonObjectReadMethod)
  164. .map(descriptor -> new BeanPropertyDefinition<>(this,
  165. descriptor))
  166. .collect(Collectors.toMap(PropertyDefinition::getName,
  167. Function.identity()));
  168. } catch (IntrospectionException e) {
  169. throw new IllegalArgumentException(
  170. "Cannot find property descriptors for "
  171. + beanType.getName(),
  172. e);
  173. }
  174. }
  175. /**
  176. * Gets a {@link BeanPropertySet} for the given bean type.
  177. *
  178. * @param beanType
  179. * the bean type to get a property set for, not <code>null</code>
  180. * @return the bean property set, not <code>null</code>
  181. */
  182. @SuppressWarnings("unchecked")
  183. public static <T> PropertySet<T> get(Class<? extends T> beanType) {
  184. Objects.requireNonNull(beanType, "Bean type cannot be null");
  185. // Cache the reflection results
  186. return (PropertySet<T>) instances.computeIfAbsent(beanType,
  187. BeanPropertySet::new);
  188. }
  189. @Override
  190. public Stream<PropertyDefinition<T, ?>> getProperties() {
  191. return definitions.values().stream();
  192. }
  193. @Override
  194. public Optional<PropertyDefinition<T, ?>> getProperty(String name) {
  195. return Optional.ofNullable(definitions.get(name));
  196. }
  197. private static boolean hasNonObjectReadMethod(
  198. PropertyDescriptor descriptor) {
  199. Method readMethod = descriptor.getReadMethod();
  200. return readMethod != null
  201. && readMethod.getDeclaringClass() != Object.class;
  202. }
  203. private static Object invokeWrapExceptions(Method method, Object target,
  204. Object... parameters) {
  205. try {
  206. return method.invoke(target, parameters);
  207. } catch (IllegalAccessException | InvocationTargetException e) {
  208. throw new RuntimeException(e);
  209. }
  210. }
  211. @Override
  212. public String toString() {
  213. return "Property set for bean " + beanType.getName();
  214. }
  215. private Object writeReplace() {
  216. /*
  217. * Instead of serializing this actual property set, only serialize a DTO
  218. * that when deserialized will get the corresponding property set from
  219. * the cache.
  220. */
  221. return new SerializedPropertySet(beanType);
  222. }
  223. }