View Javadoc
1   /**
2    * This file Copyright (c) 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.importexport.command;
35  
36  import info.magnolia.context.Context;
37  import info.magnolia.importexport.DataTransporter;
38  import info.magnolia.importexport.exporter.YamlExporter;
39  import info.magnolia.importexport.outputter.YamlOutputter;
40  import info.magnolia.jcr.decoration.ContentDecorator;
41  import info.magnolia.jcr.decoration.NodePredicateContentDecorator;
42  import info.magnolia.jcr.predicate.AbstractPredicate;
43  import info.magnolia.jcr.predicate.NodeFilteringPredicate;
44  import info.magnolia.jcr.predicate.PropertyFilteringPredicate;
45  import info.magnolia.objectfactory.Classes;
46  
47  import java.io.OutputStream;
48  import java.util.Arrays;
49  import java.util.HashMap;
50  import java.util.Map;
51  import java.util.zip.DeflaterOutputStream;
52  import java.util.zip.GZIPOutputStream;
53  import java.util.zip.ZipEntry;
54  import java.util.zip.ZipOutputStream;
55  
56  import javax.jcr.Node;
57  import javax.jcr.Property;
58  import javax.jcr.Session;
59  
60  import org.apache.commons.io.IOUtils;
61  import org.apache.commons.lang3.StringUtils;
62  import org.apache.jackrabbit.JcrConstants;
63  import org.apache.jackrabbit.commons.xml.Exporter;
64  import org.apache.jackrabbit.commons.xml.SystemViewExporter;
65  import org.jdom.output.XMLOutputter;
66  import org.jdom.transform.JDOMResult;
67  import org.xml.sax.ContentHandler;
68  
69  import com.google.common.collect.Lists;
70  
71  /**
72   * Command for exporting from a JCR workspace.
73   */
74  public class JcrExportCommand extends JcrImportCommand {
75  
76      private OutputStream outputStream;
77      private Format format = Format.XML;
78      private Compression compression = Compression.NONE;
79      private Map<String, ContentDecorator> filters = new HashMap<>();
80      private Class<? extends Exporter> exporterClass;
81      private XMLOutputter outputter;
82  
83      public JcrExportCommand() {
84          final org.jdom.output.Format format = org.jdom.output.Format.getPrettyFormat();
85          format.setTextMode(org.jdom.output.Format.TextMode.NORMALIZE);
86          format.setLineSeparator("\n");
87          getOutputter().setFormat(format);
88      }
89  
90      @Override
91      public boolean execute(Context context) throws Exception {
92          String pathName = DataTransporter.createExportPath(getPath());
93          pathName = DataTransporter.encodePath(pathName, DataTransporter.DOT, DataTransporter.UTF8);
94          if (DataTransporter.DOT.equals(pathName)) {
95              // root node
96              pathName = StringUtils.EMPTY;
97          }
98          setFileName(getRepository() + pathName + "." + getFormat().name().toLowerCase());
99          OutputStream compressionOutputStream = getOutputStream();
100         switch (compression) {
101         case ZIP:
102             final ZipOutputStream zipOutputStream = new ZipOutputStream(compressionOutputStream);
103             zipOutputStream.putNextEntry(new ZipEntry(getFileName()));
104             compressionOutputStream = zipOutputStream;
105             break;
106         case GZ:
107             compressionOutputStream = new GZIPOutputStream(compressionOutputStream);
108             break;
109         }
110         try {
111             final Session session = context.getJCRSession(getRepository()); //don't get the session from getJCRNode(context), that's a system context with superuser access!
112             final JDOMResult jdomResult = new JDOMResult();
113             final ContentHandler contentHandler = jdomResult.getHandler();
114             final Exporter exporter = Classes.getClassFactory().newInstance(getExporterClass(), session, contentHandler, true, true);
115             final XMLOutputter xmlOutputter = getOutputter();
116             final ContentDecorator contentDecorator = filters.containsKey(getRepository()) ? filters.get(getRepository()) : new DefaultFilter();
117             final Node node = contentDecorator.wrapNode(getJCRNode(context));
118 
119             exporter.export(node);
120             try {
121                 xmlOutputter.output(jdomResult.getDocument(), compressionOutputStream);
122             } catch (IllegalStateException e) {
123                 xmlOutputter.output(jdomResult.getResult(), compressionOutputStream);
124             }
125         } finally {
126             // finish the stream properly if zip stream, this is not done by the IOUtils
127             if (compressionOutputStream instanceof DeflaterOutputStream) {
128                 ((DeflaterOutputStream) compressionOutputStream).finish();
129             }
130             compressionOutputStream.flush();
131             IOUtils.closeQuietly(compressionOutputStream);
132         }
133         return true;
134     }
135 
136     public OutputStream getOutputStream() {
137         return outputStream;
138     }
139 
140     public void setOutputStream(OutputStream outputStream) {
141         this.outputStream = outputStream;
142     }
143 
144     public Format getFormat() {
145         return format;
146     }
147 
148     public void setFormat(Format format) {
149         this.format = format;
150     }
151 
152     public Compression getCompression() {
153         return compression;
154     }
155 
156     public void setCompression(Compression compression) {
157         this.compression = compression;
158     }
159 
160     public XMLOutputter getOutputter() {
161         return outputter == null ? format.getDefaultOutputter() : outputter;
162     }
163 
164     public void setOutputter(XMLOutputter outputter) {
165         this.outputter = outputter;
166     }
167 
168     public Map<String, ContentDecorator> getFilters() {
169         return filters;
170     }
171 
172     public void setFilters(Map<String, ContentDecorator> filters) {
173         this.filters = filters;
174     }
175 
176     public Class<? extends Exporter> getExporterClass() {
177         return exporterClass == null ? format.getDefaultExporterClass() : exporterClass;
178     }
179 
180     public void setExporterClass(Class<? extends Exporter> exporterClass) {
181         this.exporterClass = exporterClass;
182     }
183 
184     /**
185      * Default filters for {@link info.magnolia.importexport.command.JcrExportCommand}.
186      */
187     public static class DefaultFilter extends NodePredicateContentDecorator {
188 
189         public DefaultFilter() {
190             final NodeFilteringPredicate nodePredicate = new NodeFilteringPredicate();
191             nodePredicate.setNodeTypes(Lists.newArrayList("rep:AccessControl", "rep:root", "rep:system"));
192             final PropertyFilteringPredicate propertyPredicate = new PropertyFilteringPredicate();
193             propertyPredicate.setExcludedNames(Lists.newArrayList("jcr:createdBy", JcrConstants.JCR_CREATED));
194             setPropertyPredicate(propertyPredicate);
195             setNodePredicate(nodePredicate);
196         }
197 
198         @Override
199         public PropertyFilteringPredicate getPropertyPredicate() {
200             return (PropertyFilteringPredicate) super.getPropertyPredicate();
201         }
202 
203         @Override
204         public void setPropertyPredicate(AbstractPredicate<Property> propertyPredicate) {
205             if (propertyPredicate instanceof PropertyFilteringPredicate) {
206                 super.setPropertyPredicate(propertyPredicate);
207             } else {
208                 throw new IllegalArgumentException(String.format("Expected instances of {%s} but got {%s}", PropertyFilteringPredicate.class, propertyPredicate.getClass()));
209             }
210         }
211 
212         @Override
213         public NodeFilteringPredicate getNodePredicate() {
214             return (NodeFilteringPredicate) super.getNodePredicate();
215         }
216 
217         @Override
218         public void setNodePredicate(AbstractPredicate<Node> propertyPredicate) {
219             if (propertyPredicate instanceof NodeFilteringPredicate) {
220                 super.setNodePredicate(propertyPredicate);
221             } else {
222                 throw new IllegalArgumentException(String.format("Expected instances of {%s} but got {%s}", PropertyFilteringPredicate.class, propertyPredicate.getClass()));
223             }
224         }
225     }
226 
227 
228     /**
229      * Export format.
230      */
231     public enum Format {
232 
233         XML(SystemViewExporter.class, new XMLOutputter()),
234         YAML(YamlExporter.class, new YamlOutputter());
235 
236         private final Class<? extends Exporter> defaultExporter;
237         private final XMLOutputter defaultOutputter;
238 
239         Format(Class<? extends Exporter> defaultExporter, XMLOutputter defaultOutputter) {
240             this.defaultExporter = defaultExporter;
241             this.defaultOutputter = defaultOutputter;
242         }
243 
244         public Class<? extends Exporter> getDefaultExporterClass() {
245             return defaultExporter;
246         }
247 
248         public XMLOutputter getDefaultOutputter() {
249             return defaultOutputter;
250         }
251 
252         public static boolean isSupportedExtension(String extension) {
253             return Arrays.stream(values()).anyMatch(f -> StringUtils.equals(f.name(), StringUtils.upperCase(extension)));
254         }
255     }
256 
257     /**
258      * Exported file compression.
259      */
260     public enum Compression {
261         NONE,
262         ZIP,
263         GZ
264     }
265 }