View Javadoc
1   /**
2    * This file Copyright (c) 2015-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.commands;
35  
36  import info.magnolia.cms.security.AccessDeniedException;
37  import info.magnolia.cms.security.AccessManager;
38  import info.magnolia.cms.security.Permission;
39  import info.magnolia.commands.impl.BaseRepositoryCommand;
40  import info.magnolia.config.converters.DefinitionRawViewToYamlConverter;
41  import info.magnolia.config.registry.DefinitionProvider;
42  import info.magnolia.config.registry.DefinitionRawView;
43  import info.magnolia.config.registry.Registry;
44  import info.magnolia.config.registry.RegistryFacade;
45  import info.magnolia.context.Context;
46  import info.magnolia.context.MgnlContext;
47  import info.magnolia.repository.RepositoryConstants;
48  
49  import java.io.OutputStream;
50  import java.io.Reader;
51  import java.util.Collection;
52  
53  import javax.inject.Inject;
54  import javax.jcr.Node;
55  import javax.jcr.RepositoryException;
56  
57  import org.apache.commons.lang3.StringEscapeUtils;
58  import org.apache.commons.lang3.StringUtils;
59  import org.apache.tika.io.IOUtils;
60  import org.slf4j.Logger;
61  import org.slf4j.LoggerFactory;
62  
63  /**
64   * Converts and exports a JCR sub-tree into to Yaml file.
65   * <p>
66   * <strong>Note:</strong> Supports only those JCR paths that represent the roots of definition objects, i.e. which are possible
67   * to query from {@link RegistryFacade}.
68   * <br>
69   * <strong>Note:</strong> 'extends' property is 'expanded' meaning that exported Yaml has effective structure with all the data and no 'extends'.
70   * </p>
71   *
72   * Command assumes following input parameters to be set:
73   * <ul>
74   * <li><strong>workspace</strong> - 'config' workspace by default</li>
75   * <li><strong>path</strong> - JCR node path which represents a definition object from some {@link Registry}</li>
76   * </ul>
77   * Following output parameters are set by command:
78   * <ul>
79   * <li><strong>outputStream</strong> containing Yaml content</li>
80   * <li><strong>fileName</strong> by which the content can be downloaded</li>
81   * </ul>
82   */
83  public class ExportJcrNodeToYamlCommand extends BaseRepositoryCommand {
84  
85      public static final String EXPORT_OUTPUT_STREAM = "outputStream";
86  
87      private static final Logger log = LoggerFactory.getLogger(ExportJcrNodeToYamlCommand.class);
88  
89      private static final String YAML_EXTENSION = ".yaml";
90      private static final String SLASH = "/";
91      private static final String DOT = ".";
92  
93      private final RegistryFacade registryFacade;
94      private final DefinitionRawViewToYamlConverter definitionRawViewToYamlConverter;
95  
96      private OutputStream outputStream;
97      private String fileName;
98  
99      @Inject
100     public ExportJcrNodeToYamlCommand(RegistryFacade registryFacade, DefinitionRawViewToYamlConverter definitionRawViewToYamlConverter) {
101         this.registryFacade = registryFacade;
102         this.definitionRawViewToYamlConverter = definitionRawViewToYamlConverter;
103     }
104 
105     @Override
106     public boolean execute(Context context) throws Exception {
107         setRepository(StringUtils.isBlank(super.getRepository()) ? RepositoryConstants.CONFIG : super.getRepository());
108 
109         String repository = super.getRepository();
110         String path = super.getPath();
111         log.debug("Will export content from {} repository with uuid {} and path {}", repository, getUuid(), path);
112 
113         if (StringUtils.isBlank(path)) {
114             throw new RuntimeException("Path should not be null");
115         }
116 
117         // Check Permission
118         if (!checkPermissions(repository, path, Permission.READ)) {
119             // escape to prevent XSS attack
120             throw new AccessDeniedException("Read permission needed for export. User not allowed to READ path [" + StringEscapeUtils.escapeHtml4(path) + "]");
121         }
122 
123         final Node node = context.getJCRSession(getRepository()).getNode(path);
124 
125         final DefinitionProvider definitionProvider = definitionProviderFor(node.getPath());
126         if (definitionProvider == null) {
127             throw new IllegalStateException("JCR path has to represent a definition object");
128         }
129 
130         final DefinitionRawView definitionRawView = definitionProvider.getRaw();
131         try (Reader exportedYamlReader = definitionRawViewToYamlConverter.convert(definitionRawView)) {
132             IOUtils.copy(exportedYamlReader, outputStream);
133             sanitizeAndSetFileName(path);
134         } finally {
135             IOUtils.closeQuietly(outputStream);
136         }
137 
138         return true;
139     }
140 
141     private void sanitizeAndSetFileName(String path) {
142         String fileName = getRepository() + path + YAML_EXTENSION;
143         String sanitizedFileName = StringUtils.replaceChars(fileName, SLASH, DOT);
144         setFileName(sanitizedFileName);
145     }
146 
147     @SuppressWarnings("unchecked")
148     private DefinitionProvider definitionProviderFor(String nodePath) throws RepositoryException {
149         // We're searching for a definition that corresponds to a path in such a sub-optimal way until the issue MAGNOLIA-6086 is fixed
150         for (Registry registry : registryFacade.all()) {
151             Collection<DefinitionProvider> providers = registry.getAllProviders();
152             for (DefinitionProvider provider : providers) {
153                 if (provider.getMetadata().getLocation().equals(nodePath)) {
154                     return provider;
155                 }
156             }
157         }
158         return null;
159     }
160 
161     /**
162      * Uses access manager to authorize this request.
163      *
164      * @return {@code true} if read access is granted
165      */
166     public boolean checkPermissions(String repository, String basePath, long permissionType) {
167         AccessManager accessManager = MgnlContext.getAccessManager(repository);
168         if (accessManager != null) {
169             if (!accessManager.isGranted(basePath, permissionType)) {
170                 return false;
171             }
172         }
173         return true;
174     }
175 
176     /**
177      * @return the outputStream
178      */
179     public OutputStream getOutputStream() {
180         return outputStream;
181     }
182 
183     /**
184      * @param outputStream the outputStream to set
185      */
186     public void setOutputStream(OutputStream outputStream) {
187         this.outputStream = outputStream;
188     }
189 
190     /**
191      * @return the fileName
192      */
193     public String getFileName() {
194         return fileName;
195     }
196 
197     /**
198      * @param fileName the fileName to set
199      */
200     public void setFileName(String fileName) {
201         this.fileName = fileName;
202     }
203 }