OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libjava/] [classpath/] [gnu/] [xml/] [transform/] [TransformerImpl.java] - Blame information for rev 769

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 769 jeremybenn
/* TransformerImpl.java --
2
   Copyright (C) 2004,2005,2006 Free Software Foundation, Inc.
3
 
4
This file is part of GNU Classpath.
5
 
6
GNU Classpath is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2, or (at your option)
9
any later version.
10
 
11
GNU Classpath is distributed in the hope that it will be useful, but
12
WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
General Public License for more details.
15
 
16
You should have received a copy of the GNU General Public License
17
along with GNU Classpath; see the file COPYING.  If not, write to the
18
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
02110-1301 USA.
20
 
21
Linking this library statically or dynamically with other modules is
22
making a combined work based on this library.  Thus, the terms and
23
conditions of the GNU General Public License cover the whole
24
combination.
25
 
26
As a special exception, the copyright holders of this library give you
27
permission to link this library with independent modules to produce an
28
executable, regardless of the license terms of these independent
29
modules, and to copy and distribute the resulting executable under
30
terms of your choice, provided that you also meet, for each linked
31
independent module, the terms and conditions of the license of that
32
module.  An independent module is a module which is not derived from
33
or based on this library.  If you modify this library, you may extend
34
this exception to your version of the library, but you are not
35
obligated to do so.  If you do not wish to do so, delete this
36
exception statement from your version. */
37
 
38
package gnu.xml.transform;
39
 
40
import gnu.java.lang.CPStringBuilder;
41
 
42
import java.io.BufferedOutputStream;
43
import java.io.FileOutputStream;
44
import java.io.IOException;
45
import java.io.OutputStream;
46
import java.io.UnsupportedEncodingException;
47
import java.io.Writer;
48
import java.net.MalformedURLException;
49
import java.net.UnknownServiceException;
50
import java.net.URL;
51
import java.net.URLConnection;
52
import java.util.Collection;
53
import java.util.Iterator;
54
import java.util.LinkedList;
55
import java.util.List;
56
import java.util.Properties;
57
import java.util.StringTokenizer;
58
import javax.xml.namespace.QName;
59
import javax.xml.transform.ErrorListener;
60
import javax.xml.transform.OutputKeys;
61
import javax.xml.transform.Result;
62
import javax.xml.transform.Source;
63
import javax.xml.transform.Transformer;
64
import javax.xml.transform.TransformerConfigurationException;
65
import javax.xml.transform.TransformerException;
66
import javax.xml.transform.URIResolver;
67
import javax.xml.transform.dom.DOMSource;
68
import javax.xml.transform.dom.DOMResult;
69
import javax.xml.transform.sax.SAXResult;
70
import javax.xml.transform.stream.StreamResult;
71
import org.w3c.dom.Document;
72
import org.w3c.dom.DocumentType;
73
import org.w3c.dom.DOMImplementation;
74
import org.w3c.dom.Node;
75
import org.w3c.dom.Text;
76
import org.xml.sax.ContentHandler;
77
import org.xml.sax.SAXException;
78
import org.xml.sax.ext.LexicalHandler;
79
import gnu.xml.dom.DomDoctype;
80
import gnu.xml.dom.DomDocument;
81
import gnu.xml.dom.ls.WriterOutputStream;
82
 
83
/**
84
 * The transformation process for a given stylesheet.
85
 *
86
 * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
87
 */
88
class TransformerImpl
89
  extends Transformer
