XPPPacketReader.java 16 KB
Newer Older
Derek DeMoro's avatar
Derek DeMoro committed
1 2 3 4 5 6 7 8 9 10 11
/*
 * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved.
 *
 * This software is open source.
 * See the bottom of this file for the licence.
 *
 * $Id$
 */

package org.dom4j.io;

12
import java.io.*;
13 14 15 16 17 18 19
import java.net.URL;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.QName;
Derek DeMoro's avatar
Derek DeMoro committed
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
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

/**
 * <p><code>XPPPacketReader</code> is a Reader of DOM4J documents that
 * uses the fast
 * <a href="http://www.extreme.indiana.edu/soap/xpp/">XML Pull Parser 3.x</a>.
 * It is very fast for use in SOAP style environments.</p>
 *
 * @author <a href="mailto:pelle@neubia.com">Pelle Braendgaard</a>
 * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
 * @version $Revision$
 */
public class XPPPacketReader {

    /**
     * <code>DocumentFactory</code> used to create new document objects
     */
    private DocumentFactory factory;

    /**
     * <code>XmlPullParser</code> used to parse XML
     */
    private XmlPullParser xppParser;

    /**
     * <code>XmlPullParser</code> used to parse XML
     */
    private XmlPullParserFactory xppFactory;

    /**
     * DispatchHandler to call when each <code>Element</code> is encountered
     */
    private DispatchHandler dispatchHandler;


    public XPPPacketReader() {
    }

    public XPPPacketReader(DocumentFactory factory) {
        this.factory = factory;
    }


    /**
     * <p>Reads a Document from the given <code>File</code></p>
     *
     * @param file is the <code>File</code> to read from.
     * @return the newly created Document instance
     * @throws DocumentException              if an error occurs during parsing.
     * @throws java.net.MalformedURLException if a URL could not be made for the given File
     */
    public Document read(File file) throws DocumentException, IOException, XmlPullParserException {
        String systemID = file.getAbsolutePath();
        return read(new BufferedReader(new FileReader(file)), systemID);
    }

    /**
     * <p>Reads a Document from the given <code>URL</code></p>
     *
     * @param url <code>URL</code> to read from.
     * @return the newly created Document instance
     * @throws DocumentException if an error occurs during parsing.
     */
    public Document read(URL url) throws DocumentException, IOException, XmlPullParserException {
        String systemID = url.toExternalForm();
        return read(createReader(url.openStream()), systemID);
    }

    /**
     * <p>Reads a Document from the given URL or filename.</p>
     * <p/>
     * <p/>
     * If the systemID contains a <code>':'</code> character then it is
     * assumed to be a URL otherwise its assumed to be a file name.
     * If you want finer grained control over this mechansim then please
     * explicitly pass in either a {@link URL} or a {@link File} instance
     * instead of a {@link String} to denote the source of the document.
     * </p>
     *
     * @param systemID is a URL for a document or a file name.
     * @return the newly created Document instance
     * @throws DocumentException              if an error occurs during parsing.
     * @throws java.net.MalformedURLException if a URL could not be made for the given File
     */
    public Document read(String systemID) throws DocumentException, IOException, XmlPullParserException {
        if (systemID.indexOf(':') >= 0) {
            // lets assume its a URL
            return read(new URL(systemID));
110 111
        }
        else {
Derek DeMoro's avatar
Derek DeMoro committed
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
            // lets assume that we are given a file name
            return read(new File(systemID));
        }
    }

    /**
     * <p>Reads a Document from the given stream</p>
     *
     * @param in <code>InputStream</code> to read from.
     * @return the newly created Document instance
     * @throws DocumentException if an error occurs during parsing.
     */
    public Document read(InputStream in) throws DocumentException, IOException, XmlPullParserException {
        return read(createReader(in));
    }

    /**
     * <p>Reads a Document from the given <code>Reader</code></p>
     *
     * @param reader is the reader for the input
     * @return the newly created Document instance
     * @throws DocumentException if an error occurs during parsing.
     */
    public Document read(Reader reader) throws DocumentException, IOException, XmlPullParserException {
        getXPPParser().setInput(reader);
        return parseDocument();
    }

    /**
     * <p>Reads a Document from the given array of characters</p>
     *
     * @param text is the text to parse
     * @return the newly created Document instance
     * @throws DocumentException if an error occurs during parsing.
     */
    public Document read(char[] text) throws DocumentException, IOException, XmlPullParserException {
        getXPPParser().setInput(new CharArrayReader(text));
        return parseDocument();
    }

