View Javadoc
1   /**
2    * This file Copyright (c) 2003-2015 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.importexport;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.HierarchyManager;
38  import info.magnolia.cms.core.ItemType;
39  import info.magnolia.cms.core.NodeData;
40  import info.magnolia.cms.util.ContentUtil;
41  import info.magnolia.cms.util.OrderedProperties;
42  import org.apache.commons.beanutils.ConvertUtils;
43  import org.apache.commons.lang.StringUtils;
44  import org.apache.jackrabbit.util.ISO8601;
45  
46  import javax.jcr.PropertyType;
47  import javax.jcr.RepositoryException;
48  import javax.jcr.Value;
49  
50  import java.io.ByteArrayInputStream;
51  import java.io.IOException;
52  import java.io.InputStream;
53  import java.util.Calendar;
54  import java.util.Collection;
55  import java.util.Properties;
56  import java.util.Set;
57  
58  /**
59   * Utility class providing support for properties-like format to import/export jcr data. Useful when
60   * data regularly needs to be bootstrapped, for instance, and the jcr xml format is too cumbersome to maintain.
61   *
62   * TODO : handle conflicts (already existing nodes, properties, what to do with existing properties if we don't create new nodes, ...)
63   * TODO : consolidate syntax
64   *
65   * @deprecated since 5.2.2 - use {@link info.magnolia.jcr.util.PropertiesImportExport}.
66   */
67  public class PropertiesImportExport {
68  
69      public void createContent(Content root, InputStream propertiesStream) throws IOException, RepositoryException {
70          Properties properties = new OrderedProperties();
71  
72          properties.load(propertiesStream);
73  
74          properties = keysToInnerFormat(properties);
75  
76          for (Object o : properties.keySet()) {
77              String key = (String) o;
78              String valueStr = properties.getProperty(key);
79  
80              String propertyName = StringUtils.substringAfterLast(key, ".");
81              String path = StringUtils.substringBeforeLast(key, ".");
82  
83              String type = null;
84              if (propertyName.equals("@type")) {
85                  type = valueStr;
86              } else if (properties.containsKey(path + ".@type")) {
87                  type = properties.getProperty(path + ".@type");
88              }
89  
90              type = StringUtils.defaultIfEmpty(type, ItemType.CONTENTNODE.getSystemName());
91              Content c = ContentUtil.createPath(root, path, new ItemType(type));
92              populateContent(c, propertyName, valueStr);
93          }
94      }
95  
96      /**
97       * Transforms the keys to the following inner notation: <code>some/path/node.prop</code> or <code>some/path/node.@type</code>.
98       */
99      private Properties keysToInnerFormat(Properties properties) {
100         Properties cleaned = new OrderedProperties();
101 
102         for (Object o : properties.keySet()) {
103             String orgKey = (String) o;
104 
105             //if this is a node definition (no property)
106             String newKey = orgKey;
107 
108             // make sure we have a dot as a property separator
109             newKey = StringUtils.replace(newKey, "@", ".@");
110             // avoid double dots
111             newKey = StringUtils.replace(newKey, "..@", ".@");
112 
113             String propertyName = StringUtils.substringAfterLast(newKey, ".");
114             String keySuffix = StringUtils.substringBeforeLast(newKey, ".");
115             String path = StringUtils.replace(keySuffix, ".", "/");
116             path = StringUtils.removeStart(path, "/");
117 
118             // if this is a path (no property)
119             if (StringUtils.isEmpty(propertyName)){
120                 // no value --> is a node
121                 if(StringUtils.isEmpty(properties.getProperty(orgKey))) {
122                     // make this the type property if not defined otherwise
123                     if(!properties.containsKey(orgKey + "@type")){
124                         cleaned.put(path + ".@type", ItemType.CONTENTNODE.getSystemName());
125                     }
126                     continue;
127                 }
128                 propertyName = StringUtils.substringAfterLast(path, "/");
129                 path = StringUtils.substringBeforeLast(path, "/");
130             }
131             cleaned.put(path + "." + propertyName, properties.get(orgKey));
132         }
133         return cleaned;
134     }
135 
136     protected void populateContent(Content c, String name, String valueStr) throws RepositoryException {
137         if (StringUtils.isEmpty(name) && StringUtils.isEmpty(valueStr)) {
138             // happens if the input properties file just created a node with no properties
139             return;
140         }
141         if (name.equals("@type")) {
142             // do nothing, this has been taken into account when creating the node.
143         } else if (name.equals("@uuid")) {
144             throw new UnsupportedOperationException("Can't see UUIDs on real node. Use MockUtil if you are using MockContent instances.");
145         } else {
146             Object valueObj = convertNodeDataStringToObject(valueStr);
147             c.setNodeData(name, valueObj);
148         }
149     }
150 
151     protected Object convertNodeDataStringToObject(String valueStr) {
152         if (contains(valueStr, ':')) {
153             final String type = StringUtils.substringBefore(valueStr, ":");
154             final String value = StringUtils.substringAfter(valueStr, ":");
155 
156             // there is no beanUtils converter for Calendar
157             if (type.equalsIgnoreCase("date")) {
158                 return ISO8601.parse(value);
159             } else if (type.equalsIgnoreCase("binary")) {
160                 return new ByteArrayInputStream(value.getBytes());
161             } else {
162                 try {
163                     final Class<?> typeCl;
164                     if (type.equals("int")) {
165                         typeCl = Integer.class;
166                     } else {
167                         typeCl = Class.forName("java.lang." + StringUtils.capitalize(type));
168                     }
169                     return ConvertUtils.convert(value, typeCl);
170                 } catch (ClassNotFoundException e) {
171                     // possibly a stray :, let's ignore it for now
172                     return valueStr;
173                 }
174             }
175         }
176         // no type specified, we assume it's a string, no conversion
177         return valueStr;
178     }
179 
180     /**
181      * This method is deprecated, it returns results in a format that does not match
182      * the format that the import method uses (doesn't include @uuid or @type properties)
183      *
184      * It is kept here to support existing test and applications that might break
185      * as a result of these changes (i.e. unit tests that are expecting a specific number of
186      * properties returned, etc)
187      *
188      * @deprecated since 4.3 - use {@link info.magnolia.jcr.util.PropertiesImportExport#toProperties(javax.jcr.Node, info.magnolia.jcr.predicate.AbstractPredicate)}
189      */
190     @Deprecated
191     public static Properties toProperties(HierarchyManager hm) throws Exception {
192         return toProperties(hm.getRoot());
193     }
194 
195     /**
196      * @deprecated since 5.0 - use {@link info.magnolia.jcr.util.PropertiesImportExport#toProperties(javax.jcr.Node, info.magnolia.jcr.predicate.AbstractPredicate)}
197      */
198     public static Properties toProperties(Content rootContent) throws Exception {
199         return toProperties(rootContent, ContentUtil.EXCLUDE_META_DATA_CONTENT_FILTER, true);
200     }
201 
202     /**
203      * @deprecated since 5.0 - use {@link info.magnolia.jcr.util.PropertiesImportExport#toProperties(javax.jcr.Node, info.magnolia.jcr.predicate.AbstractPredicate)}
204      */
205     public static Properties contentToProperties(HierarchyManager hm) throws Exception {
206         return contentToProperties(hm.getRoot());
207     }
208 
209     /**
210      * @deprecated since 5.0 - use {@link info.magnolia.jcr.util.PropertiesImportExport#toProperties(javax.jcr.Node, info.magnolia.jcr.predicate.AbstractPredicate)}
211      */
212     public static Properties contentToProperties(Content rootContent) throws Exception {
213         return toProperties(rootContent, ContentUtil.EXCLUDE_META_DATA_CONTENT_FILTER, false);
214     }
215 
216     /**
217      * @deprecated since 5.0 - use {@link info.magnolia.jcr.util.PropertiesImportExport#toProperties(javax.jcr.Node, info.magnolia.jcr.predicate.AbstractPredicate)}
218      */
219     public static Properties contentToProperties(Content rootContent, Content.ContentFilter filter) throws Exception {
220         return toProperties(rootContent, filter, false);
221     }
222 
223     /**
224      * This method is private because it includes the boolean "legacymode" filter which
225      * shouldn't be exposed as part of the API because when "legacymode" is removed, it will
226      * force an API change.
227      *
228      * @param rootContent root node to convert into properties
229      * @param contentFilter a content filter to use in selecting what content to export
230      * @param legacyMode if true, will not include @uuid and @type nodes
231      * @return a Properties object representing the content starting at rootContent
232      *
233      * @deprecated since 5.0 - use {@link info.magnolia.jcr.util.PropertiesImportExport#toProperties(javax.jcr.Node, info.magnolia.jcr.predicate.AbstractPredicate)}
234      */
235     private static Properties toProperties(Content rootContent, Content.ContentFilter contentFilter, final boolean legacyMode) throws Exception {
236         final Properties out = new OrderedProperties();
237         ContentUtil.visit(rootContent, new ContentUtil.Visitor() {
238             @Override
239             public void visit(Content node) throws Exception {
240                 if (!legacyMode) {
241                     appendNodeTypeAndUUID(node, out, true);
242                 }
243                 appendNodeProperties(node, out);
244             }
245         }, contentFilter);
246         return out;
247     }
248 
249     private static void appendNodeTypeAndUUID(Content node, Properties out, final boolean dumpMetaData) throws RepositoryException {
250         String path = getExportPath(node);
251         // we don't need to export the JCR root node.
252         if (path.equals("/jcr:root")) {
253             return;
254         }
255 
256         String nodeTypeName = node.getNodeTypeName();
257         if (nodeTypeName != null && StringUtils.isNotEmpty(nodeTypeName)) {
258             out.put(path + "@type", nodeTypeName);
259         }
260         String nodeUUID = node.getUUID();
261         if (nodeUUID != null && StringUtils.isNotEmpty(nodeUUID)) {
262             out.put(path + "@uuid", node.getUUID());
263         }
264     }
265 
266     public static void appendNodeProperties(Content node, Properties out) {
267         final Collection<NodeData> props = node.getNodeDataCollection();
268         for (NodeData prop : props) {
269             final String path = getExportPath(node) + "." + prop.getName();
270 
271             String propertyValue = getPropertyString(prop);
272 
273             if (propertyValue != null) {
274                 out.setProperty(path, propertyValue);
275             }
276         }
277     }
278 
279     private static String getExportPath(Content node) {
280         return node.getHandle();
281     }
282 
283     private static String getPropertyString(NodeData prop) {
284         int propType = prop.getType();
285 
286         switch (propType) {
287         case (PropertyType.STRING): {
288             return prop.getString();
289         }
290         case (PropertyType.BOOLEAN): {
291             return convertBooleanToExportString(prop.getBoolean());
292         }
293         case (PropertyType.BINARY): {
294             return convertBinaryToExportString(prop.getValue());
295         }
296         case (PropertyType.PATH): {
297             return prop.getString();
298         }
299         case (PropertyType.DATE): {
300             return convertCalendarToExportString(prop.getDate());
301         }
302         case (PropertyType.LONG): {
303             return "" + prop.getLong();
304         }
305         case (PropertyType.DOUBLE): {
306             return "" + prop.getDouble();
307         }
308         default: {
309             return prop.getString();
310         }
311         }
312     }
313 
314     private static String convertBooleanToExportString(boolean b) {
315         return "boolean:" + (b ? "true" : "false");
316     }
317 
318     private static String convertBinaryToExportString(Value value) {
319         return "binary:" + ConvertUtils.convert(value);
320     }
321 
322     private static String convertCalendarToExportString(Calendar calendar) {
323         return "date:" + ISO8601.format(calendar);
324     }
325 
326     /**
327      * Dumps content starting at the content node out to a string in the format that matches the
328      * import method.
329      */
330     public static String dumpPropertiesToString(Content content, Content.ContentFilter filter) throws Exception {
331         Properties properties = PropertiesImportExport.contentToProperties(content, filter);
332         return dumpPropertiesToString(properties);
333     }
334 
335     public static String dumpPropertiesToString(Properties properties) {
336         final StringBuilder sb = new StringBuilder();
337         final Set<Object> propertyNames = properties.keySet();
338         for (Object propertyKey : propertyNames) {
339             final String name = propertyKey.toString();
340             final String value = properties.getProperty(name);
341             sb.append(name);
342             sb.append("=");
343             sb.append(value);
344             sb.append("\n");
345         }
346         return sb.toString();
347     }
348 
349     private static boolean contains(String s, char ch) {
350         return s.indexOf(ch) > -1;
351     }
352 }