ludc
2025-01-16 986aa62ed00bee39363bab41b4eeb8259d446efd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package org.jbpm.pvm.internal.util;
 
/*
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary formResourceName must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
 
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
/**
 * Traverse a DOM tree in order to print a document that is parsed.
 *
 * @author Andy Clark, IBM
 * @author Thomas.Diesler@jboss.org
 */
@SuppressWarnings("unchecked")
public class DOMWriter
{
  // Print writer
  private PrintWriter out;
  // True, if canonical output
  private boolean canonical;
  // True, if pretty printing should be used
  private boolean prettyprint;
  // True, if the XML declaration should be written
  private boolean writeXMLDeclaration;
  // True, if whitespace should be ignored
  private boolean ignoreWhitespace;
  // Explicit character set encoding
  private String charsetName;
  // indent for the pretty printer
  private int prettyIndent;
  // True, if the XML declaration has been written
  private boolean wroteXMLDeclaration;
  // The node that started the write
  private Node rootNode;
  // True if we want namespace completion
  private boolean completeNamespaces = true;
  // The current default namespace
  private String currentDefaultNamespace;
 
  public DOMWriter(Writer w)
  {
    this.out = new PrintWriter(w);
  }
 
  public DOMWriter(Writer w, String charsetName)
  {
    this.out = new PrintWriter(w);
    this.charsetName = charsetName;
    this.writeXMLDeclaration = true;
  }
 
  public DOMWriter(OutputStream stream)
  {
    try
    {
      this.out = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
    }
    catch (UnsupportedEncodingException e)
    {
      // ignore, UTF-8 should be available
    }
  }
 
  public DOMWriter(OutputStream stream, String charsetName)
  {
    try
    {
      this.out = new PrintWriter(new OutputStreamWriter(stream, charsetName));
      this.charsetName = charsetName;
      this.writeXMLDeclaration = true;
    }
    catch (UnsupportedEncodingException e)
    {
      throw new IllegalArgumentException("Unsupported encoding: " + charsetName);
    }
  }
 
  /**
   * Print a node with explicit prettyprinting.
   * The defaults for all other DOMWriter properties apply.
   *
   */
  public static String printNode(Node node, boolean prettyprint)
  {
    StringWriter strw = new StringWriter();
    new DOMWriter(strw).setPrettyprint(prettyprint).print(node);
    return strw.toString();
  }
 
  public boolean isCanonical()
  {
    return canonical;
  }
 
  /**
   * Set wheter entities should appear in their canonical formResourceName.
   * The default is false.
   */
  public DOMWriter setCanonical(boolean canonical)
  {
    this.canonical = canonical;
    return this;
  }
 
  public boolean isIgnoreWhitespace()
  {
    return ignoreWhitespace;
  }
 
  /**
   * Set whether whitespace should be ignored.
   * The default is false.
   */
  public DOMWriter setIgnoreWhitespace(boolean ignoreWhitespace)
  {
    this.ignoreWhitespace = ignoreWhitespace;
    return this;
  }
 
  /**
   * Set wheter subelements should have their namespaces completed.
   * Setting this to false may lead to invalid XML fragments.
   * The default is true.
   */
  public DOMWriter setCompleteNamespaces(boolean complete)
  {
    this.completeNamespaces = complete;
    return this;
  }
 
  public boolean isPrettyprint()
  {
    return prettyprint;
  }
 
  /**
   * Set wheter element should be indented.
   * The default is false.
   */
  public DOMWriter setPrettyprint(boolean prettyprint)
  {
    this.prettyprint = prettyprint;
    return this;
  }
 
  public boolean isWriteXMLDeclaration()
  {
    return writeXMLDeclaration;
  }
 
  /**
   * Set wheter the XML declaration should be written.
   * The default is false.
   */
  public DOMWriter setWriteXMLDeclaration(boolean flag)
  {
    this.writeXMLDeclaration = flag;
    return this;
  }
 
