Debian Codegraph @

net/sf/saxon/testdriver/CanonicalXML.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.testdriver;
9
10
11 import net.sf.saxon.lib.StandardEntityResolver;
12 import org.xml.sax.*;
13 import org.xml.sax.ext.LexicalHandler;
14 import org.xml.sax.helpers.AttributesImpl;
15 import org.xml.sax.helpers.DefaultHandler;
16
17 import javax.xml.transform.OutputKeys;
18 import javax.xml.transform.Transformer;
19 import javax.xml.transform.TransformerFactory;
20 import javax.xml.transform.sax.SAXResult;
21 import javax.xml.transform.sax.SAXSource;
22 import java.io.IOException;
23 import java.io.StringReader;
24 import java.io.StringWriter;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27
28 /**
29 * Modifed version of James Clark's XMLTest
30 * This tests an XML parser that has a SAX driver,
31 * by generating the canonical XML for one or more XML files.
32 * This is not written with performance in mind.
33 * <p>Modified by MHK to be callable from code and deliver the canonical XML as a string.
34 * Added an option to remove whitespace-only text nodes
35 * Added code to output all namespace nodes</p>
36 *
37 * @version Date: 1999/12/10
38 */
39 public class CanonicalXML extends DefaultHandler implements LexicalHandler {
40
41 private StringWriter out;
42 private StringBuffer buf = new StringBuffer();
43 private boolean strip = false;
44 private boolean isWhite = true;
45 private AttributesImpl namespaces = new AttributesImpl();
46
47 public String toCanonicalXML(XMLReader parser, InputSource inputSource, boolean stripSpace) {
48
49 strip = stripSpace;
50 out = new StringWriter();
51
52 parser.setContentHandler(this);
53 parser.setEntityResolver(StandardEntityResolver.getInstance());
54 try {
55 parser.setProperty("http://xml.org/sax/properties/lexical-handler", this);
56 } catch (SAXNotSupportedException err) { // this just means we won't see the comments
57 } catch (SAXNotRecognizedException err) {
58 }
59 parser.setErrorHandler(this);
60 try {
61 parser.parse(inputSource);
62 return out.toString();
63 } catch (SAXParseException e) {
64 System.err.println("XML parsing error on line " + e.getLineNumber() + " while creating Canonical XML");
65 System.err.println(e.getMessage());
66 //e.printStackTrace();
67 System.err.println("Parser: " + parser.getClass());
68 try {
69 System.err.println("Supports XML 1.1: " + parser.getFeature("http://xml.org/sax/features/xml-1.1"));
70 } catch (Exception e2) {
71 }
72 } catch (SAXException e) {
73 System.err.println("XML parsing error while creating Canonical XML");
74 System.err.println(e.getMessage());
75 } catch (IOException e) {
76 System.err.println("XML parsing error while creating Canonical XML");
77 System.err.println(e.toString());
78 }
79 return null;
80 }
81
82
83 /**
84 * Create canonical XML silently, throwing exceptions rather than displaying messages
85 *
86 * @param parser
87 * @param inputSource
88 * @param stripSpace
89 * @return
90 * @throws Exception
91 */
92
93 public String toCanonicalXML2(XMLReader parser, InputSource inputSource, boolean stripSpace) throws Exception {
94 strip = stripSpace;
95 out = new StringWriter();
96 parser.setContentHandler(this);
97 try {
98 parser.setProperty("http://xml.org/sax/properties/lexical-handler", this);
99 } catch (SAXNotSupportedException err) { // this just means we won't see the comments
100 // ignore the error
101 } catch (SAXNotRecognizedException err) {
102 // ignore the error
103 }
104 parser.setErrorHandler(this);
105 parser.parse(inputSource);
106 return out.toString();
107 }
108
109 /**
110 * Create canonical XML silently, throwing exceptions rather than displaying messages. This version
111 * of the method uses the Saxon identityTransformer rather than parsing directly, because for some reason
112 * we seem to be able to get XML 1.1 to work this way.
113 */
114
115 public String toCanonicalXML3(TransformerFactory factory, XMLReader resultParser, String inxml, boolean stripSpace) throws Exception {
116 strip = stripSpace;
117 out = new StringWriter();
118 Transformer t = factory.newTransformer();
119 SAXSource ss = new SAXSource(resultParser, new InputSource(new StringReader(inxml)));
120 ss.setSystemId("http://localhost/string-input");
121 t.setOutputProperty(OutputKeys.METHOD, "xml");
122 t.setOutputProperty(OutputKeys.INDENT, "no");
123 t.transform(ss, new SAXResult(this));
124 return out.toString();
125 }
126
127 /**
128 * Receive notification of the start of a Namespace mapping.
129 * <p>By default, do nothing. Application writers may override this
130 * method in a subclass to take specific actions at the start of
131 * each Namespace prefix scope (such as storing the prefix mapping).</p>
132 *
133 * @param prefix The Namespace prefix being declared.
134 * @param uri The Namespace URI mapped to the prefix.
135 * @throws org.xml.sax.SAXException Any SAX exception, possibly
136 * wrapping another exception.
137 * @see org.xml.sax.ContentHandler#startPrefixMapping
138 */
139 public void startPrefixMapping(String prefix, String uri) throws SAXException {
140 namespaces.addAttribute("", prefix, (prefix.equals("") ? "xmlns" : "xmlns:" + prefix), "CDATA", uri);
141 if (!"".equals(uri)) {
142 try {
143 URI u = new URI(uri);
144 if (!u.isAbsolute()) {
145 System.err.println("*** (Canonical XML:) namespace URI " + u + " is not absolute");
146 }
147 } catch (URISyntaxException err) {
148 System.err.println("*** (Canonical XML:) namespace " + uri + " is not a valid URI");
149 }
150 }
151 }
152
153 /**
154 * Receive notification of the start of an element.
155 * <p>By default, do nothing. Application writers may override this
156 * method in a subclass to take specific actions at the start of
157 * each element (such as allocating a new tree node or writing
158 * output to a file).</p>
159 *
160 * @param uri The Namespace URI, or the empty string if the
161 * element has no Namespace URI or if Namespace
162 * processing is not being performed.
163 * @param localName The local name (without prefix), or the
164 * empty string if Namespace processing is not being
165 * performed.
166 * @param qName The qualified name (with prefix), or the
167 * empty string if qualified names are not available.
168 * @param atts The attributes attached to the element. If
169 * there are no attributes, it shall be an empty
170 * Attributes object.
171 * @throws org.xml.sax.SAXException Any SAX exception, possibly
172 * wrapping another exception.
173 * @see org.xml.sax.ContentHandler#startElement
174 */
175 public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
176 flushChars();
177 write("<");
178 write(qName);
179 // output the namespaces
180 outputAttributes(namespaces);
181 // output the attributes
182 outputAttributes(atts);
183 write(">");
184 namespaces.clear();
185 }
186
187 private void outputAttributes(Attributes atts) {
188 int len = atts.getLength();
189 if (len > 0) {
190 int[] v = new int[len];
191 for (int i = 0; i < len; i++) {
192 v[i] = i;
193 }
194 /* Do an insertion sort. */
195 for (int i = 1; i < len; i++) {
196 int n = v[i];
197 String s = atts.getQName(n);
198 int j;
199 for (j = i - 1; j >= 0; j--) {
200 if (s.compareTo(atts.getQName(v[j])) >= 0) {
201 break;
202 }
203 v[j + 1] = v[j];
204 }
205 v[j + 1] = n;
206 }
207 for (int i = 0; i < len; i++) {
208 write(" ");
209 int n = v[i];
210 write(atts.getQName(n));
211 write("=\"");
212 String value = atts.getValue(n);
213 int valueLen = value.length();
214 for (int j = 0; j < valueLen; j++) {
215 appendChar(value.charAt(j));
216 }
217 flushChars();
218 write("\"");
219 }
220 }
221 }
222
223 public void ignorableWhitespace(char[] cbuf, int start, int len) {
224 characters(cbuf, start, len);
225 }
226
227 public void characters(char[] cbuf, int start, int len) {
228 while (len-- > 0) {
229 appendChar(cbuf[start++]);
230 }
231 }
232
233 private void appendChar(char c) {
234 if (strip && isWhite) {
235 if (!Character.isWhitespace(c)) {
236 isWhite = false;
237 }
238 }
239
240 switch (c) {
241 case 1:
242 case 2:
243 case 3:
244 case 4:
245 case 5:
246 case 6:
247 case 7:
248 case 8:
249 case 11:
250 case 12:
251 case 14:
252 case 15:
253 buf.append(charRef(c));
254 break;
255 case '&':
256 buf.append("&amp;");
257 break;
258 case '<':
259 buf.append("&lt;");
260 break;
261 case '>':
262 buf.append("&gt;");
263 break;
264 case '"':
265 buf.append("&quot;");
266 break;
267 case '\t':
268 buf.append("&#9;");
269 break;
270 case '\n':
271 buf.append("&#10;");
272 break;
273 case '\r':
274 buf.append("&#13;");
275 break;
276 case 128:
277 case 129:
278 case 130:
279 case 131:
280 case 132:
281 case 133:
282 case 134:
283 case 135:
284 case 136:
285 case 137:
286 case 138:
287 case 139:
288 case 140:
289 case 141:
290 case 142:
291 case 143:
292 case 144:
293 case 145:
294 case 146:
295 case 147:
296 case 148:
297 case 149:
298 case 150:
299 case 151:
300 case 152:
301 case 153:
302 case 154:
303 case 155:
304 case 156:
305 case 157:
306 case 158:
307 case 159:
308 case 160:
309 buf.append(charRef(c));
310 break;
311 default:
312 buf.append(c);
313 break;
314 }
315 }
316
317 private String charRef(char c) {
318 return "&#" + (int) c + ";";
319 }
320
321 /**
322 * Receive notification of the end of an element.
323 * <p>By default, do nothing. Application writers may override this
324 * method in a subclass to take specific actions at the end of
325 * each element (such as finalising a tree node or writing
326 * output to a file).</p>
327 *
328 * @param uri The Namespace URI, or the empty string if the
329 * element has no Namespace URI or if Namespace
330 * processing is not being performed.
331 * @param localName The local name (without prefix), or the
332 * empty string if Namespace processing is not being
333 * performed.
334 * @param qName The qualified name (with prefix), or the
335 * empty string if qualified names are not available.
336 * @throws org.xml.sax.SAXException Any SAX exception, possibly
337 * wrapping another exception.
338 * @see org.xml.sax.ContentHandler#endElement
339 */
340 public void endElement(String uri, String localName, String qName) throws SAXException {
341 flushChars();
342 write("</");
343 write(qName);
344 write(">");
345 }
346
347 public void processingInstruction(String target, String data) throws SAXException {
348 flushChars();
349 write("<?");
350 write(target);
351 write(" ");
352 write(data);
353 write("?>");
354 }
355
356
357 public void startDocument() {
358 }
359
360 public void endDocument() throws SAXException {
361 try {
362 flushChars();
363 out.close();
364 } catch (IOException e) {
365 throw new SAXException(e);
366 }
367 }
368
369 public void startDTD(String name, String publicId, String systemId) throws SAXException {
370 //
371 }
372
373 public void endDTD() throws SAXException {
374 //
375 }
376
377 public void startEntity(String name) throws SAXException {
378 //
379 }
380
381 public void endEntity(String name) throws SAXException {
382 //
383 }
384
385 public void startCDATA() throws SAXException {
386 //
387 }
388
389 public void endCDATA() throws SAXException {
390 //
391 }
392
393 public void comment(char ch[], int start, int length) throws SAXException {
394 flushChars();
395 write("<!--");
396 write(new String(ch, start, length));
397 write("-->");
398 }
399
400 private void flushChars() {
401 if (buf.length() > 0 && !(strip && isWhite)) {
402 write(buf.toString());
403 }
404 buf.setLength(0);
405 isWhite = true;
406 }
407
408 private void write(String s) {
409 int len = s.length();
410 for (int i = 0; i < len; i++) {
411 char c = s.charAt(i);
412 if (c < 0x80) {
413 out.write(c);
414 } else {
415 switch (c & 0xF800) {
416 case 0:
417 out.write((((c >> 6) & 0x1F) | 0xC0));
418 out.write(((c & 0x3F) | 0x80));
419 break;
420 case 0xD800:
421 char c2;
422 if (i + 1 < len
423 && (c & 0xFC00) == 0xD800
424 && ((c2 = s.charAt(i + 1)) & 0xFC00) == 0xDC00) {
425 ++i;
426 int n = ((c & 0x3FF) << 10) | (c2 & 0x3FF);
427 n += 0x10000;
428 out.write((((n >> 18) & 0x7) | 0xF0));
429 out.write((((n >> 12) & 0x3F) | 0x80));
430 out.write((((n >> 6) & 0x3F) | 0x80));
431 out.write(((n & 0x3F) | 0x80));
432 break;
433 }
434 /* this is an error situation really */
435 /* fall through */
436 default:
437 out.write((((c >> 12) & 0xF) | 0xE0));
438 out.write((((c >> 6) & 0x3F) | 0x80));
439 out.write(((c & 0x3F) | 0x80));
440 break;
441 }
442 }
443 }
444 }
445 }