Example usage for javax.xml.stream XMLStreamReader hasNext

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

Introduction

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

Prototype

public boolean hasNext() throws XMLStreamException;

Source Link

Document

Returns true if there are more parsing events and false if there are no more events.

Usage

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Loads <code>IliRecords</code> from the specified stream into this
 * <code>IliLoader</code>'s <code>GermaNet</code> object.
 * @param inputStream the stream containing <code>IliRecords</code> data
 * @throws javax.xml.stream.XMLStreamException
 *///from   w w w  .  j a v  a2  s .  c  om
protected void loadILI(InputStream inputStream) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(inputStream);
    int event;
    String nodeName;
    logger.debug("Loading input stream interLingualIndex_DE-EN.xml...");

    //Parse entire file, looking for ili record start elements
    while (parser.hasNext()) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            namespace = parser.getNamespaceURI();
            break;
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                IliRecord ili = processIliRecord(parser);
                germaNet.addIliRecord(ili);
            }
            break;
        }
    }
    parser.close();
    logger.debug("Done.");
}

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 w w  w.j  a v a 2  s . com*/
        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.predic8.membrane.core.http.xml.Response.java

@Override
protected void parseChildren(XMLStreamReader token, String child) throws Exception {
    if (Headers.ELEMENT_NAME.equals(child)) {
        headers = (Headers) new Headers().parse(token);
    } else if ("status".equals(child)) {
        statusCode = Integer//from w w  w .  ja v  a 2  s .c o  m
                .parseInt(StringUtils.defaultIfBlank(token.getAttributeValue("", "status-code"), "0"));
        statusMessage = "";
        while (token.hasNext()) {
            token.next();
            if (token.isStartElement()) {
                parseChildren(token, token.getName().getLocalPart());
            } else if (token.isCharacters()) {
                statusMessage += token.getText();
            } else if (token.isEndElement()) {
                break;
            }
        }
    }
}

From source file:com.autonomy.aci.client.services.impl.AbstractStAXProcessor.java

/**
 * Reads from the XML stream and tries to determine if the ACI response contains an error or not. The stream is left
 * at the end of the body content of the <tt>/autnresponse/response</tt> element, if one could be found.
 * @param xmlStreamReader The response to process
 * @return <tt>true</tt> if the response contains an error, <tt>false</tt> otherwise
 * @throws javax.xml.stream.XMLStreamException If there was a problem reading the IDOL Server response.
 *//*  w  w w . j  av  a2s.  com*/
protected boolean isErrorResponse(final XMLStreamReader xmlStreamReader) throws XMLStreamException {
    LOGGER.trace("isErrorResponse() called...");

    // Get the /autnresponse/response element...
    while (xmlStreamReader.hasNext()) {
        // Get the event type...
        final int eventType = xmlStreamReader.next();

        // Check to see if it's a start event...
        if ((XMLEvent.START_ELEMENT == eventType)
                && ("response".equalsIgnoreCase(xmlStreamReader.getLocalName()))) {
            return "ERROR".equalsIgnoreCase(xmlStreamReader.getElementText());
        }
    }

    // Couldn't find a /autnresponse/response element...
    throw new XMLStreamException("Unable to find /autnresponse/response element.");
}

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

private boolean parseJobDeleteResponse(InputStream stream) throws XMLStreamException {
    XMLStreamReader parser = factory.createXMLStreamReader(stream);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                String localName = parser.getLocalName();
                if (localName.equals("success"))
                    return true;
                else {
                    log.error(parser.getElementText());
                    return false;
                }//from  ww w  .  j ava2s  .  co m
            }
        }
    }
    return false;
}

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

private JobDetailsBean parseJobSubmit(InputStream stream) throws XMLStreamException {
    JobDetailsBean res = new JobDetailsBean();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                // only parse several attributes
                if (parser.getLocalName().equals(JobDetailsBean.STATUS)) {
                    res.setJobStatus(parser.getAttributeValue(0));
                } else if (parser.getLocalName().equals(JobDetailsBean.JOBID)) {
                    res.setJobId(parser.getElementText());
                } else if (parser.getLocalName().equals(JobDetailsBean.JOBNAME)) {
                    res.setJobTitle(parser.getElementText());
                } else if (parser.getLocalName().equals(JobDetailsBean.DATE)) {
                    res.setLastUpdatedDate(parser.getElementText());
                } else if (parser.getLocalName().equals(JobDetailsBean.USER)) {
                    res.setUserName(parser.getElementText());
                }//from  w  w  w .  ja v a2 s.  c  o m
            }
        }
    }
    return res;
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

private String findStatusLine(XMLStreamReader in) throws Exception {
    while (in.hasNext()) {
        int event = in.next();
        if (event == END_ELEMENT && PROPERTIES.equals(in.getLocalName())) {
            break;
        }/*from  w w  w  .  j a  v a  2s  .com*/
        if (event == START_ELEMENT && "property".equals(in.getLocalName())) {
            if ("execStatus".equals(findAttributeValue(in, "name"))) {
                return findAttributeValue(in, "value");
            }
        }
    }
    return "";
}

From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java

/** Extract as many as <code>limit</code> questions from the <code>reader</code>
 *  provided, writing them to <code>writer</code>.
 * @param reader//from  w  w  w  .ja v a2 s .  c  om
 * @param writer
 * @param limit
 * @return
 * @throws XMLStreamException
 */
protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit)
        throws XMLStreamException {

    int questionCount = 0;
    int attrCount;
    boolean copyElement = false;

    writer.writeStartDocument();
    writer.writeStartElement("posts");
    writer.writeCharacters("\n");
    while (reader.hasNext() && questionCount < limit) {
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            if (reader.getLocalName().equals("row")) {
                attrCount = reader.getAttributeCount();
                for (int i = 0; i < attrCount; i++) {
                    // copy only the questions.
                    if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId")
                            && reader.getAttributeValue(i).equals("1")) {
                        copyElement = true;
                        break;
                    }
                }

                if (copyElement) {
                    writer.writeCharacters("  ");
                    writer.writeStartElement("row");
                    for (int i = 0; i < attrCount; i++) {
                        writer.writeAttribute(reader.getAttributeName(i).getLocalPart(),
                                reader.getAttributeValue(i));
                    }
                    writer.writeEndElement();
                    writer.writeCharacters("\n");
                    copyElement = false;
                    questionCount++;
                }
            }
            break;
        }
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();

    return questionCount;
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

private String captureCharacters(XMLStreamReader in, String element) throws Exception {
    while (in.hasNext()) {
        int event = in.next();
        if (event == END_ELEMENT && element.equals(in.getLocalName())) {
            break;
        }//from w w w  .jav  a 2s.co  m
        if (event == CHARACTERS) {
            return in.getText();
        }
    }
    return "";
}

From source file:davmail.exchange.dav.ExchangeDavMethod.java

protected void handleMultiValuedProperty(XMLStreamReader reader, MultiStatusResponse multiStatusResponse)
        throws XMLStreamException {
    String tagLocalName = reader.getLocalName();
    Namespace namespace = Namespace.getNamespace(reader.getNamespaceURI());
    ArrayList<String> values = new ArrayList<String>();
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, tagLocalName)) {
        reader.next();//  ww  w .  j  a v  a2  s  .c  o  m
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagContent = getTagContent(reader);
            if (tagContent != null) {
                values.add(tagContent);
            }
        }
    }
    multiStatusResponse.add(new DefaultDavProperty(tagLocalName, values, namespace));
}