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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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.Arrays;
  24. import java.util.Map;
  25. import java.util.Objects;
  26. import java.util.Optional;
  27. import java.util.concurrent.ConcurrentHashMap;
  28. import java.util.concurrent.ConcurrentMap;
  29. import java.util.function.Function;
  30. import java.util.stream.Collectors;
  31. import java.util.stream.Stream;
  32. import com.vaadin.data.util.BeanUtil;
  33. import com.vaadin.server.Setter;
  34. import com.vaadin.shared.util.SharedUtil;
  35. import com.vaadin.util.ReflectTools;
  36. /**
  37. * A {@link PropertySet} that uses reflection to find bean properties.
  38. *
  39. * @author Vaadin Ltd
  40. *
  41. * @since 8.0
  42. *
  43. * @param <T>
  44. * the type of the bean
  45. */
  46. public class BeanPropertySet<T> implements PropertySet<T> {
  47. /**
  48. * Serialized form of a property set. When deserialized, the property set
  49. * for the corresponding bean type is requested, which either returns the
  50. * existing cached instance or creates a new one.
  51. *
  52. * @see #readResolve()
  53. * @see BeanPropertyDefinition#writeReplace()
  54. */
  55. private static class SerializedPropertySet implements Serializable {
  56. private final Class<?> beanType;
  57. private SerializedPropertySet(Class<?> beanType) {
  58. this.beanType = beanType;
  59. }
  60. private Object readResolve() {
  61. /*
  62. * When this instance is deserialized, it will be replaced with a
  63. * property set for the corresponding bean type and property name.
  64. */
  65. return get(beanType);
  66. }
  67. }
  68. /**
  69. * Serialized form of a property definition. When deserialized, the property
  70. * set for the corresponding bean type is requested, which either returns
  71. * the existing cached instance or creates a new one. The right property
  72. * definition is then fetched from the property set.
  73. *
  74. * @see #readResolve()
  75. * @see BeanPropertySet#writeReplace()
  76. */
  77. private static class SerializedPropertyDefinition implements Serializable {
  78. private final Class<?> beanType;
  79. private final String propertyName;
  80. private SerializedPropertyDefinition(Class<?> beanType,
  81. String propertyName) {
  82. this.beanType = beanType;
  83. this.propertyName = propertyName;
  84. }
  85. private Object readResolve() throws IOException {
  86. /*
  87. * When this instance is deserialized, it will be replaced with a
  88. * property definition for the corresponding bean type and property
  89. * name.
  90. */
  91. return get(beanType).getProperty(propertyName)
  92. .orElseThrow(() -> new IOException(
  93. beanType + " no longer has a property named "
  94. + propertyName));
  95. }
  96. }
  97. private abstract static class AbstractBeanPropertyDefinition<T, V>
  98. implements PropertyDefinition<T, V> {
  99. private final PropertyDescriptor descriptor;
  100. private final BeanPropertySet<T> propertySet;
  101. private final Class<?> propertyHolderType;
  102. public AbstractBeanPropertyDefinition(BeanPropertySet<T> propertySet,
  103. Class<?> propertyHolderType, PropertyDescriptor descriptor) {
  104. this.propertySet = propertySet;
  105. this.propertyHolderType = propertyHolderType;
  106. this.descriptor = descriptor;
  107. if (descriptor.getReadMethod() == null) {
  108. throw new IllegalArgumentException(
  109. "Bean property has no accessible getter: "
  110. + propertySet.beanType + "."
  111. + descriptor.getName());
  112. }
  113. }
  114. @SuppressWarnings("unchecked")
  115. @Override
  116. public Class<V> getType() {
  117. return (Class<V>) ReflectTools
  118. .convertPrimitiveType(descriptor.getPropertyType());
  119. }
  120. @Override
  121. public String getName() {
  122. return descriptor.getName();
  123. }
  124. @Override
  125. public String getCaption() {
  126. return SharedUtil.propertyIdToHumanFriendly(getName());
  127. }
  128. @Override
  129. public BeanPropertySet<T> getPropertySet() {
  130. return propertySet;
  131. }
  132. protected PropertyDescriptor getDescriptor() {
  133. return descriptor;
  134. }
  135. @Override
  136. public Class<?> getPropertyHolderType() {
  137. return propertyHolderType;
  138. }
  139. }
  140. private static class BeanPropertyDefinition<T, V>
  141. extends AbstractBeanPropertyDefinition<T, V> {
  142. public BeanPropertyDefinition(BeanPropertySet<T> propertySet,
  143. Class<T> propertyHolderType, PropertyDescriptor descriptor) {
  144. super(propertySet, propertyHolderType, descriptor);
  145. }
  146. @Override
  147. public ValueProvider<T, V> getGetter() {
  148. return bean -> {
  149. Method readMethod = getDescriptor().getReadMethod();
  150. Object value = invokeWrapExceptions(readMethod, bean);
  151. return getType().cast(value);
  152. };
  153. }
  154. @Override
  155. public Optional<Setter<T, V>> getSetter() {
  156. if (getDescriptor().getWriteMethod() == null) {
  157. return Optional.empty();
  158. }
  159. Setter<T, V> setter = (bean, value) -> {
  160. // Do not "optimize" this getter call,
  161. // if its done outside the code block, that will produce
  162. // NotSerializableException because of some lambda compilation
  163. // magic
  164. Method innerSetter = getDescriptor().getWriteMethod();
  165. invokeWrapExceptions(innerSetter, bean, value);
  166. };
  167. return Optional.of(setter);
  168. }
  169. private Object writeReplace() {
  170. /*
  171. * Instead of serializing this actual property definition, only
  172. * serialize a DTO that when deserialized will get the corresponding
  173. * property definition from the cache.
  174. */
  175. return new SerializedPropertyDefinition(getPropertySet().beanType,
  176. getName());
  177. }
  178. }
  179. private static class NestedBeanPropertyDefinition<T, V>
  180. extends AbstractBeanPropertyDefinition<T, V> {
  181. private final PropertyDefinition<T, ?> parent;
  182. public NestedBeanPropertyDefinition(BeanPropertySet<T> propertySet,
  183. PropertyDefinition<T, ?> parent,
  184. PropertyDescriptor descriptor) {
  185. super(propertySet, parent.getType(), descriptor);
  186. this.parent = parent;
  187. }
  188. @Override
  189. public ValueProvider<T, V> getGetter() {
  190. return bean -> {
  191. Method readMethod = getDescriptor().getReadMethod();
  192. Object value = invokeWrapExceptions(readMethod,
  193. parent.getGetter().apply(bean));
  194. return getType().cast(value);
  195. };
  196. }
  197. @Override
  198. public Optional<Setter<T, V>> getSetter() {
  199. if (getDescriptor().getWriteMethod() == null) {
  200. return Optional.empty();
  201. }
  202. Setter<T, V> setter = (bean, value) -> {
  203. // Do not "optimize" this getter call,
  204. // if its done outside the code block, that will produce
  205. // NotSerializableException because of some lambda compilation
  206. // magic
  207. Method innerSetter = getDescriptor().getWriteMethod();
  208. invokeWrapExceptions(innerSetter,
  209. parent.getGetter().apply(bean), value);
  210. };
  211. return Optional.of(setter);
  212. }
  213. private Object writeReplace() {
  214. /*
  215. * Instead of serializing this actual property definition, only
  216. * serialize a DTO that when deserialized will get the corresponding
  217. * property definition from the cache.
  218. */
  219. return new SerializedPropertyDefinition(getPropertySet().beanType,
  220. parent.getName() + "." + getName());
  221. }
  222. }
  223. private static final ConcurrentMap<Class<?>, BeanPropertySet<?>> instances = new ConcurrentHashMap<>();
  224. private final Class<T> beanType;
  225. private final Map<String, PropertyDefinition<T, ?>> definitions;
  226. private BeanPropertySet(Class<T> beanType) {
  227. this.beanType = beanType;
  228. try {
  229. definitions = BeanUtil.getBeanPropertyDescriptors(beanType).stream()
  230. .filter(BeanPropertySet::hasNonObjectReadMethod)
  231. .map(descriptor -> new BeanPropertyDefinition<>(this,
  232. beanType, descriptor))
  233. .collect(Collectors.toMap(PropertyDefinition::getName,
  234. Function.identity()));
  235. } catch (IntrospectionException e) {
  236. throw new IllegalArgumentException(
  237. "Cannot find property descriptors for "
  238. + beanType.getName(),
  239. e);
  240. }
  241. }
  242. /**
  243. * Gets a {@link BeanPropertySet} for the given bean type.
  244. *
  245. * @param beanType
  246. * the bean type to get a property set for, not <code>null</code>
  247. * @return the bean property set, not <code>null</code>
  248. */
  249. @SuppressWarnings("unchecked")
  250. public static <T> PropertySet<T> get(Class<? extends T> beanType) {
  251. Objects.requireNonNull(beanType, "Bean type cannot be null");
  252. // Cache the reflection results
  253. return (PropertySet<T>) instances.computeIfAbsent(beanType,
  254. BeanPropertySet::new);
  255. }
  256. @Override
  257. public Stream<PropertyDefinition<T, ?>> getProperties() {
  258. return definitions.values().stream();
  259. }
  260. @Override
  261. public Optional<PropertyDefinition<T, ?>> getProperty(String name)
  262. throws IllegalArgumentException {
  263. Optional<PropertyDefinition<T, ?>> definition = Optional
  264. .ofNullable(definitions.get(name));
  265. if (!definition.isPresent() && name.contains(".")) {
  266. try {
  267. String parentName = name.substring(0, name.lastIndexOf('.'));
  268. Optional<PropertyDefinition<T, ?>> parent = getProperty(
  269. parentName);
  270. if (!parent.isPresent()) {
  271. throw new IllegalArgumentException(
  272. "Cannot find property descriptor [" + parentName
  273. + "] for " + beanType.getName());
  274. }
  275. Optional<PropertyDescriptor> descriptor = Optional.ofNullable(
  276. BeanUtil.getPropertyDescriptor(beanType, name));
  277. if (descriptor.isPresent()) {
  278. NestedBeanPropertyDefinition<T, ?> nestedDefinition = new NestedBeanPropertyDefinition<>(
  279. this, parent.get(), descriptor.get());
  280. definitions.put(name, nestedDefinition);
  281. return Optional.of(nestedDefinition);
  282. } else {
  283. throw new IllegalArgumentException(
  284. "Cannot find property descriptor [" + name
  285. + "] for " + beanType.getName());
  286. }
  287. } catch (IntrospectionException e) {
  288. throw new IllegalArgumentException(
  289. "Cannot find property descriptors for "
  290. + beanType.getName(),
  291. e);
  292. }
  293. }
  294. return definition;
  295. }
  296. private static boolean hasNonObjectReadMethod(
  297. PropertyDescriptor descriptor) {
  298. Method readMethod = descriptor.getReadMethod();
  299. return readMethod != null
  300. && readMethod.getDeclaringClass() != Object.class;
  301. }
  302. private static Object invokeWrapExceptions(Method method, Object target,
  303. Object... parameters) {
  304. try {
  305. return method.invoke(target, parameters);
  306. } catch (IllegalAccessException | InvocationTargetException e) {
  307. throw new RuntimeException(e);
  308. }
  309. }
  310. @Override
  311. public String toString() {
  312. return "Property set for bean " + beanType.getName();
  313. }
  314. private Object writeReplace() {
  315. /*
  316. * Instead of serializing this actual property set, only serialize a DTO
  317. * that when deserialized will get the corresponding property set from
  318. * the cache.
  319. */
  320. return new SerializedPropertySet(beanType);
  321. }
  322. }