View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  package org.opencastproject.util;
23  
24  import static org.opencastproject.util.data.Either.left;
25  import static org.opencastproject.util.data.Either.right;
26  import static org.opencastproject.util.data.functions.Misc.chuck;
27  
28  import org.opencastproject.util.data.Either;
29  
30  import org.apache.commons.io.IOUtils;
31  import org.w3c.dom.Document;
32  import org.xml.sax.InputSource;
33  
34  import java.io.ByteArrayInputStream;
35  import java.io.ByteArrayOutputStream;
36  import java.io.IOException;
37  import java.io.InputStream;
38  import java.io.OutputStream;
39  
40  import javax.xml.parsers.DocumentBuilder;
41  import javax.xml.parsers.DocumentBuilderFactory;
42  import javax.xml.parsers.ParserConfigurationException;
43  import javax.xml.transform.OutputKeys;
44  import javax.xml.transform.Transformer;
45  import javax.xml.transform.TransformerException;
46  import javax.xml.transform.dom.DOMSource;
47  import javax.xml.transform.stream.StreamResult;
48  
49  /** XML utility functions. */
50  public final class XmlUtil {
51    private static final DocumentBuilderFactory nsDbf;
52    private static final DocumentBuilderFactory dbf;
53  
54    static {
55      nsDbf = XmlSafeParser.newDocumentBuilderFactory();
56      nsDbf.setNamespaceAware(true);
57      //
58      dbf = XmlSafeParser.newDocumentBuilderFactory();
59      dbf.setNamespaceAware(false);
60    }
61  
62    private XmlUtil() {
63    }
64  
65    /** Namespace aware parsing of <code>src</code>. */
66    public static Either<Exception, Document> parseNs(InputSource src) {
67      try {
68        DocumentBuilder docBuilder = nsDbf.newDocumentBuilder();
69        return right(docBuilder.parse(src));
70      } catch (Exception e) {
71        return left(e);
72      }
73    }
74  
75    /** Namespace aware parsing of <code>xml</code>. */
76    public static Either<Exception, Document> parseNs(String xml) {
77      return parseNs(fromXmlString(xml));
78    }
79  
80    /**
81     * Writes an xml representation to a stream.
82     *
83     * @param doc
84     *          the document
85     * @param out
86     *          the output stream
87     * @throws IOException
88     *           if there is an error transforming the dom to a stream
89     */
90    public static void toXml(Document doc, OutputStream out) throws IOException {
91      try {
92        DOMSource domSource = new DOMSource(doc);
93        StreamResult result = new StreamResult(out);
94        Transformer transformer = XmlSafeParser.newTransformerFactory()
95                .newTransformer();
96        transformer.setOutputProperty(OutputKeys.VERSION, doc.getXmlVersion());
97        transformer.transform(domSource, result);
98      } catch (TransformerException e) {
99        throw new IOException("unable to transform dom to a stream");
100     }
101   }
102 
103   /**
104    * Writes an xml representation to an input stream and return it.
105    *
106    * @param document
107    *          the document
108    * @return the input stream containing the serialized xml representation
109    * @throws IOException
110    *           if there is an error transforming the dom to a stream
111    */
112   public static InputStream serializeDocument(Document document) throws IOException {
113     ByteArrayOutputStream out = null;
114     try {
115       out = new ByteArrayOutputStream();
116       XmlUtil.toXml(document, out);
117       return new ByteArrayInputStream(out.toByteArray());
118     } finally {
119       IoSupport.closeQuietly(out);
120     }
121   }
122 
123   /**
124    * Serializes the document to a XML string
125    *
126    * @param document
127    *          the document
128    * @return the serialized XML string
129    * @throws IOException
130    *           if there is an error transforming the dom to a stream
131    */
132   public static String toXmlString(Document document) throws IOException {
133     InputStream inputStream = null;
134     try {
135       inputStream = serializeDocument(document);
136       return IOUtils.toString(inputStream, "UTF-8");
137     } finally {
138       IoSupport.closeQuietly(inputStream);
139     }
140   }
141 
142   /** Create an {@link org.xml.sax.InputSource} from an XML string. */
143   public static InputSource fromXmlString(String xml) {
144     return new InputSource(IOUtils.toInputStream(xml));
145   }
146 
147   /**
148    * Creates an xml document root and returns it.
149    *
150    * @return the document
151    */
152   public static Document newDocument() {
153     try {
154       return nsDbf.newDocumentBuilder().newDocument();
155     } catch (ParserConfigurationException e) {
156       return chuck(e);
157     }
158   }
159 
160 }