View Javadoc

1   /*
2    * Copyright 2007 - 2007 JEuclid, http://jeuclid.sf.net
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  /* $Id: MathMLSerializer.java,v 2bab6eb875e8 2010/08/11 16:45:50 max $ */
18  
19  package net.sourceforge.jeuclid;
20  
21  import java.io.StringWriter;
22  
23  import javax.annotation.concurrent.ThreadSafe;
24  import javax.xml.transform.OutputKeys;
25  import javax.xml.transform.Transformer;
26  import javax.xml.transform.TransformerException;
27  import javax.xml.transform.TransformerFactory;
28  import javax.xml.transform.dom.DOMSource;
29  import javax.xml.transform.stream.StreamResult;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.w3c.dom.Node;
34  
35  /**
36   * Utility class to serialize DOM documents back into Strings.
37   * <p>
38   * This class can be used to generate String representations for an existing DOM
39   * Tree. The functionality is not restricted to JEuclid, and can be used for
40   * other DOM trees as well. In this case, you should set the addDoctype
41   * parameter to false.
42   * 
43   * @version $Revision: 2bab6eb875e8 $
44   */
45  @ThreadSafe
46  public final class MathMLSerializer {
47  
48      /**
49       * Logger for this class
50       */
51      private static final Log LOGGER = LogFactory.getLog(MathMLSerializer.class);
52  
53      private MathMLSerializer() {
54          // empty on purpose
55      }
56  
57      /**
58       * Serialize a document back into a String.
59       * 
60       * @param doc
61       *            a DOM model of a document, or a node in a document
62       * @param addDoctype
63       *            if true, extra attributes such as docType will be set. This
64       *            ensures maximum MathML compatibility. Use only with MathML DOM
65       *            trees.
66       * @param format
67       *            if true, result will be nicely formatted.
68       * @return the document serialized to a string
69       * @see #serializeDocument(Node, boolean, boolean, boolean)
70       */
71      public static String serializeDocument(final Node doc,
72              final boolean addDoctype, final boolean format) {
73          return MathMLSerializer.serializeDocument(doc, addDoctype, format,
74                  false);
75      }
76  
77      /**
78       * Serialize a document back into a String.
79       * 
80       * @param doc
81       *            a DOM model of a document.
82       * @param addDoctype
83       *            if true, extra attributes such as docType will be set. This
84       *            ensures maximum MathML compatibility. Use only with MathML DOM
85       *            trees.
86       * @param format
87       *            if true, result will be nicely formatted.
88       * @param omitXMLDecl
89       *            if true, there will be no XML declaration.
90       * @return the document serialized to a string
91       */
92      public static String serializeDocument(final Node doc,
93              final boolean addDoctype, final boolean format,
94              final boolean omitXMLDecl) {
95          final StringWriter writer = new StringWriter();
96          try {
97              final Transformer transformer = TransformerFactory.newInstance()
98                      .newTransformer();
99              final DOMSource source = new DOMSource(doc);
100             final StreamResult result = new StreamResult(writer);
101 
102             if (addDoctype) {
103                 transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
104                         ResourceEntityResolver.MML2_PUBLICID);
105                 transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
106                         ResourceEntityResolver.MML2_SYSTEMID);
107                 transformer.setOutputProperty(OutputKeys.MEDIA_TYPE,
108                         Constants.MATHML_MIMETYPE);
109             }
110             MathMLSerializer.boolToProperty(format, OutputKeys.INDENT,
111                     transformer);
112             MathMLSerializer.boolToProperty(omitXMLDecl,
113                     OutputKeys.OMIT_XML_DECLARATION, transformer);
114             transformer.transform(source, result);
115         } catch (final TransformerException e) {
116             MathMLSerializer.LOGGER.warn(e.getMessage(), e);
117         }
118         return writer.toString();
119 
120     }
121 
122     private static void boolToProperty(final boolean bool, final String key,
123             final Transformer transformer) {
124         if (bool) {
125             transformer.setOutputProperty(key, "yes");
126         } else {
127             transformer.setOutputProperty(key, "no");
128         }
129     }
130 
131 }