    /**
     * <p>Reads a Document from the given stream</p>
     *
     * @param in       <code>InputStream</code> to read from.
     * @param systemID is the URI for the input
     * @return the newly created Document instance
     * @throws DocumentException if an error occurs during parsing.
     */
    public Document read(InputStream in, String systemID) throws DocumentException, IOException, XmlPullParserException {
        return read(createReader(in), systemID);
    }

    /**
     * <p>Reads a Document from the given <code>Reader</code></p>
     *
     * @param reader   is the reader for the input
     * @param systemID is the URI for the input
     * @return the newly created Document instance
     * @throws DocumentException if an error occurs during parsing.
     */
    public Document read(Reader reader, String systemID) throws DocumentException, IOException, XmlPullParserException {
        Document document = read(reader);
        document.setName(systemID);
        return document;
    }


    // Properties
    //-------------------------------------------------------------------------

    public XmlPullParser getXPPParser() throws XmlPullParserException {
        if (xppParser == null) {
            xppParser = getXPPFactory().newPullParser();
        }
        return xppParser;
    }

    public XmlPullParserFactory getXPPFactory() throws XmlPullParserException {
        if (xppFactory == null) {
            xppFactory = XmlPullParserFactory.newInstance();
        }
        xppFactory.setNamespaceAware(true);
        return xppFactory;
    }

    public void setXPPFactory(XmlPullParserFactory xppFactory) {
        this.xppFactory = xppFactory;
    }

    /**
     * @return the <code>DocumentFactory</code> used to create document objects
     */
    public DocumentFactory getDocumentFactory() {
        if (factory == null) {
            factory = DocumentFactory.getInstance();
        }
        return factory;
    }

    /**
     * <p>This sets the <code>DocumentFactory</code> used to create new documents.
     * This method allows the building of custom DOM4J tree objects to be implemented
     * easily using a custom derivation of {@link DocumentFactory}</p>
     *
     * @param factory <code>DocumentFactory</code> used to create DOM4J objects
     */
    public void setDocumentFactory(DocumentFactory factory) {
        this.factory = factory;
    }


    /**
     * Adds the <code>ElementHandler</code> to be called when the
     * specified path is encounted.
     *
     * @param path    is the path to be handled
     * @param handler is the <code>ElementHandler</code> to be called
     *                by the event based processor.
     */
    public void addHandler(String path, ElementHandler handler) {
        getDispatchHandler().addHandler(path, handler);
    }

    /**
     * Removes the <code>ElementHandler</code> from the event based
     * processor, for the specified path.
     *
     * @param path is the path to remove the <code>ElementHandler</code> for.
     */
    public void removeHandler(String path) {
        getDispatchHandler().removeHandler(path);
    }

    /**
     * When multiple <code>ElementHandler</code> instances have been
     * registered, this will set a default <code>ElementHandler</code>
     * to be called for any path which does <b>NOT</b> have a handler
     * registered.
     *
     * @param handler is the <code>ElementHandler</code> to be called
     *                by the event based processor.
     */
    public void setDefaultHandler(ElementHandler handler) {
        getDispatchHandler().setDefaultHandler(handler);
    }

