Example usage for javax.xml.stream XMLStreamReader nextTag

List of usage examples for javax.xml.stream XMLStreamReader nextTag

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader nextTag.

Prototype

public int nextTag() throws XMLStreamException;

Source Link

Document

Skips any white space (isWhiteSpace() returns true), COMMENT, or PROCESSING_INSTRUCTION, until a START_ELEMENT or END_ELEMENT is reached.

Usage

From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java

public PropertyList read(XMLStreamReader reader) throws XMLStreamException {
    int type = reader.getEventType();

    if (XMLStreamConstants.START_DOCUMENT == type) {
        do {/* w  w  w.j a  v  a 2 s  . co  m*/
            reader.next();
            type = reader.getEventType();
        } while (XMLStreamConstants.START_ELEMENT != type);
    }
    PropertyList result = new PropertyList();
    if (XMLStreamConstants.START_ELEMENT == type && PLIST_NODE.equals(reader.getLocalName())) {
        reader.nextTag();
        type = reader.getEventType();
        if (!(XMLStreamConstants.END_ELEMENT == type && PLIST_NODE.equals(reader.getLocalName()))) {
            result.setRoot(readValue(reader));
        }
        reader.require(XMLStreamConstants.END_ELEMENT, null, PLIST_NODE);
    }
    return result;
}

From source file:net.sf.jabref.importer.fileformat.FreeCiteImporter.java

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {//from   ww  w . j a  v a2  s . c  o m
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * /*from w w  w  . j av a2  s .  c o  m*/
 * @param fname
 * @throws XMLStreamException
 * @throws IOException
 */
private static void readProfile(String fname) throws XMLStreamException, IOException {
    //init profile map
    _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>();

    //read existing profile
    FileInputStream fis = new FileInputStream(fname);

    try {
        //xml parsing
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);

        int e = xsr.nextTag(); // profile start

        while (true) //read all instructions
        {
            e = xsr.nextTag(); // instruction start
            if (e == XMLStreamConstants.END_ELEMENT)
                break; //reached profile end tag

            //parse instruction
            int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID));
            //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR);
            HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>();
            _profile.put(ID, tmp);

            while (true) {
                e = xsr.nextTag(); // cost function start
                if (e == XMLStreamConstants.END_ELEMENT)
                    break; //reached instruction end tag

                //parse cost function
                TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE));
                TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE));
                InternalTestVariable[] pv = parseTestVariables(
                        xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES));
                DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT));
                int tDefID = getTestDefID(m, lv, df, pv);

                xsr.next(); //read characters
                double[] params = parseParams(xsr.getText());
                boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
                CostFunction cf = new CostFunction(params, multidim);
                tmp.put(tDefID, cf);

                xsr.nextTag(); // cost function end
                //System.out.println("added cost function");
            }
        }
        xsr.close();
    } finally {
        IOUtilFunctions.closeSilently(fis);
    }

    //mark profile as successfully read
    _flagReadData = true;
}

From source file:org.maodian.flyingcat.xmpp.codec.InfoQueryCodec.java

