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.

BeanFieldGroup.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.v7.data.fieldgroup;
  17. import java.beans.IntrospectionException;
  18. import java.lang.reflect.Method;
  19. import java.util.HashMap;
  20. import java.util.Map;
  21. import com.vaadin.data.util.BeanUtil;
  22. import com.vaadin.v7.data.Item;
  23. import com.vaadin.v7.data.util.BeanItem;
  24. import com.vaadin.v7.data.validator.BeanValidator;
  25. import com.vaadin.v7.ui.Field;
  26. @Deprecated
  27. public class BeanFieldGroup<T> extends FieldGroup {
  28. private final Class<T> beanType;
  29. private static Boolean beanValidationImplementationAvailable = null;
  30. private final Map<Field<?>, BeanValidator> defaultValidators;
  31. public BeanFieldGroup(Class<T> beanType) {
  32. this.beanType = beanType;
  33. this.defaultValidators = new HashMap<Field<?>, BeanValidator>();
  34. }
  35. @Override
  36. protected Class<?> getPropertyType(Object propertyId) {
  37. if (getItemDataSource() != null) {
  38. return super.getPropertyType(propertyId);
  39. } else {
  40. // Data source not set so we need to figure out the type manually
  41. /*
  42. * toString should never really be needed as propertyId should be of
  43. * form "fieldName" or "fieldName.subField[.subField2]" but the
  44. * method declaration comes from parent.
  45. */
  46. try {
  47. Class<?> type = BeanUtil.getPropertyType(beanType,
  48. propertyId.toString());
  49. if (type == null) {
  50. throw new BindException(
  51. "Cannot determine type of propertyId '" + propertyId
  52. + "'. The propertyId was not found in "
  53. + beanType.getName());
  54. }
  55. return type;
  56. } catch (IntrospectionException e) {
  57. throw new BindException("Cannot determine type of propertyId '"
  58. + propertyId + "'. Unable to introspect " + beanType,
  59. e);
  60. }
  61. }
  62. }
  63. @Override
  64. protected Object findPropertyId(java.lang.reflect.Field memberField) {
  65. String fieldName = memberField.getName();
  66. Item dataSource = getItemDataSource();
  67. if (dataSource != null
  68. && dataSource.getItemProperty(fieldName) != null) {
  69. return fieldName;
  70. } else {
  71. String minifiedFieldName = minifyFieldName(fieldName);
  72. try {
  73. return getFieldName(beanType, minifiedFieldName);
  74. } catch (SecurityException e) {
  75. } catch (NoSuchFieldException e) {
  76. }
  77. }
  78. return null;
  79. }
  80. private static String getFieldName(Class<?> cls, String propertyId)
  81. throws SecurityException, NoSuchFieldException {
  82. for (java.lang.reflect.Field field1 : cls.getDeclaredFields()) {
  83. if (propertyId.equals(minifyFieldName(field1.getName()))) {
  84. return field1.getName();
  85. }
  86. }
  87. // Try super classes until we reach Object
  88. Class<?> superClass = cls.getSuperclass();
  89. if (superClass != null && superClass != Object.class) {
  90. return getFieldName(superClass, propertyId);
  91. } else {
  92. throw new NoSuchFieldException();
  93. }
  94. }
  95. /**
  96. * Helper method for setting the data source directly using a bean. This
  97. * method wraps the bean in a {@link BeanItem} and calls
  98. * {@link #setItemDataSource(Item)}.
  99. * <p>
  100. * For null values, a null item is passed to
  101. * {@link #setItemDataSource(Item)} to be properly clear fields.
  102. *
  103. * @param bean
  104. * The bean to use as data source.
  105. */
  106. public void setItemDataSource(T bean) {
  107. if (bean == null) {
  108. setItemDataSource((Item) null);
  109. } else {
  110. setItemDataSource(new BeanItem<T>(bean, beanType));
  111. }
  112. }
  113. @Override
  114. public void setItemDataSource(Item item) {
  115. if (item == null || (item instanceof BeanItem)) {
  116. super.setItemDataSource(item);
  117. } else {
  118. throw new RuntimeException(getClass().getSimpleName()
  119. + " only supports BeanItems as item data source");
  120. }
  121. }
  122. @Override
  123. public BeanItem<T> getItemDataSource() {
  124. return (BeanItem<T>) super.getItemDataSource();
  125. }
  126. private void ensureNestedPropertyAdded(Object propertyId) {
  127. if (getItemDataSource() != null) {
  128. // The data source is set so the property must be found in the item.
  129. // If it is not we try to add it.
  130. try {
  131. getItemProperty(propertyId);
  132. } catch (BindException e) {
  133. // Not found, try to add a nested property;
  134. // BeanItem property ids are always strings so this is safe
  135. getItemDataSource().addNestedProperty((String) propertyId);
  136. }
  137. }
  138. }
  139. @Override
  140. public void bind(Field field, Object propertyId) {
  141. ensureNestedPropertyAdded(propertyId);
  142. super.bind(field, propertyId);
  143. }
  144. @Override
  145. public <T extends Field> T buildAndBind(String caption, Object propertyId,
  146. Class<T> fieldType) throws BindException {
  147. ensureNestedPropertyAdded(propertyId);
  148. return super.buildAndBind(caption, propertyId, fieldType);
  149. }
  150. @Override
  151. public void unbind(Field<?> field) throws BindException {
  152. super.unbind(field);
  153. BeanValidator removed = defaultValidators.remove(field);
  154. if (removed != null) {
  155. field.removeValidator(removed);
  156. }
  157. }
  158. @Override
  159. protected void configureField(Field<?> field) {
  160. super.configureField(field);
  161. // Add Bean validators if there are annotations
  162. if (isBeanValidationImplementationAvailable()
  163. && !defaultValidators.containsKey(field)) {
  164. BeanValidator validator = new BeanValidator(beanType,
  165. getPropertyId(field).toString());
  166. field.addValidator(validator);
  167. if (field.getLocale() != null) {
  168. validator.setLocale(field.getLocale());
  169. }
  170. defaultValidators.put(field, validator);
  171. }
  172. }
  173. /**
  174. * Checks whether a bean validation implementation (e.g. Hibernate Validator
  175. * or Apache Bean Validation) is available.
  176. *
  177. * TODO move this method to some more generic location
  178. *
  179. * @return true if a JSR-303 bean validation implementation is available
  180. */
  181. protected static boolean isBeanValidationImplementationAvailable() {
  182. if (beanValidationImplementationAvailable != null) {
  183. return beanValidationImplementationAvailable;
  184. }
  185. try {
  186. Class<?> validationClass = Class
  187. .forName("javax.validation.Validation");
  188. Method buildFactoryMethod = validationClass
  189. .getMethod("buildDefaultValidatorFactory");
  190. Object factory = buildFactoryMethod.invoke(null);
  191. beanValidationImplementationAvailable = (factory != null);
  192. } catch (Exception e) {
  193. // no bean validation implementation available
  194. beanValidationImplementationAvailable = false;
  195. }
  196. return beanValidationImplementationAvailable;
  197. }
  198. /**
  199. * Convenience method to bind Fields from a given "field container" to a
  200. * given bean with buffering disabled.
  201. * <p>
  202. * The returned {@link BeanFieldGroup} can be used for further
  203. * configuration.
  204. *
  205. * @see #bindFieldsBuffered(Object, Object)
  206. * @see #bindMemberFields(Object)
  207. * @since 7.2
  208. * @param bean
  209. * the bean to be bound
  210. * @param objectWithMemberFields
  211. * the class that contains {@link Field}s for bean properties
  212. * @return the bean field group used to make binding
  213. */
  214. public static <T> BeanFieldGroup<T> bindFieldsUnbuffered(T bean,
  215. Object objectWithMemberFields) {
  216. return createAndBindFields(bean, objectWithMemberFields, false);
  217. }
  218. /**
  219. * Convenience method to bind Fields from a given "field container" to a
  220. * given bean with buffering enabled.
  221. * <p>
  222. * The returned {@link BeanFieldGroup} can be used for further
  223. * configuration.
  224. *
  225. * @see #bindFieldsUnbuffered(Object, Object)
  226. * @see #bindMemberFields(Object)
  227. * @since 7.2
  228. * @param bean
  229. * the bean to be bound
  230. * @param objectWithMemberFields
  231. * the class that contains {@link Field}s for bean properties
  232. * @return the bean field group used to make binding
  233. */
  234. public static <T> BeanFieldGroup<T> bindFieldsBuffered(T bean,
  235. Object objectWithMemberFields) {
  236. return createAndBindFields(bean, objectWithMemberFields, true);
  237. }
  238. private static <T> BeanFieldGroup<T> createAndBindFields(T bean,
  239. Object objectWithMemberFields, boolean buffered) {
  240. @SuppressWarnings("unchecked")
  241. BeanFieldGroup<T> beanFieldGroup = new BeanFieldGroup<T>(
  242. (Class<T>) bean.getClass());
  243. beanFieldGroup.setItemDataSource(bean);
  244. beanFieldGroup.setBuffered(buffered);
  245. beanFieldGroup.bindMemberFields(objectWithMemberFields);
  246. return beanFieldGroup;
  247. }
  248. }