Search in sources :

Example 76 with XmlPullParserException

use of org.xmlpull.v1.XmlPullParserException in project j2objc by google.

the class KXmlParser method readValue.

/**
     * Returns the current text or attribute value. This also has the side
     * effect of setting isWhitespace to false if a non-whitespace character is
     * encountered.
     *
     * @param delimiter {@code <} for text, {@code "} and {@code '} for quoted
     *     attributes, or a space for unquoted attributes.
     */
private String readValue(char delimiter, boolean resolveEntities, boolean throwOnResolveFailure, ValueContext valueContext) throws IOException, XmlPullParserException {
    /*
         * This method returns all of the characters from the current position
         * through to an appropriate delimiter.
         *
         * If we're lucky (which we usually are), we'll return a single slice of
         * the buffer. This fast path avoids allocating a string builder.
         *
         * There are 6 unlucky characters we could encounter:
         *  - "&":  entities must be resolved.
         *  - "%":  parameter entities are unsupported in entity values.
         *  - "<":  this isn't permitted in attributes unless relaxed.
         *  - "]":  this requires a lookahead to defend against the forbidden
         *          CDATA section delimiter "]]>".
         *  - "\r": If a "\r" is followed by a "\n", we discard the "\r". If it
         *          isn't followed by "\n", we replace "\r" with either a "\n"
         *          in text nodes or a space in attribute values.
         *  - "\n": In attribute values, "\n" must be replaced with a space.
         *
         * We could also get unlucky by needing to refill the buffer midway
         * through the text.
         */
    int start = position;
    StringBuilder result = null;
    // if a text section was already started, prefix the start
    if (valueContext == ValueContext.TEXT && text != null) {
        result = new StringBuilder();
        result.append(text);
    }
    while (true) {
        /*
             * Make sure we have at least a single character to read from the
             * buffer. This mutates the buffer, so save the partial result
             * to the slow path string builder first.
             */
        if (position >= limit) {
            if (start < position) {
                if (result == null) {
                    result = new StringBuilder();
                }
                result.append(buffer, start, position - start);
            }
            if (!fillBuffer(1)) {
                return result != null ? result.toString() : "";
            }
            start = position;
        }
        char c = buffer[position];
        if (c == delimiter || (delimiter == ' ' && (c <= ' ' || c == '>')) || c == '&' && !resolveEntities) {
            break;
        }
        if (c != '\r' && (c != '\n' || valueContext != ValueContext.ATTRIBUTE) && c != '&' && c != '<' && (c != ']' || valueContext != ValueContext.TEXT) && (c != '%' || valueContext != ValueContext.ENTITY_DECLARATION)) {
            isWhitespace &= (c <= ' ');
            position++;
            continue;
        }
        /*
             * We've encountered an unlucky character! Convert from fast
             * path to slow path if we haven't done so already.
             */
        if (result == null) {
            result = new StringBuilder();
        }
        result.append(buffer, start, position - start);
        if (c == '\r') {
            if ((position + 1 < limit || fillBuffer(2)) && buffer[position + 1] == '\n') {
                position++;
            }
            c = (valueContext == ValueContext.ATTRIBUTE) ? ' ' : '\n';
        } else if (c == '\n') {
            c = ' ';
        } else if (c == '&') {
            // TODO: what if the entity resolves to whitespace?
            isWhitespace = false;
            readEntity(result, false, throwOnResolveFailure, valueContext);
            start = position;
            continue;
        } else if (c == '<') {
            if (valueContext == ValueContext.ATTRIBUTE) {
                checkRelaxed("Illegal: \"<\" inside attribute value");
            }
            isWhitespace = false;
        } else if (c == ']') {
            if ((position + 2 < limit || fillBuffer(3)) && buffer[position + 1] == ']' && buffer[position + 2] == '>') {
                checkRelaxed("Illegal: \"]]>\" outside CDATA section");
            }
            isWhitespace = false;
        } else if (c == '%') {
            throw new XmlPullParserException("This parser doesn't support parameter entities", this, null);
        } else {
            throw new AssertionError();
        }
        position++;
        result.append(c);
        start = position;
    }
    if (result == null) {
        return stringPool.get(buffer, start, position - start);
    } else {
        result.append(buffer, start, position - start);
        return result.toString();
    }
}
Also used : XmlPullParserException(org.xmlpull.v1.XmlPullParserException)

Example 77 with XmlPullParserException

use of org.xmlpull.v1.XmlPullParserException in project j2objc by google.

the class Driver method parseSubTree.