@Override
public Object decode(XMLStreamReader xmlsr) {
    try {//from ww  w .  jav  a  2s  .c  o m
        String id = xmlsr.getAttributeValue("", "id");
        String type = xmlsr.getAttributeValue("", "type");
        Builder builder = new Builder(id, type);

        String from = xmlsr.getAttributeValue("", "from");
        String to = xmlsr.getAttributeValue("", "to");
        String language = xmlsr.getAttributeValue(XMLConstants.XML_NS_URI, "lang");
        builder.from(from).to(to).language(language);

        switch (type) {
        case InfoQuery.GET:
        case InfoQuery.SET:
            if (xmlsr.nextTag() != XMLStreamConstants.START_ELEMENT) {
                throw new XmppException(StanzaErrorCondition.BAD_REQUEST);
            }
            QName key = xmlsr.getName();
            builder.payload(findDecoder(key, builder.build()).decode(xmlsr));
            break;
        case InfoQuery.RESULT:
            // do nothing
            break;
        case InfoQuery.ERROR:
            throw new IllegalStateException(
                    "Since this is a server, it should not dealing with incoming result and error");
        default:
            break;
        }
        return builder.build();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor.java

@Override
public void readObjectsIteratively(@NotNull ParserSource source, @NotNull ParsingContext parsingContext,
        RootXNodeHandler handler) throws SchemaException, IOException {
    InputStream is = source.getInputStream();
    XMLStreamReader stream = null;
    try {/* w  w w.j ava2s.c o m*/
        stream = XMLInputFactory.newInstance().createXMLStreamReader(is);

        int eventType = stream.nextTag();
        if (eventType != XMLStreamConstants.START_ELEMENT) {
            throw new SystemException("StAX Malfunction?");
        }
        DOMConverter domConverter = new DOMConverter();
        Map<String, String> rootNamespaceDeclarations = new HashMap<>();

        QName objectsMarker = schemaRegistry.getPrismContext().getObjectsElementName();
        if (objectsMarker != null && !QNameUtil.match(stream.getName(), objectsMarker)) {
            readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler);
        }
        for (int i = 0; i < stream.getNamespaceCount(); i++) {
            rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
        }
        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (!readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler)) {
                    return;
                }
            }
        }
    } catch (XMLStreamException ex) {
        String lineInfo = stream != null ? " on line " + stream.getLocation().getLineNumber() : "";
        throw new SchemaException("Exception while parsing XML" + lineInfo + ": " + ex.getMessage(), ex);
    } finally {
        if (source.closeStreamAfterParsing()) {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.flexive.chemistry.webdav.TextDocumentResource.java

/**
 * Set the value of a property, stream points to the start of the property tag.
 *
 * @param parser    the XML parser//from  w ww  .j a v  a 2  s .c o  m
 * @throws XMLStreamException   on parsing errors
 */
protected void processProperty(XMLStreamReader parser) throws XMLStreamException {
    int level = 0;
    String name = null;
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        if ("name".equals(parser.getAttributeName(i).getLocalPart())) {
            name = parser.getAttributeValue(i);
            break;
        }
    }
    if (name == null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("property without name attribute encountered");
        }
        return;
    }

    String value = null;
    for (int event = parser.nextTag(); event != XMLStreamConstants.END_DOCUMENT
            && level >= 0; event = parser.nextTag()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if ("value".equals(parser.getLocalName())) {
                value = parser.getElementText().trim();
            } else if ("name".equals(parser.getLocalName())) {
                name = parser.getElementText();
            } else {
                level++;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            level--;
            break;
        }
    }

    if (value != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Setting field " + name + " to " + value);
        }
        try {
            object.setValue(name, value);
        } catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed to set field " + name + " (ignored): " + e.getMessage());
            }
        }
    }
}

From source file:gate.corpora.FastInfosetDocumentFormat.java

/**
 * Unpacks markup in the GATE-specific standoff XML markup format.
 * /*  w w w . jav  a 2  s  . c o  m*/
 * @param doc
 *          the document to process
 * @param statusListener
 *          optional status listener to receive status messages
 * @throws DocumentFormatException
 *           if a fatal error occurs during parsing
 */