90
{
91
 
92
  final TransformerFactoryImpl factory;
93
  final Stylesheet stylesheet;
94
  URIResolver uriResolver;
95
  ErrorListener errorListener;
96
  Properties outputProperties;
97
 
98
  TransformerImpl(TransformerFactoryImpl factory,
99
                  Stylesheet stylesheet,
100
                  Properties outputProperties)
101
    throws TransformerConfigurationException
102
  {
103
    this.factory = factory;
104
    uriResolver = factory.userResolver;
105
    errorListener = factory.userListener;
106
    this.stylesheet = stylesheet;
107
    this.outputProperties = outputProperties;
108
    if (stylesheet != null)
109
      {
110
        // Set up parameter context for this transformer
111
        stylesheet.bindings.push(Bindings.PARAM);
112
      }
113
  }
114
 
115
  public void transform(Source xmlSource, Result outputTarget)
116
    throws TransformerException
117
  {
118
    // Get the source tree
119
    DOMSource source;
120
    synchronized (factory.resolver)
121
      {
122
        factory.resolver.setUserResolver(uriResolver);
123
        factory.resolver.setUserListener(errorListener);
124
        source = factory.resolver.resolveDOM(xmlSource, null, null);
125
      }
126
    Node context = source.getNode();
127
    Document doc = (context instanceof Document) ? (Document) context :
128
      context.getOwnerDocument();
129
    if (doc instanceof DomDocument)
130
      {
131
        // Suppress mutation events
132
        ((DomDocument) doc).setBuilding(true);
133
      }
134
    // Get the result tree
135
    Node parent = null, nextSibling = null;
136
    if (outputTarget instanceof DOMResult)
137
      {
138
        DOMResult dr = (DOMResult) outputTarget;
139
        parent = dr.getNode();
140
        nextSibling = dr.getNextSibling();
141
 
142
        Document rdoc = (parent instanceof Document) ? (Document) parent :
143
          parent.getOwnerDocument();
144
        if (rdoc instanceof DomDocument)
145
          {
146
            // Suppress mutation events and allow multiple root elements
147
            DomDocument drdoc = (DomDocument) rdoc;
148
            drdoc.setBuilding(true);
149
            drdoc.setCheckWellformedness(false);
150
          }
151
      }
152
    boolean created = false;
153
    // Transformation
154
    if (stylesheet != null)
155
      {
156
        if (parent == null)
157
          {
158
            // Create a new document to hold the result
159
            DomDocument resultDoc = new DomDocument();
160
            resultDoc.setBuilding(true);
161
            resultDoc.setCheckWellformedness(false);
162
            parent = resultDoc;
163
            created = true;
164
          }
165
        // Make a copy of the source node, and strip it
166
        context = context.cloneNode(true);
167
        strip(stylesheet, context);
168
        // XSLT transformation
169
        try
170
          {
171
            // Set output properties in the underlying stylesheet
172
            ((TransformerOutputProperties) outputProperties).apply();
173
            stylesheet.initTopLevelVariables(context);
174
            TemplateNode t = stylesheet.getTemplate(null, context, false);
175
            if (t != null)
176
              {
177
                stylesheet.current = context;
178
                t.apply(stylesheet, null, context, 1, 1, parent, nextSibling);
179
              }
180
          }
181
        catch (TransformerException e)
182
          {
183
            // Done transforming, reset document
184
            if (doc instanceof DomDocument)
185
              ((DomDocument) doc).setBuilding(false);
186
            throw e;
187
          }
188
      }
189
    else
190
      {
191
        // Identity transform
192
        Node clone = context.cloneNode(true);
193
        if (context.getNodeType() != Node.DOCUMENT_NODE)
194
          {
195
            Document resultDoc;
196
            if (parent == null)
197
              {
198
                // Create a new document to hold the result
199
                DomDocument rd = new DomDocument();
200
                rd.setBuilding(true);
201
                rd.setCheckWellformedness(false);
202
                parent = resultDoc = rd;
203
                created = true;
204
              }
205
            else
206
              {
207
                resultDoc = (parent instanceof Document) ?
208
                  (Document) parent :
209
                  parent.getOwnerDocument();
210
              }
211
            Document sourceDoc = context.getOwnerDocument();
212
            if (sourceDoc != resultDoc)
213
              clone = resultDoc.adoptNode(clone);
214
            if (nextSibling != null)
215
              parent.insertBefore(clone, nextSibling);
216
            else
217
              parent.appendChild(clone);
218
          }
219
        else
220
          {
221
            // Cannot append document to another tree
222
            parent = clone;
223
            created = true;
224
          }
225
      }
226
    String method = outputProperties.getProperty(OutputKeys.METHOD);
227
    int outputMethod = "html".equals(method) ? Stylesheet.OUTPUT_HTML :
228
      "text".equals(method) ? Stylesheet.OUTPUT_TEXT :
229
      Stylesheet.OUTPUT_XML;
230
    String encoding = outputProperties.getProperty(OutputKeys.ENCODING);
231
    String publicId = outputProperties.getProperty(OutputKeys.DOCTYPE_PUBLIC);
232
    String systemId = outputProperties.getProperty(OutputKeys.DOCTYPE_SYSTEM);
233
    String version = outputProperties.getProperty(OutputKeys.VERSION);
234
    boolean omitXmlDeclaration =
235
      "yes".equals(outputProperties.getProperty(OutputKeys.OMIT_XML_DECLARATION));
236
    boolean standalone =
237
      "yes".equals(outputProperties.getProperty(OutputKeys.STANDALONE));
238
    String mediaType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
239
    String cdataSectionElements =
240
      outputProperties.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
241
    boolean indent =
242
      "yes".equals(outputProperties.getProperty(OutputKeys.INDENT));
243
    if (created && parent instanceof DomDocument)
244
      {
245
        // Discover document element
246
        DomDocument resultDoc = (DomDocument) parent;
247
        Node root = resultDoc.getDocumentElement();
248
        // Add doctype if specified
249
        if (publicId != null || systemId != null)
250
          {
251
            if (root != null)
252
              {
253
                // We must know the name of the root element to
254
                // create the document type
255
                DocumentType doctype = new DomDoctype(resultDoc,
256
                                                      root.getNodeName(),
257
                                                      publicId,
258
                                                      systemId);
259
                resultDoc.insertBefore(doctype, root);
260
              }
261
          }
262
        resultDoc.setBuilding(false);
263
        resultDoc.setCheckWellformedness(true);
264
      }
265
    else if (publicId != null || systemId != null)
266
      {
267
        switch (parent.getNodeType())
268
          {
269
          case Node.DOCUMENT_NODE:
270
          case Node.DOCUMENT_FRAGMENT_NODE:
271
            Document resultDoc = (parent instanceof Document) ?
272
              (Document) parent :
273
              parent.getOwnerDocument();
274
            DOMImplementation impl = resultDoc.getImplementation();
275
            Node root = resultDoc.getDocumentElement();
276
            if (root != null)
277
              {
278
                DocumentType doctype =
279
                  impl.createDocumentType(root.getNodeName(),
280
                                          publicId,
281
                                          systemId);
282
                resultDoc.insertBefore(doctype, root);
283
              }
284
          }
285
      }
286
    if (version != null)
287
      parent.setUserData("version", version, stylesheet);
288
    if (omitXmlDeclaration)
289
      parent.setUserData("omit-xml-declaration", "yes", stylesheet);
290
    if (standalone)
291
      parent.setUserData("standalone", "yes", stylesheet);
292
    if (mediaType != null)
293
      parent.setUserData("media-type", mediaType, stylesheet);
294
    if (cdataSectionElements != null)
295
      {
296
        List list = new LinkedList();
297
        StringTokenizer st = new StringTokenizer(cdataSectionElements);
298
        while (st.hasMoreTokens())
299
          {
300
            String name = st.nextToken();
301
            String localName = name;
302
            String uri = null;
303
            String prefix = null;
304
            int ci = name.indexOf(':');
305
            if (ci != -1)
306
              {
307
                // Use namespaces defined on xsl:output node to resolve
308
                // namespaces for QName
309
                prefix = name.substring(0, ci);
310
                localName = name.substring(ci + 1);
311
                uri = stylesheet.output.lookupNamespaceURI(prefix);
312
              }
313
            list.add(new QName(uri, localName, prefix));
314
          }
315
        if (!list.isEmpty())
316
          {
317
            Document resultDoc = (parent instanceof Document) ?
318
              (Document) parent :
319
              parent.getOwnerDocument();
320
            convertCdataSectionElements(resultDoc, parent, list);
321
          }
322
      }
323
    if (indent)
324
      {
325
        if (created && parent instanceof DomDocument)
326
          {
327
            DomDocument domDoc = (DomDocument) parent;
328
            domDoc.setBuilding(true);
329
            domDoc.setCheckWellformedness(false);
330
          }
331
        parent.normalize();
332
        if (stylesheet != null)
333
          strip(stylesheet, parent);
334
        Document resultDoc = (parent instanceof Document) ?
335
          (Document) parent :
336
          parent.getOwnerDocument();
337
        reindent(resultDoc, parent, 0);
338
        if (created && parent instanceof DomDocument)
339
          {
340
            DomDocument domDoc = (DomDocument) parent;
341
            domDoc.setBuilding(false);
342
            domDoc.setCheckWellformedness(true);
343
          }
344
      }
345
    // Render result to the target device
346
    if (outputTarget instanceof DOMResult)
347
      {
348
        if (created)
349
          {
350
            DOMResult dr = (DOMResult) outputTarget;
351
            dr.setNode(parent);
352
            dr.setNextSibling(null);
353
          }
354
      }
355
    else if (outputTarget instanceof StreamResult)
356
      {
357
        StreamResult sr = (StreamResult) outputTarget;
358
        IOException ex = null;
359
        try
360
          {
361
            writeStreamResult(parent, sr, outputMethod, encoding);
362
          }
363
        catch (UnsupportedEncodingException e)
364
          {
365
            try
366
              {
367
                writeStreamResult(parent, sr, outputMethod, "UTF-8");
368
              }
369
            catch (IOException e2)
370
              {
371
                ex = e2;
372
              }
373
          }
374
        catch (IOException e)
375
          {
376
            ex = e;
377
          }
378
        if (ex != null)
379
          {
380
            if (errorListener != null)
381
              errorListener.error(new TransformerException(ex));
382
            else
383
              ex.printStackTrace(System.err);
384
          }
385
      }
386
    else if (outputTarget instanceof SAXResult)
387
      {
388
        SAXResult sr = (SAXResult) outputTarget;
389
        try
390
          {
391
            ContentHandler ch = sr.getHandler();
392
            LexicalHandler lh = sr.getLexicalHandler();
393
            if (lh == null && ch instanceof LexicalHandler)
394
              lh = (LexicalHandler) ch;
395
            SAXSerializer serializer = new SAXSerializer();
396
            serializer.serialize(parent, ch, lh);
397
          }
398
        catch (SAXException e)
399
          {
400
            if (errorListener != null)
401
              errorListener.error(new TransformerException(e));
402
            else
403
              e.printStackTrace(System.err);
404
          }
405
      }
406
  }
407
 
408
  /**
409
   * Strip whitespace from the source tree.
410
   */
411
  static boolean strip(Stylesheet stylesheet, Node node)
412
    throws TransformerConfigurationException
413
  {
414
    short nt = node.getNodeType();
415
    if (nt == Node.ENTITY_REFERENCE_NODE)
416
      {
417
        // Replace entity reference with its content
418
        Node parent = node.getParentNode();
419
        Node nextSibling = node.getNextSibling();
420
        Node child = node.getFirstChild();
421
        while (child != null)
422
          {
423
            Node next = child.getNextSibling();
424
            node.removeChild(child);
425
            if (nextSibling != null)
426
              parent.insertBefore(child, nextSibling);
427
            else
428
              parent.appendChild(child);
429
            child = next;
430
          }
431
        return true;
432
      }
433
    if (nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE)
434
      {
435
        // Denormalize text into whitespace and non-whitespace nodes
436
        String text = node.getNodeValue();
437
        String[] tokens = tokenizeWhitespace(text);
438
        if (tokens.length > 1)
439
          {
440
            node.setNodeValue(tokens[0]);
441
            Node parent = node.getParentNode();
442
            Node nextSibling = node.getNextSibling();
443
            Document doc = node.getOwnerDocument();
444
            for (int i = 1; i < tokens.length; i++)
445
              {
446
                Node newChild = (nt == Node.CDATA_SECTION_NODE) ?
447
                  doc.createCDATASection(tokens[i]) :
448
                  doc.createTextNode(tokens[i]);
449
                if (nextSibling != null)
450
                  parent.insertBefore(newChild, nextSibling);
451
                else
452
                  parent.appendChild(newChild);
453
              }
454
          }
455
        return !stylesheet.isPreserved((Text) node, true);
456
      }
457
    else
458
      {
459
        Node child = node.getFirstChild();
460
        while (child != null)
461
          {
462
            boolean remove = strip(stylesheet, child);
463
            Node next = child.getNextSibling();
464
            if (remove)
465
              node.removeChild(child);
466
            child = next;
467
          }
468
      }
469
    return false;
470
  }
471
 
472
  /**
473
   * Tokenize the specified text into contiguous whitespace-only and
474
   * non-whitespace chunks.
475
   */
476
  private static String[] tokenizeWhitespace(String text)
477
  {
478
    int len = text.length();
479
    int start = 0, end = len - 1;
480
    // Find index of text start
481
    for (int i = 0; i < len; i++)
482
      {
483
        char c = text.charAt(i);
484
        boolean whitespace = (c == ' ' || c == '\n' || c == '\t' || c == '\r');
485
        if (whitespace)
486
          start++;
487
        else
488
          break;
489
      }
490
    if (start == end) // all whitespace
491
      return new String[] { text };
492
    // Find index of text end
493
    for (int i = end; i > start; i--)
494
      {
495
        char c = text.charAt(i);
496
        boolean whitespace = (c == ' ' || c == '\n' || c == '\t' || c == '\r');
497
        if (whitespace)
498
          end--;
499
        else
500
          break;
501
      }
502
    if (start == 0 && end == len - 1) // all non-whitespace
503
      return new String[] { text };
504
    // whitespace, then text, then whitespace
505
    String[] ret = (start > 0 && end < len - 1) ?
506
      new String[3] : new String[2];
507
    int i = 0;
508
    if (start > 0)
509
      ret[i++] = text.substring(0, start);
510
    ret[i++] = text.substring(start, end + 1);
511
    if (end < len - 1)
512
      ret[i++] = text.substring(end + 1);
513
    return ret;
514
  }
515
 
516
  /**
517
   * Obtain a suitable output stream for writing the result to,
518
   * and use the StreamSerializer to write the result tree to the stream.
519
   */
520
  void writeStreamResult(Node node, StreamResult sr, int outputMethod,
521
                         String encoding)
522
    throws IOException
523
  {
524
    OutputStream out = null;
525
    boolean created = false;
526
    try
527
      {
528
        out = sr.getOutputStream();
529
        if (out == null)
530
          {
531
            Writer writer = sr.getWriter();
532
            if (writer != null)
533
              out = new WriterOutputStream(writer);
534
          }
535
        if (out == null)
536
          {
537
            String systemId = sr.getSystemId();
538
            try
539
              {
540
                URL url = new URL(systemId);
541
                URLConnection connection = url.openConnection();
542
                // We need to call setDoInput(false), because our
543
                // implementation of the file protocol allows writing
544
                // (unlike Sun), but it will fail with a FileNotFoundException
545
                // if we also open the connection for input and the output
546
                // file doesn't yet exist.
547
                connection.setDoInput(false);
548
                connection.setDoOutput(true);
549
                out = connection.getOutputStream();
550
              }
551
            catch (MalformedURLException e)
552
              {
553
                out = new FileOutputStream(systemId);
554
              }
555
            catch (UnknownServiceException e)
556
              {
557
                URL url = new URL(systemId);
558
                out = new FileOutputStream(url.getPath());
559
              }
560
            created = true;
561
          }
562
        out = new BufferedOutputStream(out);
563
        StreamSerializer serializer =
564
          new StreamSerializer(outputMethod, encoding, null);
565
        if (stylesheet != null)
566
          {
567
            Collection celem = stylesheet.outputCdataSectionElements;
568
            serializer.setCdataSectionElements(celem);
569
          }
570
        serializer.serialize(node, out);
571
        out.flush();
572
      }
573
    finally
574
      {
575
        try
576
          {
577
            if (out != null && created)
578
              out.close();
579
          }
580
        catch (IOException e)
581
          {
582
            if (errorListener != null)
583
              {
584
                try
585
                  {
586
                    errorListener.error(new TransformerException(e));
587
                  }
588
                catch (TransformerException e2)
589
                  {
590
                    e2.printStackTrace(System.err);
591
                  }
592
              }
593
            else
594
              e.printStackTrace(System.err);
595
          }
596
      }
597
  }
598
 
599
  void copyChildren(Document dstDoc, Node src, Node dst)
600
  {
601
    Node srcChild = src.getFirstChild();
602
    while (srcChild != null)
603
      {
604
        Node dstChild = dstDoc.adoptNode(srcChild);
605
        dst.appendChild(dstChild);
606
        srcChild = srcChild.getNextSibling();
607
      }
608
  }
609
 
610
  public void setParameter(String name, Object value)
611
  {
612
    if (stylesheet != null)
613
      stylesheet.bindings.set(new QName(null, name), value, Bindings.PARAM);
614
  }
615
 
616
  public Object getParameter(String name)
617
  {
618
    if (stylesheet != null)
619
      return stylesheet.bindings.get(new QName(null, name), null, 1, 1);
620
    return null;
621
  }
622
 
623
  public void clearParameters()
624
  {
625
    if (stylesheet != null)
626
      {
627
        stylesheet.bindings.pop(Bindings.PARAM);
628
        stylesheet.bindings.push(Bindings.PARAM);
629
      }
630
  }
631
 
632
  public void setURIResolver(URIResolver resolver)
633
  {
634
    uriResolver = resolver;
635
  }
636
 
637
  public URIResolver getURIResolver()
638
  {
639
    return uriResolver;
640
  }
641
 
642
  public void setOutputProperties(Properties oformat)
643
    throws IllegalArgumentException
644
  {
645
    if (oformat == null)
646
      outputProperties.clear();
647
    else
648
      outputProperties.putAll(oformat);
649
  }
650
 
651
  public Properties getOutputProperties()
652
  {
653
    return (Properties) outputProperties.clone();
654
  }
655
 
656
  public void setOutputProperty(String name, String value)
657
    throws IllegalArgumentException
658
  {
659
    outputProperties.put(name, value);
660
  }
661
 
662
  public String getOutputProperty(String name)
663
    throws IllegalArgumentException
664
  {
665
    return outputProperties.getProperty(name);
666
  }
667
 
668
  public void setErrorListener(ErrorListener listener)
669
  {
670
    errorListener = listener;
671
  }
672
 
673
  public ErrorListener getErrorListener()
674
  {
675
    return errorListener;
676
  }
677
 
678
  static final String INDENT_WHITESPACE = "  ";
679
 
680
  /*
681
   * Apply indent formatting to the given tree.
682
   */
683
  void reindent(Document doc, Node node, int offset)
684
  {
685
    if (node.hasChildNodes())
686
      {
687
        boolean markupContent = false;
688
        boolean textContent = false;
689
        List children = new LinkedList();
690
        Node ctx = node.getFirstChild();
691
        while (ctx != null)
692
          {
693
            switch (ctx.getNodeType())
694
              {
695
              case Node.ELEMENT_NODE:
696
              case Node.PROCESSING_INSTRUCTION_NODE:
697
              case Node.DOCUMENT_TYPE_NODE:
698
                markupContent = true;
699
                break;
700
              case Node.TEXT_NODE:
701
              case Node.CDATA_SECTION_NODE:
702
              case Node.ENTITY_REFERENCE_NODE:
703
              case Node.COMMENT_NODE:
704
                textContent = true;
705
                break;
706
              }
707
            children.add(ctx);
708
            ctx = ctx.getNextSibling();
709
          }
710
        if (markupContent)
711
          {
712
            if (textContent)
713
              {
714
                // XXX handle mixed content differently?
715
              }
716
            int nodeType = node.getNodeType();
717
            if (nodeType == Node.DOCUMENT_NODE)
718
              {
719
                for (Iterator i = children.iterator(); i.hasNext(); )
720
                  {
721
                    ctx = (Node) i.next();
722
                    reindent(doc, ctx, offset);
723
                  }
724
              }
725
            else
726
              {
727
                CPStringBuilder buf = new CPStringBuilder();
728
                buf.append('\n');
729
                for (int i = 0; i < offset + 1; i++)
730
                  buf.append(INDENT_WHITESPACE);
731
                String ws = buf.toString();
732
                for (Iterator i = children.iterator(); i.hasNext(); )
733
                  {
734
                    ctx = (Node) i.next();
735
                    node.insertBefore(doc.createTextNode(ws), ctx);
736
                    reindent(doc, ctx, offset + 1);
737
                  }
738
                buf = new CPStringBuilder();
739
                buf.append('\n');
740
                for (int i = 0; i < offset; i++)
741
                  buf.append(INDENT_WHITESPACE);
742
                ws = buf.toString();
743
                node.appendChild(doc.createTextNode(ws));
744
              }
745
          }
746
      }
747
  }
748
 
749
  /**
750
   * Converts the text node children of any cdata-section-elements in the
751
   * tree to CDATA section nodes.
752
   */
753
  void convertCdataSectionElements(Document doc, Node node, List list)
754
  {
755
    if (node.getNodeType() == Node.ELEMENT_NODE)
756
      {
757
        boolean match = false;
758
        for (Iterator i = list.iterator(); i.hasNext(); )
759
          {
760
            QName qname = (QName) i.next();
761
            if (match(qname, node))
762
              {
763
                match = true;
764
                break;
765
              }
766
          }
767
        if (match)
768
          {
769
            Node ctx = node.getFirstChild();
770
            while (ctx != null)
771
              {
772
                if (ctx.getNodeType() == Node.TEXT_NODE)
773
                  {
774
                    Node cdata = doc.createCDATASection(ctx.getNodeValue());
775
                    node.replaceChild(cdata, ctx);
776
                    ctx = cdata;
777
                  }
778
                ctx = ctx.getNextSibling();
779
              }
780
          }
781
      }
782
    Node ctx = node.getFirstChild();
783
    while (ctx != null)
784
      {
785
        if (ctx.hasChildNodes())
786
          convertCdataSectionElements(doc, ctx, list);
787
        ctx = ctx.getNextSibling();
788
      }
789
  }
790
 
791
  boolean match(QName qname, Node node)
792
  {
793
    String ln1 = qname.getLocalPart();
794
    String ln2 = node.getLocalName();
795
    if (ln2 == null)
796
      return ln1.equals(node.getNodeName());
797
    else
798
      {
799
        String uri1 = qname.getNamespaceURI();
800
        String uri2 = node.getNamespaceURI();
801
        return (uri1.equals(uri2) && ln1.equals(ln2));
802
      }
803
  }
804
 
805
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.