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

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