View Javadoc

1   /**
2    * This file Copyright (c) 2012-2014 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.form.field.factory;
35  
36  import info.magnolia.cms.i18n.I18nContentSupport;
37  import info.magnolia.objectfactory.ComponentProvider;
38  import info.magnolia.ui.api.view.View;
39  import info.magnolia.ui.form.AbstractFormItem;
40  import info.magnolia.ui.form.field.definition.FieldDefinition;
41  import info.magnolia.ui.form.field.definition.TextFieldDefinition;
42  import info.magnolia.ui.form.field.transformer.TransformedProperty;
43  import info.magnolia.ui.form.field.transformer.Transformer;
44  import info.magnolia.ui.form.field.transformer.UndefinedPropertyType;
45  import info.magnolia.ui.form.field.transformer.basic.BasicTransformer;
46  import info.magnolia.ui.form.validator.definition.FieldValidatorDefinition;
47  import info.magnolia.ui.form.validator.factory.FieldValidatorFactory;
48  import info.magnolia.ui.form.validator.registry.FieldValidatorFactoryFactory;
49  import info.magnolia.ui.vaadin.integration.ItemAdapter;
50  import info.magnolia.ui.vaadin.integration.jcr.DefaultPropertyUtil;
51  
52  import java.util.Locale;
53  
54  import org.apache.commons.lang3.StringUtils;
55  import org.slf4j.Logger;
56  import org.slf4j.LoggerFactory;
57  
58  import com.vaadin.data.Item;
59  import com.vaadin.data.Property;
60  import com.vaadin.data.util.converter.AbstractStringToNumberConverter;
61  import com.vaadin.data.util.converter.Converter;
62  import com.vaadin.server.Sizeable.Unit;
63  import com.vaadin.ui.AbstractField;
64  import com.vaadin.ui.AbstractTextField;
65  import com.vaadin.ui.Component;
66  import com.vaadin.ui.CssLayout;
67  import com.vaadin.ui.Field;
68  import com.vaadin.ui.Label;
69  
70  /**
71   * Abstract FieldFactory implementations. This class handle all common attributes defined in {@link FieldDefinition} and binds Vaadin {@link Field} instances created
72   * by subclasses to the {@link Property} they will be reading and writing to.
73   *
74   * @param <D> definition type
75   * @param <T> field value type
76   */
77  public abstract class AbstractFieldFactory<D extends FieldDefinition, T> extends AbstractFormItem implements FieldFactory {
78      private static final Logger log = LoggerFactory.getLogger(AbstractFieldFactory.class);
79      protected Item item;
80      protected Field<T> field;
81      protected D definition;
82      private FieldValidatorFactoryFactory fieldValidatorFactoryFactory;
83      private I18nContentSupport i18nContentSupport;
84      private ComponentProvider componentProvider;
85  
86      public AbstractFieldFactory(D definition, Item relatedFieldItem) {
87          this.definition = definition;
88          this.item = relatedFieldItem;
89      }
90  
91      @Override
92      public void setFieldValidatorFactoryFactory(FieldValidatorFactoryFactory fieldValidatorFactoryFactory) {
93          this.fieldValidatorFactoryFactory = fieldValidatorFactoryFactory;
94      }
95  
96      @Override
97      public void setI18nContentSupport(I18nContentSupport i18nContentSupport) {
98          this.i18nContentSupport = i18nContentSupport;
99      }
100 
101     @Override
102     public Field<T> createField() {
103         if (field == null) {
104             // Create the Vaadin field
105             this.field = createFieldComponent();
106             if (field instanceof AbstractField && definition.getConverterClass() != null) {
107                 Converter<?, ?> converter = initializeConverter(definition.getConverterClass());
108                 ((AbstractField) field).setConverter(converter);
109             }
110 
111             Property<?> property = initializeProperty();
112 
113             // MGNLUI-1855 we need to assign converter for properties with type Long because otherwise Vaadin assigns incompatible StringToNumberConverter.
114             if (Long.class.equals(property.getType()) && field instanceof AbstractTextField) {
115                 ((AbstractTextField) field).setConverter(new StringToLongConverter());
116             }
117             // Set the created property with the default value as field Property datasource.
118             setPropertyDataSourceAndDefaultValue(property);
119 
120             if (StringUtils.isNotBlank(definition.getStyleName())) {
121                 this.field.addStyleName(definition.getStyleName());
122             }
123 
124             field.setWidth(100, Unit.PERCENTAGE);
125 
126             // Set label and required marker
127             if (StringUtils.isNotBlank(getFieldDefinition().getLabel())) {
128                 this.field.setCaption(getFieldDefinition().getLabel() + (getFieldDefinition().isRequired() ? "<span class=\"requiredfield\">*</span>" : ""));
129             }
130 
131             setConstraints();
132 
133         }
134         return this.field;
135     }
136 
137     /**
138      * Set the DataSource of the current field.<br>
139      * Set the default value if : <br>
140      * - the item is an instance of {@link ItemAdapter} and this is a new Item (Not yet stored in the related datasource).<br>
141      * - the item is not an instance of {@link ItemAdapter}.<br>
142      * In this case, the Item is a custom implementation of {@link Item} and we have no possibility to define if it is or not a new Item.<br>
143      */
144     public void setPropertyDataSourceAndDefaultValue(Property<?> property) {
145         this.field.setPropertyDataSource(property);
146 
147         if ((item instanceof ItemAdapter && ((ItemAdapter) item).isNew() && property.getValue() == null) || (!(item instanceof ItemAdapter) && property.getValue() == null)) {
148             setPropertyDataSourceDefaultValue(property);
149         }
150     }
151 
152     /**
153      * Set the Field default value is required.
154      */
155     protected void setPropertyDataSourceDefaultValue(Property property) {
156         Object defaultValue = createDefaultValue(property);
157         if (defaultValue != null && !definition.isReadOnly()) {
158             if (defaultValue.getClass().isAssignableFrom(property.getType())) {
159                 property.setValue(defaultValue);
160             } else {
161                 log.warn("Default value {} is not assignable to the field of type {}.", defaultValue, field.getPropertyDataSource().getType().getName());
162             }
163         }
164     }
165 
166     /**
167      * Create a typed default value.
168      */
169     protected Object createDefaultValue(Property<?> property) {
170         String defaultValue = definition.getDefaultValue();
171         if (StringUtils.isNotBlank(defaultValue)) {
172             return DefaultPropertyUtil.createTypedValue(property.getType(), defaultValue);
173         }
174         return null;
175     }
176 
177     @Override
178     public D getFieldDefinition() {
179         return this.definition;
180     }
181 
182     /**
183      * Implemented by subclasses to create and initialize the Vaadin Field instance to use.
184      */
185     protected abstract Field<T> createFieldComponent();
186 
187     @Override
188     public View getView() {
189         final CssLayout fieldView = new CssLayout();
190         fieldView.setStyleName("field-view");
191 
192         Label label = new Label();
193         label.setSizeUndefined();
194         label.setCaption(getFieldDefinition().getLabel());
195 
196         if (getFieldDefinition().getClass().isAssignableFrom(TextFieldDefinition.class)) {
197             final TextFieldDefinition textFieldDefinition = (TextFieldDefinition) getFieldDefinition();
198             if (textFieldDefinition.getRows() > 0) {
199                 label.addStyleName("textarea");
200             }
201         }
202         if (definition.getConverterClass() != null) {
203             Converter converter = initializeConverter(definition.getConverterClass());
204             label.setConverter(converter);
205         }
206 
207         Property<?> property = initializeProperty();
208 
209         label.setPropertyDataSource(property);
210 
211         fieldView.addComponent(label);
212 
213         return new View() {
214             @Override
215             public Component asVaadinComponent() {
216                 return fieldView;
217             }
218         };
219     }
220 
221     /**
222      * Initialize the property used as field's Datasource.<br>
223      * If no {@link Transformer} is configure to the field definition, use the default {@link BasicTransformer} <br>
224      */
225     @SuppressWarnings("unchecked")
226     private Property<?> initializeProperty() {
227         Class<? extends Transformer<?>> transformerClass = definition.getTransformerClass();
228 
229         if (transformerClass == null) {
230             // TODO explain why down cast
231             transformerClass = (Class<? extends Transformer<?>>) (Object) BasicTransformer.class;
232         }
233         Transformer<?> transformer = initializeTransformer(transformerClass);
234 
235         return new TransformedProperty(transformer);
236     }
237 
238     /**
239      * Exposed method used by field's factory to initialize the property {@link Transformer}.<br>
240      * This allows to add additional constructor parameter if needed.<br>
241      */
242     protected Transformer<?> initializeTransformer(Class<? extends Transformer<?>> transformerClass) {
243         return this.componentProvider.newInstance(transformerClass, item, definition, getFieldType());
244     }
245 
246     /**
247      * Exposed method used by field's factory to initialize the property {@link Converter}.<br>
248      * This allows to add additional constructor parameter if needed.<br>
249      */
250     protected Converter<?, ?> initializeConverter(Class<? extends Converter<?, ?>> converterClass) {
251         return this.componentProvider.newInstance(converterClass, item, definition, getFieldType());
252     }
253 
254 
255     /**
256      * Define the field property value type Class.<br>
257      * Return the value defined by the configuration ('type' property).<br>
258      * If this value is not defined, return the value of the overriding method {@link AbstractFieldFactory#getDefaultFieldType()}.<br>
259      * If this method is not override, return {@link UndefinedPropertyType}.<br>
260      * In this case, the {@link Transformer} will have the responsibility to define the property type.
261      */
262     protected Class<?> getFieldType() {
263         Class<?> type = getDefinitionType();
264         if (type == null) {
265             type = getDefaultFieldType();
266         }
267         return type;
268     }
269 
270     /**
271      * @return Class Type defined into the field definition or null if not defined.
272      */
273     protected Class<?> getDefinitionType() {
274         if (StringUtils.isNotBlank(definition.getType())) {
275             return DefaultPropertyUtil.getFieldTypeClass(definition.getType());
276         }
277         return null;
278     }
279 
280     /**
281      * Exposed method used by field's factory in order to define a default Field Type (decoupled from the definition).
282      */
283     protected Class<?> getDefaultFieldType() {
284         return UndefinedPropertyType.class;
285     }
286 
287     @Override
288     protected String getI18nBasename() {
289         return definition.getI18nBasename();
290     }
291 
292     /**
293      * Set all constraints linked to the field:
294      * Build Validation rules.
295      * Set Required field.
296      * Set Read Only.
297      */
298     private void setConstraints() {
299         // Set Validation
300         for (FieldValidatorDefinition validatorDefinition : definition.getValidators()) {
301             FieldValidatorFactory validatorFactory = this.fieldValidatorFactoryFactory.createFieldValidatorFactory(validatorDefinition, item);
302             if (validatorFactory != null) {
303                 field.addValidator(validatorFactory.createValidator());
304             } else {
305                 log.warn("Not able to create Validation for the following definition {}", definition.toString());
306             }
307         }
308         // Set Required
309         if (definition.isRequired()) {
310             field.setInvalidCommitted(true);
311             field.setRequired(true);
312             field.setRequiredError(definition.getRequiredErrorMessage());
313         }
314 
315         // Set ReadOnly (field property has to be updated)
316         if (field.getPropertyDataSource() != null) {
317             field.getPropertyDataSource().setReadOnly(definition.isReadOnly());
318         }
319     }
320 
321     @Override
322     public void setComponentProvider(ComponentProvider componentProvider) {
323         this.componentProvider = componentProvider;
324     }
325 
326     /**
327      * The StringToLongConverter.<br>
328      * MGNLUI-1855 This should be handled by vaadin, but StringToNumberConverter throws conversion exception when used
329      * with a Long property in Vaadin 7.1. This should be fixed, unfortunately not before 7.2, so we need that converter
330      * for the time being.<br>
331      * As a result, this class will have a short life span, this is why it is kept private and deprecated.
332      */
333     @Deprecated
334     private static class StringToLongConverter extends AbstractStringToNumberConverter<Long> {
335 
336         @Override
337         public Long convertToModel(String value, Class<? extends Long> targetType, Locale locale) throws ConversionException {
338             Number n = convertToNumber(value, targetType, locale);
339             return n == null ? null : n.longValue();
340         }
341 
342         @Override
343         public Class<Long> getModelType() {
344             return Long.class;
345         }
346     }
347 
348 }