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.importexport.postprocessors;
35  
36  import info.magnolia.cms.core.MetaData;
37  import info.magnolia.jcr.util.NodeTypes;
38  import info.magnolia.jcr.util.NodeUtil;
39  
40  import java.util.ArrayList;
41  import java.util.HashMap;
42  import java.util.HashSet;
43  import java.util.Map;
44  import java.util.Set;
45  
46  import javax.jcr.Node;
47  import javax.jcr.NodeIterator;
48  import javax.jcr.Property;
49  import javax.jcr.PropertyIterator;
50  import javax.jcr.RepositoryException;
51  
52  import org.slf4j.Logger;
53  import org.slf4j.LoggerFactory;
54  
55  /**
56   * Converts the MetaData sub node into properties on the mixins <code>mgnl:created</code>,
57   * <code>mgnl:lastModified</code>, <code>mgnl:renderable</code>, <code>mgnl:activatable</code> and
58   * <code>mgnl:activatable</code>. It also renames the property <code>mgnl:deletedOn</code> property on the mixin
59   * <code>mgnl:deleted</code> to <code>mgnl:deleted</code>. The MetaData node itself is optionally removed if there are
60   * no additional properties on it.
61   */
62  public class MetaDataAsMixinConversionHelper {
63  
64      private static final int PERIODIC_SAVE_FREQUENCY = 20;
65      private static final String DEPRECATED_DELETION_DATE_PROPERTY_NAME = "mgnl:deletedOn";
66  
67      private final Logger logger = LoggerFactory.getLogger(MetaDataAsMixinConversionHelper.class);
68  
69      private final HashMap<String, String> propertyNameMapping = new HashMap<String, String>();
70  
71      /**
72       * Names of properties that we expect to see in MetaData after conversion.
73       */
74      private final Set<String> propertyNamesExpectedInMetaDataAfterConversion = new HashSet<String>();
75  
76      private boolean deleteMetaDataIfEmptied = false;
77      private boolean periodicSaves = false;
78  
79      public MetaDataAsMixinConversionHelper() {
80          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.CREATION_DATE, NodeTypes.Created.CREATED);
81          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.LAST_ACTION, NodeTypes.Activatable.LAST_ACTIVATED);
82          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.ACTIVATOR_ID, NodeTypes.Activatable.LAST_ACTIVATED_BY);
83          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.ACTIVATED, NodeTypes.Activatable.ACTIVATION_STATUS);
84          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.TEMPLATE, NodeTypes.Renderable.TEMPLATE);
85          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.LAST_MODIFIED, NodeTypes.LastModified.LAST_MODIFIED);
86          propertyNameMapping.put(NodeTypes.MGNL_PREFIX + MetaData.AUTHOR_ID, NodeTypes.LastModified.LAST_MODIFIED_BY);
87          propertyNameMapping.put("mgnl:comment", NodeTypes.Versionable.COMMENT);
88  
89          // We're not transferring mgnl:title and mgnl:templatetype so we'll expect those to still be present
90          propertyNamesExpectedInMetaDataAfterConversion.add(NodeTypes.MGNL_PREFIX + MetaData.TITLE);
91          propertyNamesExpectedInMetaDataAfterConversion.add(NodeTypes.MGNL_PREFIX + MetaData.TEMPLATE_TYPE);
92  
93          // Since we don't transfer a property if it already exists on the content node we need to expect all of those
94          // we transfer to still be present afterwards
95          propertyNamesExpectedInMetaDataAfterConversion.addAll(propertyNameMapping.keySet());
96      }
97  
98      public boolean isDeleteMetaDataIfEmptied() {
99          return deleteMetaDataIfEmptied;
100     }
101 
102     public void setDeleteMetaDataIfEmptied(boolean deleteMetaDataIfEmptied) {
103         this.deleteMetaDataIfEmptied = deleteMetaDataIfEmptied;
104     }
105 
106     public boolean isPeriodicSaves() {
107         return periodicSaves;
108     }
109 
110     /**
111      * Sets whether to save periodically as the sub tree is converted. This reduces the amount of memory required.
112      */
113     public void setPeriodicSaves(boolean periodicSaves) {
114         this.periodicSaves = periodicSaves;
115     }
116 
117     public void convertNodeAndChildren(Node startNode) throws RepositoryException {
118 
119         int nodesProcessed = 0;
120         ArrayList<Node> nodes = new ArrayList<Node>();
121         nodes.add(startNode);
122 
123         while (!nodes.isEmpty()) {
124             // Take the most recently added node creating a depth-first scan because it has smaller memory footprint
125             // than a breadth-first scan.
126             Node node = nodes.remove(nodes.size() - 1);
127 
128             processNode(node);
129 
130             // Save the session every x nodes if period saves is enabled
131             nodesProcessed++;
132             if (periodicSaves && nodesProcessed % PERIODIC_SAVE_FREQUENCY == 0) {
133                 node.getSession().save();
134             }
135 
136             // Queue child nodes
137             NodeIterator children = node.getNodes();
138             while (children.hasNext()) {
139                 Node child = children.nextNode();
140                 if (!(child.getName().equals(MetaData.DEFAULT_META_NODE) && NodeUtil.isNodeType(child, NodeTypes.MetaData.NAME))) {
141                     nodes.add(child);
142                 }
143             }
144         }
145     }
146 
147     private void processNode(Node node) throws RepositoryException {
148 
149         // Rename mgnl:deletedOn to mgnl:deleted for mixin mgnl:deleted
150         if (node.hasProperty(DEPRECATED_DELETION_DATE_PROPERTY_NAME)) {
151             moveProperty(node, DEPRECATED_DELETION_DATE_PROPERTY_NAME, node, NodeTypes.Deleted.DELETED);
152         }
153 
154         // Transfer properties from the MetaData node
155         if (node.hasNode(MetaData.DEFAULT_META_NODE)) {
156             Node metaDataNode = node.getNode(MetaData.DEFAULT_META_NODE);
157             if (NodeUtil.isNodeType(metaDataNode, NodeTypes.MetaData.NAME)) {
158                 moveProperties(node, metaDataNode, propertyNameMapping);
159 
160                 if (deleteMetaDataIfEmptied && isEmptyMetaDataNode(metaDataNode)) {
161                     metaDataNode.remove();
162                 }
163             }
164         }
165     }
166 
167     /**
168      * Returns true if the MetaData node is considered empty, i.e. has no sub nodes and no unexpected properties.
169      */
170     private boolean isEmptyMetaDataNode(Node node) throws RepositoryException {
171         if (node.getNodes().getSize() != 0) {
172             logger.warn("MetaData node not removed because it has sub nodes {}", node.getPath());
173             return false;
174         }
175         PropertyIterator iterator = node.getProperties();
176         while (iterator.hasNext()) {
177             Property property = iterator.nextProperty();
178             if (!isExpectedMetaDataProperty(property)) {
179                 logger.warn("MetaData node not removed because of unrecognized property: {}", property.getPath());
180                 return false;
181             }
182         }
183         return true;
184     }
185 
186     /**
187      * Returns true if the property is expected to be found on the MetaData node after conversion.
188      */
189     private boolean isExpectedMetaDataProperty(Property property) throws RepositoryException {
190         String propertyName = property.getName();
191 
192         // We expect there to be standard JCR properties like jcr:createdBy etc
193         if (propertyName.startsWith("jcr:")) {
194             return true;
195         }
196 
197         // Legacy property deprecated in Magnolia 3.0
198         if (propertyName.equals(NodeTypes.MGNL_PREFIX + "Data") && property.getString().equals("MetaData")) {
199             return true;
200         }
201 
202         return propertyNamesExpectedInMetaDataAfterConversion.contains(propertyName);
203     }
204 
205     /**
206      * Moves a set of properties from one node to another changing their names in the process.
207      *
208      * @param dstNode node to move properties to
209      * @param srcNode node to move properties from
210      * @param nameMappings maps current property names to their new names
211      */
212     private void moveProperties(Node dstNode, Node srcNode, Map<String, String> nameMappings) throws RepositoryException {
213         for (Map.Entry<String, String> entry : nameMappings.entrySet()) {
214             String srcPropertyName = entry.getKey();
215             String dstPropertyName = entry.getValue();
216             if (!dstNode.hasProperty(dstPropertyName) && srcNode.hasProperty(srcPropertyName)) {
217                 moveProperty(srcNode, srcPropertyName, dstNode, dstPropertyName);
218             }
219         }
220     }
221 
222     /**
223      * Moves a property from a node to another node and changes its name in the process. If a property already exists on
224      * the destination node it will be overwritten.
225      *
226      * @param srcNode node containing the property
227      * @param srcPropertyName name of the property
228      * @param dstNode node to which the property should be moved
229      * @param dstPropertyName new name after the move
230      * @throws javax.jcr.PathNotFoundException if the source property does not exist
231      */
232     private void moveProperty(Node srcNode, String srcPropertyName, Node dstNode, String dstPropertyName) throws RepositoryException {
233         Property srcProperty = srcNode.getProperty(srcPropertyName);
234         if (srcProperty.isMultiple()) {
235             dstNode.setProperty(dstPropertyName, srcProperty.getValues());
236         } else {
237             dstNode.setProperty(dstPropertyName, srcProperty.getValue());
238         }
239         srcProperty.remove();
240     }
241 }