View Javadoc
1   /**
2    * This file Copyright (c) 2012-2018 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.vaadin.integration.jcr;
35  
36  import info.magnolia.cms.util.DateUtil;
37  
38  import java.math.BigDecimal;
39  import java.text.ParseException;
40  import java.text.SimpleDateFormat;
41  import java.util.Arrays;
42  import java.util.Date;
43  import java.util.List;
44  
45  import javax.jcr.Binary;
46  import javax.jcr.PropertyType;
47  
48  import org.apache.commons.lang3.BooleanUtils;
49  import org.apache.commons.lang3.StringUtils;
50  import org.slf4j.Logger;
51  import org.slf4j.LoggerFactory;
52  
53  import com.google.common.collect.Sets;
54  import com.vaadin.v7.data.Property;
55  import com.vaadin.v7.data.util.ObjectProperty;
56  
57  /**
58   * Default Property Utility Class.
59   *
60   * Allows the creation of custom Value Object.
61   */
62  @Deprecated
63  public class DefaultPropertyUtil {
64  
65      private static final Logger log = LoggerFactory.getLogger(DefaultPropertyUtil.class);
66  
67      /**
68       * Create a default Vaadin Property and set the value after conversion.
69       */
70      public static <T> Property<T> newProperty(String value, Class<T> type) {
71          Object typedValue = null;
72          try {
73              typedValue = createTypedValue(type, value);
74          } catch (Exception e) {
75              log.error("Exception during Value creation", e);
76          }
77          return new ObjectProperty<>((T) typedValue, type);
78      }
79  
80      /**
81       * Create a DefaultProperty and set the defaultValue after conversion.
82       *
83       * @deprecated since 5.4.12, use {@link #newProperty(String, Class)} instead
84       */
85      @Deprecated
86      public static <T> DefaultProperty<T> newDefaultProperty(Class<T> type, String defaultValue) {
87          Object value = null;
88          try {
89              value = createTypedValue(type, defaultValue);
90          } catch (Exception e) {
91              log.error("Exception during Value creation", e);
92          }
93          return new DefaultProperty<>(type, (T) value);
94      }
95  
96      /**
97       * Create a new DefaultProperty by passing the value as a String.
98       * If fieldType is defined, create a Typed Value.
99       * If fieldType is not defined, create a String Value.
100      * If stringValue is defined, create a typed value based on fieldType.
101      *
102      * @deprecated since 5.1. use {@link DefaultPropertyUtil#newDefaultProperty(Class, String)} instead.
103      */
104     @Deprecated
105     public static DefaultProperty newDefaultProperty(String fieldType, String stringValue) throws NumberFormatException {
106         Object value = null;
107         try {
108             value = createTypedValue(fieldType, stringValue);
109         } catch (Exception e) {
110             log.error("Exception during Value creation", e);
111         }
112         return new DefaultProperty(getFieldTypeClass(fieldType), value);
113     }
114 
115     /**
116      * Create a DefaultProperty based on types defined in {@link PropertyType}.
117      *
118      * @deprecated since 5.1. use {@link DefaultPropertyUtil#newDefaultProperty(Class, String)} instead.
119      */
120     @Deprecated
121     public static DefaultProperty newDefaultProperty(int fieldType, Object value) throws NumberFormatException {
122         return new DefaultProperty(getFieldTypeClass(fieldType), value);
123     }
124 
125     /**
126      * Create a custom Field Object based on the Type and defaultValue.
127      * If the fieldType is null, the defaultValue will be returned as String or null.
128      * If the defaultValue is null, null will be returned.
129      *
130      * @throws NumberFormatException In case of the default value could not be parsed to the desired class.
131      * @deprecated since 5.1. use {@link DefaultPropertyUtil#createTypedValue(Class, String)} instead.
132      */
133     @Deprecated
134     public static Object createTypedValue(String fieldType, String defaultValue) throws NumberFormatException {
135         if (StringUtils.isBlank(fieldType)) {
136             return defaultValue;
137         } else if (defaultValue != null) {
138             Class<?> type = getFieldTypeClass(fieldType);
139             return createTypedValue(type, defaultValue);
140         }
141         return null;
142     }
143 
144     /**
145      * Create a custom Field Object based on the Type and defaultValue.
146      * If the fieldType is null, the defaultValue will be returned as String or null.
147      * If the defaultValue is null, null will be returned.
148      *
149      * @throws NumberFormatException In case of the default value could not be parsed to the desired class.
150      */
151     public static Object createTypedValue(Class<?> type, String defaultValue) throws NumberFormatException {
152         if (StringUtils.isBlank(defaultValue)) {
153             return defaultValue;
154         } else if (defaultValue != null) {
155             if (type.getName().equals(String.class.getName())) {
156                 return defaultValue;
157             } else if (type.getName().equals(Long.class.getName())) {
158                 return Long.decode(defaultValue);
159             } else if (type.isAssignableFrom(Binary.class)) {
160                 return null;
161             } else if (type.getName().equals(Double.class.getName())) {
162                 return Double.valueOf(defaultValue);
163             } else if (type.getName().equals(Date.class.getName())) {
164                 try {
165                     return new SimpleDateFormat(DateUtil.YYYY_MM_DD).parse(defaultValue);
166                 } catch (ParseException e) {
167                     throw new IllegalArgumentException(e);
168                 }
169             } else if (type.getName().equals(Boolean.class.getName())) {
170                 return BooleanUtils.toBoolean(defaultValue);
171             } else if (type.getName().equals(BigDecimal.class.getName())) {
172                 return BigDecimal.valueOf(Long.decode(defaultValue));
173             } else if (type.isAssignableFrom(List.class)) {
174                 return Arrays.asList(defaultValue.split(","));
175             } else {
176                 throw new IllegalArgumentException("Unsupported property type " + type.getName());
177             }
178         }
179         return null;
180     }
181 
182     /**
183      * DefaultPropertyUtil mainly provides string-based conversion to JCR common property types.
184      * In some cases, client may want to know in advance if this will apply to a given type, to implement alternative
185      * strategies of creating/parsing property values.
186      *
187      * @see #createTypedValue(Class, String)
188      */
189     public static boolean canConvertStringValue(Class<?> type) {
190         // basically mirroring conditions in impl above (as fishy as it is)
191         if (type.getName().equals(String.class.getName())
192                 || type.getName().equals(Long.class.getName())
193                 || type.isAssignableFrom(Binary.class)
194                 || type.getName().equals(Double.class.getName())
195                 || type.getName().equals(Date.class.getName())
196                 || type.getName().equals(Boolean.class.getName())
197                 || type.getName().equals(BigDecimal.class.getName())
198                 || type.isAssignableFrom(List.class)) {
199             return true;
200         }
201         return false;
202     }
203 
204     public static boolean isKnownJcrTypeName(String typeName) {
205         return Sets.newHashSet(
206                 PropertyType.TYPENAME_STRING,
207                 PropertyType.TYPENAME_BINARY,
208                 PropertyType.TYPENAME_LONG,
209                 PropertyType.TYPENAME_DOUBLE,
210                 PropertyType.TYPENAME_DATE,
211                 PropertyType.TYPENAME_BOOLEAN,
212                 PropertyType.TYPENAME_DECIMAL
213         ).contains(typeName);
214     }
215 
216     /**
217      * Return the related Class for a desired Type by String. Using {@link PropertyType} to read the type from the String.
218      * If no fieldType is defined, the default is String.
219      *
220      * @throws IllegalArgumentException if the Type is not supported.
221      */
222     public static Class<?> getFieldTypeClass(String fieldType) {
223         if (StringUtils.isNotEmpty(fieldType)) {
224             int valueType = PropertyType.valueFromName(fieldType);
225             return getFieldTypeClass(valueType);
226         } else {
227             return String.class;
228         }
229     }
230 
231     /**
232      * Return the related Class for a desired Type.
233      * If no fieldType is defined, the default is String.
234      *
235      * @throws IllegalArgumentException if the Type is not supported.
236      */
237     public static Class<?> getFieldTypeClass(int fieldType) {
238         if (fieldType > 0) {
239             switch (fieldType) {
240             case PropertyType.STRING:
241                 return String.class;
242             case PropertyType.BINARY:
243                 return Binary.class;
244             case PropertyType.LONG:
245                 return Long.class;
246             case PropertyType.DOUBLE:
247                 return Double.class;
248             case PropertyType.DATE:
249                 // we use Date here instead of Calendar simply because the vaadin DateField uses Date not Calendar
250                 return Date.class;
251             case PropertyType.BOOLEAN:
252                 return Boolean.class;
253             case PropertyType.DECIMAL:
254                 return BigDecimal.class;
255             default:
256                 throw new IllegalArgumentException("Unsupported property type " + PropertyType.nameFromValue(fieldType));
257             }
258         } else {
259             return String.class;
260         }
261     }
262 }