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.dam.app.setup.migration;
35  
36  import info.magnolia.dam.api.ItemKey;
37  import info.magnolia.dam.jcr.DamConstants;
38  import info.magnolia.jcr.wrapper.StringPropertyValueFilteringNodeWrapper;
39  import info.magnolia.module.InstallContext;
40  import info.magnolia.module.delta.TaskExecutionException;
41  
42  import java.util.List;
43  
44  import javax.jcr.ItemNotFoundException;
45  import javax.jcr.Node;
46  import javax.jcr.NodeIterator;
47  import javax.jcr.Property;
48  import javax.jcr.PropertyIterator;
49  import javax.jcr.RepositoryException;
50  import javax.jcr.Session;
51  import javax.jcr.query.QueryResult;
52  
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  /**
57   * This task is responsible for changing the old DMS/Data/... references to DAM
58   * references.<br>
59   * Steps:<br>
60   * 
61   * <pre>
62   * Iterate the list of contentPathsList,
63   *  Perform a JCR query that search for properties containing 'dms' and return the related node.
64   *  Iterate the query result list
65   *  For every Node,
66   *   Node has also a related property index+DmsUUID (like imageDmsUUID)
67   *    Copy the value of the index+DmsUUID (imageDmsUUID) property into index (image)
68   *    Remove the index+DmsUUID (imageDmsUUID) property.
69   *    Check existence of the UUID: UUID not found in DAM
70   *     Remove the index property
71   *   No related property index+DmsUUID (like imageDmsUUID) found
72   *   Remove the index property.
73   * </pre>
74   * 
75   * <pre>
76   * <b>Normal handling</b>:
77   * Move from:
78   *  property sv:name="image" sv:type="String"
79   *  value = dms
80   *  property sv:name="imageDmsUUID" sv:type="String"
81   *  value = 4c291aa5-9807-4bbe-b372-ce523f82e600
82   * To:
83   *  property sv:name="image" sv:type="String"
84   *  value = jcr:4c291aa5-9807-4bbe-b372-ce523f82e600
85   * 
86   * <b>Specific handling</b>:
87   *  In case of the UUID does not exist any more, remove properties.
88   *  In case of the property imageDMSUUID does not exist, remove properties.
89   * </pre>
90   **/
91  public class ChangeWebsiteDmsReferenceToDamMigrationTask extends AbstractPropertyValueSearchDamMigrationTask {
92  
93      private static final Logger log = LoggerFactory.getLogger(ChangeWebsiteDmsReferenceToDamMigrationTask.class);
94  
95      private List<String> contentPathsList;
96      private String contentRepository;
97      private Session contentSession;
98      private Session damSession;
99      private String propertySuffix = "DmsUUID";
100 
101     /**
102      * Default constructor.
103      */
104     public ChangeWebsiteDmsReferenceToDamMigrationTask(String taskName, String taskDescription, String contentRepository, List<String> contentPathsList) {
105         super(taskName, taskDescription, "dms");
106         this.contentPathsList = contentPathsList;
107         this.contentRepository = contentRepository;
108     }
109 
110     @Override
111     public void doExecute(InstallContext ctx) throws TaskExecutionException {
112         log.info("Start to update DATA reference to DAM for the following repository ");
113         try {
114             // Init
115             contentSession = ctx.getJCRSession(contentRepository);
116             damSession = ctx.getJCRSession(DamConstants.WORKSPACE);
117             for (String path : this.contentPathsList) {
118                 if (!contentSession.nodeExists(path)) {
119                     log.warn("'{}' path do not exist for the following repository: '{}' No Data migration will be performed ", path, contentRepository);
120                     continue;
121                 }
122                 // Handle path
123                 handlePath(path);
124             }
125         } catch (Exception e) {
126             log.error("Unable to execute update of DATA reference to DAM", e);
127             ctx.error("Unable to perform Migration task " + getName(), e);
128             throw new TaskExecutionException(e.getMessage());
129         }
130         log.info("Successfully execute update of DATA reference to DAM for the following repository ");
131     }
132 
133     /**
134      * Perform the changing reference task on the passed path and sub path.
135      */
136     private void handlePath(String path) throws RepositoryException {
137         // Create Query
138         Node rootNode = contentSession.getNode(path);
139         if (rootNode.hasNodes()) {
140             String query = createQuery(path);
141             QueryResult result = executeQuery(query, contentSession);
142             if (result != null) {
143                 NodeIterator nodeIterator = result.getNodes();
144                 while (nodeIterator.hasNext()) {
145                     Node node = nodeIterator.nextNode();
146                     handleDamReferenceForNode(node);
147                 }
148             } else {
149                 log.info("No Node found for the following JCR-JQOM query '{}' against the following session '{}'", query, contentSession.getWorkspace().getName());
150             }
151         }
152         // due to https://issues.apache.org/jira/browse/JCR-2797 we have to
153         // check the root node
154         handleDamReferenceForNode(rootNode);
155     }
156 
157     /**
158      * Handle each filtered properties related to the found node.
159      */
160     private void handleDamReferenceForNode(Node node) throws RepositoryException {
161         Node wrappedNode = new StringPropertyValueFilteringNodeWrapper(node, getPropertyValue());
162         PropertyIterator propertyIterator = wrappedNode.getProperties();
163         while (propertyIterator.hasNext()) {
164             Property property = propertyIterator.nextProperty();
165             String propertyName = property.getName();
166             String propertyUUIDName = DamMigrationUtil.buildI18nSuffixPropertyName(propertyName, propertySuffix);
167             // Take Action
168             handleDamReferenceForProperty(node, property, propertyUUIDName);
169         }
170     }
171 
172 
173     /**
174      * Take action of the node property:
175      * Node has a property named: propertyUUIDName
176      * Copy the value of the propertyUUIDName property into propertyName
177      * Remove the propertyUUIDName property.
178      * Check existence of the UUID: UUID not found in DAM
179      * Remove the propertyName property
180      * No related property propertyUUIDName found in Node
181      * Remove the propertyName.
182      */
183     private void handleDamReferenceForProperty(Node node, Property property, String propertyUUIDName) throws RepositoryException {
184         if (node.hasProperty(propertyUUIDName)) {
185 
186             Property uuid = node.getProperty(propertyUUIDName);
187             String propertyName = property.getName();
188             property.setValue(new ItemKey(DamConstants.DEFAULT_JCR_PROVIDER_ID, uuid.getString()).asString());
189             if (!damNodeExist(uuid.getString())) {
190                 log.warn("The property '{}' will be removed from the following content node '{}'", propertyName, node.getPath());
191                 property.remove();
192             }
193             log.debug("Property was removed, '{}' changed to contain the following UUID link '{}'", propertyName, uuid.getString());
194             uuid.remove();
195 
196         } else {
197             log.warn("Following content should have an UUID link named:'{}' but don't have one. This property will be removed from the following content node '{}'", propertyUUIDName, node.getPath());
198             property.remove();
199         }
200     }
201 
202 
203     /**
204      * Utility method. Check if the identifier exist in the DAM repository.
205      */
206     private boolean damNodeExist(String identifier) {
207         try {
208             damSession.getNodeByIdentifier(identifier);
209             return true;
210         } catch (ItemNotFoundException infe) {
211             log.warn("Following identifier not found in the DAM workspace " + identifier);
212             return false;
213         } catch (RepositoryException re) {
214             log.warn("DamSession.getNodeByIdentifier(" + identifier + ") generated a RepositoryException.", re);
215             return false;
216         }
217     }
218 }