  public void print(Node node)
  {
    if (prettyprint && ignoreWhitespace)
      throw new IllegalStateException("Cannot pretty print and ignore whitespace");
 
    rootNode = node;
    printInternal(node, false);
  }
 
  private void printInternal(Node node, boolean indentEndMarker)
  {
    // is there anything to do?
    if (node == null)
    {
      return;
    }
 
    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node = ((Document)node).getDocumentElement();
 
    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false)
    {
      out.print("<?xml version='1.0'");
      if (charsetName != null)
        out.print(" encoding='" + charsetName + "'");
 
      out.print("?>");
      if (prettyprint)
        out.println();
 
      wroteXMLDeclaration = true;
    }
 
    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;
 
    String nodeName = node.getNodeName();
    switch (type)
    {
      // print document
      case Node.DOCUMENT_NODE:
      {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++)
        {
          printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
      }
 
      // print element with attributes
      case Node.ELEMENT_NODE:
      {
        Element element = (Element)node;
        if (prettyprint)
        {
          for (int i = 0; i < prettyIndent; i++)
          {
            out.print(' ');
          }
          prettyIndent++;
        }
 
        out.print('<');
        out.print(nodeName);
 
        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null)
        {
          String nsURI = getNamespaceURI(elPrefix, element, rootNode);
          nsMap.put(elPrefix, nsURI);
        }
 
        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++)
        {
          Attr attr = attrs[i];
          String atPrefix = attr.getPrefix();
          String atName = attr.getNodeName();
          String atValue = normalize(attr.getNodeValue(), canonical);
 
          if (atName.equals("xmlns"))
            currentDefaultNamespace = atValue;
 
          if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml"))
          {
            String nsURI = getNamespaceURI(atPrefix, element, rootNode);
            nsMap.put(atPrefix, nsURI);
            // xsi:type='ns1:SubType', xsi:type='xsd:string'
            if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0)
            {
              // xsi defined on the envelope
              if (nsURI == null)
                nsURI = getNamespaceURI(atPrefix, element, null);
 
              if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI))
              {
                String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                nsMap.put(typePrefix, typeURI);
              }
            }
          }
 
          out.print(" " + atName + "='" + atValue + "'");
        }
 
        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces)
        {
          Iterator itPrefix = nsMap.keySet().iterator();
          while (itPrefix.hasNext())
          {
            String prefix = (String)itPrefix.next();
            String nsURI = (String)nsMap.get(prefix);
            if (nsURI == null)
            {
              nsURI = getNamespaceURI(prefix, element, null);
              out.print(" xmlns:" + prefix + "='" + nsURI + "'");
            }
          }
        }
 
        // The SAX ContentHandler will by default not add the namespace declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null)
        {
          String defaultNamespace = element.getAttribute("xmlns");
          if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace))
          {
            out.print(" xmlns='" + elNamespaceURI + "'");
            currentDefaultNamespace = elNamespaceURI;
          }
        }
 
        if (hasChildNodes)
        {
          out.print('>');
        }
 
        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);
 
        if (indentEndMarker)
        {
          out.print('\n');
        }
 
        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++)
        {
          Node childNode = childNodes.item(i);
          printInternal(childNode, false);
        }
        break;
      }
 
      // handle entity reference nodes
      case Node.ENTITY_REFERENCE_NODE:
      {
        if (canonical)
        {
          NodeList children = node.getChildNodes();
          if (children != null)
          {
            int len = children.getLength();
            for (int i = 0; i < len; i++)
            {
              printInternal(children.item(i), false);
            }
          }
        }
        else
        {
          out.print('&');
          out.print(nodeName);
          out.print(';');
        }
        break;
      }
 
      // print cdata sections
      case Node.CDATA_SECTION_NODE:
      {
        if (canonical)
        {
          out.print(normalize(node.getNodeValue(), canonical));
        }
        else
        {
          out.print("<![CDATA[");
          out.print(node.getNodeValue());
          out.print("]]>");
        }
        break;
      }
 
      // print text
      case Node.TEXT_NODE:
      {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0)
        {
          out.print(text);
        }
        else if (prettyprint == false && ignoreWhitespace == false)
        {
          out.print(text);
        }
        break;
      }
 
      // print processing instruction
      case Node.PROCESSING_INSTRUCTION_NODE:
      {
        out.print("<?");
        out.print(nodeName);
        String data = node.getNodeValue();
        if (data != null && data.length() > 0)
        {
          out.print(' ');
          out.print(data);
        }
        out.print("?>");
        break;
      }
 
      // print comment
      case Node.COMMENT_NODE:
      {
        for (int i = 0; i < prettyIndent; i++)
        {
          out.print(' ');
        }
 
        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null)
        {
          out.print(data);
        }
        out.print("-->");
 
        if (prettyprint)
        {
          out.print('\n');
        }
 
        break;
      }
    }
 
    if (type == Node.ELEMENT_NODE)
    {
      if (prettyprint)
        prettyIndent--;
 
      if (hasChildNodes == false)
      {
        out.print("/>");
      }
      else
      {
        if (indentEndMarker)
        {
          for (int i = 0; i < prettyIndent; i++)
          {
            out.print(' ');
          }
        }
 
        out.print("</");
        out.print(nodeName);
        out.print('>');
      }
 
      if (prettyIndent > 0)
      {
        out.print('\n');
      }
    }
    out.flush();
  }
 
  private String getNamespaceURI(String prefix, Element element, Node stopNode)
  {
    Node parent = element.getParentNode();
    String nsURI = element.getAttribute("xmlns:" + prefix);
    if (nsURI.length() == 0 && element != stopNode && parent instanceof Element)
      return getNamespaceURI(prefix, (Element)parent, stopNode);
 
    return (nsURI.length() > 0 ? nsURI : null);
  }
 
  private boolean isEndMarkerIndented(Node node)
  {
    if (prettyprint)
    {
      NodeList childNodes = node.getChildNodes();
      int len = childNodes.getLength();
      for (int i = 0; i < len; i++)
      {
        Node children = childNodes.item(i);
        if (children.getNodeType() == Node.ELEMENT_NODE)
        {
          return true;
        }
      }
    }
    return false;
  }
 
  /** Returns a sorted list of attributes. */
  private Attr[] sortAttributes(NamedNodeMap attrs)
  {
 
    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++)
    {
      array[i] = (Attr)attrs.item(i);
    }
    for (int i = 0; i < len - 1; i++)
    {
      String name = array[i].getNodeName();
      int index = i;
      for (int j = i + 1; j < len; j++)
      {
        String curName = array[j].getNodeName();
        if (curName.compareTo(name) < 0)
        {
          name = curName;
          index = j;
        }
      }
      if (index != i)
      {
        Attr temp = array[i];
        array[i] = array[index];
        array[index] = temp;
      }
    }
    return (array);
  }
 
  /** Normalizes the given string. */
  public static String normalize(String s, boolean canonical)
  {
      StringBuilder normal = new StringBuilder();
 
    int len = (s != null) ? s.length() : 0;
    for (int i = 0; i < len; i++)
    {
      char ch = s.charAt(i);
      switch (ch)
      {
        case '<':
        {
          normal.append("&lt;");
          break;
        }
        case '>':
        {
          normal.append("&gt;");
          break;
        }
        case '&':
        {
          normal.append("&amp;");
          break;
        }
        case '"':
        {
          normal.append("&quot;");
          break;
        }
        case '\'':
        {
          normal.append("&apos;");
          break;
        }
        case '\r':
        case '\n':
        {
          if (canonical)
          {
            normal.append("&#");
            normal.append(Integer.toString(ch));
            normal.append(';');
            break;
          }
          // else, default append char
        }
        default:
        {
          normal.append(ch);
        }
      }
    }
    return (normal.toString());
  }
}