File: NokogiriHandler.java

package info (click to toggle)
ruby-nokogiri 1.10.0%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,088 kB
  • sloc: xml: 28,081; ruby: 16,687; java: 13,293; ansic: 4,954; yacc: 265; sh: 76; makefile: 19
file content (330 lines) | stat: -rw-r--r-- 11,624 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
/**
 * (The MIT License)
 *
 * Copyright (c) 2008 - 2011:
 *
 * * {Aaron Patterson}[http://tenderlovemaking.com]
 * * {Mike Dalessio}[http://mike.daless.io]
 * * {Charles Nutter}[http://blog.headius.com]
 * * {Sergio Arbeo}[http://www.serabe.com]
 * * {Patrick Mahoney}[http://polycrystal.org]
 * * {Yoko Harada}[http://yokolet.blogspot.com]
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package nokogiri.internals;

import static nokogiri.internals.NokogiriHelpers.getLocalPart;
import static nokogiri.internals.NokogiriHelpers.getPrefix;
import static nokogiri.internals.NokogiriHelpers.isNamespace;
import static nokogiri.internals.NokogiriHelpers.stringOrNil;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

import nokogiri.XmlSyntaxError;

import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyObject;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ext.DefaultHandler2;

/**
 * A handler for SAX parsing.
 *
 * @author sergio
 * @author Yoko Harada <yokolet@gmail.com>
 */
public class NokogiriHandler extends DefaultHandler2 implements XmlDeclHandler {

    StringBuilder charactersBuilder;
    private final Ruby runtime;
    private final RubyClass attrClass;
    private final IRubyObject object;

    /**
     * Stores parse errors with the most-recent error last.
     *
     * TODO: should these be stored in the document 'errors' array?
     * Currently only string messages are stored there.
     */
    private final LinkedList<RaiseException> errors = new LinkedList<RaiseException>();

    private Locator locator;
    private boolean needEmptyAttrCheck;

    public NokogiriHandler(Ruby runtime, IRubyObject object) {
        assert object != null;
        this.runtime = runtime;
        this.attrClass = (RubyClass) runtime.getClassFromPath("Nokogiri::XML::SAX::Parser::Attribute");
        this.object = object;
        charactersBuilder = new StringBuilder();
        String objectName = object.getMetaClass().getName();
        if ("Nokogiri::HTML::SAX::Parser".equals(objectName)) needEmptyAttrCheck = true;
    }

    @Override
    public void skippedEntity(String skippedEntity) {
        call("error", runtime.newString("Entity '" + skippedEntity + "' not defined\n"));
    }

    @Override
    public void setDocumentLocator(Locator locator) {
        this.locator = locator;
    }

    @Override
    public void startDocument() {
        call("start_document");
    }

    @Override
    public void xmlDecl(String version, String encoding, String standalone) {
        call("xmldecl", stringOrNil(runtime, version), stringOrNil(runtime, encoding), stringOrNil(runtime, standalone));
    }

    @Override
    public void endDocument() {
        populateCharacters();
        call("end_document");
    }

    @Override
    public void processingInstruction(String target, String data) {
        call("processing_instruction", runtime.newString(target), runtime.newString(data));
    }