private void unpackGateFormatMarkup(Document doc, StatusListener statusListener)
        throws DocumentFormatException {
    boolean docHasContentButNoValidURL = hasContentButNoValidUrl(doc);

    try {
        Reader inputReader = null;
        InputStream inputStream = null;
        XMLStreamReader xsr = null;
        String encoding = ((TextualDocument) doc).getEncoding();
        if (docHasContentButNoValidURL) {
            xsr = new StAXDocumentParser(IOUtils.toInputStream(doc.getContent().toString(), encoding),
                    getStAXManager());
        } else {
            inputStream = doc.getSourceUrl().openStream();
            xsr = new StAXDocumentParser(inputStream, getStAXManager());
        }

        // find the opening GateDocument tag
        xsr.nextTag();

        // parse the document
        try {
            DocumentStaxUtils.readGateXmlDocument(xsr, doc, statusListener);
        } finally {
            xsr.close();
            if (inputStream != null) {
                inputStream.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        }
    } catch (XMLStreamException e) {
        doc.getFeatures().put("parsingError", Boolean.TRUE);

        Boolean bThrow = (Boolean) doc.getFeatures().get(GateConstants.THROWEX_FORMAT_PROPERTY_NAME);

        if (bThrow != null && bThrow.booleanValue()) {
            // the next line is commented to avoid Document creation fail on
            // error
            throw new DocumentFormatException(e);
        } else {
            Out.println("Warning: Document remains unparsed. \n" + "\n  Stack Dump: ");
            e.printStackTrace(Out.getPrintWriter());
        } // if
    } catch (IOException ioe) {
        throw new DocumentFormatException("I/O exception for " + doc.getSourceUrl().toString(), ioe);
    }
}

From source file:com.evolveum.midpoint.common.validator.Validator.java

public void validate(InputStream inputStream, OperationResult validatorResult,
        String objectResultOperationName) {

    XMLStreamReader stream = null;
    try {//from w  w  w  .  jav a 2  s. co m

        Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(inputStream);

        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!stream.getName().equals(SchemaConstants.C_OBJECTS)) {
                // This has to be an import file with a single objects. Try
                // to process it.
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    // Make sure that unexpected error is recorded.
                    objectResult.recordFatalError(e);
                    throw e;
                }

                if (!cont.isCont()) {
                    String message = null;
                    if (cont.getReason() != null) {
                        message = cont.getReason();
                    } else {
                        message = "Object validation failed (no reason given)";
                    }
                    if (objectResult.isUnknown()) {
                        objectResult.recordFatalError(message);
                    }
                    validatorResult.recordFatalError(message);
                    return;
                }
                // return to avoid processing objects in loop
                validatorResult.computeStatus("Validation failed", "Validation warnings");
                return;
            }
            // Extract root namespace declarations
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new SystemException("StAX Malfunction?");
        }

        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {

                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    // Read and validate individual object from the stream
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    if (objectResult.isUnknown()) {
                        // Make sure that unexpected error is recorded.
                        objectResult.recordFatalError(e);
                    }
                    throw e;
                }

                if (objectResult.isError()) {
                    errors++;
                }

                objectResult.cleanupResult();
                validatorResult.summarize();

                if (cont.isStop()) {
                    if (cont.getReason() != null) {
                        validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason());
                    } else {
                        validatorResult.recordFatalError("Processing has been stopped");
                    }
                    // This means total stop, no other objects will be
                    // processed
                    return;
                }
                if (!cont.isCont()) {
                    if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
                        validatorResult.recordFatalError("Too many errors (" + errors + ")");
                        return;
                    }
                }
            }
        }

    } catch (XMLStreamException ex) {
        // validatorResult.recordFatalError("XML parsing error: " +
        // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
        validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
        if (handler != null) {
            handler.handleGlobalError(validatorResult);
        }
        return;
    }

    // Error count is sufficient. Detailed messages are in subresults
    validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");

}

From source file:com.widowcrawler.exo.parse.Parser.java

