View Javadoc

1   /**
2    * This file Copyright (c) 2012-2013 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.i18n.I18NAwareProperty;
39  import info.magnolia.ui.api.view.View;
40  import info.magnolia.ui.form.AbstractFormItem;
41  import info.magnolia.ui.form.field.definition.FieldDefinition;
42  import info.magnolia.ui.form.field.definition.TextFieldDefinition;
43  import info.magnolia.ui.form.validator.definition.FieldValidatorDefinition;
44  import info.magnolia.ui.form.validator.factory.FieldValidatorFactory;
45  import info.magnolia.ui.form.validator.registry.FieldValidatorFactoryFactory;
46  import info.magnolia.ui.vaadin.integration.jcr.DefaultPropertyUtil;
47  import info.magnolia.ui.vaadin.integration.jcr.JcrNewNodeAdapter;
48  import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter;
49  
50  import java.util.Locale;
51  
52  import javax.jcr.Node;
53  import javax.jcr.RepositoryException;
54  
55  import org.apache.commons.lang.StringUtils;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  import com.vaadin.data.Item;
60  import com.vaadin.data.Property;
61  import com.vaadin.data.util.converter.AbstractStringToNumberConverter;
62  import com.vaadin.server.Sizeable.Unit;
63  import com.vaadin.ui.AbstractTextField;
64  import com.vaadin.ui.Component;
65  import com.vaadin.ui.CssLayout;
66  import com.vaadin.ui.Field;
67  import com.vaadin.ui.Label;
68  
69  /**
70   * Abstract FieldFactory implementations. This class handle all common attributes defined in {@link FieldDefinition} and binds Vaadin {@link Field} instances created
71   * by subclasses to the {@link Property} they will be reading and writing to.
72   *
73   * @param <D> definition type
74   * @param <T> field value type
75   */
76  public abstract class AbstractFieldFactory<D extends FieldDefinition, T> extends AbstractFormItem implements FieldFactory {
77      private static final Logger log = LoggerFactory.getLogger(AbstractFieldFactory.class);
78      protected Item item;
79      protected Field<T> field;
80      protected D definition;
81      private FieldValidatorFactoryFactory fieldValidatorFactoryFactory;
82      private I18nContentSupport i18nContentSupport;
83      private ComponentProvider componentProvider;
84  
85      public AbstractFieldFactory(D definition, Item relatedFieldItem) {
86          this.definition = definition;
87          this.item = relatedFieldItem;
88      }
89  
90      @Override
91      public void setFieldValidatorFactoryFactory(FieldValidatorFactoryFactory fieldValidatorFactoryFactory) {
92          this.fieldValidatorFactoryFactory = fieldValidatorFactoryFactory;
93      }
94  
95      @Override
96      public void setI18nContentSupport(I18nContentSupport i18nContentSupport) {
97          this.i18nContentSupport = i18nContentSupport;
98      }
99  
100     @Override
101     public Field<T> createField() {
102         if (field == null) {
103             // Create the Vaadin field
104             this.field = createFieldComponent();
105 
106             Property<?> property = getOrCreateProperty();
107 
108             // MGNLUI-1855 we need to assign converter for properties with type Long because otherwise Vaadin assigns incompatible StringToNumberConverter.
109             if (Long.class.equals(property.getType()) && field instanceof AbstractTextField) {
110                 ((AbstractTextField) field).setConverter(new StringToLongConverter());
111             }
112             setPropertyDataSource(property);
113 
114             if (StringUtils.isNotBlank(definition.getStyleName())) {
115                 this.field.addStyleName(definition.getStyleName());
116             }
117 
118             field.setWidth(100, Unit.PERCENTAGE);
119 
120             // Set label and required marker
121             this.field.setCaption(getMessage(getFieldDefinition().getLabel()) + (getFieldDefinition().isRequired() ? "<span class=\"requiredfield\">*</span>" : ""));
122 
123             setConstraints();
124 
125         }
126         return this.field;
127     }
128 
129     @Override
130     public D getFieldDefinition() {
131         return this.definition;
132     }
133 
134     /**
135      * Set the DataSource of the current field.
136      */
137     public void setPropertyDataSource(Property<?> property) {
138         this.field.setPropertyDataSource(property);
139     }
140 
141     /**
142      * Implemented by subclasses to create and initialize the Vaadin Field instance to use.
143      */
144     protected abstract Field<T> createFieldComponent();
145 
146     @Override
147     public View getView() {
148         Property<?> property = getOrCreateProperty();
149 
150         final CssLayout fieldView = new CssLayout();
151         fieldView.setStyleName("field-view");
152 
153         Label label = new Label();
154         label.setSizeUndefined();
155         label.setCaption(getFieldDefinition().getLabel());
156 
157         if (getFieldDefinition().getClass().isAssignableFrom(TextFieldDefinition.class)) {
158             final TextFieldDefinition textFieldDefinition = (TextFieldDefinition) getFieldDefinition();
159             if (textFieldDefinition.getRows() > 0) {
160                 label.addStyleName("textarea");
161             }
162         }
163         label.setPropertyDataSource(property);
164 
165         fieldView.addComponent(label);
166 
167         return new View() {
168             @Override
169             public Component asVaadinComponent() {
170                 return fieldView;
171             }
172         };
173     }
174 
175     /**
176      * Get a property from the current Item.
177      * <p>
178      *     if the field is i18n-aware - create a special property that would delegate
179      *     the values to the proper localized properties. Otherwise - follow the default pattern.
180      * </p>
181      *
182      * <p>
183      * If the property already exists, return this property.
184      * If the property does not exist, create a new property based on the defined type, default value, and saveInfo.
185      * </p>
186      */
187     protected Property<?> getOrCreateProperty() {
188         String propertyName = definition.getName();
189         Class<?> fieldType = getFieldType(definition);
190         String defaultValue = definition.getDefaultValue();
191         if (definition.isI18n()) {
192             I18NAwareProperty<String> property = componentProvider.newInstance(I18NAwareProperty.class, propertyName, fieldType, item);
193             property.setDefaultValue(defaultValue);
194             return property;
195 
196         } else {
197             Property<?> property = item.getItemProperty(propertyName);
198             if (property == null) {
199                 property = DefaultPropertyUtil.newDefaultProperty(fieldType.getSimpleName(), defaultValue);
200                 item.addItemProperty(propertyName, property);
201             }
202             return property;
203         }
204     }
205 
206     /**
207      * Return the Class field Type if define in the configuration.
208      * If the Type is not defined in the configuration or not of a supported type, throws
209      * a {@link IllegalArgumentException}:
210      */
211     protected Class<?> getFieldType(FieldDefinition fieldDefinition) {
212         if (StringUtils.isNotBlank(fieldDefinition.getType())) {
213             return DefaultPropertyUtil.getFieldTypeClass(fieldDefinition.getType());
214         }
215         return getDefaultFieldType(fieldDefinition);
216     }
217 
218     protected Class<?> getDefaultFieldType(FieldDefinition fieldDefinition) {
219         return String.class;
220     }
221 
222     /**
223      * Returns the field related node.
224      * If field is of type JcrNewNodeAdapter then return the parent node.
225      * Else get the node associated with the Vaadin item.
226      */
227     protected Node getRelatedNode(Item fieldRelatedItem) throws RepositoryException {
228         return (fieldRelatedItem instanceof JcrNewNodeAdapter) ? ((JcrNewNodeAdapter) fieldRelatedItem).getJcrItem() : ((JcrNodeAdapter) fieldRelatedItem).applyChanges();
229     }
230 
231     public String getPropertyName() {
232         return definition.getName();
233     }
234 
235     @Override
236     protected String getI18nBasename() {
237         return definition.getI18nBasename();
238     }
239 
240     /**
241      * Set all constraints linked to the field:
242      * Build Validation rules.
243      * Set Required field.
244      * Set Read Only.
245      */
246     private void setConstraints() {
247         // Set Validation
248         for (FieldValidatorDefinition validatorDefinition : definition.getValidators()) {
249             FieldValidatorFactory validatorFactory = this.fieldValidatorFactoryFactory.createFieldValidatorFactory(validatorDefinition, item);
250             if (validatorFactory != null) {
251                 this.field.addValidator(validatorFactory.createValidator());
252             } else {
253                 log.warn("Not able to create Validation for the following definition {}", definition.toString());
254             }
255         }
256         // Set Required
257         if (definition.isRequired()) {
258             field.setRequired(true);
259             field.setRequiredError(getMessage(definition.getRequiredErrorMessage()));
260         }
261 
262         // Set ReadOnly (field property has to be updated)
263         if (field.getPropertyDataSource() != null) {
264             field.getPropertyDataSource().setReadOnly(definition.isReadOnly());
265         }
266     }
267 
268     @Override
269     public void setComponentProvider(ComponentProvider componentProvider) {
270         this.componentProvider = componentProvider;
271     }
272 
273     /**
274      * The StringToLongConverter.<br>
275      * MGNLUI-1855 This should be handled by vaadin, but StringToNumberConverter throws conversion exception when used
276      * with a Long property in Vaadin 7.1. This should be fixed, unfortunately not before 7.2, so we need that converter
277      * for the time being.<br>
278      * As a result, this class will have a short life span, this is why it is kept private and deprecated.
279      */
280     @Deprecated
281     private static class StringToLongConverter extends AbstractStringToNumberConverter<Long> {
282 
283         @Override
284         public Long convertToModel(String value, Class<? extends Long> targetType, Locale locale) throws ConversionException {
285             Number n = convertToNumber(value, targetType, locale);
286             return n == null ? null : n.longValue();
287         }
288 
289         @Override
290         public Class<Long> getModelType() {
291             return Long.class;
292         }
293     }
294 }