File: XmlReader.java

package info (click to toggle)
ruby-nokogiri 1.13.10%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,416 kB
  • sloc: ansic: 38,198; xml: 28,086; ruby: 22,271; java: 15,517; cpp: 7,037; yacc: 244; sh: 148; makefile: 136
file content (614 lines) | stat: -rw-r--r-- 17,854 bytes parent folder | download
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
package nokogiri;

import static nokogiri.internals.NokogiriHelpers.getNokogiriClass;
import static nokogiri.internals.NokogiriHelpers.stringOrBlank;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.xs.opti.DefaultXMLDocumentHandler;
import org.apache.xerces.parsers.StandardParserConfiguration;
import org.apache.xerces.util.EntityResolver2Wrapper;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParseException;
import org.apache.xerces.xni.parser.XMLPullParserConfiguration;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.IOInputStream;
import org.xml.sax.InputSource;

import nokogiri.internals.NokogiriEntityResolver;
import nokogiri.internals.ParserContext;
import nokogiri.internals.ParserContext.Options;
import nokogiri.internals.ReaderNode;
import nokogiri.internals.ReaderNode.ClosingNode;
import nokogiri.internals.ReaderNode.ElementNode;
import nokogiri.internals.ReaderNode.TextNode;

/**
 * Class for Nokogiri:XML::Reader
 *
 * @author sergio
 * @author Yoko Harada <yokolet@gmail.com>
 */
@JRubyClass(name = "Nokogiri::XML::Reader")
public class XmlReader extends RubyObject
{

  private static final int XML_TEXTREADER_MODE_INITIAL = 0;
  private static final int XML_TEXTREADER_MODE_INTERACTIVE = 1;
  private static final int XML_TEXTREADER_MODE_ERROR = 2;
  private static final int XML_TEXTREADER_MODE_EOF = 3;
  private static final int XML_TEXTREADER_MODE_CLOSED = 4;
  private static final int XML_TEXTREADER_MODE_READING = 5;

  List<ReaderNode> nodeQueue;
  private int state;
  private int position = 0;
  private XMLPullParserConfiguration config;
  private boolean continueParsing = true;

  public
  XmlReader(Ruby runtime, RubyClass klazz)
  {
    super(runtime, klazz);
  }

  /**
   * Create and return a copy of this object.
   *
   * @return a clone of this object
   */
  @Override
  public Object
  clone() throws CloneNotSupportedException
  {
    return super.clone();
  }

  public void
  init(Ruby runtime)
  {
    nodeQueue = new LinkedList<ReaderNode>();
    nodeQueue.add(new ReaderNode.EmptyNode(runtime));
  }

  private void
  setInput(ThreadContext context, InputStream in, IRubyObject url, Options options)
  {
    this.setState(XML_TEXTREADER_MODE_READING);
    config = this.createReader(context.getRuntime(), options);
    InputSource inputSource = new InputSource();
    ParserContext.setUrl(context, inputSource, url);
    XMLInputSource xmlInputSource = new XMLInputSource(inputSource.getPublicId(),
        inputSource.getSystemId(), null, in, null);
    try {
      config.setInputSource(xmlInputSource);
    } catch (IOException e) {
      throw context.getRuntime().newRuntimeError(e.getMessage());
    }
    this.setState(XML_TEXTREADER_MODE_CLOSED);
  }

  private void
  setState(int state) { this.state = state; }

  @JRubyMethod
  public IRubyObject
  attribute(ThreadContext context, IRubyObject name)
  {
    return currentNode().getAttributeByName(name);
  }

  @JRubyMethod
  public IRubyObject
  attribute_at(ThreadContext context, IRubyObject index)
  {
    return currentNode().getAttributeByIndex(index);
  }

  @JRubyMethod
  public IRubyObject
  attribute_count(ThreadContext context)
  {
    return currentNode().getAttributeCount();
  }

  @JRubyMethod
  public IRubyObject
  attribute_nodes(ThreadContext context)
  {
    context.runtime.getWarnings().warn("Reader#attribute_nodes is deprecated and will be removed in a future version of Nokogiri. Please use Reader#attribute_hash instead.");
    return currentNode().getAttributesNodes();
  }

  @JRubyMethod
  public IRubyObject
  attribute_hash(ThreadContext context)
  {
    return currentNode().getAttributes(context);
  }

  @JRubyMethod(name = "attributes?")
  public IRubyObject
  attributes_p(ThreadContext context)
  {
    return currentNode().hasAttributes();
  }