public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException {

    final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8");

    final Sitemap retval = new Sitemap(new HashSet<>());

    final Set<SitemapURL> sitemapURLs = new HashSet<>();
    SitemapURL.Builder urlBuilder = null;
    String urlContent;//from w w  w. j  av  a  2 s.  c  o m

    reader.getEventType();

    while (reader.hasNext()) {
        switch (state) {
        case START:
            reader.nextTag();

            if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) {
                state = State.URLSET;
            } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) {
                state = State.SITEMAPINDEX;
            } else {
                String message = "Invalid root element. Must be either urlset or sitemapindex";
                logger.error(message);
                throw new SitemapParseException(message);
            }

            break;

        case END:
            // consume all end tags
            if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
                String message = decorate("There should be only one root element in each sitemap.xml",
                        reader.getLocation());
                logger.error(message);
                throw new SitemapParseException(message);
            }

            reader.next();
            break;

        /////////////////////
        // URLSET Hierarchy
        /////////////////////
        case URLSET:
            // If we're done with the URLs, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            // Check that we're entering into a <url> element
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) {
                String message = "A <urlset> element can only contain <url> elements. Found: "
                        + reader.getLocalName();
                logger.error(message);
                throw new SitemapParseException(message);
            }

            urlBuilder = new SitemapURL.Builder();
            state = State.URL;
            break;

        case URL:
            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                //logger.info("reader.getLocalName(): " + reader.getLocalName());
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                case CHANGEFREQ_TAG_NAME:
                    state = State.URL_PROP_CHANGEFREQ;
                    break;
                case PRIORITY_TAG_NAME:
                    state = State.URL_PROP_PRIORITY;
                    break;
                case MOBILE_TAG_NAME:
                    state = State.URL_PROP_MOBILE;
                    break;
                default:
                    String message = "Unexpected tag in url: " + reader.getLocalName();
                    logger.error(message);
                    throw new SitemapParseException(message);
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }
            break;

        case URL_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                assert urlBuilder != null;
                urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent)));

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }
            state = State.URL;
            break;

        case URL_PROP_LASTMOD:
            assert urlBuilder != null;
            urlBuilder.withLastModified(DateTime.parse(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_CHANGEFREQ:
            assert urlBuilder != null;
            urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText())));
            state = State.URL;
            break;

        case URL_PROP_PRIORITY:
            assert urlBuilder != null;
            urlBuilder.withPriority(Double.valueOf(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_MOBILE:
            assert urlBuilder != null;
            urlBuilder.withIsMobileContent(true);
            // consume until "end tag" of self-closing tag
            // Also works if someone puts content in
            reader.getElementText();
            state = State.URL;
            break;

        ///////////////////////////
        // SITEMAPINDEX Hierarchy
        ///////////////////////////
        case SITEMAPINDEX:
            // If we're done with all the Sitemaps, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            state = State.SITEMAP;
            break;

        case SITEMAP:
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) {
                throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements");
            }

            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                default:
                    throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName());
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }

        case SITEMAP_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                URL sitemapURL = new URL(StringUtils.trimToNull(urlContent));

                Sitemap temp = Retry.retry(() -> {
                    try {
                        return Exo.parse(sitemapURL.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                });

                retval.merge(temp);

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);

            } catch (InterruptedException e) {
                logger.warn("Thread interrupted while (re)trying");
                Thread.currentThread().interrupt();

            } catch (RetryFailedException e) {
                String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }

            state = State.URL;
            break;

        case SITEMAP_PROP_LASTMOD:
            // Do nothing with this data for now
            reader.getElementText();
            break;
        }

        //System.out.println(state);
    }

    return retval.merge(new Sitemap(sitemapURLs));
}

From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java

private void benchParse(XMLInputFactory inputFactory, @Nonnull String contentSample) throws XMLStreamException {
    for (int i = 0; i < BIG; i++) {
        XMLStreamReader parser = inputFactory.createXMLStreamReader(new StringReader(contentSample));

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("fileType", parser.getLocalName());
        assertEquals("fileType", parser.getName().getLocalPart());

        boolean dependent = Boolean.parseBoolean(parser.getAttributeValue(null, "dependent"));

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("id", parser.getName().getLocalPart());
        assertEquals(XMLStreamReader.CHARACTERS, parser.next());

        String id = parser.getText();

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("extension", parser.getName().getLocalPart());

        boolean isDefault = Boolean.parseBoolean(parser.getAttributeValue(null, "default"));
        String delimiter = parser.getAttributeValue(null, "delimiter");

        assertEquals(XMLStreamReader.CHARACTERS, parser.next());

        String extension = parser.getText();
        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("extension", parser.getName().getLocalPart());

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("fileType", parser.getName().getLocalPart());
        assertEquals(XMLStreamReader.END_DOCUMENT, parser.next());

        parser.close();/* w w  w  .  ja  va 2 s  .c  o m*/

        FileType type = new FileType(id, new Extension(delimiter, extension, isDefault), dependent);
        assertNotNull(type);
    }
}