    // Implementation methods
    //-------------------------------------------------------------------------
260
    public Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
Derek DeMoro's avatar
Derek DeMoro committed
261 262 263 264
        DocumentFactory df = getDocumentFactory();
        Document document = df.createDocument();
        Element parent = null;
        XmlPullParser pp = getXPPParser();
265
        int count = 0;
Derek DeMoro's avatar
Derek DeMoro committed
266
        while (true) {
267
            int type = -1;
268
            type = pp.nextToken();
Derek DeMoro's avatar
Derek DeMoro committed
269
            switch (type) {
Matt Tucker's avatar
Matt Tucker committed
270 271 272 273 274
                case XmlPullParser.PROCESSING_INSTRUCTION: {
                    String text = pp.getText();
                    int loc = text.indexOf(" ");
                    if (loc >= 0) {
                        document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1));
Derek DeMoro's avatar
Derek DeMoro committed
275
                    }
Matt Tucker's avatar
Matt Tucker committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
                    else
                        document.addProcessingInstruction(text, "");
                    break;
                }
                case XmlPullParser.COMMENT: {
                    if (parent != null)
                        parent.addComment(pp.getText());
                    else
                        document.addComment(pp.getText());
                    break;
                }
                case XmlPullParser.CDSECT: {
                    String text = pp.getText();
                    if (parent != null) {
                        parent.addCDATA(text);
Derek DeMoro's avatar
Derek DeMoro committed
291
                    }
Matt Tucker's avatar
Matt Tucker committed
292 293 294
                    else {
                        if (text.trim().length() > 0) {
                            throw new DocumentException("Cannot have text content outside of the root document");
295
                        }
Matt Tucker's avatar
Matt Tucker committed
296 297
                    }
                    break;
Derek DeMoro's avatar
Derek DeMoro committed
298

Matt Tucker's avatar
Matt Tucker committed
299 300 301 302 303
                }
                case XmlPullParser.ENTITY_REF: {
                    String text = pp.getText();
                    if (parent != null) {
                        parent.addText(text);
Derek DeMoro's avatar
Derek DeMoro committed
304
                    }
Matt Tucker's avatar
Matt Tucker committed
305 306 307
                    else {
                        if (text.trim().length() > 0) {
                            throw new DocumentException("Cannot have an entityref outside of the root document");
308
                        }
Derek DeMoro's avatar
Derek DeMoro committed
309
                    }
Matt Tucker's avatar
Matt Tucker committed
310 311 312 313 314 315
                    break;
                }
                case XmlPullParser.END_DOCUMENT: {
                    return document;
                }
                case XmlPullParser.START_TAG: {
Derek DeMoro's avatar
Derek DeMoro committed
316
                        QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace()) : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
317 318 319 320 321 322 323
                        Element newElement = null;
                        if ("jabber:client".equals(qname.getNamespaceURI())) {
                            newElement = df.createElement(pp.getName());
                        }
                        else {
                            newElement = df.createElement(qname);
                        }
324
                       // Element newElement = DocumentHelper.createElement(pp.getName());
Derek DeMoro's avatar
Derek DeMoro committed
325 326 327 328 329 330 331 332 333 334 335
                        int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
                        int nsEnd = pp.getNamespaceCount(pp.getDepth());
                        for (int i = nsStart; i < nsEnd; i++)
                            if (pp.getNamespacePrefix(i) != null)
                                newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                        for (int i = 0; i < pp.getAttributeCount(); i++) {
                            QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i)) : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i), pp.getAttributeNamespace(i));
                            newElement.addAttribute(qa, pp.getAttributeValue(i));
                        }
                        if (parent != null) {
                            parent.add(newElement);
336 337
                        }
                        else {
Derek DeMoro's avatar
Derek DeMoro committed
338 339 340
                            document.add(newElement);
                        }
                        parent = newElement;
341
                        count++;
Derek DeMoro's avatar
Derek DeMoro committed
342 343
                        break;
                    }
Matt Tucker's avatar
Matt Tucker committed
344 345 346
                case XmlPullParser.END_TAG: {
                    if (parent != null) {
                        parent = parent.getParent();
Derek DeMoro's avatar
Derek DeMoro committed
347
                    }
Matt Tucker's avatar
Matt Tucker committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361
                    count--;
                    if (count == 0) {
                        return document;
                    }
                    break;
                }
                case XmlPullParser.TEXT: {
                    String text = pp.getText();
                    if (parent != null) {
                        parent.addText(text);
                    }
                    else {
                        if (text.trim().length() > 0) {
                            throw new DocumentException("Cannot have text content outside of the root document");
Derek DeMoro's avatar
Derek DeMoro committed
362 363
                        }
                    }
Matt Tucker's avatar
Matt Tucker committed
364 365
                    break;
                }
Derek DeMoro's avatar
Derek DeMoro committed
366
                default:
Matt Tucker's avatar
Matt Tucker committed
367 368 369
                {
                    ;
                }
Derek DeMoro's avatar
Derek DeMoro committed
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
            }
        }
    }

    protected DispatchHandler getDispatchHandler() {
        if (dispatchHandler == null) {
            dispatchHandler = new DispatchHandler();
        }
        return dispatchHandler;
    }

    protected void setDispatchHandler(DispatchHandler dispatchHandler) {
        this.dispatchHandler = dispatchHandler;
    }

    /**
     * Factory method to create a Reader from the given InputStream.
     */
    protected Reader createReader(InputStream in) throws IOException {
        return new BufferedReader(new InputStreamReader(in));
    }
}

/*
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form 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 name "DOM4J" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of MetaStuff, Ltd.  For written permission,
 *    please contact dom4j-info@metastuff.com.
 *
 * 4. Products derived from this Software may not be called "DOM4J"
 *    nor may "DOM4J" appear in their names without prior written
 *    permission of MetaStuff, Ltd. DOM4J is a registered
 *    trademark of MetaStuff, Ltd.
 *
 * 5. Due credit should be given to the DOM4J Project -
 *    http://www.dom4j.org
 *
 * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
 * ``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
 * METASTUFF, LTD. 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.
 *
 * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved.
 *
 * $Id$
 */