  @JRubyMethod
  public IRubyObject
  base_uri(ThreadContext context)
  {
    return currentNode().getXmlBase();
  }

  @JRubyMethod(name = "default?")
  public IRubyObject
  default_p(ThreadContext context)
  {
    return currentNode().isDefault();
  }

  @JRubyMethod
  public IRubyObject
  depth(ThreadContext context)
  {
    return currentNode().getDepth();
  }

  @JRubyMethod(name = {"empty_element?", "self_closing?"})
  public IRubyObject
  empty_element_p(ThreadContext context)
  {
    ReaderNode readerNode = currentNode();
    ensureNodeClosed(context);

    if (readerNode == null) { return context.getRuntime().getNil(); }
    if (!(readerNode instanceof ElementNode)) { context.getRuntime().getFalse(); }
    return RubyBoolean.newBoolean(context.getRuntime(), !readerNode.hasChildren);
  }

  @JRubyMethod
  public IRubyObject
  encoding(ThreadContext context)
  {
    IRubyObject constructor_encoding = getInstanceVariable("@encoding");
    if (!constructor_encoding.isNil()) {
      return constructor_encoding;
    }
    // TODO: get the parser's detected encoding
    return context.getRuntime().getNil();
  }

  @JRubyMethod(meta = true, rest = true)
  public static IRubyObject
  from_io(ThreadContext context, IRubyObject cls, IRubyObject args[])
  {
    // Only to pass the  source test.
    Ruby runtime = context.getRuntime();
    // Not nil allowed!
    if (args[0].isNil()) { throw runtime.newArgumentError("io cannot be nil"); }

    XmlReader reader = (XmlReader) NokogiriService.XML_READER_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime,
                       "Nokogiri::XML::Reader"));
    reader.init(runtime);
    reader.setInstanceVariable("@source", args[0]);
    reader.setInstanceVariable("@errors", runtime.newArray());
    IRubyObject url = context.nil;
    if (args.length > 1) { url = args[1]; }
    if (args.length > 2) { reader.setInstanceVariable("@encoding", args[2]); }

    Options options;
    if (args.length > 3) {
      options = new ParserContext.Options((Long)args[3].toJava(Long.class));
    } else {
      // use the default options RECOVER | NONET
      options = new ParserContext.Options(2048 | 1);
    }

    InputStream in = new IOInputStream(args[0]);
    reader.setInput(context, in, url, options);
    return reader;
  }

  @JRubyMethod(meta = true, rest = true)
  public static IRubyObject
  from_memory(ThreadContext context, IRubyObject cls, IRubyObject args[])
  {
    // args[0]: string, args[1]: url, args[2]: encoding, args[3]: options
    Ruby runtime = context.getRuntime();
    // Not nil allowed!
    if (args[0].isNil()) { throw runtime.newArgumentError("string cannot be nil"); }

    XmlReader reader = (XmlReader) NokogiriService.XML_READER_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime,
                       "Nokogiri::XML::Reader"));
    reader.init(runtime);
    reader.setInstanceVariable("@source", args[0]);
    reader.setInstanceVariable("@errors", runtime.newArray());
    IRubyObject url = context.nil;
    if (args.length > 1) { url = args[1]; }
    if (args.length > 2) { reader.setInstanceVariable("@encoding", args[2]); }

    Options options;
    if (args.length > 3) {
      options = new ParserContext.Options((Long)args[3].toJava(Long.class));
    } else {
      // use the default options RECOVER | NONET
      options = new ParserContext.Options(2048 | 1);
    }
    IRubyObject stringIO = runtime.getClass("StringIO").newInstance(context, args[0], Block.NULL_BLOCK);
    InputStream in = new IOInputStream(stringIO);
    reader.setInput(context, in, url, options);
    return reader;
  }

  @JRubyMethod
  public IRubyObject
  node_type(ThreadContext context)
  {
    IRubyObject node_type = currentNode().getNodeType();
    return node_type == null ? RubyFixnum.zero(context.getRuntime()) : node_type;
  }

  @JRubyMethod
  public IRubyObject
  inner_xml(ThreadContext context)
  {
    ensureNodeClosed(context);
    return stringOrBlank(context.getRuntime(), getInnerXml(currentNode()));
  }

  private String
  getInnerXml(ReaderNode current)
  {
    if (current.depth < 0) { return null; }
    if (!current.hasChildren) { return null; }
    StringBuffer sb = new StringBuffer();
    for (int i = current.startOffset + 1; i <= current.endOffset - 1; i++) {
      sb.append(nodeQueue.get(i).getString());
    }
    return new String(sb);
  }

  @JRubyMethod
  public IRubyObject
  outer_xml(ThreadContext context)
  {
    ensureNodeClosed(context);
    return stringOrBlank(context.getRuntime(), getOuterXml());
  }

  private String
  getOuterXml()
  {
    ReaderNode current = currentNode();
    if (current == null || current.depth < 0) { return null; }

    if (current instanceof ClosingNode) {
      return "<" + current.name + "/>";
    }

    StringBuilder sb = new StringBuilder();
    for (int i = position; i <= current.endOffset; i++) {
      sb.append(nodeQueue.get(i).getString());
    }
    return new String(sb);
  }

  @JRubyMethod
  public IRubyObject
  lang(ThreadContext context)
  {
    return currentNode().getLang();
  }

  @JRubyMethod
  public IRubyObject
  local_name(ThreadContext context)
  {
    return currentNode().getLocalName();
  }

  @JRubyMethod
  public IRubyObject
  name(ThreadContext context)
  {
    return currentNode().getName();
  }

  @JRubyMethod
  public IRubyObject
  namespace_uri(ThreadContext context)
  {
    return currentNode().getUri();
  }

  @JRubyMethod
  public IRubyObject
  namespaces(ThreadContext context)
  {
    return currentNode().getNamespaces(context);
  }

  @JRubyMethod
  public IRubyObject
  prefix(ThreadContext context)
  {
    return currentNode().getPrefix();
  }

  private void
  readMoreData(ThreadContext context)
  {
    if (!continueParsing) { throw context.runtime.newRuntimeError("Cannot parse more data"); }
    try {
      continueParsing = config.parse(false);
    } catch (XNIException e) {
      throw XmlSyntaxError.createXMLSyntaxError(context.runtime, e).toThrowable(); // Nokogiri::XML::SyntaxError
    } catch (IOException e) {
      throw context.runtime.newRuntimeError(e.toString());
    }
  }

  private void
  ensureNodeClosed(ThreadContext context)
  {
    ReaderNode node = currentNode();
    if (node instanceof TextNode) { return; }
    while (node.endOffset < 1) { readMoreData(context); }
  }

  @JRubyMethod
  public IRubyObject
  read(ThreadContext context)
  {
    position++;
    try {
      while (nodeQueue.size() <= position && continueParsing) {
        readMoreData(context);
      }
      return setAndRaiseErrorsIfAny(context.runtime, null);
    } catch (RaiseException ex) {
      return setAndRaiseErrorsIfAny(context.runtime, ex);
    }
  }

  private IRubyObject
  setAndRaiseErrorsIfAny(final Ruby runtime, final RaiseException ex) throws RaiseException
  {
    final ReaderNode currentNode = currentNode();
    if (currentNode == null) { return runtime.getNil(); }
    if (currentNode.isError()) {
      RubyArray errors = (RubyArray) getInstanceVariable("@errors");
      IRubyObject error = currentNode.toSyntaxError();
      errors.append(error);
      setInstanceVariable("@errors", errors);

      throw ex != null ? ex : ((XmlSyntaxError) error).toThrowable();
    }
    if (ex != null) { throw ex; }
    return this;
  }

  private ReaderNode
  currentNode()
  {
    if (position >= nodeQueue.size()) { return null; }
    return nodeQueue.get(position);
  }

  @JRubyMethod
  public IRubyObject
  state(ThreadContext context)
  {
    return context.getRuntime().newFixnum(this.state);
  }

  @JRubyMethod
  public IRubyObject
  value(ThreadContext context)
  {
    return currentNode().getValue();
  }

  @JRubyMethod(name = "value?")
  public IRubyObject
  value_p(ThreadContext context)
  {
    return currentNode().hasValue();
  }

  @JRubyMethod
  public IRubyObject
  xml_version(ThreadContext context)
  {
    return currentNode().getXmlVersion();
  }

  protected XMLPullParserConfiguration
  createReader(Ruby ruby, Options options)
  {
    StandardParserConfiguration config = new StandardParserConfiguration();
    DocumentHandler handler = new DocumentHandler(ruby);
    // XMLReader reader = XMLReaderFactory.createXMLReader();
    config.setDocumentHandler(handler);
    config.setDTDHandler(handler);
    config.setErrorHandler(handler);
    config.setEntityResolver(new EntityResolver2Wrapper(new NokogiriEntityResolver(ruby, null, options)));
    // config.setFeature("http://xml.org/sax/features/xmlns-uris", true);
    // config.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    config.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", options.dtdLoad
                      || options.dtdValid);
    return config;
  }

  private class DocumentHandler extends DefaultXMLDocumentHandler implements XMLErrorHandler
  {

    Stack<String> langStack;
    int depth;
    Stack<String> xmlBaseStack;
    Stack<ReaderNode.ElementNode> elementStack;
    private final Ruby ruby;

    public
    DocumentHandler(Ruby ruby)
    {
      this.ruby = ruby;
    }

    @Override
    public void
    startGeneralEntity(String name, XMLResourceIdentifier identifier,
                       String encoding, Augmentations augs) throws XNIException
    {
      Object entitySkipped;
      if (augs != null && (entitySkipped = augs.getItem(Constants.ENTITY_SKIPPED)) != null && ((Boolean) entitySkipped)) {
        nodeQueue.add(new ReaderNode.ExceptionNode(ruby, null));
      }
    }



    @Override
    public void
    startDocument(XMLLocator locator, String encoding, NamespaceContext context, Augmentations augs)
    {
      depth = 0;
      langStack = new Stack<String>();
      xmlBaseStack = new Stack<String>();
      elementStack = new Stack<ReaderNode.ElementNode>();
    }

    @Override
    public void
    endDocument(Augmentations augs)
    {
      langStack = null;
      xmlBaseStack = null;
      elementStack = null;
    }

    @Override
    public void
    startElement(QName element, XMLAttributes attrs, Augmentations augs)
    {
      commonElement(element, attrs, false);
    }

    @Override
    public void
    endElement(QName element, Augmentations augs)
    {
      String uri = element.uri;
      String localName = element.localpart;
      String qName = element.rawname;
      depth--;
      ElementNode startElementNode = elementStack.pop();
      ReaderNode node = ReaderNode.createClosingNode(ruby, uri, localName, qName, depth, langStack, xmlBaseStack);

      startElementNode.endOffset = nodeQueue.size() - 1;

      if (startElementNode.endOffset != startElementNode.startOffset) {
        // this node isn't empty
        node.attributeList = startElementNode.attributeList;
        node.namespaces = startElementNode.namespaces;
        node.startOffset = startElementNode.startOffset;
        node.endOffset = ++startElementNode.endOffset;
        node.hasChildren = startElementNode.hasChildren = true;
        nodeQueue.add(node);
      }
      if (!langStack.isEmpty()) { langStack.pop(); }
      if (!xmlBaseStack.isEmpty()) { xmlBaseStack.pop(); }
    }

    @Override
    public void
    emptyElement(QName element, XMLAttributes attrs, Augmentations augs)
    {
      commonElement(element, attrs, true);
    }

    private void
    commonElement(QName element, XMLAttributes attrs, boolean isEmpty)
    {
      String qName = element.rawname;
      String uri = element.uri;
      String localName = element.localpart;
      ReaderNode readerNode = ReaderNode.createElementNode(ruby, uri, localName, qName, attrs, depth, langStack,
                              xmlBaseStack);
      if (!elementStack.isEmpty()) {
        ElementNode parent = elementStack.peek();
        parent.hasChildren = true;
      }
      nodeQueue.add(readerNode);
      readerNode.startOffset = nodeQueue.size() - 1;
      if (!isEmpty) {
        depth++;
        if (readerNode.lang != null) { langStack.push(readerNode.lang); }
        if (readerNode.xmlBase != null) { xmlBaseStack.push(readerNode.xmlBase); }
        elementStack.push((ReaderNode.ElementNode)readerNode);
      } else {
        readerNode.endOffset = readerNode.startOffset;
        readerNode.hasChildren = false;
      }
    }

    @Override
    public void
    characters(XMLString string, Augmentations augs)
    {
      ReaderNode.TextNode node = ReaderNode.createTextNode(ruby, string.toString(), depth, langStack, xmlBaseStack);
      nodeQueue.add(node);
      node.startOffset = node.endOffset = nodeQueue.size() - 1;
    }

    @Override
    public void
    error(String domain, String key, XMLParseException ex)
    {
      nodeQueue.add(new ReaderNode.ExceptionNode(ruby, ex));
      throw ex;
    }

    @Override
    public void
    fatalError(String domain, String key, XMLParseException ex)
    {
      nodeQueue.add(new ReaderNode.ExceptionNode(ruby, ex));
      throw ex;
    }

    @Override
    public void
    warning(String domain, String key, XMLParseException ex)
    {
      nodeQueue.add(new ReaderNode.ExceptionNode(ruby, ex));
      throw ex;
    }
  }
}