View Javadoc
1   /**
2    * This file Copyright (c) 2014-2016 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.for2_0;
35  
36  import info.magnolia.jcr.util.NodeTypes;
37  import info.magnolia.jcr.util.NodeUtil;
38  import info.magnolia.module.InstallContext;
39  import info.magnolia.module.delta.AbstractTask;
40  import info.magnolia.module.delta.TaskExecutionException;
41  
42  import java.util.ArrayList;
43  import java.util.Arrays;
44  import java.util.HashMap;
45  import java.util.Iterator;
46  import java.util.List;
47  import java.util.Map;
48  
49  import javax.jcr.Node;
50  import javax.jcr.RepositoryException;
51  import javax.jcr.Session;
52  
53  import org.apache.commons.lang3.StringUtils;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  import com.google.common.net.MediaType;
58  
59  /**
60   * Move and update the dam app configuration. <br>
61   * In Dam 1.x, the app configuration took place under the dam module. <br>
62   * With Dam 2.0, the app configuration is located under dam-app module. <br>
63   * In addition, Dam 2.0 introduce the {@link MediaType} instead of voters to link with media editor.
64   */
65  public class UpdateDamAppConfigurationTask extends AbstractTask {
66      private static final Logger log = LoggerFactory.getLogger(UpdateDamAppConfigurationTask.class);
67  
68      private final List<String> configNodeToMove = Arrays.asList("dialogs", "commands", "fieldTypes", "apps");
69      private final Map<String, MediaType> defaultMediaType;
70      private Session configSession;
71      private InstallContext ctx;
72  
73      public UpdateDamAppConfigurationTask(String taskName, String taskDescription) {
74          super(taskName, taskDescription);
75          defaultMediaType = new HashMap<String, MediaType>();
76          defaultMediaType.put("application.*(msword)", MediaType.MICROSOFT_WORD);
77          defaultMediaType.put("application.*(excel|xls)", MediaType.MICROSOFT_EXCEL);
78          defaultMediaType.put("application.*(powerpoint)", MediaType.MICROSOFT_POWERPOINT);
79      }
80  
81      @Override
82      public void execute(InstallContext installContext) throws TaskExecutionException {
83          try {
84              ctx = installContext;
85              configSession = ctx.getConfigJCRSession();
86              // check and create
87              ctx.getOrCreateCurrentModuleConfigNode();
88              // basic copy
89              moveNodes();
90              // move and update mediaType configuration
91              moveUpdateConfigNode();
92              // remove dam 1.x mediatype configuration
93          } catch (RepositoryException re) {
94              ctx.error("Could not update the dam-app configuration based on the previously installed dam version:", re);
95          }
96      }
97  
98      /**
99       * Copy all nodes path defined in 'configNodeToMove' from '/modules/dam/' to '/modules/dam-app/'.
100      */
101     private void moveNodes() throws RepositoryException {
102         for (String config : configNodeToMove) {
103             if (configSession.nodeExists("/modules/dam/" + config)) {
104                 configSession.move("/modules/dam/" + config, "/modules/dam-app/" + config);
105             }
106         }
107     }
108 
109     /**
110      * Transform the configuration from 1.x into a 2.0.<br>
111      * - move and rename the uploadConfig.
112      * - transform the voters into mediaType.
113      */
114     private void moveUpdateConfigNode() throws RepositoryException {
115         if (!configSession.nodeExists("/modules/dam/config/mediaTypes")) {
116             ctx.warn("dam module has no '/modules/dam/config/mediaTypes' configuration nodes. No migration will be performed");
117             return;
118         }
119         // Create
120         Node config = NodeUtil.createPath(configSession.getRootNode(), "modules/dam-app/config", NodeTypes.Content.NAME);
121         Node editAssetConfigurations = config.addNode("editAssetAppConfigurations", NodeTypes.ContentNode.NAME);
122         Node mediaTypes = configSession.getNode("/modules/dam/config/mediaTypes");
123         Iterator<Node> mediaTypesIterator = NodeUtil.getNodes(mediaTypes, NodeTypes.ContentNode.NAME).iterator();
124         while (mediaTypesIterator.hasNext()) {
125             convertMediaTypeToUploadConfig(editAssetConfigurations, mediaTypesIterator.next());
126         }
127         mediaTypes.remove();
128     }
129 
130     private void convertMediaTypeToUploadConfig(Node newParentRootNode, Node oldMediaTypeConfigurationNode) throws RepositoryException {
131         // Copy and rename uploadConfig
132         if (oldMediaTypeConfigurationNode.hasNode("uploadConfig")) {
133             // Copy and rename uploadConfig
134             String srcAbsPath = oldMediaTypeConfigurationNode.getNode("uploadConfig").getPath();
135             String destAbsPath = newParentRootNode.getPath() + "/" + oldMediaTypeConfigurationNode.getName() + "UploadConfig";
136             configSession.move(srcAbsPath, destAbsPath);
137             log.info("Move and rename '{}' to '{}'", srcAbsPath, destAbsPath);
138             if (oldMediaTypeConfigurationNode.hasNode("voter")) {
139                 // Transform voter to MediaType
140                 transformVoters(oldMediaTypeConfigurationNode.getNode("voter"), configSession.getNode(destAbsPath));
141                 // remove the voter node
142                 oldMediaTypeConfigurationNode.getNode("voter").remove();
143             }
144         }
145     }
146 
147     /**
148      * Transform the voters pattern definition into a {@link MediaType#toString()} representation.
149      */
150     private void transformVoters(Node voters, Node target) throws RepositoryException {
151         Iterator<Node> votersIterator = NodeUtil.getNodes(voters, NodeTypes.ContentNode.NAME).iterator();
152         List<MediaType> mediatypes = new ArrayList<MediaType>();
153         if (votersIterator.hasNext()) {
154             while (votersIterator.hasNext()) {
155                 mediatypes.add(convertVoterToMediaType(votersIterator.next()));
156             }
157         } else {
158             mediatypes.add(convertVoterToMediaType(voters));
159         }
160         configureMediaTypes(mediatypes, target);
161     }
162 
163     /**
164      * @return {@link MediaType#parse(String)} based on the pattern property value. Null in case of exception or if not found in the defaultMediaType Map.
165      */
166     private MediaType convertVoterToMediaType(Node voter) throws RepositoryException {
167         if (voter.hasProperty("pattern")) {
168             String pattern = voter.getProperty("pattern").getString();
169             try {
170                 if (defaultMediaType.containsKey(pattern)) {
171                     return defaultMediaType.get(pattern);
172                 }
173                 if (pattern.endsWith("/.*")) {
174                     pattern = pattern.replace("/.*", "/*");
175                 }
176                 return MediaType.parse(pattern);
177             } catch (IllegalArgumentException iae) {
178                 ctx.warn("Could not convert the following pattern '" + pattern + "' from voter definition '" + voter.getPath() + "' to a MediaType due to a convertion exception. Please configure the corresponding MediaType under " + voter.getPath());
179                 return null;
180             }
181         }
182         ctx.warn("Could not convert the following voter definition '" + voter.getPath() + "' to a MediaType due to a missing 'pattern' definition. Please configure the corresponding MediaType under " + voter.getPath());
183         return null;
184     }
185 
186     /**
187      * Create a properties containing the mediaType string representation.
188      */
189     private void configureMediaTypes(List<MediaType> mediatypes, Node targetNode) throws RepositoryException {
190         Node supportedMediaTypes = targetNode.addNode("supportedMediaTypes", NodeTypes.ContentNode.NAME);
191         // propertyName = mediaType Type value
192         if (mediatypes.size() == 1) {
193             supportedMediaTypes.setProperty(mediatypes.get(0).type(), mediatypes.get(0).toString());
194             return;
195         }
196         for (MediaType mediaType : mediatypes) {
197             String propertyName = null;
198             if (StringUtils.endsWith(mediaType.subtype(), "*")) {
199                 propertyName = mediaType.type();
200             } else if (StringUtils.contains(mediaType.subtype(), "-")) {
201                 propertyName = StringUtils.substringAfterLast(mediaType.subtype(), "-");
202             } else {
203                 propertyName = mediaType.subtype();
204             }
205             // if the configuration already contains a property with the same name,
206             // propertyName = mediaType
207             if (supportedMediaTypes.hasProperty(propertyName)) {
208                 propertyName = mediaType.toString();
209             }
210             supportedMediaTypes.setProperty(propertyName, mediaType.toString());
211         }
212 
213     }
214 }