    /*
     * This calls "start_element_namespace".
     *
     * Attributes that define namespaces are passed in a separate
     * array of <code>[:prefix, :uri]</code> arrays and are not
     * passed with the other attributes.
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
        final Ruby runtime = this.runtime;
        final ThreadContext context = runtime.getCurrentContext();

        // for attributes other than namespace attrs
        RubyArray rubyAttr = RubyArray.newArray(runtime);
        // for namespace defining attributes
        RubyArray rubyNSAttr = RubyArray.newArray(runtime);

        boolean fromFragmentHandler = false; // isFromFragmentHandler();

        for (int i = 0; i < attrs.getLength(); i++) {
            String u = attrs.getURI(i);
            String qn = attrs.getQName(i);
            String ln = attrs.getLocalName(i);
            String val = attrs.getValue(i);
            String pre;

            pre = getPrefix(qn);
            if (ln == null || ln.isEmpty()) ln = getLocalPart(qn);

            if (isNamespace(qn) && !fromFragmentHandler) {
                // I haven't figured the reason out yet, but, in somewhere,
                // namespace is converted to array in array and cause
                // TypeError at line 45 in fragment_handler.rb
                if (ln.equals("xmlns")) ln = null;
                rubyNSAttr.append( runtime.newArray( stringOrNil(runtime, ln), runtime.newString(val) ) );
            } else {
                IRubyObject[] args = null;
                if (needEmptyAttrCheck) {
                    if (isEmptyAttr(ln)) {
                        args = new IRubyObject[] {
                            stringOrNil(runtime, ln),
                            stringOrNil(runtime, pre),
                            stringOrNil(runtime, u)
                        };
                    }
                }
                if (args == null) {
                    args = new IRubyObject[] {
                        stringOrNil(runtime, ln),
                        stringOrNil(runtime, pre),
                        stringOrNil(runtime, u),
                        stringOrNil(runtime, val)
                    };
                }

                rubyAttr.append( RuntimeHelpers.invoke(context, attrClass, "new", args) );
            }
        }

        if (localName == null || localName.isEmpty()) localName = getLocalPart(qName);
        populateCharacters();
        call("start_element_namespace",
             stringOrNil(runtime, localName),
             rubyAttr,
             stringOrNil(runtime, getPrefix(qName)),
             stringOrNil(runtime, uri),
             rubyNSAttr);
    }

    static final Set<String> EMPTY_ATTRS;
    static {
        final String[] emptyAttrs = {
            "checked", "compact", "declare", "defer", "disabled", "ismap", "multiple",
            "noresize", "nohref", "noshade", "nowrap", "readonly", "selected"
        };
        EMPTY_ATTRS = new HashSet<String>(Arrays.asList(emptyAttrs));
    }
    
    private static boolean isEmptyAttr(String name) {
        return EMPTY_ATTRS.contains(name);
    }
    
    public final Integer getLine() { // -1 if none is available
        final int line = locator.getLineNumber();
        return line == -1 ? null : line;
    }
    
    public final Integer getColumn() { // -1 if none is available
        final int column = locator.getColumnNumber();
        return column == -1 ? null : column - 1;
    }

    @Override
    public void endElement(String uri, String localName, String qName) {
        populateCharacters();
        call("end_element_namespace",
             stringOrNil(runtime, localName),
             stringOrNil(runtime, getPrefix(qName)),
             stringOrNil(runtime, uri));
    }

    @Override
    public void characters(char[] ch, int start, int length) {
        charactersBuilder.append(ch, start, length);
    }

    @Override
    public void comment(char[] ch, int start, int length) {
        populateCharacters();
        call("comment", runtime.newString(new String(ch, start, length)));
    }

    @Override
    public void startCDATA() {
        populateCharacters();
    }

    @Override
    public void endCDATA() {
        call("cdata_block", runtime.newString(charactersBuilder.toString()));
        charactersBuilder.setLength(0);
    }

    @Override
    public void error(SAXParseException ex) {
        try {
            final String msg = ex.getMessage();
            call("error", runtime.newString(msg == null ? "" : msg));
            addError(new RaiseException(XmlSyntaxError.createError(runtime, ex), true));
        } catch(RaiseException e) {
            addError(e);
        }
    }

    @Override
    public void fatalError(SAXParseException ex) {
        try {
            final String msg = ex.getMessage();
            call("error", runtime.newString(msg == null ? "" : msg));
            addError(new RaiseException(XmlSyntaxError.createFatalError(runtime, ex), true));

        } catch(RaiseException e) {
            addError(e);
        }
    }

    @Override
    public void warning(SAXParseException ex) {
        final String msg = ex.getMessage();
        call("warning", runtime.newString(msg == null ? "" : msg));
    }

    protected synchronized void addError(RaiseException e) {
        errors.add(e);
    }

    public synchronized int getErrorCount() {
        return errors.size();
    }

    public synchronized RaiseException getLastError() {
        return errors.getLast();
    }

    private void call(String methodName) {
        ThreadContext context = runtime.getCurrentContext();
        RuntimeHelpers.invoke(context, document(context), methodName);
    }

    private void call(String methodName, IRubyObject argument) {
        ThreadContext context = runtime.getCurrentContext();
        RuntimeHelpers.invoke(context, document(context), methodName, argument);
    }

    private void call(String methodName, IRubyObject arg1, IRubyObject arg2) {
        ThreadContext context = runtime.getCurrentContext();
        RuntimeHelpers.invoke(context, document(context), methodName, arg1, arg2);
    }

    private void call(String methodName, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3) {
        ThreadContext context = runtime.getCurrentContext();
        RuntimeHelpers.invoke(context, document(context), methodName, arg1, arg2, arg3);
    }

    private void call(String methodName,
                      IRubyObject arg0,
                      IRubyObject arg1,
                      IRubyObject arg2,
                      IRubyObject arg3,
                      IRubyObject arg4) {
        ThreadContext context = runtime.getCurrentContext();
        RuntimeHelpers.invoke(context, document(context), methodName, arg0, arg1, arg2, arg3, arg4);
    }

    private IRubyObject document(ThreadContext context) {
        return object.getInstanceVariables().getInstanceVariable("@document");
    }

    protected void populateCharacters() {
        if (charactersBuilder.length() > 0) {
            call("characters", runtime.newString(charactersBuilder.toString()));
            charactersBuilder.setLength(0);
        }
    }
}