Debian Codegraph @

rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XmlProcessor.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.xmlimpl;
6
7 import org.w3c.dom.*;
8
9 import javax.xml.parsers.DocumentBuilder;
10 import javax.xml.parsers.ParserConfigurationException;
11
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.io.Serializable;
15 import java.util.List;
16 import java.util.ArrayList;
17 import java.util.concurrent.LinkedBlockingDeque;
18
19 import org.mozilla.javascript.*;
20
21 // Disambiguate from org.mozilla.javascript.Node
22 import org.w3c.dom.Node;
23 import org.xml.sax.ErrorHandler;
24 import org.xml.sax.SAXParseException;
25
26 class XmlProcessor implements Serializable {
27
28 private static final long serialVersionUID = 6903514433204808713L;
29
30 private boolean ignoreComments;
31 private boolean ignoreProcessingInstructions;
32 private boolean ignoreWhitespace;
33 private boolean prettyPrint;
34 private int prettyIndent;
35
36 private transient javax.xml.parsers.DocumentBuilderFactory dom;
37 private transient javax.xml.transform.TransformerFactory xform;
38 private transient LinkedBlockingDeque<DocumentBuilder> documentBuilderPool;
39 private RhinoSAXErrorHandler errorHandler = new RhinoSAXErrorHandler();
40
41 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
42 stream.defaultReadObject();
43 this.dom = javax.xml.parsers.DocumentBuilderFactory.newInstance();
44 this.dom.setNamespaceAware(true);
45 this.dom.setIgnoringComments(false);
46 this.xform = javax.xml.transform.TransformerFactory.newInstance();
47 int poolSize = Runtime.getRuntime().availableProcessors() * 2;
48 this.documentBuilderPool = new LinkedBlockingDeque<DocumentBuilder>(poolSize);
49 }
50
51 private static class RhinoSAXErrorHandler implements ErrorHandler, Serializable {
52
53 private static final long serialVersionUID = 6918417235413084055L;
54
55 private void throwError(SAXParseException e) {
56 throw ScriptRuntime.constructError("TypeError", e.getMessage(),
57 e.getLineNumber() - 1);
58 }
59
60 public void error(SAXParseException e) {
61 throwError(e);
62 }
63
64 public void fatalError(SAXParseException e) {
65 throwError(e);
66 }
67
68 public void warning(SAXParseException e) {
69 Context.reportWarning(e.getMessage());
70 }
71 }
72
73 XmlProcessor() {
74 setDefault();
75 this.dom = javax.xml.parsers.DocumentBuilderFactory.newInstance();
76 this.dom.setNamespaceAware(true);
77 this.dom.setIgnoringComments(false);
78 this.xform = javax.xml.transform.TransformerFactory.newInstance();
79 int poolSize = Runtime.getRuntime().availableProcessors() * 2;
80 this.documentBuilderPool = new LinkedBlockingDeque<DocumentBuilder>(poolSize);
81 }
82
83 final void setDefault() {
84 this.setIgnoreComments(true);
85 this.setIgnoreProcessingInstructions(true);
86 this.setIgnoreWhitespace(true);
87 this.setPrettyPrinting(true);
88 this.setPrettyIndent(2);
89 }
90
91 final void setIgnoreComments(boolean b) {
92 this.ignoreComments = b;
93 }
94
95 final void setIgnoreWhitespace(boolean b) {
96 this.ignoreWhitespace = b;
97 }
98
99 final void setIgnoreProcessingInstructions(boolean b) {
100 this.ignoreProcessingInstructions = b;
101 }
102
103 final void setPrettyPrinting(boolean b) {
104 this.prettyPrint = b;
105 }
106
107 final void setPrettyIndent(int i) {
108 this.prettyIndent = i;
109 }
110
111 final boolean isIgnoreComments() {
112 return ignoreComments;
113 }
114
115 final boolean isIgnoreProcessingInstructions() {
116 return ignoreProcessingInstructions;
117 }
118
119 final boolean isIgnoreWhitespace() {
120 return ignoreWhitespace;
121 }
122
123 final boolean isPrettyPrinting() {
124 return prettyPrint;
125 }
126
127 final int getPrettyIndent() {
128 return prettyIndent;
129 }
130
131 private String toXmlNewlines(String rv) {
132 StringBuilder nl = new StringBuilder();
133 for (int i=0; i<rv.length(); i++) {
134 if (rv.charAt(i) == '\r') {
135 if (rv.charAt(i+1) == '\n') {
136 // DOS, do nothing and skip the \r
137 } else {
138 // Macintosh, substitute \n
139 nl.append('\n');
140 }
141 } else {
142 nl.append(rv.charAt(i));
143 }
144 }
145 return nl.toString();
146 }
147
148 private javax.xml.parsers.DocumentBuilderFactory getDomFactory() {
149 return dom;
150 }
151
152 // Get from pool, or create one without locking, if needed.
153 private DocumentBuilder getDocumentBuilderFromPool()
154 throws ParserConfigurationException {
155 DocumentBuilder builder = documentBuilderPool.pollFirst();
156 if (builder == null){
157 builder = getDomFactory().newDocumentBuilder();
158 }
159 builder.setErrorHandler(errorHandler);
160 return builder;
161 }
162
163 // Insert into pool, if resettable. Pool capacity is limited to
164 // number of processors * 2.
165 private void returnDocumentBuilderToPool(DocumentBuilder db) {
166 try {
167 db.reset();
168 documentBuilderPool.offerFirst(db);
169 } catch (UnsupportedOperationException e) {
170 // document builders that don't support reset() can't be pooled
171 }
172 }
173
174 private void addProcessingInstructionsTo(List<Node> list, Node node) {
175 if (node instanceof ProcessingInstruction) {
176 list.add(node);
177 }
178 if (node.getChildNodes() != null) {
179 for (int i=0; i<node.getChildNodes().getLength(); i++) {
180 addProcessingInstructionsTo(list, node.getChildNodes().item(i));
181 }
182 }
183 }
184
185 private void addCommentsTo(List<Node> list, Node node) {
186 if (node instanceof Comment) {
187 list.add(node);
188 }
189 if (node.getChildNodes() != null) {
190 for (int i=0; i<node.getChildNodes().getLength(); i++) {
191 addProcessingInstructionsTo(list, node.getChildNodes().item(i));
192 }
193 }
194 }
195
196 private void addTextNodesToRemoveAndTrim(List<Node> toRemove, Node node) {
197 if (node instanceof Text) {
198 Text text = (Text)node;
199 boolean BUG_369394_IS_VALID = false;
200 if (!BUG_369394_IS_VALID) {
201 text.setData(text.getData().trim());
202 } else {
203 if (text.getData().trim().length() == 0) {
204 text.setData("");
205 }
206 }
207 if (text.getData().length() == 0) {
208 toRemove.add(node);
209 }
210 }
211 if (node.getChildNodes() != null) {
212 for (int i=0; i<node.getChildNodes().getLength(); i++) {
213 addTextNodesToRemoveAndTrim(toRemove, node.getChildNodes().item(i));
214 }
215 }
216 }
217
218 final Node toXml(String defaultNamespaceUri, String xml) throws org.xml.sax.SAXException {
219 // See ECMA357 10.3.1
220 DocumentBuilder builder = null;
221 try {
222 String syntheticXml = "<parent xmlns=\"" + defaultNamespaceUri +
223 "\">" + xml + "</parent>";
224 builder = getDocumentBuilderFromPool();
225 Document document = builder.parse( new org.xml.sax.InputSource(new java.io.StringReader(syntheticXml)) );
226 if (ignoreProcessingInstructions) {
227 List<Node> list = new java.util.ArrayList<Node>();
228 addProcessingInstructionsTo(list, document);
229 for (Node node: list) {
230 node.getParentNode().removeChild(node);
231 }
232 }
233 if (ignoreComments) {
234 List<Node> list = new java.util.ArrayList<Node>();
235 addCommentsTo(list, document);
236 for (Node node: list) {
237 node.getParentNode().removeChild(node);
238 }
239 }
240 if (ignoreWhitespace) {
241 // Apparently JAXP setIgnoringElementContentWhitespace() has a different meaning, it appears from the Javadoc
242 // Refers to element-only content models, which means we would need to have a validating parser and DTD or schema
243 // so that it would know which whitespace to ignore.
244
245 // Instead we will try to delete it ourselves.
246 List<Node> list = new java.util.ArrayList<Node>();
247 addTextNodesToRemoveAndTrim(list, document);
248 for (Node node: list) {
249 node.getParentNode().removeChild(node);
250 }
251 }
252 NodeList rv = document.getDocumentElement().getChildNodes();
253 if (rv.getLength() > 1) {
254 throw ScriptRuntime.constructError("SyntaxError", "XML objects may contain at most one node.");
255 } else if (rv.getLength() == 0) {
256 Node node = document.createTextNode("");
257 return node;
258 } else {
259 Node node = rv.item(0);
260 document.getDocumentElement().removeChild(node);
261 return node;
262 }
263 } catch (java.io.IOException e) {
264 throw new RuntimeException("Unreachable.");
265 } catch (javax.xml.parsers.ParserConfigurationException e) {
266 throw new RuntimeException(e);
267 } finally {
268 if (builder != null)
269 returnDocumentBuilderToPool(builder);
270 }
271 }
272
273 Document newDocument() {
274 DocumentBuilder builder = null;
275 try {
276 // TODO Should this use XML settings?
277 builder = getDocumentBuilderFromPool();
278 return builder.newDocument();
279 } catch (javax.xml.parsers.ParserConfigurationException ex) {
280 // TODO How to handle these runtime errors?
281 throw new RuntimeException(ex);
282 } finally {
283 if (builder != null)
284 returnDocumentBuilderToPool(builder);
285 }
286 }
287
288 // TODO Cannot remember what this is for, so whether it should use settings or not
289 private String toString(Node node) {
290 javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(node);
291 java.io.StringWriter writer = new java.io.StringWriter();
292 javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(writer);
293 try {
294 javax.xml.transform.Transformer transformer = xform.newTransformer();
295 transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
296 transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "no");
297 transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "xml");
298 transformer.transform(source, result);
299 } catch (javax.xml.transform.TransformerConfigurationException ex) {
300 // TODO How to handle these runtime errors?
301 throw new RuntimeException(ex);
302 } catch (javax.xml.transform.TransformerException ex) {
303 // TODO How to handle these runtime errors?
304 throw new RuntimeException(ex);
305 }
306 return toXmlNewlines(writer.toString());
307 }
308
309 String escapeAttributeValue(Object value) {
310 String text = ScriptRuntime.toString(value);
311
312 if (text.length() == 0) return "";
313
314 Document dom = newDocument();
315 Element e = dom.createElement("a");
316 e.setAttribute("b", text);
317 String elementText = toString(e);
318 int begin = elementText.indexOf('"');
319 int end = elementText.lastIndexOf('"');
320 return elementText.substring(begin+1,end);
321 }
322
323 String escapeTextValue(Object value) {
324 if (value instanceof XMLObjectImpl) {
325 return ((XMLObjectImpl)value).toXMLString();
326 }
327
328 String text = ScriptRuntime.toString(value);
329
330 if (text.length() == 0) return text;
331
332 Document dom = newDocument();
333 Element e = dom.createElement("a");
334 e.setTextContent(text);
335 String elementText = toString(e);
336
337 int begin = elementText.indexOf('>') + 1;
338 int end = elementText.lastIndexOf('<');
339 return (begin < end) ? elementText.substring(begin, end) : "";
340 }
341
342 private String escapeElementValue(String s) {
343 // TODO Check this
344 return escapeTextValue(s);
345 }
346
347 private String elementToXmlString(Element element) {
348 // TODO My goodness ECMA is complicated (see 10.2.1). We'll try this first.
349 Element copy = (Element)element.cloneNode(true);
350 if (prettyPrint) {
351 beautifyElement(copy, 0);
352 }
353 return toString(copy);
354 }
355
356 final String ecmaToXmlString(Node node) {
357 // See ECMA 357 Section 10.2.1
358 StringBuilder s = new StringBuilder();
359 int indentLevel = 0;
360 if (prettyPrint) {
361 for (int i=0; i<indentLevel; i++) {
362 s.append(' ');
363 }
364 }
365 if (node instanceof Text) {
366 String data = ((Text)node).getData();
367 // TODO Does Java trim() work same as XMLWhitespace?
368 String v = (prettyPrint) ? data.trim() : data;
369 s.append(escapeElementValue(v));
370 return s.toString();
371 }
372 if (node instanceof Attr) {
373 String value = ((Attr)node).getValue();
374 s.append(escapeAttributeValue(value));
375 return s.toString();
376 }
377 if (node instanceof Comment) {
378 s.append("<!--" + ((Comment)node).getNodeValue() + "-->");
379 return s.toString();
380 }
381 if (node instanceof ProcessingInstruction) {
382 ProcessingInstruction pi = (ProcessingInstruction)node;
383 s.append("<?" + pi.getTarget() + " " + pi.getData() + "?>");
384 return s.toString();
385 }
386 s.append(elementToXmlString((Element)node));
387 return s.toString();
388 }
389
390 private void beautifyElement(Element e, int indent) {
391 StringBuilder s = new StringBuilder();
392 s.append('\n');
393 for (int i=0; i<indent; i++) {
394 s.append(' ');
395 }
396 String afterContent = s.toString();
397 for (int i=0; i<prettyIndent; i++) {
398 s.append(' ');
399 }
400 String beforeContent = s.toString();
401
402 // We "mark" all the nodes first; if we tried to do this loop otherwise, it would behave unexpectedly (the inserted nodes
403 // would contribute to the length and it might never terminate).
404 ArrayList<Node> toIndent = new ArrayList<Node>();
405 boolean indentChildren = false;
406 for (int i=0; i<e.getChildNodes().getLength(); i++) {
407 if (i == 1) indentChildren = true;
408 if (e.getChildNodes().item(i) instanceof Text) {
409 toIndent.add(e.getChildNodes().item(i));
410 } else {
411 indentChildren = true;
412 toIndent.add(e.getChildNodes().item(i));
413 }
414 }
415 if (indentChildren) {
416 for (int i=0; i<toIndent.size(); i++) {
417 e.insertBefore(e.getOwnerDocument().createTextNode(beforeContent),
418 toIndent.get(i));
419 }
420 }
421 NodeList nodes = e.getChildNodes();
422 ArrayList<Element> list = new ArrayList<Element>();
423 for (int i=0; i < nodes.getLength(); i++) {
424 if (nodes.item(i) instanceof Element) {
425 list.add((Element)nodes.item(i));
426 }
427 }
428 for (Element elem: list) {
429 beautifyElement(elem, indent + prettyIndent);
430 }
431 if (indentChildren) {
432 e.appendChild(e.getOwnerDocument().createTextNode(afterContent));
433 }
434 }
435 }