public void parseSubTree(XmlPullParser pp) throws SAXException, IOException {
    this.pp = pp;
    final boolean namespaceAware = pp.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES);
    try {
        if (pp.getEventType() != XmlPullParser.START_TAG) {
            throw new SAXException("start tag must be read before skiping subtree" + pp.getPositionDescription());
        }
        final int[] holderForStartAndLength = new int[2];
        final StringBuilder rawName = new StringBuilder(16);
        String prefix = null;
        String name = null;
        int level = pp.getDepth() - 1;
        int type = XmlPullParser.START_TAG;
        LOOP: do {
            switch(type) {
                case XmlPullParser.START_TAG:
                    if (namespaceAware) {
                        final int depth = pp.getDepth() - 1;
                        final int countPrev = (level > depth) ? pp.getNamespaceCount(depth) : 0;
                        //int countPrev = pp.getNamespaceCount(pp.getDepth() - 1);
                        final int count = pp.getNamespaceCount(depth + 1);
                        for (int i = countPrev; i < count; i++) {
                            contentHandler.startPrefixMapping(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                        }
                        name = pp.getName();
                        prefix = pp.getPrefix();
                        if (prefix != null) {
                            rawName.setLength(0);
                            rawName.append(prefix);
                            rawName.append(':');
                            rawName.append(name);
                        }
                        startElement(pp.getNamespace(), name, // TODO Fixed this. Was "not equals".
                        prefix == null ? name : rawName.toString());
                    } else {
                        startElement(pp.getNamespace(), pp.getName(), pp.getName());
                    }
                    break;
                case XmlPullParser.TEXT:
                    {
                        final char[] chars = pp.getTextCharacters(holderForStartAndLength);
                        contentHandler.characters(chars, //start
                        holderForStartAndLength[0], //len
                        holderForStartAndLength[1]);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    //--level;
                    if (namespaceAware) {
                        name = pp.getName();
                        prefix = pp.getPrefix();
                        if (prefix != null) {
                            rawName.setLength(0);
                            rawName.append(prefix);
                            rawName.append(':');
                            rawName.append(name);
                        }
                        contentHandler.endElement(pp.getNamespace(), name, prefix != null ? name : rawName.toString());
                        // when entering show prefixes for all levels!!!!
                        final int depth = pp.getDepth();
                        final int countPrev = (level > depth) ? pp.getNamespaceCount(pp.getDepth()) : 0;
                        int count = pp.getNamespaceCount(pp.getDepth() - 1);
                        // undeclare them in reverse order
                        for (int i = count - 1; i >= countPrev; i--) {
                            contentHandler.endPrefixMapping(pp.getNamespacePrefix(i));
                        }
                    } else {
                        contentHandler.endElement(pp.getNamespace(), pp.getName(), pp.getName());
                    }
                    break;
                case XmlPullParser.END_DOCUMENT:
                    break LOOP;
            }
            type = pp.next();
        } while (pp.getDepth() > level);
    } catch (XmlPullParserException ex) {
        final SAXParseException saxException = new SAXParseException("parsing error: " + ex, this, ex);
        ex.printStackTrace();
        errorHandler.fatalError(saxException);
    }
}
Also used : SAXParseException(org.xml.sax.SAXParseException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) SAXException(org.xml.sax.SAXException)

Example 78 with XmlPullParserException

use of org.xmlpull.v1.XmlPullParserException in project j2objc by google.

the class KXmlParser method readEntityDeclaration.

/**
     * Read an entity declaration. The value of internal entities are inline:
     *   <!ENTITY foo "bar">
     *
     * The values of external entities must be retrieved by URL or path:
     *   <!ENTITY foo SYSTEM "http://host/file">
     *   <!ENTITY foo PUBLIC "-//Android//Foo//EN" "http://host/file">
     *   <!ENTITY foo SYSTEM "../file.png" NDATA png>
     *
     * Entities may be general or parameterized. Parameterized entities are
     * marked by a percent sign. Such entities may only be used in the DTD:
     *   <!ENTITY % foo "bar">
     */
private void readEntityDeclaration() throws IOException, XmlPullParserException {
    read(START_ENTITY);
    boolean generalEntity = true;
    skip();
    if (peekCharacter() == '%') {
        generalEntity = false;
        position++;
        skip();
    }
    String name = readName();
    skip();
    int quote = peekCharacter();
    String entityValue;
    if (quote == '"' || quote == '\'') {
        position++;
        entityValue = readValue((char) quote, true, false, ValueContext.ENTITY_DECLARATION);
        position++;
    } else if (readExternalId(true, false)) {
        /*
             * Map external entities to the empty string. This is dishonest,
             * but it's consistent with Android's Expat pull parser.
             */
        entityValue = "";
        skip();
        if (peekCharacter() == NDATA[0]) {
            read(NDATA);
            skip();
            readName();
        }
    } else {
        throw new XmlPullParserException("Expected entity value or external ID", this, null);
    }
    if (generalEntity && processDocDecl) {
        if (documentEntities == null) {
            documentEntities = new HashMap<String, char[]>();
        }
        documentEntities.put(name, entityValue.toCharArray());
    }
    skip();
    read('>');
}
Also used : XmlPullParserException(org.xmlpull.v1.XmlPullParserException)

Example 79 with XmlPullParserException

use of org.xmlpull.v1.XmlPullParserException in project j2objc by google.

the class KXmlParser method parseStartTag.

/**
     * Sets name and attributes
     */
private void parseStartTag(boolean xmldecl, boolean throwOnResolveFailure) throws IOException, XmlPullParserException {
    if (!xmldecl) {
        read('<');
    }
    name = readName();
    attributeCount = 0;
    while (true) {
        skip();
        if (position >= limit && !fillBuffer(1)) {
            checkRelaxed(UNEXPECTED_EOF);
            return;
        }
        int c = buffer[position];
        if (xmldecl) {
            if (c == '?') {
                position++;
                read('>');
                return;
            }
        } else {
            if (c == '/') {
                degenerated = true;
                position++;
                skip();
                read('>');
                break;
            } else if (c == '>') {
                position++;
                break;
            }
        }
        String attrName = readName();
        int i = (attributeCount++) * 4;
        attributes = ensureCapacity(attributes, i + 4);
        attributes[i] = "";
        attributes[i + 1] = null;
        attributes[i + 2] = attrName;
        skip();
        if (position >= limit && !fillBuffer(1)) {
            checkRelaxed(UNEXPECTED_EOF);
            return;
        }
        if (buffer[position] == '=') {
            position++;
            skip();
            if (position >= limit && !fillBuffer(1)) {
                checkRelaxed(UNEXPECTED_EOF);
                return;
            }
            char delimiter = buffer[position];
            if (delimiter == '\'' || delimiter == '"') {
                position++;
            } else if (relaxed) {
                delimiter = ' ';
            } else {
                throw new XmlPullParserException("attr value delimiter missing!", this, null);
            }
            attributes[i + 3] = readValue(delimiter, true, throwOnResolveFailure, ValueContext.ATTRIBUTE);
            if (delimiter != ' ') {
                // end quote
                position++;
            }
        } else if (relaxed) {
            attributes[i + 3] = attrName;
        } else {
            checkRelaxed("Attr.value missing f. " + attrName);
            attributes[i + 3] = attrName;
        }
    }
    int sp = depth++ * 4;
    elementStack = ensureCapacity(elementStack, sp + 4);
    elementStack[sp + 3] = name;
    if (depth >= nspCounts.length) {
        int[] bigger = new int[depth + 4];
        System.arraycopy(nspCounts, 0, bigger, 0, nspCounts.length);
        nspCounts = bigger;
    }
    nspCounts[depth] = nspCounts[depth - 1];
    if (processNsp) {
        adjustNsp();
    } else {
        namespace = "";
    }
    // For consistency with Expat, add default attributes after fixing namespaces.
    if (defaultAttributes != null) {
        Map<String, String> elementDefaultAttributes = defaultAttributes.get(name);
        if (elementDefaultAttributes != null) {
            for (Map.Entry<String, String> entry : elementDefaultAttributes.entrySet()) {
                if (getAttributeValue(null, entry.getKey()) != null) {
                    // an explicit value overrides the default
                    continue;
                }
                int i = (attributeCount++) * 4;
                attributes = ensureCapacity(attributes, i + 4);
                attributes[i] = "";
                attributes[i + 1] = null;
                attributes[i + 2] = entry.getKey();
                attributes[i + 3] = entry.getValue();
            }
        }
    }
    elementStack[sp] = namespace;
    elementStack[sp + 1] = prefix;
    elementStack[sp + 2] = name;
}
Also used : XmlPullParserException(org.xmlpull.v1.XmlPullParserException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 80 with XmlPullParserException

use of org.xmlpull.v1.XmlPullParserException in project j2objc by google.

the class KXmlParser method readQuotedId.

/**
     * Reads a quoted string, performing no entity escaping of the contents.
     */
private String readQuotedId(boolean returnText) throws IOException, XmlPullParserException {
    int quote = peekCharacter();
    char[] delimiter;
    if (quote == '"') {
        delimiter = DOUBLE_QUOTE;
    } else if (quote == '\'') {
        delimiter = SINGLE_QUOTE;
    } else {
        throw new XmlPullParserException("Expected a quoted string", this, null);
    }
    position++;
    return readUntil(delimiter, returnText);
}
Also used : XmlPullParserException(org.xmlpull.v1.XmlPullParserException)

Aggregations

XmlPullParserException (org.xmlpull.v1.XmlPullParserException)1071 IOException (java.io.IOException)630 XmlPullParser (org.xmlpull.v1.XmlPullParser)440 FileNotFoundException (java.io.FileNotFoundException)187 XmlResourceParser (android.content.res.XmlResourceParser)186 FileInputStream (java.io.FileInputStream)182 AttributeSet (android.util.AttributeSet)159 TypedArray (android.content.res.TypedArray)156 Resources (android.content.res.Resources)101 File (java.io.File)101 ArrayList (java.util.ArrayList)99 PackageManager (android.content.pm.PackageManager)62 HashMap (java.util.HashMap)58 ComponentName (android.content.ComponentName)57 InputStream (java.io.InputStream)57 Intent (android.content.Intent)54 XmlSerializer (org.xmlpull.v1.XmlSerializer)54 AtomicFile (android.util.AtomicFile)50 BufferedInputStream (java.io.BufferedInputStream)44 TypedValue (android.util.TypedValue)43