Example usage for javax.xml.stream XMLStreamReader getLocalName

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

Introduction

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

Prototype

public String getLocalName();

Source Link

Document

Returns the (local) name of the current event.

Usage

From source file:ar.com.zauber.commons.spring.test.impl.TamperdataHttpServletRequestFactory.java

/** hace el trabajo sucio 
 * @throws UnsupportedEncodingException */
private HttpServletRequest parse(final XMLStreamReader reader)
        throws XMLStreamException, UnsupportedEncodingException {
    final MockHttpServletRequest ret = new MockHttpServletRequest();
    ret.setMethod("POST");
    String header = null;/*w w w .j a  v  a 2  s  .  c om*/
    String postHeader = null;
    int event;
    while ((event = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            final String name = reader.getLocalName();
            if (name.equals("tdRequestHeader") || name.equals("tdPostHeader")) {
                header = reader.getAttributeValue(0);
            } else if (name.equals("tdPostElements")) {
                ret.setMethod("POST");
            } else if (name.equals("tdPostElement")) {
                postHeader = reader.getAttributeValue(0);
            }
        } else if (event == XMLStreamConstants.CHARACTERS) {
            String text = reader.getText();
            if (text.length() > 1 && Character.isWhitespace(text.charAt(0))) {
                text = text.substring(1);
            }
            if (text.length() > 1 && Character.isWhitespace(text.charAt(text.length() - 1))) {
                text = text.substring(0, text.length() - 1);
            }

            final String value = URLDecoder.decode(URLDecoder.decode(text, encoding), encoding);
            if (header != null) {
                ret.addHeader(header, value);
            } else if (postHeader != null) {
                ret.addParameter(postHeader, value);
            }
            header = null;
            postHeader = null;
        } else {
            header = null;
            postHeader = null;
        }
    }
    reader.close();
    return ret;
}

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

protected void handleResponse(XMLStreamReader reader) throws XMLStreamException {
    String href = null;/*  ww  w  .  j a  va 2 s.co m*/
    String responseStatus = "";
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, "response")) {
        reader.next();
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagLocalName = reader.getLocalName();
            if ("href".equals(tagLocalName)) {
                href = reader.getElementText();
            } else if ("status".equals(tagLocalName)) {
                responseStatus = reader.getElementText();
            } else if ("propstat".equals(tagLocalName)) {
                MultiStatusResponse multiStatusResponse = new MultiStatusResponse(href, responseStatus);
                handlePropstat(reader, multiStatusResponse);
                responses.add(multiStatusResponse);
            }
        }
    }

}

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 {/*from   ww  w.ja va 2s.c  o 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   w w  w  .  j av a  2s . 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:au.org.ala.bhl.DocumentPaginator.java

private void paginateImpl(XMLStreamReader parser, PageHandler handler) throws Exception {

    if (parser == null) {
        return;/*from w  ww  .j  a va2  s .  c o  m*/
    }

    StringBuilder buffer = new StringBuilder();

    String currentPage = null;

    while (true) {
        int event = parser.next();
        if (event == XMLStreamConstants.END_DOCUMENT) {
            parser.close();
            break;
        }

        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.getLocalName().equals("PARAM")) {
                String attrName = parser.getAttributeValue("", "name");
                if (attrName.equals("PAGE")) {

                    if (!StringUtils.isEmpty(currentPage)) {
                        if (handler != null) {
                            handler.handlePage(currentPage, buffer.toString());
                        }
                    }

                    buffer = new StringBuilder();
                    currentPage = parser.getAttributeValue("", "value");
                }
            }
        }

        if (event == XMLStreamConstants.CHARACTERS) {
            String value = StringUtils.trim(parser.getText());
            if (!StringUtils.isEmpty(value)) {
                buffer.append(value).append(" ");
            }
        }
    }

}

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 ww  .j  a  v a 2  s . c o  m*/
        if (event == START_ELEMENT && "property".equals(in.getLocalName())) {
            if ("execStatus".equals(findAttributeValue(in, "name"))) {
                return findAttributeValue(in, "value");
            }
        }
    }
    return "";
}

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

protected void handleResponse(XMLStreamReader reader) throws XMLStreamException {
    MultiStatusResponse multiStatusResponse = null;
    String href = null;//from   w w w  . j  a va2s  .c  o m
    String responseStatus = "";
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, "response")) {
        reader.next();
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagLocalName = reader.getLocalName();
            if ("href".equals(tagLocalName)) {
                href = reader.getElementText();
            } else if ("status".equals(tagLocalName)) {
                responseStatus = reader.getElementText();
            } else if ("propstat".equals(tagLocalName)) {
                if (multiStatusResponse == null) {
                    multiStatusResponse = new MultiStatusResponse(href, responseStatus);
                }
                handlePropstat(reader, multiStatusResponse);
            }
        }
    }
    if (multiStatusResponse != null) {
        responses.add(multiStatusResponse);
    }
}

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;
        }/*  w w  w. ja v a 2s  . co m*/
        if (event == CHARACTERS) {
            return in.getText();
        }
    }
    return "";
}

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

protected void handleProperty(XMLStreamReader reader, MultiStatusResponse multiStatusResponse)
        throws XMLStreamException {
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, "prop")) {
        reader.next();/*  ww  w .  j av  a  2  s . co m*/
        if (XMLStreamUtil.isStartTag(reader)) {
            Namespace namespace = Namespace.getNamespace(reader.getNamespaceURI());
            String tagLocalName = reader.getLocalName();
            if (reader.getAttributeCount() > 0 && "mv.string".equals(reader.getAttributeValue(0))) {
                handleMultiValuedProperty(reader, multiStatusResponse);
            } else {
                String tagContent = getTagContent(reader);
                if (tagContent != null) {
                    multiStatusResponse.add(new DefaultDavProperty(tagLocalName, tagContent, namespace));
                }
            }
        }
    }
}

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 . j  av  a2  s . co  m
 * @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;
}