View Javadoc
1   /**
2    * This file Copyright (c) 2016-2017 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.setup;
35  
36  import info.magnolia.cms.core.version.VersionManager;
37  import info.magnolia.jcr.util.NodeTypes;
38  import info.magnolia.jcr.util.NodeUtil;
39  import info.magnolia.module.InstallContext;
40  import info.magnolia.module.delta.AbstractRepositoryTask;
41  import info.magnolia.module.delta.TaskExecutionException;
42  import info.magnolia.repository.RepositoryConstants;
43  import info.magnolia.repository.RepositoryManager;
44  
45  import java.util.Collections;
46  import java.util.HashMap;
47  import java.util.List;
48  import java.util.Map;
49  import java.util.stream.Collectors;
50  
51  import javax.jcr.ItemNotFoundException;
52  import javax.jcr.Node;
53  import javax.jcr.RepositoryException;
54  import javax.jcr.Session;
55  
56  import org.apache.commons.lang3.StringUtils;
57  import org.slf4j.Logger;
58  import org.slf4j.LoggerFactory;
59  
60  /**
61   * Migrates version store to the new structure.
62   * <p>New structure is generated from node's uuid, level 1 node - first two letters from the first part, level 2 node - two letters from the second part and level 3 node - two letters from third part.</p>
63   * <p>It might happen that versions are corrupted (when multiple nodes have same uuid across different workspaces), in that case we resolve new structure from the node where
64   * primary node type matches the versioned node node type, we also log warning so users can fix the problem.</p>
65   */
66  public class MigrateVersionWorkspacesToNewStructureTask extends AbstractRepositoryTask {
67  
68      private static final Logger log = LoggerFactory.getLogger(MigrateVersionWorkspacesToNewStructureTask.class);
69  
70      private static final String FOUND_IN_MULTIPLE_WORKSPACES_MESSAGE = "Node [%s:%s:%s] found in multiple workspaces [%s]. This means that versions for both nodes are most likely broken and versions needs to be removed.";
71      private static final String ORIGINAL_NODE_NOT_FOUND_MESSAGE = "Version found for node [%s:%s:%s], but original node no longer exists";
72  
73      private final RepositoryManager repositoryManager;
74  
75      private Map<String, Session> sessions = new HashMap<>();
76  
77      public MigrateVersionWorkspacesToNewStructureTask(RepositoryManager repositoryManager) {
78          super("Migrate version workspace", "Migrate version workspace to new structure");
79          this.repositoryManager = repositoryManager;
80      }
81  
82      @Override
83      protected void doExecute(InstallContext installContext) throws RepositoryException, TaskExecutionException {
84          List<String> versionWorkspaces = repositoryManager.getWorkspaceNames().stream().filter(input -> StringUtils.endsWith(input, RepositoryConstants.VERSION_STORE)).collect(Collectors.toList());
85          // remove system and version workspaces
86          List<String> workspacesToSearchIn = repositoryManager.getWorkspaceNames().stream().filter(input -> !(StringUtils.endsWith(input, RepositoryConstants.VERSION_STORE) || StringUtils.endsWith(input, RepositoryConstants.SYSTEM))).collect(Collectors.toList());
87          // reorder workspaces to have most important ones in the beginning
88          Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf(RepositoryConstants.WEBSITE), 0);
89          if (workspacesToSearchIn.contains("dam")) {
90              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("dam"), 1);
91          }
92          if (workspacesToSearchIn.contains("contacts")) {
93              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("contacts"), 2);
94          }
95          if (workspacesToSearchIn.contains("segments")) {
96              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("segments"), 3);
97          }
98          if (workspacesToSearchIn.contains("personas")) {
99              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("personas"), 4);
100         }
101         // go through each version workspace and try to find original node for each version node
102         for (String versionWorkspace : versionWorkspaces) {
103             Session versionSession = installContext.getJCRSession(versionWorkspace);
104             for (Node versionNode : NodeUtil.getNodes(versionSession.getRootNode())) {
105                 if (versionNode.getName().equals(VersionManager.TMP_REFERENCED_NODES) || StringUtils.startsWith(versionNode.getName(), NodeTypes.REP_PREFIX)) {
106                     continue;
107                 }
108                 String uuid = versionNode.getIdentifier();
109 
110                 Map<String, Node> found = new HashMap<>();
111                 Node originalNode = null;
112                 for (String workspace : workspacesToSearchIn) {
113                     if (!sessions.containsKey(workspace)) {
114                         sessions.put(workspace, installContext.getJCRSession(workspace));
115                     }
116                     try {
117                         Node node = sessions.get(workspace).getNodeByIdentifier(uuid);
118                         if (node.getPrimaryNodeType().getName().equals(versionNode.getPrimaryNodeType().getName())) {
119                             originalNode = node;
120                         }
121                         found.put(workspace, node);
122                     } catch (ItemNotFoundException e) {
123                         // ignore - node was just not found
124                     }
125                 }
126 
127                 if (found.size() == 0 || originalNode == null) {
128                     // warn if original node was not found
129                     installContext.warn(String.format(ORIGINAL_NODE_NOT_FOUND_MESSAGE, versionNode.getName(), versionNode.getIdentifier(), versionNode.getPrimaryNodeType().getName()));
130                     continue;
131                 } else if (found.size() > 1) {
132                     // if found in multiple workspaces, warn user that they will have probably broken versions and will need to fix them
133                     installContext.warn(String.format(FOUND_IN_MULTIPLE_WORKSPACES_MESSAGE, versionNode.getName(), versionNode.getIdentifier(), versionNode.getPrimaryNodeType().getName(), StringUtils.join(found, ":")));
134                 }
135 
136                 // finally move node to its new location
137                 Node newParent = NodeUtil.createPath(versionSession.getRootNode(), getSavePath(originalNode), NodeTypes.Folder.NAME, true);
138                 NodeUtil.moveNode(versionNode, newParent);
139                 originalNode.addMixin(NodeTypes.HasVersion.NAME);
140                 log.debug("Moved [{}] to the new location [{}]", newParent.getPath() + "/" + versionNode.getName());
141             }
142         }
143     }
144 
145     String getSavePath(Node node) throws RepositoryException {
146         String uuid = node.getIdentifier();
147         return String.format("%s/%s/%s", StringUtils.substring(uuid, 0, 2), StringUtils.substring(uuid, 9, 11), StringUtils.substring(uuid, 14, 16));
148     }
149 }